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 -1
View File
@@ -69,6 +69,7 @@ AOI 最大重叠面积匹配的预处理不在当前仓库内,界面直接使
- `source/Grid_5G.gpkg`
<!-- - `source/Grid_4G.gpkg`:用户量停用后不再读取。 -->
- `source/BuildingInfo.gpkg`
- `source/NRBuildingsData.csv` 与 `source/NRBuildPolygon.csv`:楼宇查询结果及其轮廓源数据。开始出图时自动清洗并生成 `source/NRBuildingsData.gpkg`。
- `source/GIS.qgz`
- `output/AOI级报表_市场网格匹配.gpkg`:已完成最大重叠面积归属匹配的 AOI 总表。
2. 运行:
@@ -101,7 +102,7 @@ output/全量网格图层.zip
└── 竟对信号.tif
```
所有成果包均不再包含 CSV 或 `用户量.tif`,专题 TIF 只生成 `竟对信号.tif`。程序先合并本次参与处理的全部市场网格边界,再生成全域竟对信号图;网格之间没有数据的区域保持透明。`BuildingInfo.gpkg` 在汇总包中为完整源文件副本并保留样式支撑表;`GIS.qgz` 使用全网 BuildingInfo 范围作为初始画布。竟对信号使用固定八档 RSRP 图例,并将竟对 MR 总采样点为 `0` 的符合条件 Grid 标红。设置 `LIMIT` 时,TIF 汇总范围与本次受限处理的市场保持一致。
所有成果包均不再包含 CSV 或 `用户量.tif`,专题 TIF 只生成 `竟对信号.tif`。程序先合并本次参与处理的全部市场网格边界,再生成全域竟对信号图;网格之间没有数据的区域保持透明。`BuildingInfo.gpkg` 在汇总包中为完整源文件副本并保留样式支撑表。楼宇查询结果会删除失败行和查询过程字段,按 `building_id` 回填 `WKT`,生成带 `rtree_NRBuildingsData_geom` 空间索引的 `NRBuildingsData.gpkg`;每个市场包按与市场边界相交拆分该图层,并在 `GIS.qgz` 中显示。`GIS.qgz` 使用全网 BuildingInfo 范围作为初始画布。竟对信号使用固定八档 RSRP 图例,并将竟对 MR 总采样点为 `0` 的符合条件 Grid 标红。设置 `LIMIT` 时,TIF 汇总范围与本次受限处理的市场保持一致。
用户量的生成入口、4G 读取、阈值汇总、图例和结果写入代码以注释保留;专用算法函数仍保留供恢复使用。QGIS 模板中的原用户量图层配置保存为 XML 注释,打开项目时不会加载。恢复时需同时恢复这些代码入口和模板配置。
+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")
+37
View File
@@ -0,0 +1,37 @@
import csv
import sqlite3
import tempfile
import unittest
from pathlib import Path
from marketgrid.nrdata import build_gpkg
class NrDataTest(unittest.TestCase):
def test_build_gpkg_drops_failed_rows_and_creates_spatial_index(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
polygon = root / "NRBuildPolygon.csv"
data = root / "NRBuildingsData.csv"
output = root / "NRBuildingsData.gpkg"
polygon.write_text(
"WKT,building_id\n\"POLYGON ((112 22,113 22,113 23,112 23,112 22))\",A\n",
encoding="utf-8",
)
with data.open("w", encoding="gbk", newline="") as stream:
writer = csv.writer(stream)
writer.writerow(["输入行号", "building_id", "查询状态", "错误信息", "building_name"])
writer.writerow(["1", "A", "成功", "", "甲楼"])
writer.writerow(["2", "A", "失败", "超时", ""])
result = build_gpkg(data, polygon, output)
self.assertEqual(result["feature_count"], 1)
conn = sqlite3.connect(output)
try:
columns = [row[1] for row in conn.execute('pragma table_info("NRBuildingsData")')]
self.assertNotIn("输入行号", columns)
self.assertNotIn("查询状态", columns)
self.assertIn("WKT", columns)
self.assertEqual(conn.execute('select count(*) from "NRBuildingsData"').fetchone()[0], 1)
self.assertEqual(conn.execute("select count(*) from rtree_NRBuildingsData_geom").fetchone()[0], 1)
finally:
conn.close()
+11
View File
@@ -2,8 +2,10 @@
import sqlite3
import zipfile
import streamlit as st
from pathlib import Path
from toolbox.tasks import start_task
from toolbox.validation import SOURCES, market_options
from marketgrid.nrdata import build_gpkg
from .inputs import file_input
from .task_panel import show_started, task_panel
@@ -55,6 +57,15 @@ def render():
if submitted:
params["SELECTED_MARKET_IDS"] = [fid for fid, _ in options] if all_markets else chosen
try:
data_csv = Path("source/NRBuildingsData.csv")
polygon_csv = Path("source/NRBuildPolygon.csv")
data_gpkg = Path("source/NRBuildingsData.gpkg")
if not data_csv.is_file() or not polygon_csv.is_file():
raise ValueError("缺少 source/NRBuildingsData.csv 或 source/NRBuildPolygon.csv。")
if not data_gpkg.exists() or data_gpkg.stat().st_mtime < max(data_csv.stat().st_mtime, polygon_csv.stat().st_mtime):
st.info("正在整理楼宇结果并生成边界图层,请稍候……")
build_gpkg(data_csv, polygon_csv, data_gpkg)
params["NR_BUILDINGS_DATA_GPKG"] = str(data_gpkg)
if any(value is None for key, value in params.items() if key in SOURCES):
raise ValueError("请完成所需数据的导入。")
show_started(start_task("market", params))