fix: 恢复BuildingInfo源分割

This commit is contained in:
RBP15P
2026-07-17 15:24:23 +08:00
parent 9765d4fe86
commit 4fd8f36700
2 changed files with 74 additions and 120 deletions
+4 -5
View File
@@ -51,12 +51,11 @@
- 市场网格结果改为 zip 包输出:`python main.py` 会先在系统临时目录生成结果,再写入 `output/JMXXXX.zip`,zip 根目录直接包含 `GIS.qgz`、`信号.tif`、`用户量.tif`、`信号差用户量.tif`、`BuildingInfo.gpkg`,不再保留 `output/JMXXXX/` 文件夹。
## 2026-07-17
- 建筑信息输出不再依赖 `source/BuildingInfo.gpkg`,改为从 `source/Building.gpkg` 按市场网格相交关系抽取建筑要素,并在结果包内生成兼容 QGIS 项目的 `BuildingInfo.gpkg`。
- 结果包内建筑图层名固定为 `BuildingInfo`,字段固定为 `fid`、`geom`、`name`、`floor`、`height`;`name` 按 `building_name`、`building_id`、`area_name` 顺序取第一个非空值,`height` 来自源 `height` 字段,`floor` 默认按 `height / 3.0` 估算。
- 输出 `BuildingInfo.gpkg` 会写入 GeoPackage 基础元数据、`gpkg_geometry_columns`、`gpkg_ogr_contents` 和 `rtree_BuildingInfo_geom`,以保持 `source/MapPark/GIS.qgz` 中 `./BuildingInfo.gpkg|layername=BuildingInfo` 的引用可用。
- 当前测试市场 `JM010404` 已验证:zip 内包含 `BuildingInfo.gpkg`、`GIS.qgz`、`信号.tif`、`用户量.tif`、`信号差用户量.tif`;`BuildingInfo` 要素数和 RTree 数量均为 11215,`pragma integrity_check` 为 `ok`。
- 结果包内的 `BuildingInfo.gpkg` 已改回从 `source/BuildingInfo.gpkg` 按市场网格相交关系分割生成,保留源图层字段、`layer_styles`、`gpkg_metadata`、`gpkg_ogr_contents`、`gpkg_spatial_ref_sys` 等支撑表,并重建输出 RTree。
- `source/Building.gpkg` 继续用于生成 `楼宇指标.csv`,不再用于生成结果包内的 `BuildingInfo.gpkg`;这是因为 `Building.gpkg` 的 `building_name` 字段为空,QGIS 项目仍应使用 `source/BuildingInfo.gpkg` 的建筑名称和样式。
- 当前测试市场 `JM010404` 已验证:临时输出 zip 内包含 `BuildingInfo.gpkg`、`GIS.qgz`、`信号.tif`、`用户量.tif`、`信号差用户量.tif`、`楼宇指标.csv`、`栅格指标.csv`;`BuildingInfo` 要素数和 RTree 数量均为 9495,`pragma integrity_check` 为 `ok`,`layer_styles` 表存在且有 1 条样式记录。
- RSRP 红色端阈值已按用户手动配置纳入当前版本:`HEATMAP_BAD_RSRP = -105.0`。
- 每个市场网格 zip 现在额外包含两个 GBK 编码 CSV:`楼宇指标.csv` 和 `栅格指标.csv`,均按市场网格几何相交/触碰规则筛选源图层要素。
- `楼宇指标.csv` 来源为 `source/Building.gpkg`,并通过 `source/BuildingInfo.gpkg` 的 `BuildingInfo.name` 做空间匹配补回建筑名称;匹配时优先取与 Building 要素相交面积最大的 BuildingInfo 名称,匹配不到则建筑名称留空。
- 两个指标 CSV 使用统一字段口径:区域类型、区域名称、经度、纬度、竟对采样点总、竟对弱覆盖采样点、竟对平均信号值、移动信号、竟对信号;楼宇指标额外包含建筑名称。`ssb_rsrp_yd` 和 `ssb_rsrp_dl` 会按 `< -105` 较差、`<= -95` 一般、`> -95` 正常转换为中文信号等级。
- 两个指标 CSV 使用统一字段口径:区域类型、区域名称、经度、纬度、竟对采样点总、竟对弱覆盖采样点、竟对平均信号值、移动信号、竟对信号;楼宇指标额外包含建筑名称。`ssb_rsrp_yd` 和 `ssb_rsrp_dl` 会按 `< -105` 较差、`<= -95` 一般、`> -95` 正常转换为中文信号等级,空值输出 `无采集信息`。
- 当前测试市场 `JM010404` 已验证:`楼宇指标.csv` 共 11215 行数据,匹配建筑名称 10497 行;`栅格指标.csv` 共 17883 行数据,两个 CSV 均可用 GBK 解码。
+70 -115
View File
@@ -20,8 +20,8 @@ DEFAULT_SOURCE_DIR = Path("source") # 源数据目录,存放 MarketMap.gpkg
OUTPUT_DIR = Path("output") # 输出根目录,每个市场网格会在这里生成一个 JMXXXX.zip 结果包。
MARKET_GPKG = DEFAULT_SOURCE_DIR / "MarketMap.gpkg" # 市场网格 GeoPackage 文件路径。
GRID_GPKG = DEFAULT_SOURCE_DIR / "grid.gpkg" # Grid 栅格指标 GeoPackage 文件路径。
BUILDING_GPKG = DEFAULT_SOURCE_DIR / "Building.gpkg" # 建筑指标 GeoPackage 文件路径,拆分时只抽取当前 BuildingInfo 图层需要的字段。
BUILDING_INFO_GPKG = DEFAULT_SOURCE_DIR / "BuildingInfo.gpkg" # 建筑信息 GeoPackage 文件路径,仅用于给楼宇指标 CSV 匹配建筑名称。
BUILDING_GPKG = DEFAULT_SOURCE_DIR / "Building.gpkg" # 建筑指标 GeoPackage 文件路径,用于生成楼宇指标 CSV。
BUILDING_INFO_GPKG = DEFAULT_SOURCE_DIR / "BuildingInfo.gpkg" # 建筑信息 GeoPackage 文件路径,用于结果包 BuildingInfo 分割和楼宇指标 CSV 名称匹配。
MAP_PARK_DIR = DEFAULT_SOURCE_DIR / "MapPark" # QGIS 项目模板目录,里面的 GIS.qgz 会复制到每个市场网格结果包。
GIS_PROJECT_SOURCE = MAP_PARK_DIR / "GIS.qgz" # 每个市场网格结果包要复制的 QGIS 项目文件来源。
RSRP_FIELD = "ssb_rsrp_dl" # 用于生成热力图的电信 RSRP 字段名。
@@ -35,10 +35,6 @@ MARKET_CODE_FIELD = "micro_grid" # 市场网格编码字段,用于输出 zip
MARKET_NAME_FIELD = "micro_gr_1" # 市场网格名称字段,用于日志和汇总信息。
SIGNAL_OUTPUT_FILENAME = "信号.tif" # RSRP 连续热力图输出文件名。
BUILDING_INFO_OUTPUT_FILENAME = "BuildingInfo.gpkg" # 每个市场网格结果包内输出的建筑信息拆分文件名。
BUILDING_INFO_OUTPUT_LAYER = "BuildingInfo" # 输出给 GIS.qgz 使用的图层名,需保持 BuildingInfo 不变。
BUILDING_NAME_FIELDS = ("building_name", "building_id", "area_name") # 输出 name 字段来源,按顺序取第一个非空值。
BUILDING_HEIGHT_FIELD = "height" # 输出 height 字段来源。
BUILDING_FLOOR_HEIGHT_METERS = 3.0 # 输出 floor 字段按 height 估算时使用的单层高度。
BUILDING_METRICS_CSV_FILENAME = "楼宇指标.csv" # 每个市场网格结果包内输出的楼宇指标 CSV 文件名。
GRID_METRICS_CSV_FILENAME = "栅格指标.csv" # 每个市场网格结果包内输出的栅格指标 CSV 文件名。
CSV_ENCODING = "gbk" # 指标 CSV 输出编码,供 Excel/传统 GIS 工具直接打开。
@@ -306,15 +302,55 @@ def create_table_like_source(source_conn, target_conn, table_name):
target_conn.execute(sqlite_create_sql(source_conn, table_name))
def source_layer_geometry_type(source_conn, layer):
row = source_conn.execute(
"select geometry_type_name from gpkg_geometry_columns where table_name = ? and column_name = ?",
(layer.table_name, layer.geom_col),
).fetchone()
return row[0] if row else "MULTIPOLYGON"
def copy_matching_rows(target_conn, table_name, columns, rows):
if not rows:
return
column_sql = ", ".join(quote_identifier(column) for column in columns)
placeholders = ", ".join(["?"] * len(columns))
target_conn.executemany(
f"insert into {quote_identifier(table_name)} ({column_sql}) values ({placeholders})",
rows,
)
def initialize_building_info_output_gpkg(source_conn, output_path, source_layer, feature_count, extent):
def copy_gpkg_support_tables(source_conn, target_conn, layer, feature_count, extent):
support_tables = [
"gpkg_spatial_ref_sys",
"gpkg_contents",
"gpkg_geometry_columns",
"gpkg_ogr_contents",
"gpkg_extensions",
"gpkg_metadata",
"gpkg_metadata_reference",
"gpkg_tile_matrix_set",
"gpkg_tile_matrix",
"layer_styles",
]
for table_name in support_tables:
create_table_like_source(source_conn, target_conn, table_name)
for table_name in support_tables:
copy_all_rows(source_conn, target_conn, table_name)
minx, miny, maxx, maxy = extent if extent else (None, None, None, None)
target_conn.execute(
"""
update gpkg_contents
set min_x = ?, min_y = ?, max_x = ?, max_y = ?
where table_name = ?
""",
(minx, miny, maxx, maxy, layer.table_name),
)
if table_exists(target_conn, "gpkg_ogr_contents"):
target_conn.execute(
"update gpkg_ogr_contents set feature_count = ? where table_name = ?",
(feature_count, layer.table_name),
)
def initialize_split_output_gpkg(source_conn, output_path, layer, rtree, feature_count, extent):
if output_path.exists():
if not OVERWRITE:
return None
@@ -324,92 +360,21 @@ def initialize_building_info_output_gpkg(source_conn, output_path, source_layer,
target_conn.execute("pragma foreign_keys = off")
target_conn.execute(f"pragma application_id = {source_conn.execute('pragma application_id').fetchone()[0]}")
target_conn.execute(f"pragma user_version = {source_conn.execute('pragma user_version').fetchone()[0]}")
for table_name in ("gpkg_spatial_ref_sys", "gpkg_contents", "gpkg_geometry_columns", "gpkg_ogr_contents", "gpkg_extensions"):
create_table_like_source(source_conn, target_conn, table_name)
copy_all_rows(source_conn, target_conn, "gpkg_spatial_ref_sys")
target_conn.execute(
f"""
create table {quote_identifier(BUILDING_INFO_OUTPUT_LAYER)} (
"fid" integer primary key autoincrement not null,
"geom" {source_layer_geometry_type(source_conn, source_layer)},
"name" text,
"floor" mediumint,
"height" real
)
"""
)
minx, miny, maxx, maxy = extent if extent else (None, None, None, None)
source_contents = source_conn.execute(
"select description, last_change, srs_id from gpkg_contents where table_name = ?",
(source_layer.table_name,),
).fetchone()
description, last_change, srs_id = source_contents if source_contents else ("", None, source_layer.srs_id)
target_conn.execute(
"""
insert into gpkg_contents
(table_name, data_type, identifier, description, last_change, min_x, min_y, max_x, max_y, srs_id)
values (?, 'features', ?, ?, coalesce(?, strftime('%Y-%m-%dT%H:%M:%fZ','now')), ?, ?, ?, ?, ?)
""",
(BUILDING_INFO_OUTPUT_LAYER, BUILDING_INFO_OUTPUT_LAYER, description, last_change, minx, miny, maxx, maxy, srs_id),
)
target_conn.execute(
"insert into gpkg_geometry_columns values (?, ?, ?, ?, ?, ?)",
(
BUILDING_INFO_OUTPUT_LAYER,
"geom",
source_layer_geometry_type(source_conn, source_layer),
srs_id,
0,
0,
),
)
if table_exists(target_conn, "gpkg_ogr_contents"):
target_conn.execute(
"insert into gpkg_ogr_contents (table_name, feature_count) values (?, ?)",
(BUILDING_INFO_OUTPUT_LAYER, feature_count),
)
output_rtree = f"rtree_{BUILDING_INFO_OUTPUT_LAYER}_geom"
target_conn.execute(f"create virtual table {quote_identifier(output_rtree)} using rtree(id, minx, maxx, miny, maxy)")
if table_exists(target_conn, "gpkg_extensions"):
target_conn.execute(
"""
insert into gpkg_extensions (table_name, column_name, extension_name, definition, scope)
values (?, 'geom', 'gpkg_rtree_index', 'http://www.geopackage.org/spec120/#extension_rtree', 'write-only')
""",
(BUILDING_INFO_OUTPUT_LAYER,),
)
copy_gpkg_support_tables(source_conn, target_conn, layer, feature_count, extent)
target_conn.execute(sqlite_create_sql(source_conn, layer.table_name))
target_conn.execute(sqlite_create_sql(source_conn, rtree))
return target_conn
def first_non_empty(values):
for value in values:
if value is not None and str(value).strip():
return str(value).strip()
return None
def estimate_floor_from_height(height):
value = to_float(height)
if value is None or value <= 0:
return None
return max(1, int(round(value / BUILDING_FLOOR_HEIGHT_METERS)))
def collect_intersecting_building_info(source_conn, layer, rtree, market):
source_fields = [field for field in (*BUILDING_NAME_FIELDS, BUILDING_HEIGHT_FIELD) if field]
require_columns(source_conn, layer.table_name, source_fields)
def collect_intersecting_features(source_conn, layer, rtree, market):
table = quote_identifier(layer.table_name)
pk = quote_identifier(layer.pk_col)
geom = quote_identifier(layer.geom_col)
rtree_table = quote_identifier(rtree)
field_sql = ", ".join(f"b.{quote_identifier(field)}" for field in source_fields)
columns = table_columns(source_conn, layer.table_name)
column_sql = ", ".join(f"b.{quote_identifier(column)}" for column in columns)
min_market_x, min_market_y, max_market_x, max_market_y = market.geometry.bounds
query = f"""
select b.{pk}, b.{geom}, {field_sql}
select {column_sql}
from {rtree_table} r
join {table} b on b.{pk} = r."id"
where r."minx" <= ?
@@ -418,6 +383,8 @@ def collect_intersecting_building_info(source_conn, layer, rtree, market):
and r."maxy" >= ?
"""
geom_index = columns.index(layer.geom_col)
pk_index = columns.index(layer.pk_col)
prepared_market = prep(market.geometry)
rows = []
rtree_rows = []
@@ -426,8 +393,7 @@ def collect_intersecting_building_info(source_conn, layer, rtree, market):
for row in source_conn.execute(query, (max_market_x, min_market_x, max_market_y, min_market_y)):
candidates += 1
source_fid = row[0]
geom_blob = row[1]
geom_blob = row[geom_index]
if geom_blob is None:
continue
try:
@@ -438,12 +404,8 @@ def collect_intersecting_building_info(source_conn, layer, rtree, market):
continue
minx, miny, maxx, maxy = geometry.bounds
source_values = dict(zip(source_fields, row[2:]))
building_name = first_non_empty(source_values.get(field) for field in BUILDING_NAME_FIELDS)
height = to_float(source_values.get(BUILDING_HEIGHT_FIELD))
floor = estimate_floor_from_height(height)
rows.append((source_fid, geom_blob, building_name, floor, height))
rtree_rows.append((source_fid, minx, maxx, miny, maxy))
rows.append(row)
rtree_rows.append((row[pk_index], minx, maxx, miny, maxy))
if extent is None:
extent = [minx, miny, maxx, maxy]
else:
@@ -452,17 +414,17 @@ def collect_intersecting_building_info(source_conn, layer, rtree, market):
extent[2] = max(extent[2], maxx)
extent[3] = max(extent[3], maxy)
return rows, rtree_rows, tuple(extent) if extent else None, candidates
return columns, rows, rtree_rows, tuple(extent) if extent else None, candidates
def export_market_building_info_gpkg(source_conn, layer, rtree, market, output_path):
rows, rtree_rows, extent, candidates = collect_intersecting_building_info(
columns, rows, rtree_rows, extent, candidates = collect_intersecting_features(
source_conn,
layer,
rtree,
market,
)
target_conn = initialize_building_info_output_gpkg(source_conn, output_path, layer, len(rows), extent)
target_conn = initialize_split_output_gpkg(source_conn, output_path, layer, rtree, len(rows), extent)
if target_conn is None:
return {
"market_code": market.code,
@@ -474,17 +436,10 @@ def export_market_building_info_gpkg(source_conn, layer, rtree, market, output_p
}
try:
target_conn.executemany(
f"""
insert into {quote_identifier(BUILDING_INFO_OUTPUT_LAYER)}
("fid", "geom", "name", "floor", "height")
values (?, ?, ?, ?, ?)
""",
rows,
)
copy_matching_rows(target_conn, layer.table_name, columns, rows)
if rtree_rows:
target_conn.executemany(
f"insert into {quote_identifier(f'rtree_{BUILDING_INFO_OUTPUT_LAYER}_geom')} values (?, ?, ?, ?, ?)",
f"insert into {quote_identifier(rtree)} values (?, ?, ?, ?, ?)",
rtree_rows,
)
target_conn.commit()
@@ -510,7 +465,7 @@ def csv_text(value):
def signal_level(value):
number = to_float(value)
if number is None:
return ""
return "无采集信息"
if number < SIGNAL_BAD_THRESHOLD:
return "较差"
if number <= SIGNAL_NORMAL_THRESHOLD:
@@ -1343,9 +1298,9 @@ def main():
building_info_path = market_dir / BUILDING_INFO_OUTPUT_FILENAME
print(f" 拆分 BuildingInfo:{building_info_path.name}")
building_info_result = export_market_building_info_gpkg(
building_conn,
building_layer,
building_rtree,
building_info_conn,
building_info_layer,
building_info_rtree,
market,
building_info_path,
)