feat: 将楼宇查询边界接入市场网格出图

This commit is contained in:
nixevol
2026-09-21 09:58:46 +08:00
parent cab073bc0c
commit 8db2d96116
8 changed files with 165 additions and 1 deletions
+2
View File
@@ -8,6 +8,7 @@ GRID_5G_GPKG = DEFAULT_SOURCE_DIR / "Grid_5G.gpkg" # 5G Grid;竟对信号仅
# 用户量图层停用;以下原代码以注释保留,便于按需恢复。
# GRID_4G_GPKG = DEFAULT_SOURCE_DIR / "Grid_4G.gpkg" # 4G Grid;仅参与竟对用户量合并。
BUILDING_INFO_GPKG = DEFAULT_SOURCE_DIR / "BuildingInfo.gpkg" # 建筑信息 GeoPackage 文件路径,用于结果包 BuildingInfo 分割和楼宇指标 CSV 名称匹配。
NR_BUILDINGS_DATA_GPKG = DEFAULT_SOURCE_DIR / "NRBuildingsData.gpkg" # 清洗后的楼宇边界数据。
GIS_PROJECT_SOURCE = DEFAULT_SOURCE_DIR / "GIS.qgz" # 每个市场网格结果包使用的 QGIS 项目模板来源。
AOI_OUTPUT_FILENAME = "AOI级报表_市场网格匹配.gpkg"
AOI_GPKG = OUTPUT_DIR / AOI_OUTPUT_FILENAME # 已完成市场归属匹配的 AOI 总表。
@@ -29,6 +30,7 @@ MARKET_CODE_FIELD = "fid" # GridMap 市场网格唯一 ID 前缀字段。
MARKET_NAME_FIELD = "Name" # GridMap 市场网格名称字段。
MARKET_ID_SEPARATOR = "-" # 市场网格唯一 ID 拼接符,输出为 fid-name,例如 1-城区蓬江。
BUILDING_INFO_OUTPUT_FILENAME = "BuildingInfo.gpkg" # 每个市场网格结果包内输出的建筑信息拆分文件名。
NR_BUILDINGS_DATA_OUTPUT_FILENAME = "NRBuildingsData.gpkg" # 每个市场网格结果包内输出的楼宇边界文件名。
BUILDING_METRICS_CSV_FILENAME = "楼宇指标.csv" # 每个市场网格结果包内输出的楼宇指标 CSV 文件名。
GRID_METRICS_CSV_FILENAME = "栅格指标.csv" # 每个市场网格结果包内输出的栅格指标 CSV 文件名。
CSV_ENCODING = "gbk" # 指标 CSV 输出编码,供 Excel/传统 GIS 工具直接打开。
+9
View File
@@ -47,6 +47,7 @@ def process_market(market, pixel_width, pixel_height, output_dir):
open_read_connection(config.GRID_5G_GPKG) as grid_5g_conn,
# open_read_connection(GRID_4G_GPKG) as grid_4g_conn,
open_read_connection(config.BUILDING_INFO_GPKG) as building_info_conn,
open_read_connection(config.NR_BUILDINGS_DATA_GPKG) as nr_buildings_conn,
open_read_connection(config.AOI_GPKG) as aoi_conn,
):
grid_5g_layer = resolve_feature_layer(grid_5g_conn, config.GRID_5G_LAYER)
@@ -55,6 +56,8 @@ def process_market(market, pixel_width, pixel_height, output_dir):
grid_5g_rtree = rtree_name(grid_5g_conn, grid_5g_layer)
# grid_4g_rtree = rtree_name(grid_4g_conn, grid_4g_layer)
building_info_rtree = rtree_name(building_info_conn, building_info_layer)
nr_buildings_layer = resolve_feature_layer(nr_buildings_conn)
nr_buildings_rtree = rtree_name(nr_buildings_conn, nr_buildings_layer)
aoi_layer = resolve_feature_layer(aoi_conn, config.AOI_LAYER)
aoi_rtree = rtree_name(aoi_conn, aoi_layer)
@@ -92,6 +95,10 @@ def process_market(market, pixel_width, pixel_height, output_dir):
market,
building_info_path,
)
nr_buildings_path = market_dir / config.NR_BUILDINGS_DATA_OUTPUT_FILENAME
nr_buildings_result = export_market_building_info_gpkg(
nr_buildings_conn, nr_buildings_layer, nr_buildings_rtree, market, nr_buildings_path,
)
aoi_result = export_market_aoi_gpkg(
aoi_conn, aoi_layer, aoi_rtree, market, market_dir / config.AOI_OUTPUT_FILENAME,
)
@@ -102,6 +109,7 @@ def process_market(market, pixel_width, pixel_height, output_dir):
building_info_result["extent"],
competitor_signal_result["raster_extent"],
aoi_result=aoi_result,
nr_buildings_result=nr_buildings_result,
)
building_elapsed = perf_counter() - building_started_at
@@ -121,6 +129,7 @@ def process_market(market, pixel_width, pixel_height, output_dir):
market_dir,
),
"building_info_result": rewrite_result_for_zip(building_info_result, zip_path, market_dir),
"nr_buildings_result": rewrite_result_for_zip(nr_buildings_result, zip_path, market_dir),
"aoi_result": rewrite_result_for_zip(aoi_result, zip_path, market_dir),
"gis_project_result": rewrite_result_for_zip(gis_project_result, zip_path, market_dir),
"zip_result": zip_result,
+58
View File
@@ -0,0 +1,58 @@
"""楼宇查询结果清洗、轮廓回填和 GeoPackage 生成。"""
import csv
import sqlite3
from pathlib import Path
from shapely import wkt, to_wkb
DROP_COLUMNS = {"输入行号", "查询状态", "错误信息"}
LAYER_NAME = "NRBuildingsData"
GEOM_COLUMN = "geom"
def _encoding(path):
for enc in ("gbk", "utf-8-sig", "utf-8"):
try:
with Path(path).open(encoding=enc, newline="") as f:
next(csv.reader(f))
return enc
except (UnicodeDecodeError, StopIteration):
continue
raise ValueError("无法识别楼宇结果 CSV 编码")
def _gpkg_blob(geometry):
return b"GP" + bytes((0, 1, 0, 0, 0, 0, 0, 0)) + to_wkb(geometry)
def build_gpkg(data_csv, polygon_csv, output_path):
data_csv, polygon_csv, output_path = map(Path, (data_csv, polygon_csv, output_path))
polygons = {}
with polygon_csv.open(encoding=_encoding(polygon_csv), newline="") as f:
for row in csv.DictReader(f):
try: geometry = wkt.loads(row["WKT"])
except Exception: continue
if not geometry.is_empty and geometry.is_valid:
polygons.setdefault(str(row["building_id"]), geometry)
with data_csv.open(encoding=_encoding(data_csv), newline="") as f:
reader = csv.DictReader(f)
fields = [x for x in (reader.fieldnames or []) if x not in DROP_COLUMNS]
if "building_id" not in fields: raise ValueError("楼宇结果 CSV 缺少 building_id 字段")
fields.append("WKT")
rows=[]
for row in reader:
geometry=polygons.get(str(row.get("building_id", "")).strip())
if not geometry or (row.get("查询状态", "").strip() and row.get("查询状态", "").strip() not in {"成功", "命中"}): continue
clean={x:row.get(x, "") for x in fields if x != "WKT"}; clean["WKT"]=geometry.wkt; rows.append((clean,geometry))
output_path.parent.mkdir(parents=True, exist_ok=True)
if output_path.exists(): output_path.unlink()
conn=sqlite3.connect(output_path)
try:
conn.executescript("""CREATE TABLE gpkg_spatial_ref_sys (srs_name TEXT NOT NULL, srs_id INTEGER PRIMARY KEY, organization TEXT NOT NULL, organization_coordsys_id INTEGER NOT NULL, definition TEXT NOT NULL, description TEXT); INSERT INTO gpkg_spatial_ref_sys VALUES ('WGS 84 geodetic',4326,'EPSG',4326,'GEOGCS[\"WGS 84\"]',''); CREATE TABLE gpkg_contents (table_name TEXT PRIMARY KEY, data_type TEXT NOT NULL, identifier TEXT UNIQUE, description TEXT DEFAULT '', last_change DATETIME NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), min_x DOUBLE, min_y DOUBLE, max_x DOUBLE, max_y DOUBLE, srs_id INTEGER); CREATE TABLE gpkg_geometry_columns (table_name TEXT PRIMARY KEY, column_name TEXT NOT NULL, geometry_type_name TEXT NOT NULL, srs_id INTEGER NOT NULL, z TINYINT NOT NULL, m TINYINT NOT NULL);""")
esc=lambda x:'"'+x.replace('"','""')+'"'
conn.execute(f'CREATE TABLE {esc(LAYER_NAME)} (fid INTEGER PRIMARY KEY AUTOINCREMENT, '+', '.join(esc(x)+' TEXT' for x in fields)+f', {esc(GEOM_COLUMN)} BLOB NOT NULL)')
conn.execute('CREATE VIRTUAL TABLE rtree_NRBuildingsData_geom USING rtree(id,minx,maxx,miny,maxy)')
conn.execute('INSERT INTO gpkg_contents(table_name,data_type,identifier,srs_id) VALUES (?,?,?,?)',(LAYER_NAME,'features',LAYER_NAME,4326))
conn.execute('INSERT INTO gpkg_geometry_columns VALUES (?,?,?,?,?,?)',(LAYER_NAME,GEOM_COLUMN,'MULTIPOLYGON',4326,0,0))
cols=','.join(esc(x) for x in fields)
for clean,geometry in rows:
vals=[clean[x] for x in fields]+[_gpkg_blob(geometry)]; cur=conn.execute(f'INSERT INTO {esc(LAYER_NAME)} ({cols},{esc(GEOM_COLUMN)}) VALUES ({",".join("?" for _ in vals)})',vals); fid=cur.lastrowid; x1,y1,x2,y2=geometry.bounds; conn.execute('INSERT INTO rtree_NRBuildingsData_geom VALUES (?,?,?,?,?)',(fid,x1,x2,y1,y2))
conn.commit()
finally: conn.close()
return {"output":str(output_path),"feature_count":len(rows)}
+1
View File
@@ -53,6 +53,7 @@ def main(settings=None, progress=None):
config.GRID_5G_GPKG,
# GRID_4G_GPKG,
config.BUILDING_INFO_GPKG,
config.NR_BUILDINGS_DATA_GPKG,
config.GIS_PROJECT_SOURCE,
config.AOI_GPKG,
)
+45
View File
@@ -139,6 +139,48 @@ def add_market_aoi_layer(root, aoi_result, fallback_extent):
legend.insert(0, legend_layer)
def add_nr_buildings_layer(root, result, fallback_extent):
"""向工程加入清洗后的楼宇边界图层。"""
layer_id = "nr_buildings_data"
datasource = f"./{config.NR_BUILDINGS_DATA_OUTPUT_FILENAME}|layername=NRBuildingsData"
layer = ET.SubElement(root.find("projectlayers"), "maplayer", {
"type": "vector", "geometry": "Polygon", "hasScaleBasedVisibilityFlag": "0",
"styleCategories": "AllStyleCategories", "labelsEnabled": "0",
})
extent = result.get("extent") or fallback_extent
for tag in ("extent", "wgs84extent"):
set_xml_extent(ET.SubElement(layer, tag), extent)
for tag, value in (("id", layer_id), ("datasource", datasource), ("layername", "NRBuildingsData")):
ET.SubElement(layer, tag).text = value
spatial_ref = ET.SubElement(ET.SubElement(layer, "srs"), "spatialrefsys", nativeFormat="Wkt")
for tag, value in (("srid", "4326"), ("authid", "EPSG:4326"), ("description", "WGS 84")):
ET.SubElement(spatial_ref, tag).text = value
ET.SubElement(layer, "provider", encoding="UTF-8").text = "ogr"
ET.SubElement(layer, "displayfield").text = "building_id"
renderer = ET.SubElement(layer, "renderer-v2", type="singleSymbol", symbollevels="0", enableorderby="0")
symbol = ET.SubElement(ET.SubElement(renderer, "symbols"), "symbol", name="0", type="fill", alpha="1")
symbol_layer = ET.SubElement(symbol, "layer", {"class": "SimpleFill", "enabled": "1", "locked": "0", "pass": "0"})
options = ET.SubElement(symbol_layer, "Option", type="Map")
for name, value in {"color": "255,170,0,45", "outline_color": "255,120,0,220", "outline_width": "0.35", "outline_width_unit": "MM"}.items():
ET.SubElement(options, "Option", name=name, value=value, type="QString")
ET.SubElement(layer, "blendMode").text = "0"
ET.SubElement(layer, "layerOpacity").text = "1"
tree = root.find("layer-tree-group")
tree_layer = ET.Element("layer-tree-layer", {"id": layer_id, "name": "NRBuildingsData", "source": datasource, "providerKey": "ogr", "checked": "Qt::Checked", "expanded": "0"})
tree.insert(0, tree_layer)
custom_order = tree.find("custom-order")
if custom_order is not None:
item = ET.Element("item"); item.text = layer_id; custom_order.insert(0, item)
order = root.find("layerorder")
if order is not None: order.insert(0, ET.Element("layer", id=layer_id))
legend = root.find("legend")
if legend is not None:
legend_layer = ET.Element("legendlayer", {"name": "NRBuildingsData", "checked": "Qt::Checked", "open": "false", "drawingOrder": "-1"})
group = ET.SubElement(legend_layer, "filegroup", hidden="false", open="false")
ET.SubElement(group, "legendlayerfile", layerid=layer_id, visible="1", isInOverview="0")
legend.insert(0, legend_layer)
def copy_gis_project_to_market(
source_path,
output_path,
@@ -147,6 +189,7 @@ def copy_gis_project_to_market(
raster_extent=None,
include_cell_data=False,
aoi_result=None,
nr_buildings_result=None,
):
if output_path.exists() and not config.OVERWRITE:
return {
@@ -182,6 +225,8 @@ def copy_gis_project_to_market(
remove_qgis_layer(root, "CellData.gpkg", required=False)
if aoi_result is not None:
add_market_aoi_layer(root, aoi_result, market.geometry.bounds)
if nr_buildings_result is not None:
add_nr_buildings_layer(root, nr_buildings_result, market.geometry.bounds)
canvas = root.find(".//mapcanvas[@name='theMapCanvas']")
if canvas is None:
raise ValueError("QGIS 项目模板缺少主画布 theMapCanvas")