diff --git a/README.md b/README.md index 84fe630..cc06baf 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ npm run dev 同一时间只运行一个工具箱任务。任务由独立 Python 进程执行,刷新、切页或关闭浏览器不会重启或中断计算。出图停止在几何批处理边界生效,当前文件写入/打包可能需要等待;楼宇查询停止领取新坐标,正在处理的请求和结果写完后退出。已完成文件保留,失败和停止不标为成功;重启后意外退出的进程标为中断。**起始行只控制输入跳过,不是自动断点续传**,重试会创建新任务成果。 -界面导入 `source/江门市AOI级报表.csv` 后,按 AOI 与市场网格的最大接触面积自动写入 `source/AOI级报表_市场网格匹配.gpkg` 的 `所属市场网格`。只贴边、没有正面积的不归属。用户量仍停用。4G Grid 可以在导入区选择,当前出图不读取,留给后续 4G+5G 采样点统计。 +界面导入 `source/江门市AOI级报表.csv` 后,按 AOI 与市场网格的最大接触面积自动写入 `source/AOI级报表_市场网格匹配.gpkg` 的 `所属市场网格`。只贴边、没有正面积的不归属。用户量仍停用。4G Grid 与 5G Grid 按栅格中心 8 米内合并为 `采样点图层`,竞对信号仍只使用 5G。 市场网格出图页的导入区一行一个文件:标题、路径、选择文件。「市场边界」行的「操作」菜单可以编辑图层,增删改面和字段;「QGIS 工程模板」行可以增删改模板图层的名称、勾选、数据源和顺序。并行进程数、分辨率倍数和其他出图参数在「设置」弹窗里。规则引擎仍未做。 @@ -78,7 +78,7 @@ npm run dev 1. 准备源数据目录: - `source/GridMap.gpkg` - `source/Grid_5G.gpkg` - - `source/Grid_4G.gpkg`:界面启动时要求文件存在;当前出图不读取,留给后续 4G+5G 采样点统计。 + - `source/Grid_4G.gpkg`:与 5G Grid 合并为采样点图层。 - `source/BuildingInfo.gpkg` - `source/NRBuildingsData.csv` 与 `source/NRBuildPolygon.csv`:楼宇查询结果及其轮廓源数据。开始出图时自动清洗并生成 `source/NRBuildingsData.gpkg`。 - `source/GIS.qgz` @@ -104,6 +104,7 @@ Result.xlsx 移动C端采样点比例_AOI.gpkg 移动C端采样点比例_楼宇.gpkg 竞对信号.tif +采样点图层.gpkg 城区蓬江边界.gpkg # 当前市场名称 + 边界 ``` @@ -117,12 +118,13 @@ output/全量网格图层.zip ├── 移动C端采样点比例_AOI.gpkg ├── 移动C端采样点比例_楼宇.gpkg ├── 竞对信号.tif +├── 采样点图层.gpkg └── 全量网格图层边界.gpkg ``` 所有成果包均不再包含 CSV 或 `用户量.tif`,专题 TIF 只生成 `竞对信号.tif`。程序先合并本次参与处理的全部市场网格边界,再生成全域竞对信号图;网格之间没有数据的区域保持透明。`BuildingInfo.gpkg`、楼宇专题、AOI 和 `Result.xlsx` 在汇总包中为完整源文件副本(AOI 仍会做字段精简和样式写入)。楼宇查询结果会删除失败行和查询过程字段,按 `building_id` 回填 `WKT`,生成带 `rtree_NRBuildingsData_geom` 空间索引的 `NRBuildingsData.gpkg`;每个市场包按与市场边界相交拆分该图层,并在 `GIS.qgz` 中显示。`GIS.qgz` 使用全网 BuildingInfo 范围作为初始画布。竞对信号使用固定八档 RSRP 图例,并将竞对 MR 总采样点为 `0` 的符合条件 Grid 标红。设置 `LIMIT` 时,TIF 汇总范围与本次受限处理的市场保持一致。 -用户量的生成入口、4G 读取、阈值汇总、图例和结果写入代码以注释保留;专用算法函数仍保留供恢复使用。QGIS 模板中的原用户量图层配置保存为 XML 注释,打开项目时不会加载。恢复时需同时恢复这些代码入口和模板配置。 +用户量的生成入口、旧的按 `grid20_id` 合并、阈值汇总、图例和结果写入代码以注释保留;专用算法函数仍保留供恢复使用。现在读取 4G 只用于生成 `采样点图层`。QGIS 模板中的原用户量图层配置保存为 XML 注释,打开项目时不会加载。恢复时需同时恢复这些代码入口和模板配置。 ## 裁切规则 @@ -136,7 +138,7 @@ AOI 先按与市场网格的最大接触面积写入 `所属市场网格`,再 来源:`source/GIS.qgz` -说明:以该文件为模板生成到每个结果包。单市场图层从上到下为 `移动C端采样点比例_楼宇`、`移动C端采样点比例_AOI`、`竞对信号`、`BuildInfo`、`<市场名称>边界`、`GoogleCN`、`必应地图`、`online`;全量汇总包相同(数据完整未拆分,边界图层叫 `全量网格图层边界`),但不加入 `online`,也不包含小区数据图层。默认只勾选市场边界、`GoogleCN` 和 `online`;其他图层的勾选以 `marketgrid/styles/visibility.json` 为准。用户量图层已停用,兼容旧模板时也会移除其引用。`online` 是透明统计底图,地址为 `https://xyz.asio.asia/tiles/<市场名称的 URL 编码>/{z}/{x}/{y}.png`,每个市场使用自己的 Name。程序把 BuildInfo 图层范围更新为当前市场实际楼宇范围,并将 QGIS 主画布设置为该范围四周增加 5% 留白。 +说明:以该文件为模板生成到每个结果包。单市场图层从上到下为 `移动C端采样点比例_楼宇`、`移动C端采样点比例_AOI`、`采样点图层`、`竞对信号`、`BuildInfo`、`<市场名称>边界`、`GoogleCN`、`必应地图`、`online`;全量汇总包相同(数据完整未拆分,边界图层叫 `全量网格图层边界`),但不加入 `online`,也不包含小区数据图层。默认勾选 `采样点图层`、市场边界、`GoogleCN` 和 `online`;其他图层的勾选以 `marketgrid/styles/visibility.json` 为准。用户量图层已停用,兼容旧模板时也会移除其引用。`online` 是透明统计底图,地址为 `https://xyz.asio.asia/tiles/<市场名称的 URL 编码>/{z}/{x}/{y}.png`,每个市场使用自己的 Name。程序把 BuildInfo 图层范围更新为当前市场实际楼宇范围,并将 QGIS 主画布设置为该范围四周增加 5% 留白。 QGZ 内的样式数据库、其他图层配置和项目结构保持不变;如果当前市场没有 BuildingInfo 要素,画布范围会回退到市场网格范围。 @@ -197,6 +199,10 @@ AOI 在包内 `GIS.qgz` 中使用相对路径引用,默认不勾选。`output/ +### 采样点图层.gpkg + +来源:`source/Grid_5G.gpkg` 与 `source/Grid_4G.gpkg`。按当前市场范围筛出栅格后,比较栅格图形中心;相距 8 米以内视为同一个栅格,保留 5G 的图形(没有 5G 时保留 4G)。两边都有的 `mro_total_dl`、`mro_total_gd`、`mro_total_yd` 分别相加,`总采样点数` 是这三个和。不计入 `mro_total_dx`、`mro_total_lt`。属性缺失按 0。工程中放在竞对信号上面,默认勾选,蓝色空心边,避免挡住下面的竞对信号。 + ### 竞对信号.tif 来源:`source/Grid_5G.gpkg` @@ -263,7 +269,7 @@ QGIS 中竞对信号默认不勾选,用户量和小区数据图层均已移除 当前处理流程已做以下加速: -- 5G Grid 在同一市场内只执行一次 RTree 查询,用于竞对信号;用户量停用后不再查询 4G、不构建 4G/5G 用户量合并索引。 +- 5G Grid 在同一市场内查询竞对信号;4G 与 5G 再各查一次,只为合并采样点。用户量停用后不再按 `grid20_id` 构建用户量索引。 - Grid 和 BuildingInfo 使用 Shapely 批量解析 WKB、判断几何相交并提取边界,减少大量 Python 逐要素调用。 - 市场边界使用 Prepared Geometry 加速同一边界与大量 Grid 候选的重复拓扑判断;汇总任务会先修复边界副本的无效拓扑,再执行全域合并。 diff --git a/marketgrid/config.py b/marketgrid/config.py index 14be3a4..7a54f83 100644 --- a/marketgrid/config.py +++ b/marketgrid/config.py @@ -5,8 +5,11 @@ DEFAULT_SOURCE_DIR = Path("source") # 源数据目录,存放 GridMap.gpkg、G OUTPUT_DIR = Path("output") # 输出根目录,每个市场网格会在这里生成一个 JMXXXX.zip 结果包。 MARKET_GPKG = DEFAULT_SOURCE_DIR / "GridMap.gpkg" # 市场网格 GeoPackage 文件路径。 GRID_5G_GPKG = DEFAULT_SOURCE_DIR / "Grid_5G.gpkg" # 5G Grid;竞对信号仅使用该文件。 -# 界面已可选。当前出图仍不打开该文件,留给后续 4G+5G 采样点统计。 -GRID_4G_GPKG = DEFAULT_SOURCE_DIR / "Grid_4G.gpkg" # 4G Grid。 +GRID_4G_GPKG = DEFAULT_SOURCE_DIR / "Grid_4G.gpkg" # 4G Grid;与 5G 合并为采样点图层。 +SAMPLE_LAYER_NAME = "采样点图层" +SAMPLE_LAYER_FILENAME = "采样点图层.gpkg" +SAMPLE_MATCH_METERS = 8.0 # 栅格中心相距不超过该距离时视为同一个栅格。 +SAMPLE_VALUE_FIELDS = ("mro_total_dl", "mro_total_gd", "mro_total_yd") # 用户量图层停用;以下原代码以注释保留,便于按需恢复。 BUILDING_INFO_GPKG = DEFAULT_SOURCE_DIR / "BuildingInfo.gpkg" # 建筑信息 GeoPackage 文件路径,用于结果包 BuildingInfo 分割和楼宇指标 CSV 名称匹配。 NR_BUILDINGS_DATA_GPKG = DEFAULT_SOURCE_DIR / "NRBuildingsData.gpkg" # 清洗后的楼宇边界数据。 diff --git a/marketgrid/jobs.py b/marketgrid/jobs.py index 9258273..6dfb630 100644 --- a/marketgrid/jobs.py +++ b/marketgrid/jobs.py @@ -17,6 +17,7 @@ from .competitor import export_market_grid_outputs from .gpkg import gpkg_layer_extent from .market_boundary import boundary_filename from .market_boundary import export_market_boundary_gpkg +from .sample_grid import export_sample_grid from .files import market_zip_output_path from .gpkg import open_read_connection from .files import remove_file_with_retry @@ -50,15 +51,18 @@ def process_market(market, pixel_width, pixel_height, output_dir): with ( open_read_connection(config.GRID_5G_GPKG) as grid_5g_conn, + open_read_connection(config.GRID_4G_GPKG) as grid_4g_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) + grid_4g_layer = resolve_feature_layer(grid_4g_conn) # grid_4g_layer = resolve_feature_layer(grid_4g_conn, GRID_4G_LAYER) building_info_layer = resolve_feature_layer(building_info_conn, config.BUILDING_INFO_LAYER) grid_5g_rtree = rtree_name(grid_5g_conn, grid_5g_layer) + grid_4g_rtree = rtree_name(grid_4g_conn, grid_4g_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) @@ -89,6 +93,11 @@ def process_market(market, pixel_width, pixel_height, output_dir): None, # (grid_4g_conn, grid_4g_layer, grid_4g_rtree), ) + sample_result = export_sample_grid( + grid_5g_conn, grid_5g_layer, grid_5g_rtree, + grid_4g_conn, grid_4g_layer, grid_4g_rtree, + market, market_dir / config.SAMPLE_LAYER_FILENAME, + ) grid_elapsed = perf_counter() - grid_started_at building_info_path = market_dir / config.BUILDING_INFO_OUTPUT_FILENAME @@ -128,6 +137,7 @@ def process_market(market, pixel_width, pixel_height, output_dir): aoi_result=aoi_result, building_themes_result=nr_buildings_result, boundary_result=boundary_result, + sample_result=sample_result, ) building_elapsed = perf_counter() - building_started_at @@ -151,6 +161,7 @@ def process_market(market, pixel_width, pixel_height, output_dir): "result_xlsx": rewrite_result_for_zip(result_xlsx, zip_path, market_dir), "aoi_result": rewrite_result_for_zip(aoi_result, zip_path, market_dir), "boundary_result": rewrite_result_for_zip(boundary_result, zip_path, market_dir), + "sample_result": rewrite_result_for_zip(sample_result, zip_path, market_dir), "gis_project_result": rewrite_result_for_zip(gis_project_result, zip_path, market_dir), "zip_result": zip_result, "timings": { @@ -181,9 +192,14 @@ def process_summary_grid_outputs(markets, pixel_width, pixel_height, output_dir) "elapsed_seconds": perf_counter() - started_at, } - with open_read_connection(config.GRID_5G_GPKG) as grid_5g_conn: + with ( + open_read_connection(config.GRID_5G_GPKG) as grid_5g_conn, + open_read_connection(config.GRID_4G_GPKG) as grid_4g_conn, + ): grid_5g_layer = resolve_feature_layer(grid_5g_conn, config.GRID_5G_LAYER) + grid_4g_layer = resolve_feature_layer(grid_4g_conn) grid_5g_rtree = rtree_name(grid_5g_conn, grid_5g_layer) + grid_4g_rtree = rtree_name(grid_4g_conn, grid_4g_layer) with tempfile.TemporaryDirectory(prefix="market_grid_summary_") as temp_dir: summary_dir = Path(temp_dir) competitor_signal_path = summary_dir / competitor_signal_raster_filename() @@ -201,6 +217,11 @@ def process_summary_grid_outputs(markets, pixel_width, pixel_height, output_dir) None, max_raster_pixels=config.SUMMARY_MAX_RASTER_PIXELS, ) + sample_result = export_sample_grid( + grid_5g_conn, grid_5g_layer, grid_5g_rtree, + grid_4g_conn, grid_4g_layer, grid_4g_rtree, + summary_market, summary_dir / config.SAMPLE_LAYER_FILENAME, + ) building_info_path = summary_dir / config.BUILDING_INFO_OUTPUT_FILENAME shutil.copy2(config.BUILDING_INFO_GPKG, building_info_path) with open_read_connection(config.BUILDING_INFO_GPKG) as building_info_conn: @@ -257,6 +278,7 @@ def process_summary_grid_outputs(markets, pixel_width, pixel_height, output_dir) building_themes_result=nr_buildings_result, include_online=False, boundary_result=boundary_result, + sample_result=sample_result, ) zip_result = write_market_zip(summary_dir, zip_path, summary_market) legacy_zip_path = output_dir / config.LEGACY_SUMMARY_OUTPUT_FILENAME @@ -274,6 +296,7 @@ def process_summary_grid_outputs(markets, pixel_width, pixel_height, output_dir) "result_xlsx": rewrite_result_for_zip(result_xlsx, zip_path, summary_dir), "aoi_result": rewrite_result_for_zip(aoi_result, zip_path, summary_dir), "boundary_result": rewrite_result_for_zip(boundary_result, zip_path, summary_dir), + "sample_result": rewrite_result_for_zip(sample_result, zip_path, summary_dir), "gis_project_result": rewrite_result_for_zip(gis_project_result, zip_path, summary_dir), "zip_result": zip_result, "elapsed_seconds": perf_counter() - started_at, diff --git a/marketgrid/qgis.py b/marketgrid/qgis.py index 298b6d4..cc1d5ad 100644 --- a/marketgrid/qgis.py +++ b/marketgrid/qgis.py @@ -178,6 +178,98 @@ def add_market_boundary_layer(root, boundary_result): _insert_after(legend, existing, legend_layer) +def add_sample_layer(root, sample_result): + """把采样点图层插到竞对信号上面,默认勾选。""" + from .sample_grid import TABLE + layer_id = "sample_points_4g5g" + layer_name = sample_result["layer_name"] + datasource = f"./{sample_result['filename']}|layername={TABLE}" + remove_qgis_layer(root, sample_result["filename"], required=False) + template = next( + ( + layer + for layer in root.findall(".//projectlayers/maplayer") + if Path((layer.findtext("datasource") or "").replace("\\", "/").split("|", 1)[0]).name + == config.BUILDING_INFO_OUTPUT_FILENAME + ), + None, + ) + if template is None: + raise ValueError(f"QGIS 项目模板缺少 {config.BUILDING_INFO_OUTPUT_FILENAME} 图层") + style = ET.parse(Path(__file__).with_name("styles") / "sample_points.qml").getroot() + layer = copy.deepcopy(template) + layer.set("labelsEnabled", "0") + layer.set("wkbType", "Polygon") + layer.find("id").text = layer_id + layer.find("datasource").text = datasource + layer.find("layername").text = layer_name + renderer = layer.find("renderer-v2") + replacement = style.find("renderer-v2") + if renderer is None or replacement is None: + raise ValueError("采样点样式缺少渲染器") + index = list(layer).index(renderer) + layer.remove(renderer) + layer.insert(index, copy.deepcopy(replacement)) + for tag in ( + "fieldConfiguration", "aliases", "defaults", "constraints", "constraintExpressions", + "expressionfields", "attributetableconfig", "conditionalstyles", "editable", + "labelOnTop", "reuseLastValuePolicy", + ): + for child in list(layer.findall(tag)): + layer.remove(child) + extent = tuple(sample_result["extent"]) + for tag in ("extent", "wgs84extent"): + element = layer.find(tag) + if element is None: + element = ET.SubElement(layer, tag) + set_xml_extent(element, extent) + root.find("projectlayers").append(layer) + + tree = root.find("layer-tree-group") + signal_name = Path(config.COMPETITOR_SIGNAL_OUTPUT_FILENAME).stem + signal_node = next((item for item in tree.findall("layer-tree-layer") if item.get("name") == signal_name), None) + if signal_node is None: + raise ValueError(f"QGIS 项目模板缺少 {signal_name} 图层") + node = ET.Element("layer-tree-layer", { + "id": layer_id, "name": layer_name, "source": datasource, "providerKey": "ogr", + "checked": "Qt::Checked", "expanded": "0", + }) + tree.insert(list(tree).index(signal_node), node) + signal_id = signal_node.get("id") + order = tree.find("custom-order") + if order is not None: + existing = next((child for child in order if (child.text or "").strip() == signal_id), None) + item = ET.Element("item") + item.text = layer_id + if existing is None: + order.insert(0, item) + else: + order.insert(list(order).index(existing), item) + layerorder = root.find("layerorder") + if layerorder is not None: + existing = next((child for child in layerorder if child.get("id") == signal_id), None) + new_item = ET.Element("layer", id=layer_id) + if existing is None: + layerorder.insert(0, new_item) + else: + layerorder.insert(list(layerorder).index(existing), new_item) + legend = root.find("legend") + if legend is not None: + existing = next( + (child for child in legend if child.tag == "legendlayer" and child.get("name") == signal_name), + None, + ) + legend_layer = ET.Element("legendlayer", { + "name": layer_name, "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") + if existing is None: + legend.insert(0, legend_layer) + else: + legend.insert(list(legend).index(existing), legend_layer) + + def add_market_aoi_layer(root, aoi_result, fallback_extent): from .aoi_theme import aoi_layer_template template = aoi_layer_template() @@ -348,6 +440,7 @@ def copy_gis_project_to_market( building_themes_result=None, include_online=True, boundary_result=None, + sample_result=None, ): if output_path.exists() and not config.OVERWRITE: return { @@ -392,6 +485,8 @@ def copy_gis_project_to_market( add_online_basemap(root, market.name) if boundary_result is not None: add_market_boundary_layer(root, boundary_result) + if sample_result is not None: + add_sample_layer(root, sample_result) canvas = root.find(".//mapcanvas[@name='theMapCanvas']") if canvas is None: raise ValueError("QGIS 项目模板缺少主画布 theMapCanvas") diff --git a/marketgrid/sample_grid.py b/marketgrid/sample_grid.py new file mode 100644 index 0000000..c233a36 --- /dev/null +++ b/marketgrid/sample_grid.py @@ -0,0 +1,238 @@ +"""把同一位置的 4G、5G 栅格合并成采样点图层。""" +from collections import defaultdict +from datetime import datetime, timezone +from pathlib import Path +import math +import sqlite3 + +from shapely import Point, centroid, to_wkb +import shapely + +from . import config +from .gpkg import iter_geometry_batches, quote_identifier, require_columns +from .raster_math import to_float + +TABLE = "采样点图层" +GEOM = "geom" +SRS_ID = 4326 +FIELDS = ("mro_total_dl", "mro_total_gd", "mro_total_yd", "总采样点数") +STYLES = Path(__file__).with_name("styles") +WGS84 = ( + 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,' + 'AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,' + 'AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],' + 'AXIS["Latitude",NORTH],AXIS["Longitude",EAST],AUTHORITY["EPSG","4326"]]' +) + + +def export_sample_grid(grid_5g_conn, grid_5g_layer, grid_5g_rtree, grid_4g_conn, grid_4g_layer, grid_4g_rtree, market, output_path): + five = _collect(grid_5g_conn, grid_5g_layer, grid_5g_rtree, market) + four = _collect(grid_4g_conn, grid_4g_layer, grid_4g_rtree, market) + lat0 = (market.geometry.bounds[1] + market.geometry.bounds[3]) / 2 + merged = merge_sample_records(five, four, lat0, config.SAMPLE_MATCH_METERS) + _write(output_path, merged, market.geometry.bounds) + return { + "market_code": market.code, + "market_name": market.name, + "layer_name": config.SAMPLE_LAYER_NAME, + "filename": Path(output_path).name, + "output": str(output_path), + "extent": list(_extent(merged, market.geometry.bounds)), + "feature_count": len(merged), + "source_5g_count": len(five), + "source_4g_count": len(four), + "match_meters": config.SAMPLE_MATCH_METERS, + "skipped": False, + } + + +def merge_sample_records(five, four, latitude, meters): + """中心相距不超过 meters 的 4G、5G 栅格合成一条,图形保留 5G。""" + scale_x = 111_320 * math.cos(math.radians(latitude)) + scale_y = 110_540 + bins = defaultdict(list) + located = [] + for record in five: + x, y = record["lon"] * scale_x, record["lat"] * scale_y + located.append((x, y)) + bins[_bin(x, y, meters)].append(len(located) - 1) + totals = [[record["dl"], record["gd"], record["yd"]] for record in five] + used = [False] * len(four) + for index, record in enumerate(four): + x, y = record["lon"] * scale_x, record["lat"] * scale_y + ix, iy = _bin(x, y, meters) + nearest = None + nearest_distance = None + for nx in (ix - 1, ix, ix + 1): + for ny in (iy - 1, iy, iy + 1): + for candidate in bins.get((nx, ny), ()): + ox, oy = located[candidate] + distance = math.hypot(x - ox, y - oy) + if distance <= meters and (nearest_distance is None or distance < nearest_distance): + nearest, nearest_distance = candidate, distance + if nearest is None: + continue + used[index] = True + totals[nearest][0] += record["dl"] + totals[nearest][1] += record["gd"] + totals[nearest][2] += record["yd"] + merged = [] + for index, record in enumerate(five): + dl, gd, yd = totals[index] + merged.append({**record, "dl": dl, "gd": gd, "yd": yd, "total": dl + gd + yd}) + for index, record in enumerate(four): + if used[index]: + continue + merged.append({**record, "total": record["dl"] + record["gd"] + record["yd"]}) + return merged + + +def _meters(lon1, lat1, lon2, lat2): + scale_x = 111_320 * math.cos(math.radians((lat1 + lat2) / 2)) + return math.hypot((lon1 - lon2) * scale_x, (lat1 - lat2) * 110_540) + + +def _bin(x, y, meters): + return math.floor(x / meters), math.floor(y / meters) + + +def _collect(conn, layer, rtree, market): + value_fields = config.SAMPLE_VALUE_FIELDS + columns = ["longitude", "latitude", *value_fields] + require_columns(conn, layer.table_name, columns) + table = quote_identifier(layer.table_name) + pk = quote_identifier(layer.pk_col) + geom = quote_identifier(layer.geom_col) + selected = [geom, *(quote_identifier(name) for name in columns)] + query = f""" + select b.{pk}, {", ".join(f"b.{name}" for name in selected)} + from {quote_identifier(rtree)} r + join {table} b on b.{pk} = r."id" + where r."minx" <= ? and r."maxx" >= ? and r."miny" <= ? and r."maxy" >= ? + """ + minx, miny, maxx, maxy = market.geometry.bounds + rows = [] + shapely.prepare(market.geometry) + try: + cursor = conn.execute(query, (maxx, minx, maxy, miny)) + for batch, geometries, valid in iter_geometry_batches(cursor, 1): + hits = valid & shapely.intersects(market.geometry, geometries) + centers = centroid(geometries) + for index, row in enumerate(batch): + if not valid[index] or not hits[index]: + continue + center_lon, center_lat = float(centers[index].x), float(centers[index].y) + lon, lat = to_float(row[2]), to_float(row[3]) + # 属性里的中心点若明显不在该栅格上,改用图形中心,避免空值或 0 把不相邻的栅格拼到一起。 + if lon is None or lat is None or _meters(lon, lat, center_lon, center_lat) > 20: + lon, lat = center_lon, center_lat + if config.CLIP_MODE == "center" and not market.geometry.covers(Point(lon, lat)): + continue + values = [to_float(row[offset]) or 0.0 for offset in range(4, 7)] + bounds = geometries[index].bounds + rows.append({ + "lon": lon, "lat": lat, "dl": values[0], "gd": values[1], "yd": values[2], + "blob": _gp_blob(geometries[index]), "bounds": bounds, + }) + finally: + shapely.destroy_prepared(market.geometry) + return rows + + +def _gp_blob(geometry): + return b"GP" + bytes((0, 1)) + int(SRS_ID).to_bytes(4, "little", signed=True) + to_wkb(geometry) + + +def _extent(records, fallback): + if not records: + return fallback + minx = min(item["bounds"][0] for item in records) + miny = min(item["bounds"][1] for item in records) + maxx = max(item["bounds"][2] for item in records) + maxy = max(item["bounds"][3] for item in records) + return minx, miny, maxx, maxy + + +def _write(output_path, records, fallback_extent): + output_path = Path(output_path) + output_path.parent.mkdir(parents=True, exist_ok=True) + if output_path.exists(): + output_path.unlink() + minx, miny, maxx, maxy = _extent(records, fallback_extent) + qml = (STYLES / "sample_points.qml").read_text(encoding="utf-8") + conn = sqlite3.connect(output_path) + try: + conn.execute("PRAGMA application_id=1196444487") + conn.execute("PRAGMA user_version=10400") + conn.executescript( + """ + CREATE TABLE gpkg_spatial_ref_sys ( + srs_name TEXT NOT NULL, srs_id INTEGER NOT NULL PRIMARY KEY, + organization TEXT NOT NULL, organization_coordsys_id INTEGER NOT NULL, + definition TEXT NOT NULL, description TEXT); + CREATE TABLE gpkg_contents ( + table_name TEXT NOT NULL 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 NOT NULL, column_name TEXT NOT NULL, geometry_type_name TEXT NOT NULL, + srs_id INTEGER NOT NULL, z TINYINT NOT NULL, m TINYINT NOT NULL, + CONSTRAINT pk_geom_cols PRIMARY KEY (table_name, column_name)); + CREATE TABLE gpkg_ogr_contents (table_name TEXT NOT NULL PRIMARY KEY, feature_count INTEGER); + CREATE TABLE gpkg_extensions ( + table_name TEXT, column_name TEXT, extension_name TEXT NOT NULL, + definition TEXT NOT NULL, scope TEXT NOT NULL, + CONSTRAINT ge_tce UNIQUE (table_name, column_name, extension_name)); + CREATE TABLE layer_styles ( + id INTEGER PRIMARY KEY, f_table_catalog TEXT, f_table_schema TEXT, + f_table_name TEXT, f_geometry_column TEXT, styleName TEXT, styleQML TEXT, + styleSLD TEXT, useAsDefault BOOLEAN, description TEXT, owner TEXT, ui TEXT, + update_time DATETIME); + """ + ) + quoted_fields = ", ".join(f'"{name}" REAL' for name in FIELDS) + conn.execute(f'CREATE TABLE "{TABLE}" (fid INTEGER PRIMARY KEY, "{GEOM}" POLYGON, {quoted_fields})') + conn.execute(f'CREATE VIRTUAL TABLE "rtree_{TABLE}_{GEOM}" USING rtree(id, minx, maxx, miny, maxy)') + now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%fZ") + conn.executemany( + "INSERT INTO gpkg_spatial_ref_sys VALUES (?,?,?,?,?,?)", + [ + ("Undefined Cartesian", -1, "NONE", -1, "undefined", "undefined cartesian"), + ("Undefined geographic", 0, "NONE", 0, "undefined", "undefined geographic"), + ("WGS 84", SRS_ID, "EPSG", SRS_ID, WGS84, "WGS 84"), + ], + ) + conn.execute( + "INSERT INTO gpkg_contents VALUES (?,?,?,?,?,?,?,?,?,?)", + (TABLE, "features", TABLE, "", now, minx, miny, maxx, maxy, SRS_ID), + ) + conn.execute( + "INSERT INTO gpkg_geometry_columns VALUES (?,?,?,?,?,?)", + (TABLE, GEOM, "POLYGON", SRS_ID, 0, 0), + ) + conn.execute("INSERT INTO gpkg_ogr_contents VALUES (?,?)", (TABLE, len(records))) + conn.execute( + "INSERT INTO gpkg_extensions VALUES (?,?,?,?,?)", + (TABLE, GEOM, "gpkg_rtree_index", "http://www.geopackage.org/spec120/#extension_rtree", "read-write"), + ) + conn.execute( + "INSERT INTO layer_styles (f_table_catalog,f_table_schema,f_table_name,f_geometry_column," + "styleName,styleQML,styleSLD,useAsDefault,description,owner,ui,update_time) " + "VALUES ('','',?,?,?,?,?,1,'','',NULL,?)", + (TABLE, GEOM, "Default", qml, "", now), + ) + for index, record in enumerate(records, start=1): + conn.execute( + f'INSERT INTO "{TABLE}" (fid, "{GEOM}", "mro_total_dl", "mro_total_gd", "mro_total_yd", "总采样点数") ' + "VALUES (?,?,?,?,?,?)", + (index, record["blob"], record["dl"], record["gd"], record["yd"], record["total"]), + ) + minx, miny, maxx, maxy = record["bounds"] + conn.execute( + f'INSERT INTO "rtree_{TABLE}_{GEOM}" VALUES (?,?,?,?,?)', + (index, minx, maxx, miny, maxy), + ) + conn.commit() + finally: + conn.close() diff --git a/marketgrid/styles/sample_points.qml b/marketgrid/styles/sample_points.qml new file mode 100644 index 0000000..4c8692f --- /dev/null +++ b/marketgrid/styles/sample_points.qml @@ -0,0 +1,24 @@ + + + + + + + + + + + + diff --git a/tests/test_sample_grid.py b/tests/test_sample_grid.py new file mode 100644 index 0000000..7a2529e --- /dev/null +++ b/tests/test_sample_grid.py @@ -0,0 +1,80 @@ +"""4G 与 5G 采样点按中心距离合并。""" +from pathlib import Path +import sqlite3 +import tempfile +import unittest +import zipfile +import xml.etree.ElementTree as ET + +from shapely.geometry import box + +from marketgrid import config, qgis +from marketgrid.models import MarketFeature +from marketgrid.sample_grid import merge_sample_records +from tests.test_toolbox import create_gpkg +from marketgrid.gpkg import open_read_connection, resolve_feature_layer, rtree_name +from marketgrid.sample_grid import export_sample_grid + + +def _record(lon, lat, dl, gd, yd): + return {"lon": lon, "lat": lat, "dl": dl, "gd": gd, "yd": yd, "blob": b"", "bounds": (lon, lat, lon, lat)} + + +class SampleMergeTests(unittest.TestCase): + def test_cells_within_eight_meters_sum_and_keep_five_g_geometry(self): + five = [_record(113.0, 22.0, 10, 1, 100)] + four = [_record(113.0, 22.0 + 7.9 / 110_540, 4, 6, 8)] + merged = merge_sample_records(five, four, 22.0, 8) + self.assertEqual(len(merged), 1) + self.assertEqual(merged[0]["blob"], b"") + self.assertEqual((merged[0]["dl"], merged[0]["gd"], merged[0]["yd"], merged[0]["total"]), (14, 7, 108, 129)) + + def test_cells_farther_than_eight_meters_stay_separate(self): + five = [_record(113.0, 22.0, 1, 0, 0)] + four = [_record(113.0, 22.0 + 8.2 / 110_540, 2, 3, 4)] + merged = merge_sample_records(five, four, 22.0, 8) + self.assertEqual(len(merged), 2) + self.assertEqual({item["total"] for item in merged}, {1, 9}) + + def test_export_writes_summed_fields(self): + market_box = box(112, 22, 112.02, 22.02) + cell = box(112.001, 22.001, 112.011, 22.011) + market = MarketFeature(1, "1-甲", "甲", market_box) + with tempfile.TemporaryDirectory() as temp_dir: + root = Path(temp_dir) + fields = '"longitude" real,"latitude" real,"mro_total_dl" real,"mro_total_gd" real,"mro_total_yd" real' + create_gpkg(root / "5g.gpkg", "grid5", fields, [(1, cell, [112.006, 22.006, 10, 1, 100])]) + shifted = box(112.001, 22.001 + 3 / 110_540, 112.011, 22.011 + 3 / 110_540) + create_gpkg(root / "4g.gpkg", "grid4", fields, [(1, shifted, [112.006, 22.006, 4, 6, 8])]) + with open_read_connection(root / "5g.gpkg") as five_conn, open_read_connection(root / "4g.gpkg") as four_conn: + five_layer, four_layer = resolve_feature_layer(five_conn), resolve_feature_layer(four_conn) + result = export_sample_grid( + five_conn, five_layer, rtree_name(five_conn, five_layer), + four_conn, four_layer, rtree_name(four_conn, four_layer), + market, root / "采样点图层.gpkg", + ) + self.assertEqual(result["feature_count"], 1) + conn = sqlite3.connect(root / "采样点图层.gpkg") + try: + row = conn.execute('select "mro_total_dl","mro_total_gd","mro_total_yd","总采样点数" from "采样点图层"').fetchone() + finally: + conn.close() + self.assertEqual(row, (14, 7, 108, 129)) + + def test_project_places_checked_sample_layer_above_competitor_signal(self): + market = MarketFeature(1, "1-甲", "甲", box(0, 0, 1, 1)) + sample = {"filename": "采样点图层.gpkg", "layer_name": "采样点图层", "extent": [0, 0, 1, 1]} + with tempfile.TemporaryDirectory() as temp_dir: + output = Path(temp_dir) / "GIS.qgz" + qgis.copy_gis_project_to_market(config.GIS_PROJECT_SOURCE, output, market, None, sample_result=sample) + with zipfile.ZipFile(output) as archive: + root = ET.fromstring(archive.read("GIS.qgs")) + names = [item.get("name") for item in root.findall("./layer-tree-group/layer-tree-layer")] + self.assertEqual(names[names.index("竞对信号") - 1], "采样点图层") + node = root.find("./layer-tree-group/layer-tree-layer[@name='采样点图层']") + self.assertEqual(node.get("checked"), "Qt::Checked") + self.assertEqual(node.get("source"), "./采样点图层.gpkg|layername=采样点图层") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_toolbox.py b/tests/test_toolbox.py index 7ef89de..65de10e 100644 --- a/tests/test_toolbox.py +++ b/tests/test_toolbox.py @@ -164,12 +164,14 @@ class TaskIntegrationTest(unittest.TestCase): def test_parallel_market_settings_reach_spawned_workers(self): a, b = box(112, 22, 112.01, 22.01), box(112.02, 22, 112.03, 22.01) create_gpkg(self.root / "markets.gpkg", "MarketMap", '"Name" text', [(31, a, ["甲"]), (42, b, ["乙"])]) - fields = list(dict.fromkeys([*config.CSV_SOURCE_FIELDS, config.MOBILE_TOTAL_FIELD, config.MOBILE_WEAK_COVER_FIELD])) + fields = list(dict.fromkeys([*config.CSV_SOURCE_FIELDS, config.MOBILE_TOTAL_FIELD, config.MOBILE_WEAK_COVER_FIELD, "mro_total_gd"])) values = {field: 0 for field in fields} 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 / "grid4.gpkg", "grid4", '"grid20_id" text', [(1, a, ["g1"])]) + create_gpkg(self.root / "grid4.gpkg", "grid4", + '"longitude" real,"latitude" real,"mro_total_dl" real,"mro_total_gd" real,"mro_total_yd" real', + [(1, a, [0, 0, 4, 6, 8]), (2, b, [0, 0, 1, 2, 3])]) create_gpkg(self.root / "buildings.gpkg", "BuildingInfo", '"name" text,"floor" integer,"height" real', [(1, a, ["建筑甲", 2, 7.8]), (2, b, ["建筑乙", 3, 11.7])]) from marketgrid.building_themes import THEMES, ACTIVE_THEMES nr_fields = list(dict.fromkeys(n for t in THEMES for n, _ in t["fields"] if n not in ("floor", "height"))) @@ -215,6 +217,23 @@ class TaskIntegrationTest(unittest.TestCase): boundary = next(item for item in xml.iter("layer-tree-layer") if item.get("name") == boundary_name) self.assertEqual(boundary.get("checked"), "Qt::Checked") self.assertIn(boundary_name + ".gpkg", members) + self.assertEqual(names[names.index("竞对信号") - 1], "采样点图层") + sample_node = next(item for item in xml.iter("layer-tree-layer") if item.get("name") == "采样点图层") + self.assertEqual(sample_node.get("checked"), "Qt::Checked") + self.assertIn("采样点图层.gpkg", members) + sample_path = self.root / f"sample-{name}.gpkg" + sample_path.write_bytes(archive.read("采样点图层.gpkg")) + sample_conn = sqlite3.connect(sample_path) + try: + totals = {row[-1] for row in sample_conn.execute('select "mro_total_dl","mro_total_gd","mro_total_yd","总采样点数" from "采样点图层"')} + finally: + sample_conn.close() + if name == "31-甲.zip": + self.assertEqual(totals, {118}) + elif name == "42-乙.zip": + self.assertEqual(totals, {106}) + else: + self.assertEqual(totals, {118, 106}) if name == "全量网格图层.zip": self.assertNotIn("online", names) expected_count = 2 diff --git a/toolbox/validation.py b/toolbox/validation.py index 12c96c0..cfe77fc 100644 --- a/toolbox/validation.py +++ b/toolbox/validation.py @@ -34,11 +34,12 @@ def validate(kind, params): allowed = config.BUILDING_INFO_ALLOWED_SRS_IDS if key == "BUILDING_INFO_GPKG" else (4326,) if layer.srs_id not in allowed: raise ValueError(f"{label}坐标系不支持:{layer.srs_id}") - if key in {"GRID_5G_GPKG", "BUILDING_INFO_GPKG"}: + if key in {"GRID_5G_GPKG", "GRID_4G_GPKG", "BUILDING_INFO_GPKG"}: gpkg.rtree_name(conn, layer) fields = { "MARKET_GPKG": ["fid", "Name"], "BUILDING_INFO_GPKG": ["name"], - "GRID_5G_GPKG": [*config.CSV_SOURCE_FIELDS, config.MOBILE_TOTAL_FIELD, config.MOBILE_WEAK_COVER_FIELD], + "GRID_5G_GPKG": [*config.CSV_SOURCE_FIELDS, config.MOBILE_TOTAL_FIELD, config.MOBILE_WEAK_COVER_FIELD, "mro_total_gd"], + "GRID_4G_GPKG": ["longitude", "latitude", *config.SAMPLE_VALUE_FIELDS], }.get(key, []) gpkg.require_columns(conn, layer.table_name, fields) elif suffix == "csv":