feat: 按最大重叠面积匹配楼宇楼层和高度
This commit is contained in:
@@ -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}
|
||||
Reference in New Issue
Block a user