feat: 按最大重叠面积匹配楼宇楼层和高度

This commit is contained in:
nixevol
2026-09-21 15:20:21 +08:00
parent 0e3fbd2a23
commit a0edcbae2e
5 changed files with 112 additions and 1 deletions
+2
View File
@@ -213,6 +213,8 @@ QGIS 中竟对信号默认显示,用户量和小区数据图层均已移除。
## 常用配置
每个市场包的 `NRBuildingsData` 追加数值字段 `floor` 和 `height`。使用本次选择的建筑信息图层,按多边形最大相交面积匹配;面积相同取源主键较小的一条。无正面积重叠(包括仅边线接触)时,使用 `floor=1`、`height=3.9`;命中建筑的空属性也使用对应默认值。旧成果需重新出图才能获得这些字段。
命令行常用配置集中在 `marketgrid/config.py`:
| 配置 | 当前值 | 说明 |
+64
View File
@@ -0,0 +1,64 @@
"""按最大相交面积从建筑信息匹配楼层和高度。"""
from contextlib import closing
import math
import sqlite3
from shapely import from_wkb, make_valid
from . import config
from .gpkg import gpkg_blob_to_wkb, quote_identifier, require_columns, rtree_name
def match_attributes(source, layer, geometry):
"""只接受正面积交集;面积相同时按源主键取第一条。"""
table, pk, geom = map(quote_identifier, (layer.table_name, layer.pk_col, layer.geom_col))
index = quote_identifier(rtree_name(source, layer))
x1, y1, x2, y2 = geometry.bounds
rows = source.execute(
f'SELECT b.{geom}, b."floor", b."height" FROM {table} b '
f'JOIN {index} r ON r.id=b.{pk} '
f'WHERE r.minx<=? AND r.maxx>=? AND r.miny<=? AND r.maxy>=? ORDER BY b.{pk}',
(x2, x1, y2, y1),
)
best_area, values = 0.0, (1, 3.9)
geometry = make_valid(geometry) if not geometry.is_valid else geometry
for blob, floor, height in rows:
candidate = from_wkb(gpkg_blob_to_wkb(blob))
if not candidate.is_valid:
candidate = make_valid(candidate)
area = geometry.intersection(candidate).area
if area > best_area:
best_area = area
values = (floor, height)
# 匹配到建筑但属性为空或非有限值时,对应字段仍使用默认值。
def numeric(value, default):
if value is None or value == "":
return default
number = float(value)
return number if math.isfinite(number) else default
return numeric(values[0], 1), numeric(values[1], 3.9), best_area > 0
def enrich_building_attributes(output_path, source, source_layer):
"""在独立市场成果中写入数值字段,不修改源建筑文件。"""
require_columns(source, source_layer.table_name, ["floor", "height"])
if source_layer.srs_id not in config.BUILDING_INFO_ALLOWED_SRS_IDS:
raise ValueError("建筑信息必须使用 WGS84 经纬度坐标")
matched = defaults = 0
with closing(sqlite3.connect(output_path)) as target, target:
columns = {r[1] for r in target.execute('PRAGMA table_info("NRBuildingsData")')}
for name in ("floor", "height"):
if name not in columns:
target.execute(f'ALTER TABLE "NRBuildingsData" ADD COLUMN "{name}" REAL')
cursor = target.execute('SELECT fid, geom FROM "NRBuildingsData"')
while rows := cursor.fetchmany(config.GEOMETRY_BATCH_SIZE):
config.check_cancelled()
updates = []
for fid, blob in rows:
geometry = from_wkb(gpkg_blob_to_wkb(blob))
floor, height, found = match_attributes(source, source_layer, geometry)
matched += int(found)
defaults += int(not found)
updates.append((floor, height, fid))
target.executemany('UPDATE "NRBuildingsData" SET floor=?, height=? WHERE fid=?', updates)
return {"matched": matched, "defaults": defaults}
+4
View File
@@ -4,6 +4,7 @@ from time import perf_counter
import shutil
import tempfile
from . import config
from .building_attributes import enrich_building_attributes
from .gpkg import build_summary_market
from .files import competitor_signal_raster_filename
from .files import copy_full_source_file
@@ -99,6 +100,9 @@ def process_market(market, pixel_width, pixel_height, output_dir):
nr_buildings_result = export_market_building_info_gpkg(
nr_buildings_conn, nr_buildings_layer, nr_buildings_rtree, market, nr_buildings_path,
)
nr_buildings_result["attributes"] = enrich_building_attributes(
nr_buildings_path, building_info_conn, building_info_layer,
)
aoi_result = export_market_aoi_gpkg(
aoi_conn, aoi_layer, aoi_rtree, market, market_dir / config.AOI_OUTPUT_FILENAME,
)
+39
View File
@@ -0,0 +1,39 @@
import sqlite3
import tempfile
import unittest
from contextlib import closing
from pathlib import Path
from shapely.geometry import box
from marketgrid.models import LayerInfo
from marketgrid.nrdata import _gpkg_blob
from marketgrid.building_attributes import match_attributes, enrich_building_attributes
class BuildingAttributesTest(unittest.TestCase):
def test_maximum_overlap_ties_touch_and_defaults(self):
with closing(sqlite3.connect(":memory:")) as source:
source.executescript('CREATE TABLE buildings(fid INTEGER PRIMARY KEY, geom BLOB, floor INTEGER, height REAL); CREATE VIRTUAL TABLE rtree_buildings_geom USING rtree(id,minx,maxx,miny,maxy);')
for fid, geometry, floor, height in [
(1, box(0, 0, 1, 1), 2, 7.8),
(2, box(1, 0, 4, 1), 8, 31.2),
(3, box(5, 0, 6, 1), None, None),
]:
source.execute('INSERT INTO buildings VALUES (?,?,?,?)', (fid, _gpkg_blob(geometry), floor, height))
x1, y1, x2, y2 = geometry.bounds
source.execute('INSERT INTO rtree_buildings_geom VALUES (?,?,?,?,?)', (fid, x1, x2, y1, y2))
layer = LayerInfo('buildings', 'geom', 'fid', 100000)
self.assertEqual(match_attributes(source, layer, box(0, 0, 4, 1)), (8, 31.2, True))
self.assertEqual(match_attributes(source, layer, box(0, 0, 2, 1)), (2, 7.8, True))
self.assertEqual(match_attributes(source, layer, box(-1, 0, 0, 1)), (1, 3.9, False))
self.assertEqual(match_attributes(source, layer, box(10, 0, 11, 1)), (1, 3.9, False))
self.assertEqual(match_attributes(source, layer, box(5, 0, 6, 1)), (1, 3.9, True))
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / 'target.gpkg'
with closing(sqlite3.connect(path)) as target, target:
target.execute('CREATE TABLE NRBuildingsData(fid INTEGER PRIMARY KEY, geom BLOB)')
target.execute('INSERT INTO NRBuildingsData VALUES (1,?)', (_gpkg_blob(box(0, 0, 4, 1)),))
self.assertEqual(enrich_building_attributes(path, source, layer), {'matched': 1, 'defaults': 0})
enrich_building_attributes(path, source, layer)
with closing(sqlite3.connect(path)) as target:
self.assertEqual(target.execute('SELECT floor,height FROM NRBuildingsData').fetchone(), (8, 31.2))
+3 -1
View File
@@ -169,11 +169,13 @@ class TaskIntegrationTest(unittest.TestCase):
values.update(mro_total_yd=100, rsrp_lt_neg105_yd=10, ssb_rsrp_dl=-115, mro_total_dl=0)
create_gpkg(self.root / "grid.gpkg", "grid", ','.join(f'"{f}" real' for f in fields),
[(1, a, [values[f] for f in fields]), (2, b, [values[f] for f in fields])])
create_gpkg(self.root / "buildings.gpkg", "BuildingInfo", '"name" text', [(1, a, ["建筑甲"]), (2, b, ["建筑乙"])])
create_gpkg(self.root / "buildings.gpkg", "BuildingInfo", '"name" text,"floor" integer,"height" real', [(1, a, ["建筑甲", 2, 7.8]), (2, b, ["建筑乙", 3, 11.7])])
create_gpkg(self.root / "nr.gpkg", "NRBuildingsData", '"building_id" text', [(1, a, ["A"]), (2, b, ["B"])])
create_gpkg(self.root / "aoi.gpkg", config.AOI_LAYER,
'"所属市场网格" text,"AOI唯一标签" text,"AOI名称" text',
[(1, a, ["甲", "a", "甲AOI"]), (2, b, ["乙", "b", "乙AOI"])])
params = {"MARKET_GPKG": str(self.root / "markets.gpkg"), "GRID_5G_GPKG": str(self.root / "grid.gpkg"),
"NR_BUILDINGS_DATA_GPKG": str(self.root / "nr.gpkg"),
"BUILDING_INFO_GPKG": str(self.root / "buildings.gpkg"), "AOI_GPKG": str(self.root / "aoi.gpkg"),
"GIS_PROJECT_SOURCE": str(tasks.ROOT / "source/GIS.qgz"), "MAX_WORKERS": 2,
"SCALE": 1, "MAX_RASTER_PIXELS": 64, "SUMMARY_MAX_RASTER_PIXELS": 64,