From fbd856d54deee17735d7fd9c4bb84d56a3e5b7be Mon Sep 17 00:00:00 2001 From: nixevol Date: Wed, 16 Sep 2026 16:28:27 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9E=E6=A8=A1=E5=9D=97?= =?UTF-8?q?=E5=8C=96Streamlit=E6=9C=AC=E5=9C=B0=E5=B7=A5=E5=85=B7=E7=AE=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + .streamlit/config.toml | 16 + GetNRBuildingsData.py | 7 +- README.md | 48 +- app.py | 18 + main.py | 2637 +------------------------------ marketgrid/__init__.py | 1 + marketgrid/competitor.py | 416 +++++ marketgrid/config.py | 111 ++ marketgrid/files.py | 137 ++ marketgrid/gpkg.py | 409 +++++ marketgrid/jobs.py | 243 +++ marketgrid/legacy_user_count.py | 426 +++++ marketgrid/legends.py | 48 + marketgrid/metrics.py | 250 +++ marketgrid/models.py | 18 + marketgrid/pipeline.py | 284 ++++ marketgrid/qgis.py | 243 +++ marketgrid/raster_math.py | 205 +++ requirements-ui.txt | 6 + start-ui.cmd | 3 + start-ui.ps1 | 21 + tests/test_main.py | 232 +-- tests/test_toolbox.py | 219 +++ toolbox/__init__.py | 1 + toolbox/artifacts.py | 87 + toolbox/tasks.py | 122 ++ toolbox/validation.py | 70 + toolbox/worker.py | 78 + ui/__init__.py | 1 + ui/building_page.py | 42 + ui/home_page.py | 36 + ui/inputs.py | 41 + ui/market_page.py | 56 + ui/results_page.py | 93 ++ ui/task_panel.py | 41 + ui/tasks_page.py | 8 + 37 files changed, 3921 insertions(+), 2754 deletions(-) create mode 100644 .streamlit/config.toml create mode 100644 app.py create mode 100644 marketgrid/__init__.py create mode 100644 marketgrid/competitor.py create mode 100644 marketgrid/config.py create mode 100644 marketgrid/files.py create mode 100644 marketgrid/gpkg.py create mode 100644 marketgrid/jobs.py create mode 100644 marketgrid/legacy_user_count.py create mode 100644 marketgrid/legends.py create mode 100644 marketgrid/metrics.py create mode 100644 marketgrid/models.py create mode 100644 marketgrid/pipeline.py create mode 100644 marketgrid/qgis.py create mode 100644 marketgrid/raster_math.py create mode 100644 requirements-ui.txt create mode 100644 start-ui.cmd create mode 100644 start-ui.ps1 create mode 100644 tests/test_toolbox.py create mode 100644 toolbox/__init__.py create mode 100644 toolbox/artifacts.py create mode 100644 toolbox/tasks.py create mode 100644 toolbox/validation.py create mode 100644 toolbox/worker.py create mode 100644 ui/__init__.py create mode 100644 ui/building_page.py create mode 100644 ui/home_page.py create mode 100644 ui/inputs.py create mode 100644 ui/market_page.py create mode 100644 ui/results_page.py create mode 100644 ui/task_panel.py create mode 100644 ui/tasks_page.py diff --git a/.gitignore b/.gitignore index 421bfa1..e5d9870 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ .venv/ +.venv-ui/ __pycache__/ *.py[cod] diff --git a/.streamlit/config.toml b/.streamlit/config.toml new file mode 100644 index 0000000..49b5966 --- /dev/null +++ b/.streamlit/config.toml @@ -0,0 +1,16 @@ +[server] +address = "127.0.0.1" +maxUploadSize = 4096 + +[browser] +gatherUsageStats = false + +[client] +toolbarMode = "minimal" + +[theme] +primaryColor = "#0D827A" +backgroundColor = "#F7F9FC" +secondaryBackgroundColor = "#EDF2F7" +textColor = "#163047" +font = "sans serif" diff --git a/GetNRBuildingsData.py b/GetNRBuildingsData.py index 653b1b2..09a805d 100644 --- a/GetNRBuildingsData.py +++ b/GetNRBuildingsData.py @@ -166,7 +166,7 @@ class StreamingCsvWriter: self.file.close() -async def async_main(*, handle_signals=True): +async def async_main(*, handle_signals=True, should_stop=None, progress=None): parts = urlsplit(URL.strip()) if parts.scheme not in ("http", "https") or not parts.netloc or not COOKIES.strip(): raise ValueError("请先在脚本顶部填写完整 URL 和 COOKIES") @@ -196,6 +196,9 @@ async def async_main(*, handle_signals=True): async def query_worker(session, selected): nonlocal stop_reason while not stop.is_set(): + if should_stop and should_stop(): + request_stop() + break # 同一事件循环中读取下一行,无 await,不会并发推进 CSV 迭代器。 point = next(selected, None) if point is None: @@ -240,6 +243,8 @@ async def async_main(*, handle_signals=True): status_key = {"成功": "命中坐标", "未命中": "未命中坐标"}.get(metadata["查询状态"], "失败坐标") counts[status_key] += 1 counts["楼宇结果行"] += len(features) + if progress: + progress(dict(counts)) if counts["查询坐标"] == 1 or counts["查询坐标"] % PROGRESS_EVERY == 0: print(f"已写入 {counts['查询坐标']} 个坐标,命中 {counts['命中坐标']},未命中 {counts['未命中坐标']},失败 {counts['失败坐标']}", flush=True) finally: diff --git a/README.md b/README.md index 881ae62..85ce2da 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,50 @@ 本项目按 `source/GridMap.gpkg` 中的市场网格切分 Grid 和 BuildingInfo 数据,并为每个市场网格生成一个 zip 结果包。`CellData.gpkg` 仅保留在全量汇总包中。 +## 本地工具箱界面 + +Windows 双击 `start-ui.cmd`,或在项目目录运行 `./start-ui.ps1`。启动脚本使用独立的 `.venv-ui` 环境,首次安装依赖后在本机打开 Streamlit(默认 `http://127.0.0.1:8501`)。支持 Python 3.13;安装了 uv 时自动使用 uv 创建环境,否则使用系统 Python。原 `.venv` 不会被覆盖。 + +手动启动(包括 Linux): + +```text +python -m venv .venv-ui +# 激活 .venv-ui 后执行 +python -m pip install -r requirements-ui.txt +python -m streamlit run app.py +``` + +界面包含五个可用页面: + +- **工具箱首页**:默认输入文件状态与任务概况。 +- **市场网格出图**:保持完整流程,在同一页面分别导入市场边界、5G Grid、建筑、已归属 AOI、小区数据和 QGIS 模板。各数据源均支持本地路径、点击选文件及拖拽上传;选择全部或指定市场,设置进程数、分辨率、像元上限和汇总开关。 +- **楼宇数据查询**:坐标 CSV 导入、编码选择、起始行、查询数量、并发、超时和重试配置,默认复用现有脚本配置,也可输入仅本次使用的连接参数。 +- **任务中心**:每两秒更新进度,查看日志和历史任务,请求停止任务。 +- **成果浏览**:选择已有正式成果或任务成果,浏览 ZIP 成员,预览 CSV、JSON、QGIS 图层、GeoPackage 属性与抽样几何、GeoTIFF 缩略图,按需下载或打开本地目录。 + +每次任务使用 `output/toolbox/tasks/<任务ID>/results/`,不覆盖 `output/` 下原有成果。任务配置、状态和日志持久保存,连接参数只通过标准输入传递,不进入任务历史。上传副本放在 `output/toolbox/imports/`。大文件推荐使用本地路径;Streamlit 上传会占用额外内存,单文件上限 4 GB。超过 128 MB 的成果直接从本地目录复制,避免下载占用服务内存。 + +同一时间只运行一个工具箱任务。任务由独立 Python 进程执行,刷新、切页或关闭浏览器不会重启或中断计算。出图停止在几何批处理边界生效,当前文件写入/打包可能需要等待;楼宇查询停止领取新坐标,正在处理的请求和结果写完后退出。已完成文件保留,失败和停止不标为成功;重启后意外退出的进程标为中断。**起始行只控制输入跳过,不是自动断点续传**,重试会创建新任务成果。 + +AOI 最大重叠面积匹配的预处理不在当前仓库内,界面直接使用已匹配的 AOI GPKG,不提供未实现的 AOI 匹配入口。用户量和 4G 流程仍停用。 + +## 代码结构 + +`main.py` 保留为命令行入口;默认配置位于 `marketgrid/config.py`。 + +| 目录 / 模块 | 职责 | +| --- | --- | +| `marketgrid/pipeline.py`、`jobs.py` | 完整流程、多进程调度与单市场/汇总成果生成 | +| `marketgrid/gpkg.py` | GeoPackage、空间索引、建筑/AOI 子集 | +| `marketgrid/competitor.py`、`raster_math.py` | 竟对信号计算与 GeoTIFF | +| `marketgrid/qgis.py`、`files.py`、`legends.py` | QGIS 工程、ZIP 原子落盘与图例 | +| `marketgrid/legacy_user_count.py`、`metrics.py` | 保留的历史用户量与指标算法 | +| `toolbox/` | 输入验证、独立任务进程、任务记录和成果读取 | +| `ui/` | 页面和通用文件导入、任务进度组件 | +| `GetNRBuildingsData.py` | 可独立运行的异步楼宇查询 | + +测试:`.venv-ui/Scripts/python.exe -m unittest discover -s tests -v`。 + ## 独立楼宇批量查询 `GetNRBuildingsData.py` 独立运行,不调用 `main.py`。先运行 `python -m pip install -r requirements-nr-buildings.txt` 安装异步请求依赖 `aiohttp`。 @@ -10,7 +54,7 @@ 2. 默认读取 `source/NRBuildingsPoint.csv`,使用 `序号`、`经度`、`维度` 三列,输入编码为 GBK/GB18030。 3. 运行 `python GetNRBuildingsData.py`,当前 `LIMIT = 1000`,输出 `output/NRBuildingsData.csv`。将 `LIMIT` 改为 `None` 可查询剩余全部;`START_ROW` 可指定起始数据行。 -脚本自动把 URL 中的 `CQL_FILTER` 替换成 `POINT(经度 纬度)` 点查询,坐标之间使用空格。输出表头包含查询坐标、状态以及所有返回 `properties` 字段;一个坐标命中多个楼宇时输出多行,未命中或失败时保留状态行。Git 中的 URL 和 Cookies 留空,本地可填写默认值;有效凭证不得提交到 Git。 +脚本自动把 URL 中的 `CQL_FILTER` 替换成 `POINT(经度 纬度)` 点查询,坐标之间使用空格。输出表头包含查询坐标、状态以及所有返回 `properties` 字段;一个坐标命中多个楼宇时输出多行,未命中或失败时保留状态行。脚本顶部保存现有本地连接配置;界面可覆盖本次连接参数,覆盖值不写入任务配置或日志。 `CONCURRENCY = 8` 控制并发查询协程数。网络请求共用连接池,完成后进入最多缓存 `CONCURRENCY × 2` 个结果的队列。唯一的写入线程按返回顺序逐次追加 CSV 并 `flush`,因此未查完也能看到已返回的数据;用查询序号关联原坐标,输出不保证输入顺序。若后续响应新增字段,写入线程会原子替换 CSV 以扩展表头并保留已有行。 @@ -176,7 +220,7 @@ QGIS 中竟对信号默认显示,用户量已移除。单市场 QGIS 不包含 ## 常用配置 -常用配置集中在 `main.py` 顶部: +命令行常用配置集中在 `marketgrid/config.py`: | 配置 | 当前值 | 说明 | | --- | --- | --- | diff --git a/app.py b/app.py new file mode 100644 index 0000000..5054441 --- /dev/null +++ b/app.py @@ -0,0 +1,18 @@ +"""本地工具箱入口:streamlit run app.py。""" +import streamlit as st +from ui import home_page, market_page, building_page, tasks_page, results_page + +st.set_page_config(page_title="MarketGrid 工具箱", page_icon="🗺️", layout="wide") +pages = { + "home": st.Page(home_page.render, title="工具箱首页", icon="🏠", default=True), + "market": st.Page(market_page.render, title="市场网格出图", icon="🗺️", url_path="market"), + "buildings": st.Page(building_page.render, title="楼宇数据查询", icon="🏢", url_path="buildings"), + "tasks": st.Page(tasks_page.render, title="任务中心", icon="⏳", url_path="tasks"), + "results": st.Page(results_page.render, title="成果浏览", icon="📦", url_path="results"), +} +st.session_state["pages"] = pages +with st.sidebar: + st.title("MarketGrid") + st.caption("本地空间数据工具箱") +st.navigation({"工具": [pages["home"], pages["market"], pages["buildings"]], + "工作记录": [pages["tasks"], pages["results"]]}).run() diff --git a/main.py b/main.py index 6d544b1..64bc118 100644 --- a/main.py +++ b/main.py @@ -1,2638 +1,5 @@ -import csv -import json -import math -import re -import shutil -import sqlite3 -import tempfile -import xml.etree.ElementTree as ET -import zipfile -from concurrent.futures import ProcessPoolExecutor, as_completed -from contextlib import contextmanager -from dataclasses import dataclass -from pathlib import Path -from time import perf_counter, sleep - -import numpy as np -import shapely -import tifffile -from shapely import Point, STRtree, from_wkb -from shapely.errors import GEOSException - - -DEFAULT_SOURCE_DIR = Path("source") # 源数据目录,存放 GridMap.gpkg、Grid_5G.gpkg、Grid_4G.gpkg 等输入文件。 -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;竟对信号仅使用该文件。 -# 用户量图层停用;以下原代码以注释保留,便于按需恢复。 -# GRID_4G_GPKG = DEFAULT_SOURCE_DIR / "Grid_4G.gpkg" # 4G Grid;仅参与竟对用户量合并。 -BUILDING_INFO_GPKG = DEFAULT_SOURCE_DIR / "BuildingInfo.gpkg" # 建筑信息 GeoPackage 文件路径,用于结果包 BuildingInfo 分割和楼宇指标 CSV 名称匹配。 -CELL_DATA_GPKG = DEFAULT_SOURCE_DIR / "CellData.gpkg" # 小区数据 GeoPackage;仅完整复制到汇总结果包。 -GIS_PROJECT_SOURCE = DEFAULT_SOURCE_DIR / "GIS.qgz" # 每个市场网格结果包使用的 QGIS 项目模板来源。 -AOI_OUTPUT_FILENAME = "AOI级报表_市场网格匹配.gpkg" -AOI_GPKG = OUTPUT_DIR / AOI_OUTPUT_FILENAME # 已完成市场归属匹配的 AOI 总表。 -AOI_LAYER = "AOI市场网格匹配" -AOI_MARKET_FIELD = "所属市场网格" -RSRP_FIELD = "ssb_rsrp_dl" # 用于生成热力图的电信 RSRP 字段名。 -# EXCELLENT_CELL_FIELD = "mro_total_dl" # 用于生成用户量热力图的字段名,值越大越红。 -EXCELLENT_CELL_FIELD = "mro_total_dl" # 竟对信号筛选仍需使用的 5G 竟对总采样量字段。 -GRID_ID_FIELD = "grid20_id" # 4G/5G 用户量合并去重的唯一索引字段。 -WEAK_COVER_FIELD = "rsrp_lt_neg105_dl" # 用于生成信号差用户量热力图的字段名,值越大越红。 -MOBILE_TOTAL_FIELD = "mro_total_yd" # 移动采样点总数字段,用作移动弱覆盖比例分母。 -MOBILE_WEAK_COVER_FIELD = "rsrp_lt_neg105_yd" # 移动弱覆盖采样点字段,用作目标 Grid 筛选。 -MARKET_LAYER = None # 市场网格图层名;None 表示自动使用 GPKG 中第一个 feature 图层。 -GRID_5G_LAYER = None # 5G Grid 图层名;None 表示自动使用 GPKG 中第一个 feature 图层。 -# GRID_4G_LAYER = None # 4G Grid 图层名;None 表示自动使用 GPKG 中第一个 feature 图层。 -BUILDING_LAYER = None # Building 建筑指标图层名;None 表示自动使用 GPKG 中第一个 feature 图层。 -BUILDING_INFO_LAYER = None # BuildingInfo 建筑信息图层名;None 表示自动使用 GPKG 中第一个 feature 图层。 -MARKET_CODE_FIELD = "fid" # GridMap 市场网格唯一 ID 前缀字段。 -MARKET_NAME_FIELD = "Name" # GridMap 市场网格名称字段。 -MARKET_ID_SEPARATOR = "-" # 市场网格唯一 ID 拼接符,输出为 fid-name,例如 1-城区蓬江。 -BUILDING_INFO_OUTPUT_FILENAME = "BuildingInfo.gpkg" # 每个市场网格结果包内输出的建筑信息拆分文件名。 -CELL_DATA_OUTPUT_FILENAME = "CellData.gpkg" # 汇总结果包内的小区数据文件名。 -BUILDING_METRICS_CSV_FILENAME = "楼宇指标.csv" # 每个市场网格结果包内输出的楼宇指标 CSV 文件名。 -GRID_METRICS_CSV_FILENAME = "栅格指标.csv" # 每个市场网格结果包内输出的栅格指标 CSV 文件名。 -CSV_ENCODING = "gbk" # 指标 CSV 输出编码,供 Excel/传统 GIS 工具直接打开。 -CSV_SOURCE_FIELDS = ("area_type", "area_name", "longitude", "latitude", "mro_total_dl", "rsrp_lt_neg105_dl", "ssb_rsrp_dl", "ssb_rsrp_yd") # 指标 CSV 从源图层提取的字段。 -SIGNAL_BAD_THRESHOLD = -105.0 # 信号等级“较差”的阈值,小于等于该值输出较差。 -SIGNAL_NORMAL_THRESHOLD = -95.0 # 信号等级“一般/正常”的分界,大于该值输出正常。 -GIS_PROJECT_OUTPUT_FILENAME = "GIS.qgz" # 每个市场网格结果包内输出的 QGIS 项目文件名,画布范围按 BuildingInfo 自动更新。 -HEATMAP_SMOOTH_RADIUS = 10 # 热力图平滑半径,数值越大边界感越弱但细节越柔。 -HEATMAP_ALPHA = 191 # 热力图有效像元透明度;191 约等于 75% 不透明度。 -PROJECT_EXTENT_PADDING_RATIO = 0.05 # QGIS 打开后的画布留白比例;0.05 表示在 BuildingInfo 范围四周各增加 5%。 -# USER_COUNT_OUTPUT_FILENAME = "用户量.tif" # 采样点数量热力图输出文件名。 -USER_COUNT_OUTPUT_FILENAME = "用户量.tif" # 保留文件名,以移除旧模板中的用户量图层引用。 -COMPETITOR_SIGNAL_OUTPUT_FILENAME = "竟对信号.tif" # 移动非弱覆盖区域内的竟对 MR 弱覆盖/零采样信号图。 -COMPETITOR_SIGNAL_MOBILE_WEAK_RATIO_MAX = 20.0 # 移动弱覆盖比例必须严格小于该百分比。 -COMPETITOR_SIGNAL_WEAK_RATIO_MIN = 20.0 # 竟对 MR 弱覆盖比例必须严格大于该百分比。 -COMPETITOR_SIGNAL_RSRP_BREAKS = (-110.0, -104.0, -98.0, -92.0, -86.0, -80.0, -74.0) # 八档颜色的七个分界点。 -COMPETITOR_SIGNAL_RSRP_COLORS = ( - (253, 0, 5), # < -110,红色。 - (255, 138, 0), # [-110, -104),橙色。 - (254, 253, 2), # [-104, -98),黄色。 - (214, 251, 199), # [-98, -92),浅绿色。 - (42, 231, 41), # [-92, -86),亮绿色。 - (34, 174, 51), # [-86, -80),深绿色。 - (0, 149, 231), # [-80, -74),蓝色。 - (58, 14, 247), # [-74, 0],紫色。 -) -SUMMARY_OUTPUT_ENABLED = True # 是否额外生成全部市场网格汇总 TIF 结果包。 -# SUMMARY_OUTPUT_FILENAME = "全量网格图层.zip" # 汇总结果包文件名,包含两张 TIF、GIS.qgz、BuildingInfo.gpkg 和 CellData.gpkg。 -SUMMARY_OUTPUT_FILENAME = "全量网格图层.zip" # 包含竟对信号 TIF、GIS.qgz、BuildingInfo.gpkg 和 CellData.gpkg。 -LEGACY_SUMMARY_OUTPUT_FILENAME = "所有网格汇总.zip" # 旧汇总包文件名;新包成功生成后自动清理。 -SUMMARY_MARKET_CODE = "全量网格图层" # 汇总任务在日志和 summary.json 中使用的标识。 -SUMMARY_MAX_RASTER_PIXELS = 100_000_000 # 汇总 TIF 最大像元数;提高该值可增强清晰度,但会增加内存、耗时和文件体积。 -EXCELLENT_PERCENT_STEPS = (0.1, 0.4, 0.7) # 按最终有效像元降序分档:前 10% 红,其余三档各约 30%。 -EXCELLENT_COLORS = ( - (255, 0, 0), # 高值端,红色。 - (255, 255, 0), # 偏高值,黄色。 - (0, 112, 255), # 偏低值,蓝色。 - (0, 176, 80), # 低值端,绿色。 -) -PIXEL_WIDTH = None # 输出像元宽度;None 表示自动按 Grid 单元宽度估算。 -PIXEL_HEIGHT = None # 输出像元高度;None 表示自动按 Grid 单元高度估算。 -SCALE = 5.0 # 分辨率倍数;2.0 表示像元宽高减半,放大查看更清晰。 -SAMPLE_SIZE = 10000 # 自动估算像元大小时抽样读取的 Grid 要素数量。 -LIMIT = None # 限制处理前 N 个市场网格;None 表示处理全部市场网格。 -MAX_WORKERS = 4 # 市场网格并行处理进程数;当前 4 核/32GB 环境实测 4 进程吞吐最佳,内存较小时可降为 2。 -GEOMETRY_BATCH_SIZE = 10000 # Shapely 批量解析和空间判断的每批要素数;增大可减少循环,过大会增加瞬时内存。 -MAX_RASTER_PIXELS = 25_000_000 # 单张 TIF 最大像元数;超限时自动降低该市场分辨率,避免内存溢出。 -CLIP_MODE = "intersects" # 裁切方式:intersects 按几何相交裁切,center 按 Grid 中心点落入裁切。 -BUILDING_ALLOWED_SRS_IDS = (4326, 100000) # Building 允许的经纬度坐标系 ID;100000 是 CRS84。 -BUILDING_INFO_ALLOWED_SRS_IDS = (4326, 100000) # BuildingInfo 允许的经纬度坐标系 ID;100000 是源文件中的 CRS84。 -OVERWRITE = True # 输出文件已存在时是否覆盖。 -TRANSPARENT_PIXEL = (0, 0, 0, 0) # 无数据/背景像元颜色,RGBA 中 alpha=0 表示透明。 - - -@dataclass(frozen=True) -class LayerInfo: - table_name: str - geom_col: str - pk_col: str - srs_id: int - - -@dataclass(frozen=True) -class MarketFeature: - fid: int - code: str - name: str - geometry: object - - -def quote_identifier(name): - return '"' + str(name).replace('"', '""') + '"' - - -def safe_filename(value): - text = str(value or "").strip() - text = re.sub(r'[<>:"/\\|?*\s]+', "_", text) - text = text.strip("._") - return text or "unnamed" - - -def market_output_dir(output_dir, market): - return output_dir / safe_filename(market.code) - - -def market_zip_output_path(output_dir, market): - return output_dir / f"{safe_filename(market.code)}.zip" - - -def build_summary_market(markets): - if not markets: - raise ValueError("至少需要一个市场网格才能生成汇总 TIF") - geometries = np.asarray([market.geometry for market in markets], dtype=object) - geometry = shapely.union_all(shapely.make_valid(geometries)) - if geometry.is_empty: - raise ValueError("市场网格合并结果为空,无法生成汇总 TIF") - return MarketFeature(0, SUMMARY_MARKET_CODE, SUMMARY_MARKET_CODE, geometry) - - -def excellent_heatmap_raster_filename(_field): - return USER_COUNT_OUTPUT_FILENAME - - -def competitor_signal_raster_filename(): - return COMPETITOR_SIGNAL_OUTPUT_FILENAME - - -def set_xml_extent(extent_element, extent): - for tag, value in zip(("xmin", "ymin", "xmax", "ymax"), extent): - child = extent_element.find(tag) - if child is None: - child = ET.SubElement(extent_element, tag) - child.text = format(float(value), ".17g") - - -def padded_extent(extent, padding_ratio): - minx, miny, maxx, maxy = (float(value) for value in extent) - width = maxx - minx - height = maxy - miny - padding_x = width * padding_ratio if width > 0 else (1e-6 if padding_ratio > 0 else 0.0) - padding_y = height * padding_ratio if height > 0 else (1e-6 if padding_ratio > 0 else 0.0) - return minx - padding_x, miny - padding_y, maxx + padding_x, maxy + padding_y - - -def serialize_qgis_project(root, original_data): - bom = b"\xef\xbb\xbf" if original_data.startswith(b"\xef\xbb\xbf") else b"" - payload = original_data[len(bom):] - first_line = payload.splitlines()[0] if payload else b"" - doctype = first_line if first_line.startswith(b"> 1) & 0b111 - envelope_sizes = { - 0: 0, - 1: 32, - 2: 48, - 3: 48, - 4: 64, - } - return data[8 + envelope_sizes.get(envelope_code, 0):] - - -def iter_geometry_batches(cursor, geom_index): - while True: - rows = cursor.fetchmany(GEOMETRY_BATCH_SIZE) - if not rows: - return - - wkbs = np.empty(len(rows), dtype=object) - for index, row in enumerate(rows): - geom_blob = row[geom_index] - wkbs[index] = gpkg_blob_to_wkb(geom_blob) if geom_blob is not None else None - geometries = from_wkb(wkbs, on_invalid="ignore") - valid_mask = ~shapely.is_missing(geometries) & ~shapely.is_empty(geometries) - yield rows, geometries, valid_mask - - -def gpkg_primary_key(conn, table_name): - for row in conn.execute(f"pragma table_info({quote_identifier(table_name)})"): - if row[5]: - return row[1] - return "fid" - - -def resolve_feature_layer(conn, preferred_table=None): - rows = conn.execute( - """ - select c.table_name, g.column_name, g.srs_id - from gpkg_contents c - join gpkg_geometry_columns g on c.table_name = g.table_name - where c.data_type = 'features' - order by c.table_name - """ - ).fetchall() - if not rows: - raise ValueError("未找到 GeoPackage feature 图层") - - if preferred_table: - for table_name, geom_col, srs_id in rows: - if table_name == preferred_table: - return LayerInfo(table_name, geom_col, gpkg_primary_key(conn, table_name), srs_id) - raise ValueError(f"未找到指定图层:{preferred_table}") - - table_name, geom_col, srs_id = rows[0] - return LayerInfo(table_name, geom_col, gpkg_primary_key(conn, table_name), srs_id) - - -def table_columns(conn, table_name): - return [row[1] for row in conn.execute(f"pragma table_info({quote_identifier(table_name)})")] - - -def require_columns(conn, table_name, columns): - available = set(table_columns(conn, table_name)) - missing = [column for column in columns if column not in available] - if missing: - raise ValueError(f"{table_name} 缺少字段:{', '.join(missing)}") - - -def rtree_name(conn, layer): - candidate = f"rtree_{layer.table_name}_{layer.geom_col}" - found = conn.execute( - "select 1 from sqlite_master where type='table' and name=?", - (candidate,), - ).fetchone() - if not found: - raise ValueError(f"未找到 RTree 空间索引:{candidate}") - return candidate - - -def table_exists(conn, table_name): - return conn.execute( - "select 1 from sqlite_master where type = 'table' and name = ?", - (table_name,), - ).fetchone() is not None - - -def sqlite_create_sql(conn, table_name): - row = conn.execute( - "select sql from sqlite_master where type = 'table' and name = ?", - (table_name,), - ).fetchone() - if not row or not row[0]: - raise ValueError(f"未找到表结构:{table_name}") - return row[0] - - -def copy_all_rows(source_conn, target_conn, table_name): - if not table_exists(source_conn, table_name): - return - - rows = source_conn.execute(f"select * from {quote_identifier(table_name)}").fetchall() - if not rows: - return - - placeholders = ", ".join(["?"] * len(rows[0])) - target_conn.executemany( - f"insert into {quote_identifier(table_name)} values ({placeholders})", - rows, - ) - - -def create_table_like_source(source_conn, target_conn, table_name): - if table_exists(source_conn, table_name): - target_conn.execute(sqlite_create_sql(source_conn, table_name)) - - -def copy_matching_rows(target_conn, table_name, columns, rows): - if not rows: - return - - column_sql = ", ".join(quote_identifier(column) for column in columns) - placeholders = ", ".join(["?"] * len(columns)) - target_conn.executemany( - f"insert into {quote_identifier(table_name)} ({column_sql}) values ({placeholders})", - rows, - ) - - -def copy_gpkg_support_tables(source_conn, target_conn, layer, feature_count, extent): - support_tables = [ - "gpkg_spatial_ref_sys", - "gpkg_contents", - "gpkg_geometry_columns", - "gpkg_ogr_contents", - "gpkg_extensions", - "gpkg_metadata", - "gpkg_metadata_reference", - "gpkg_tile_matrix_set", - "gpkg_tile_matrix", - "layer_styles", - ] - - for table_name in support_tables: - create_table_like_source(source_conn, target_conn, table_name) - - for table_name in support_tables: - copy_all_rows(source_conn, target_conn, table_name) - - minx, miny, maxx, maxy = extent if extent else (None, None, None, None) - target_conn.execute( - """ - update gpkg_contents - set min_x = ?, min_y = ?, max_x = ?, max_y = ? - where table_name = ? - """, - (minx, miny, maxx, maxy, layer.table_name), - ) - if table_exists(target_conn, "gpkg_ogr_contents"): - target_conn.execute( - "update gpkg_ogr_contents set feature_count = ? where table_name = ?", - (feature_count, layer.table_name), - ) - - -def initialize_split_output_gpkg(source_conn, output_path, layer, rtree, feature_count, extent): - if output_path.exists(): - if not OVERWRITE: - return None - output_path.unlink() - - target_conn = sqlite3.connect(output_path) - target_conn.execute("pragma foreign_keys = off") - target_conn.execute(f"pragma application_id = {source_conn.execute('pragma application_id').fetchone()[0]}") - target_conn.execute(f"pragma user_version = {source_conn.execute('pragma user_version').fetchone()[0]}") - copy_gpkg_support_tables(source_conn, target_conn, layer, feature_count, extent) - target_conn.execute(sqlite_create_sql(source_conn, layer.table_name)) - target_conn.execute(sqlite_create_sql(source_conn, rtree)) - return target_conn - - -def collect_intersecting_features(source_conn, layer, rtree, market): - table = quote_identifier(layer.table_name) - pk = quote_identifier(layer.pk_col) - rtree_table = quote_identifier(rtree) - columns = table_columns(source_conn, layer.table_name) - column_sql = ", ".join(f"b.{quote_identifier(column)}" for column in columns) - min_market_x, min_market_y, max_market_x, max_market_y = market.geometry.bounds - query = f""" - select {column_sql} - from {rtree_table} r - join {table} b on b.{pk} = r."id" - where r."minx" <= ? - and r."maxx" >= ? - and r."miny" <= ? - and r."maxy" >= ? - """ - - geom_index = columns.index(layer.geom_col) - pk_index = columns.index(layer.pk_col) - rows = [] - rtree_rows = [] - extent = None - candidates = 0 - - cursor = source_conn.execute(query, (max_market_x, min_market_x, max_market_y, min_market_y)) - for batch_rows, geometries, valid_mask in iter_geometry_batches(cursor, geom_index): - candidates += len(batch_rows) - intersects_mask = valid_mask & shapely.intersects(market.geometry, geometries) - matched_indexes = np.flatnonzero(intersects_mask) - if matched_indexes.size == 0: - continue - matched_bounds = shapely.bounds(geometries[matched_indexes]) - for index, bounds in zip(matched_indexes, matched_bounds): - row = batch_rows[int(index)] - minx, miny, maxx, maxy = bounds.tolist() - rows.append(row) - rtree_rows.append((row[pk_index], minx, maxx, miny, maxy)) - if extent is None: - extent = [minx, miny, maxx, maxy] - else: - extent[0] = min(extent[0], minx) - extent[1] = min(extent[1], miny) - extent[2] = max(extent[2], maxx) - extent[3] = max(extent[3], maxy) - - return columns, rows, rtree_rows, tuple(extent) if extent else None, candidates - - -def export_market_building_info_gpkg(source_conn, layer, rtree, market, output_path): - columns, rows, rtree_rows, extent, candidates = collect_intersecting_features( - source_conn, - layer, - rtree, - market, - ) - target_conn = initialize_split_output_gpkg(source_conn, output_path, layer, rtree, len(rows), extent) - if target_conn is None: - return { - "market_code": market.code, - "market_name": market.name, - "output": str(output_path), - "candidates": candidates, - "feature_count": None, - "extent": list(extent) if extent else None, - "skipped": True, - } - - try: - copy_matching_rows(target_conn, layer.table_name, columns, rows) - if rtree_rows: - target_conn.executemany( - f"insert into {quote_identifier(rtree)} values (?, ?, ?, ?, ?)", - rtree_rows, - ) - target_conn.commit() - finally: - target_conn.close() - - return { - "market_code": market.code, - "market_name": market.name, - "output": str(output_path), - "candidates": candidates, - "feature_count": len(rows), - "extent": list(extent) if extent else None, - "skipped": False, - } - - -def export_market_aoi_gpkg(source_conn, layer, rtree, market, output_path): - require_columns(source_conn, layer.table_name, [AOI_MARKET_FIELD, "AOI唯一标签", "AOI名称"]) - if layer.srs_id != 4326: - raise ValueError("AOI 图层必须使用 EPSG:4326") - table = quote_identifier(layer.table_name) - owner = quote_identifier(AOI_MARKET_FIELD) - pk = quote_identifier(layer.pk_col) - columns = table_columns(source_conn, layer.table_name) - rows = source_conn.execute(f"select * from {table} where {owner} = ? order by {pk}", (market.name,)).fetchall() - rtree_rows = source_conn.execute( - f"select r.* from {quote_identifier(rtree)} r join {table} a on a.{pk} = r.id " - f"where a.{owner} = ? order by r.id", (market.name,), - ).fetchall() - extent = None - if rtree_rows: - extent = (min(row[1] for row in rtree_rows), min(row[3] for row in rtree_rows), - max(row[2] for row in rtree_rows), max(row[4] for row in rtree_rows)) - srs_wkt = source_conn.execute("select definition from gpkg_spatial_ref_sys where srs_id = ?", (layer.srs_id,)).fetchone()[0] - result = { - "market_code": market.code, "market_name": market.name, "output": str(output_path), - "layer_name": layer.table_name, "feature_count": len(rows), "extent": list(extent) if extent else None, - "srs_wkt": srs_wkt, "match_field": AOI_MARKET_FIELD, "match_value": market.name, - } - target_conn = initialize_split_output_gpkg(source_conn, output_path, layer, rtree, len(rows), extent) - if target_conn is None: - return {**result, "skipped": True} - try: - copy_matching_rows(target_conn, layer.table_name, columns, rows) - target_conn.executemany(f"insert into {quote_identifier(rtree)} values (?, ?, ?, ?, ?)", rtree_rows) - target_conn.commit() - finally: - target_conn.close() - return {**result, "bytes": output_path.stat().st_size, "skipped": False} - - -def csv_text(value): - if value is None: - return "" - return str(value).strip() - - -def signal_level(value): - number = to_float(value) - if number is None: - return "无采集信息" - if number <= SIGNAL_BAD_THRESHOLD: - return "较差" - if number <= SIGNAL_NORMAL_THRESHOLD: - return "一般" - return "正常" - - -def collect_intersecting_metric_features(source_conn, layer, rtree, market, fields): - require_columns(source_conn, layer.table_name, fields) - table = quote_identifier(layer.table_name) - pk = quote_identifier(layer.pk_col) - geom = quote_identifier(layer.geom_col) - rtree_table = quote_identifier(rtree) - field_sql = ", ".join(f"b.{quote_identifier(field)}" for field in fields) - min_market_x, min_market_y, max_market_x, max_market_y = market.geometry.bounds - query = f""" - select b.{pk}, b.{geom}, {field_sql} - from {rtree_table} r - join {table} b on b.{pk} = r."id" - where r."minx" <= ? - and r."maxx" >= ? - and r."miny" <= ? - and r."maxy" >= ? - """ - - rows = [] - candidates = 0 - cursor = source_conn.execute(query, (max_market_x, min_market_x, max_market_y, min_market_y)) - for batch_rows, geometries, valid_mask in iter_geometry_batches(cursor, 1): - candidates += len(batch_rows) - intersects_mask = valid_mask & shapely.intersects(market.geometry, geometries) - for index in np.flatnonzero(intersects_mask): - row = batch_rows[int(index)] - rows.append((dict(zip(fields, row[2:])), geometries[index])) - - return rows, candidates - - -def load_building_name_index(building_info_conn, layer, rtree, bounds): - geometries = [] - names = [] - if bounds is None: - return None - table = quote_identifier(layer.table_name) - geom = quote_identifier(layer.geom_col) - pk = quote_identifier(layer.pk_col) - rtree_table = quote_identifier(rtree) - minx, miny, maxx, maxy = bounds - query = f""" - select b."name", b.{geom} - from {rtree_table} r - join {table} b on b.{pk} = r."id" - where r."minx" <= ? - and r."maxx" >= ? - and r."miny" <= ? - and r."maxy" >= ? - order by b.{pk} - """ - cursor = building_info_conn.execute(query, (maxx, minx, maxy, miny)) - for batch_rows, batch_geometries, valid_mask in iter_geometry_batches(cursor, 1): - for index in np.flatnonzero(valid_mask): - name = csv_text(batch_rows[int(index)][0]) - if not name: - continue - geometries.append(batch_geometries[index]) - names.append(name) - if not geometries: - return None - return STRtree(geometries), geometries, names - - -def match_building_info_name(name_index, geometry): - if name_index is None: - return "" - tree, geometries, names = name_index - best_name = "" - best_score = -1.0 - for candidate_index in tree.query(geometry, predicate="intersects"): - index = int(candidate_index) - info_geometry = geometries[index] - try: - score = geometry.intersection(info_geometry).area - except GEOSException: - score = 0.0 - if score > best_score: - best_name = names[index] - best_score = score - - return best_name - - -def match_building_info_names(name_index, building_geometries): - if name_index is None or not building_geometries: - return [""] * len(building_geometries) - - tree, info_geometries, names = name_index - building_array = np.asarray(building_geometries, dtype=object) - info_array = np.asarray(info_geometries, dtype=object) - pairs = tree.query(building_array, predicate="intersects") - if pairs.shape[1] == 0: - return [""] * len(building_geometries) - - result = np.full(len(building_geometries), "", dtype=object) - names_array = np.asarray(names, dtype=object) - match_counts = np.bincount(pairs[0], minlength=len(building_geometries)) - single_pair_mask = match_counts[pairs[0]] == 1 - single_pairs = pairs[:, single_pair_mask] - result[single_pairs[0]] = names_array[single_pairs[1]] - - multiple_pairs = pairs[:, ~single_pair_mask] - if multiple_pairs.shape[1]: - try: - areas = shapely.area( - shapely.intersection( - building_array[multiple_pairs[0]], - info_array[multiple_pairs[1]], - ) - ) - except GEOSException: - return [match_building_info_name(name_index, geometry) for geometry in building_geometries] - - pair_positions = np.arange(multiple_pairs.shape[1]) - order = np.lexsort((pair_positions, -areas, multiple_pairs[0])) - ordered_sources = multiple_pairs[0][order] - _, first_positions = np.unique(ordered_sources, return_index=True) - best_pair_positions = order[first_positions] - result[multiple_pairs[0, best_pair_positions]] = names_array[multiple_pairs[1, best_pair_positions]] - - return result.tolist() - - -def write_metric_csv(output_path, headers, rows): - if output_path.exists() and not OVERWRITE: - return True - with output_path.open("w", newline="", encoding=CSV_ENCODING, errors="replace") as file: - writer = csv.writer(file) - writer.writerow(headers) - writer.writerows(rows) - return False - - -def metric_row(values): - return [ - csv_text(values.get("area_type")), - csv_text(values.get("area_name")), - csv_text(values.get("longitude")), - csv_text(values.get("latitude")), - csv_text(values.get("mro_total_dl")), - csv_text(values.get("rsrp_lt_neg105_dl")), - csv_text(values.get("ssb_rsrp_dl")), - signal_level(values.get("ssb_rsrp_yd")), - signal_level(values.get("ssb_rsrp_dl")), - ] - - -def export_market_building_metrics_csv( - building_conn, - building_layer, - building_rtree, - building_info_conn, - building_info_layer, - building_info_rtree, - market, - output_path, -): - rows, candidates = collect_intersecting_metric_features( - building_conn, - building_layer, - building_rtree, - market, - CSV_SOURCE_FIELDS, - ) - building_geometries = [geometry for _values, geometry in rows] - building_bounds = shapely.total_bounds(building_geometries) if building_geometries else None - building_name_index = load_building_name_index( - building_info_conn, - building_info_layer, - building_info_rtree, - building_bounds, - ) - headers = [ - "网格ID", - "区域类型", - "区域名称", - "建筑名称", - "经度", - "纬度", - "竟对采样点总", - "竟对弱覆盖采样点", - "竟对平均信号值", - "移动信号", - "竟对信号", - ] - csv_rows = [] - matched_names = 0 - building_names = match_building_info_names(building_name_index, building_geometries) - for (values, _geometry), building_name in zip(rows, building_names): - if building_name: - matched_names += 1 - common_row = metric_row(values) - csv_rows.append([market.code, common_row[0], common_row[1], building_name, *common_row[2:]]) - - skipped = write_metric_csv(output_path, headers, csv_rows) - return { - "market_code": market.code, - "market_name": market.name, - "output": str(output_path), - "candidates": candidates, - "row_count": len(csv_rows), - "matched_names": matched_names, - "skipped": skipped, - } - - -def load_market_features(conn, layer, code_field, name_field): - require_columns(conn, layer.table_name, [code_field, name_field]) - table = quote_identifier(layer.table_name) - pk = quote_identifier(layer.pk_col) - geom = quote_identifier(layer.geom_col) - code = quote_identifier(code_field) - name = quote_identifier(name_field) - query = f"select {pk}, {code}, {name}, {geom} from {table} order by {pk}" - - features = [] - for fid, market_code, market_name, geom_blob in conn.execute(query): - if geom_blob is None: - continue - try: - geometry = from_wkb(gpkg_blob_to_wkb(geom_blob)) - except (GEOSException, ValueError): - continue - if not geometry.is_empty: - name = str(market_name or fid).strip() - code_prefix = str(market_code or fid).strip() - market_code_text = f"{code_prefix}{MARKET_ID_SEPARATOR}{name}" if name else code_prefix - features.append(MarketFeature(fid, market_code_text, name, geometry)) - return features - - -def estimate_pixel_size(conn, layer, sample_size): - table = quote_identifier(layer.table_name) - geom = quote_identifier(layer.geom_col) - widths = [] - heights = [] - query = f"select {geom} from {table} where {geom} is not null limit ?" - for (geom_blob,) in conn.execute(query, (sample_size,)): - try: - geometry = from_wkb(gpkg_blob_to_wkb(geom_blob)) - except (GEOSException, ValueError): - continue - minx, miny, maxx, maxy = geometry.bounds - width = maxx - minx - height = maxy - miny - if width > 0 and height > 0: - widths.append(width) - heights.append(height) - - if not widths or not heights: - raise ValueError("无法从 Grid 图层估算像元大小") - - return float(np.median(widths)), float(np.median(heights)) - - -def percentile_thresholds_from_values(values, percent_steps): - sorted_values = np.sort(np.asarray(values, dtype=np.float32))[::-1] - sorted_values = sorted_values[np.isfinite(sorted_values)] - if sorted_values.size == 0: - return [] - - thresholds = [] - for percent in percent_steps: - index = max(0, math.ceil(sorted_values.size * percent)) - index = min(index, sorted_values.size - 1) - thresholds.append(float(sorted_values[index])) - return thresholds - - -def ranked_pixel_rgb_for_values(values, data_mask, colors, percent_steps): - result = np.zeros((*values.shape, 3), dtype=np.uint8) - valid_positions = np.flatnonzero(data_mask.ravel()) - if valid_positions.size == 0: - return result, [], [] - if len(percent_steps) != len(colors) - 1: - raise ValueError("颜色数量必须比分位阈值数量多 1") - - valid_values = values.ravel()[valid_positions] - thresholds = percentile_thresholds_from_values(valid_values, percent_steps) - flat_result = result.reshape(-1, 3) - remaining = np.ones(valid_values.shape, dtype=bool) - rank_counts = [] - for color, threshold in zip(colors[:-1], thresholds): - selected = remaining & (valid_values > threshold) - flat_result[valid_positions[selected]] = color - rank_counts.append(int(np.count_nonzero(selected))) - remaining &= ~selected - flat_result[valid_positions[remaining]] = colors[-1] - rank_counts.append(int(np.count_nonzero(remaining))) - - return result, thresholds, rank_counts - - -def ranked_pixel_rgb_for_values_with_thresholds(values, data_mask, colors, thresholds): - result = np.zeros((*values.shape, 3), dtype=np.uint8) - valid_positions = np.flatnonzero(data_mask.ravel()) - if valid_positions.size == 0: - return result, [] - if len(thresholds) != len(colors) - 1: - raise ValueError("颜色数量必须比分位阈值数量多 1") - - valid_values = values.ravel()[valid_positions] - flat_result = result.reshape(-1, 3) - remaining = np.ones(valid_values.shape, dtype=bool) - rank_counts = [] - for color, threshold in zip(colors[:-1], thresholds): - selected = remaining & (valid_values > threshold) - flat_result[valid_positions[selected]] = color - rank_counts.append(int(np.count_nonzero(selected))) - remaining &= ~selected - flat_result[valid_positions[remaining]] = colors[-1] - rank_counts.append(int(np.count_nonzero(remaining))) - return result, rank_counts - - -def smooth_rgb_inside_mask(rgb, data_mask, radius): - if radius <= 0: - return rgb - - weight = data_mask.astype(np.float32) - blurred_weight = gaussian_blur(weight, radius) - smoothed = np.zeros_like(rgb, dtype=np.float32) - for channel in range(3): - blurred_channel = gaussian_blur(rgb[..., channel].astype(np.float32) * weight, radius) - np.divide(blurred_channel, blurred_weight, out=smoothed[..., channel], where=blurred_weight > 0) - smoothed[~data_mask] = 0 - return np.clip(smoothed, 0, 255).astype(np.uint8) - - -def gaussian_kernel(radius): - if radius <= 0: - return np.array([1.0], dtype=np.float32) - sigma = max(radius / 2.0, 0.1) - x = np.arange(-radius, radius + 1, dtype=np.float32) - kernel = np.exp(-(x * x) / (2.0 * sigma * sigma)) - return kernel / kernel.sum() - - -def validate_smoothing_radius(name, radius): - if isinstance(radius, bool) or not isinstance(radius, int) or radius < 0: - raise ValueError(f"{name} 必须是非负整数") - - -def convolve_axis(array, kernel, axis): - if kernel.size == 1: - return array - radius = kernel.size // 2 - pad_width = [(0, 0)] * array.ndim - pad_width[axis] = (radius, radius) - padded = np.pad(array, pad_width, mode="edge") - windows = np.lib.stride_tricks.sliding_window_view(padded, kernel.size, axis=axis) - return (windows @ kernel).astype(np.float32, copy=False) - - -def gaussian_blur(array, radius): - kernel = gaussian_kernel(radius) - blurred = convolve_axis(array.astype(np.float32), kernel, axis=0) - return convolve_axis(blurred, kernel, axis=1) - - -def to_float(value): - if value is None: - return None - if isinstance(value, (int, float)): - number = float(value) - return number if math.isfinite(number) else None - try: - text = str(value).strip() - if not text: - return None - number = float(text) - if not math.isfinite(number): - return None - return number - except ValueError: - return None - - -def competitor_signal_filter_reason(mobile_weak, mobile_total, competitor_weak, competitor_total): - if mobile_weak is None or mobile_total is None or competitor_total is None: - return "invalid_fields" - if mobile_total <= 0 or mobile_weak < 0 or competitor_total < 0: - return "invalid_fields" - mobile_weak_ratio = mobile_weak / mobile_total * 100.0 - if mobile_weak_ratio >= COMPETITOR_SIGNAL_MOBILE_WEAK_RATIO_MAX: - return "mobile_weak_ratio" - if competitor_total == 0: - return None - if competitor_weak is None or competitor_weak < 0: - return "invalid_fields" - competitor_weak_ratio = competitor_weak / competitor_total * 100.0 - if competitor_weak_ratio <= COMPETITOR_SIGNAL_WEAK_RATIO_MIN: - return "competitor_weak_ratio" - return None - - -def competitor_signal_is_eligible(mobile_weak, mobile_total, competitor_weak, competitor_total): - return competitor_signal_filter_reason(mobile_weak, mobile_total, competitor_weak, competitor_total) is None - - -def competitor_signal_rsrp_rgb_for_values(values): - values = np.asarray(values, dtype=np.float32) - colors = np.zeros((*values.shape, 3), dtype=np.uint8) - valid_mask = np.isfinite(values) & (values <= 0) - if np.any(valid_mask): - color_indices = np.searchsorted( - np.asarray(COMPETITOR_SIGNAL_RSRP_BREAKS, dtype=np.float32), - values[valid_mask], - side="right", - ) - colors[valid_mask] = np.asarray(COMPETITOR_SIGNAL_RSRP_COLORS, dtype=np.uint8)[color_indices] - return colors, valid_mask - - -def geotiff_extratags(minx, maxy, pixel_width, pixel_height): - model_pixel_scale = (pixel_width, pixel_height, 0.0) - model_tiepoint = (0.0, 0.0, 0.0, minx, maxy, 0.0) - geo_key_directory = ( - 1, 1, 0, 4, - 1024, 0, 1, 2, - 1025, 0, 1, 1, - 2048, 0, 1, 4326, - 2054, 0, 1, 9102, - ) - return [ - (33550, "d", 3, model_pixel_scale, False), - (33922, "d", 6, model_tiepoint, False), - (34735, "H", len(geo_key_directory), geo_key_directory, False), - ] - - -def write_rgba_geotiff(path, image, minx, maxy, pixel_width, pixel_height): - tifffile.imwrite( - path, - image, - photometric="rgb", - extrasamples=["unassalpha"], - metadata=None, - extratags=geotiff_extratags(minx, maxy, pixel_width, pixel_height), - ) - - -def pixel_window_for_bounds(bounds, minx, maxy, pixel_width, pixel_height, width, height): - geom_minx, geom_miny, geom_maxx, geom_maxy = bounds - col_start = max(0, int(math.floor((geom_minx - minx) / pixel_width))) - col_stop = min(width, int(math.ceil((geom_maxx - minx) / pixel_width))) - row_start = max(0, int(math.floor((maxy - geom_maxy) / pixel_height))) - row_stop = min(height, int(math.ceil((maxy - geom_miny) / pixel_height))) - if row_start >= row_stop or col_start >= col_stop: - return None - return row_start, row_stop, col_start, col_stop - - -def pixel_center_mask_for_geometry(geometry, window, minx, maxy, pixel_width, pixel_height): - row_start, row_stop, col_start, col_stop = window - x_coordinates = minx + (np.arange(col_start, col_stop, dtype=np.float64) + 0.5) * pixel_width - y_coordinates = maxy - (np.arange(row_start, row_stop, dtype=np.float64) + 0.5) * pixel_height - x_grid, y_grid = np.meshgrid(x_coordinates, y_coordinates) - return np.asarray(shapely.contains_xy(geometry, x_grid, y_grid), dtype=bool) - - -def pixel_window_from_point(x, y, minx, maxy, pixel_width, pixel_height, width, height): - col = int((x - minx) / pixel_width) - row = int((maxy - y) / pixel_height) - if 0 <= row < height and 0 <= col < width: - return row, row + 1, col, col + 1 - return None - - -def grid_metrics_headers(): - return [ - "网格ID", - "区域类型", - "区域名称", - "经度", - "纬度", - "竟对采样点总", - "竟对弱覆盖采样点", - "竟对平均信号值", - "移动信号", - "竟对信号", - ] - - -def market_raster_layout(bounds, pixel_width, pixel_height, max_raster_pixels=None): - minx, miny, maxx, maxy = bounds - width = max(1, int(math.ceil((maxx - minx) / pixel_width))) - height = max(1, int(math.ceil((maxy - miny) / pixel_height))) - scale_factor = 1.0 - pixel_limit = MAX_RASTER_PIXELS if max_raster_pixels is None else max_raster_pixels - if pixel_limit and width * height > pixel_limit: - scale_factor = math.sqrt((width * height) / pixel_limit) - pixel_width *= scale_factor - pixel_height *= scale_factor - width = max(1, int(math.ceil((maxx - minx) / pixel_width))) - height = max(1, int(math.ceil((maxy - miny) / pixel_height))) - while width * height > pixel_limit: - scale_factor *= 1.001 - pixel_width *= 1.001 - pixel_height *= 1.001 - width = max(1, int(math.ceil((maxx - minx) / pixel_width))) - height = max(1, int(math.ceil((maxy - miny) / pixel_height))) - return minx, miny, maxx, maxy, pixel_width, pixel_height, width, height, scale_factor - - -def replace_file_with_retry(source_path, target_path, attempts=20, delay_seconds=0.5): - for attempt in range(attempts): - try: - source_path.replace(target_path) - return - except PermissionError: - if attempt == attempts - 1: - raise - sleep(delay_seconds) - - -def remove_file_with_retry(path, attempts=20, delay_seconds=0.5): - for attempt in range(attempts): - try: - path.unlink(missing_ok=True) - return - except PermissionError: - if attempt == attempts - 1: - raise - sleep(delay_seconds) - - -def copy_full_source_file(source_path, output_path, market): - if output_path.exists() and not OVERWRITE: - return { - "market_code": market.code, - "market_name": market.name, - "source": str(source_path), - "output": str(output_path), - "skipped": True, - } - shutil.copy2(source_path, output_path) - return { - "market_code": market.code, - "market_name": market.name, - "source": str(source_path), - "output": str(output_path), - "bytes": output_path.stat().st_size, - "copied_full_source": True, - "skipped": False, - } - - -def render_ranked_raster( - state, - market, - output_path, - minx, - maxy, - pixel_width, - pixel_height, - width, - height, - candidates, - colors, - percent_steps, -): - image = np.full((height, width, 4), TRANSPARENT_PIXEL, dtype=np.uint8) - value_sum = state["value_sum"] - value_weight = state["value_weight"] - data_mask = value_weight > 0 - thresholds = [] - rank_pixel_counts = [] - if np.any(data_mask): - value_raster = np.zeros_like(value_sum) - np.divide(value_sum, value_weight, out=value_raster, where=data_mask) - ranked_rgb, thresholds, rank_pixel_counts = ranked_pixel_rgb_for_values( - value_raster, - data_mask, - colors, - percent_steps, - ) - smoothed_rgb = smooth_rgb_inside_mask(ranked_rgb, data_mask, HEATMAP_SMOOTH_RADIUS) - image[data_mask, :3] = smoothed_rgb[data_mask] - image[data_mask, 3] = HEATMAP_ALPHA - - write_rgba_geotiff(output_path, image, minx, maxy, pixel_width, pixel_height) - return { - "market_code": market.code, - "market_name": market.name, - "output": str(output_path), - "candidates": candidates, - "painted_cells": state["painted_cells"], - "data_pixels": int(np.count_nonzero(data_mask)), - "skipped_no_value": state["skipped_no_value"], - "threshold_value_count": int(np.count_nonzero(data_mask)), - "thresholds": thresholds, - "rank_pixel_counts": rank_pixel_counts, - "percent_steps": list(percent_steps), - "width": width, - "height": height, - "skipped": False, - } - - -def normalized_grid_id(value): - if value is None: - return None - if isinstance(value, bytes): - value = value.decode("utf-8", errors="replace") - normalized = str(value).strip() - return normalized or None - - -def merge_user_count_record(records, grid_id, window, value, source_name, prefer_geometry=False): - grid_id = normalized_grid_id(grid_id) - if grid_id is None: - return False - record = records.get(grid_id) - if record is None: - record = { - "window": window, - "value_sum": 0.0, - "has_value": False, - "sources": set(), - } - records[grid_id] = record - elif prefer_geometry: - record["window"] = window - record["sources"].add(source_name) - if value is not None: - record["value_sum"] += value - record["has_value"] = True - return True - - -def collect_user_count_source( - records, - conn, - layer, - rtree, - market, - minx, - maxy, - pixel_width, - pixel_height, - width, - height, - source_name, - prefer_geometry=False, -): - fields = [GRID_ID_FIELD, EXCELLENT_CELL_FIELD] - if CLIP_MODE == "center": - fields.extend(("longitude", "latitude")) - require_columns(conn, layer.table_name, fields) - table = quote_identifier(layer.table_name) - pk = quote_identifier(layer.pk_col) - geom = quote_identifier(layer.geom_col) - rtree_table = quote_identifier(rtree) - field_sql = ", ".join(f"b.{quote_identifier(field)}" for field in fields) - query = f""" - select b.{pk}, b.{geom}, {field_sql} - from {rtree_table} r - join {table} b on b.{pk} = r."id" - where r."minx" <= ? - and r."maxx" >= ? - and r."miny" <= ? - and r."maxy" >= ? - """ - market_minx, market_miny, market_maxx, market_maxy = market.geometry.bounds - params = (market_maxx, market_minx, market_maxy, market_miny) - candidates = 0 - clipped_rows = 0 - invalid_grid_ids = 0 - try: - shapely.prepare(market.geometry) - cursor = conn.execute(query, params) - for batch_rows, geometries, valid_mask in iter_geometry_batches(cursor, 1): - candidates += len(batch_rows) - intersects_mask = valid_mask & shapely.intersects(market.geometry, geometries) - geometry_bounds = shapely.bounds(geometries) - for index, row in enumerate(batch_rows): - if not valid_mask[index]: - continue - values = dict(zip(fields, row[2:])) - if CLIP_MODE == "intersects": - if not bool(intersects_mask[index]): - continue - window = pixel_window_for_bounds( - geometry_bounds[index], - minx, - maxy, - pixel_width, - pixel_height, - width, - height, - ) - else: - lon = to_float(values.get("longitude")) - lat = to_float(values.get("latitude")) - if lon is None or lat is None or not market.geometry.covers(Point(lon, lat)): - continue - window = pixel_window_from_point( - lon, - lat, - minx, - maxy, - pixel_width, - pixel_height, - width, - height, - ) - if window is None: - continue - clipped_rows += 1 - if not merge_user_count_record( - records, - values.get(GRID_ID_FIELD), - window, - to_float(values.get(EXCELLENT_CELL_FIELD)), - source_name, - prefer_geometry, - ): - invalid_grid_ids += 1 - finally: - shapely.destroy_prepared(market.geometry) - return { - "candidates": candidates, - "clipped_rows": clipped_rows, - "invalid_grid_ids": invalid_grid_ids, - } - - -def build_merged_user_count_state(records, height, width, row_offset=0, col_offset=0): - value_sum = np.zeros((height, width), dtype=np.float32) - value_weight = np.zeros((height, width), dtype=np.uint16) - painted_cells = 0 - skipped_no_value = 0 - for record in records.values(): - if not record["has_value"]: - skipped_no_value += 1 - continue - row_start, row_stop, col_start, col_stop = record["window"] - row_start -= row_offset - row_stop -= row_offset - col_start -= col_offset - col_stop -= col_offset - value_sum[row_start:row_stop, col_start:col_stop] += record["value_sum"] - value_weight[row_start:row_stop, col_start:col_stop] += 1 - painted_cells += 1 - return { - "value_sum": value_sum, - "value_weight": value_weight, - "painted_cells": painted_cells, - "skipped_no_value": skipped_no_value, - } - - -def render_merged_user_count_records(records, canvas_height, canvas_width, thresholds=None): - valid_records = [record for record in records.values() if record["has_value"]] - if not valid_records: - empty_mask = np.zeros((0, 0), dtype=bool) - empty_rgb = np.zeros((0, 0, 3), dtype=np.uint8) - return { - "window": (0, 0, 0, 0), - "data_mask": empty_mask, - "rgb": empty_rgb, - "thresholds": [], - "rank_pixel_counts": [], - "painted_cells": 0, - "skipped_no_value": len(records), - } - - row_start = min(record["window"][0] for record in valid_records) - row_stop = max(record["window"][1] for record in valid_records) - col_start = min(record["window"][2] for record in valid_records) - col_stop = max(record["window"][3] for record in valid_records) - padding = HEATMAP_SMOOTH_RADIUS - row_start = max(0, row_start - padding) - row_stop = min(canvas_height, row_stop + padding) - col_start = max(0, col_start - padding) - col_stop = min(canvas_width, col_stop + padding) - - state = build_merged_user_count_state( - records, - row_stop - row_start, - col_stop - col_start, - row_offset=row_start, - col_offset=col_start, - ) - value_sum = state["value_sum"] - value_weight = state["value_weight"] - data_mask = value_weight > 0 - value_raster = np.zeros_like(value_sum) - np.divide(value_sum, value_weight, out=value_raster, where=data_mask) - if thresholds: - ranked_rgb, rank_pixel_counts = ranked_pixel_rgb_for_values_with_thresholds( - value_raster, - data_mask, - EXCELLENT_COLORS, - thresholds, - ) - applied_thresholds = [float(value) for value in thresholds] - else: - ranked_rgb, applied_thresholds, rank_pixel_counts = ranked_pixel_rgb_for_values( - value_raster, - data_mask, - EXCELLENT_COLORS, - EXCELLENT_PERCENT_STEPS, - ) - smoothed_rgb = smooth_rgb_inside_mask(ranked_rgb, data_mask, HEATMAP_SMOOTH_RADIUS) - return { - "window": (row_start, row_stop, col_start, col_stop), - "data_mask": data_mask, - "rgb": smoothed_rgb, - "thresholds": applied_thresholds, - "rank_pixel_counts": rank_pixel_counts, - "painted_cells": state["painted_cells"], - "skipped_no_value": state["skipped_no_value"], - } - - -def merged_user_count_metadata(records, source_stats): - shared_grids = 0 - five_g_only_grids = 0 - four_g_only_grids = 0 - for record in records.values(): - sources = record["sources"] - if sources == {"5G", "4G"}: - shared_grids += 1 - elif "5G" in sources: - five_g_only_grids += 1 - elif "4G" in sources: - four_g_only_grids += 1 - return { - "data_source_mode": "Grid_5G + Grid_4G sum by grid20_id", - "grid_id_field": GRID_ID_FIELD, - "value_field": EXCELLENT_CELL_FIELD, - "merge_rule": "union grid20_id; sum mro_total_dl for duplicate ids", - "merged_grid_count": len(records), - "shared_grid_count": shared_grids, - "five_g_only_grid_count": five_g_only_grids, - "four_g_only_grid_count": four_g_only_grids, - "source_stats": source_stats, - } - - -def render_summary_user_count_by_market( - grid_sources, - markets, - pixel_width, - pixel_height, - output_path, - max_raster_pixels, - market_thresholds=None, -): - summary_market = build_summary_market(markets) - minx, miny, maxx, maxy, pixel_width, pixel_height, width, height, scale_factor = market_raster_layout( - summary_market.geometry.bounds, - pixel_width, - pixel_height, - max_raster_pixels, - ) - image = np.full((height, width, 4), TRANSPARENT_PIXEL, dtype=np.uint8) - market_results = [] - total_candidates = 0 - total_painted_cells = 0 - total_skipped_no_value = 0 - for market in markets: - records = {} - source_stats = {} - for source_name, conn, layer, rtree in grid_sources: - source_stats[source_name] = collect_user_count_source( - records, - conn, - layer, - rtree, - market, - minx, - maxy, - pixel_width, - pixel_height, - width, - height, - source_name, - prefer_geometry=source_name == "5G", - ) - candidates = sum(stats["candidates"] for stats in source_stats.values()) - render_result = render_merged_user_count_records( - records, - height, - width, - (market_thresholds or {}).get(market.code), - ) - painted_cells = render_result["painted_cells"] - skipped_no_value = render_result["skipped_no_value"] - data_mask = render_result["data_mask"] - thresholds = render_result["thresholds"] - rank_pixel_counts = render_result["rank_pixel_counts"] - data_pixels = int(np.count_nonzero(data_mask)) - if data_pixels: - row_start, row_stop, col_start, col_stop = render_result["window"] - target = image[row_start:row_stop, col_start:col_stop] - target[data_mask, :3] = render_result["rgb"][data_mask] - target[data_mask, 3] = HEATMAP_ALPHA - - total_candidates += candidates - total_painted_cells += painted_cells - total_skipped_no_value += skipped_no_value - market_result = { - "market_code": market.code, - "market_name": market.name, - "candidates": candidates, - "painted_cells": painted_cells, - "data_pixels": data_pixels, - "skipped_no_value": skipped_no_value, - "thresholds": thresholds, - "threshold_source": "market_zip" if (market_thresholds or {}).get(market.code) else "summary_raster", - "rank_pixel_counts": rank_pixel_counts, - "render_window": list(render_result["window"]), - "render_buffer_pixels": int(data_mask.size), - } - market_result.update(merged_user_count_metadata(records, source_stats)) - market_results.append(market_result) - - write_rgba_geotiff(output_path, image, minx, maxy, pixel_width, pixel_height) - return { - "market_code": summary_market.code, - "market_name": summary_market.name, - "output": str(output_path), - "candidates": total_candidates, - "painted_cells": total_painted_cells, - "data_pixels": int(np.count_nonzero(image[..., 3])), - "skipped_no_value": total_skipped_no_value, - "threshold_value_count": int(np.count_nonzero(image[..., 3])), - "thresholds": None, - "rank_pixel_counts": None, - "percent_steps": list(EXCELLENT_PERCENT_STEPS), - "color_scope": "per_market", - "threshold_source": "market_zip", - "render_scope": "market_local_window", - "render_padding_pixels": HEATMAP_SMOOTH_RADIUS, - "market_results": market_results, - "width": width, - "height": height, - "raster_extent": [ - minx, - maxy - height * pixel_height, - minx + width * pixel_width, - maxy, - ], - "pixel_width": pixel_width, - "pixel_height": pixel_height, - "resolution_scale_factor": scale_factor, - "skipped": False, - } - - -def render_competitor_signal_raster( - state, - market, - output_path, - minx, - maxy, - pixel_width, - pixel_height, - width, - height, - candidates, -): - image = np.full((height, width, 4), TRANSPARENT_PIXEL, dtype=np.uint8) - value_sum = state["value_sum"] - value_weight = state["value_weight"] - rsrp_mask = value_weight > 0 - zero_total_mask = state["zero_total_mask"] - data_mask = rsrp_mask | zero_total_mask - class_pixel_counts = [0] * len(COMPETITOR_SIGNAL_RSRP_COLORS) - if np.any(rsrp_mask): - value_raster = np.zeros_like(value_sum) - np.divide(value_sum, value_weight, out=value_raster, where=rsrp_mask) - colors, valid_rsrp_mask = competitor_signal_rsrp_rgb_for_values(value_raster) - render_mask = rsrp_mask & valid_rsrp_mask - image[render_mask, :3] = colors[render_mask] - image[zero_total_mask, :3] = COMPETITOR_SIGNAL_RSRP_COLORS[0] - image[data_mask, 3] = HEATMAP_ALPHA - for index, color in enumerate(COMPETITOR_SIGNAL_RSRP_COLORS): - color_mask = data_mask & np.all(image[..., :3] == color, axis=-1) - class_pixel_counts[index] = int(np.count_nonzero(color_mask)) - - write_rgba_geotiff(output_path, image, minx, maxy, pixel_width, pixel_height) - return { - "market_code": market.code, - "market_name": market.name, - "output": str(output_path), - "candidates": candidates, - "painted_cells": state["painted_cells"], - "data_pixels": int(np.count_nonzero(image[..., 3])), - "skipped_no_value": state["skipped_no_value"], - "color_mode": "discrete_competitor_signal", - "rsrp_breaks": list(COMPETITOR_SIGNAL_RSRP_BREAKS), - "colors": [list(color) for color in COMPETITOR_SIGNAL_RSRP_COLORS], - "class_pixel_counts": class_pixel_counts, - "zero_total_pixels": int(np.count_nonzero(zero_total_mask)), - "smooth_radius": 0, - "width": width, - "height": height, - "skipped": False, - } - - -def export_market_grid_outputs( - grid_5g_conn, - grid_5g_layer, - grid_5g_rtree, - market, - pixel_width, - pixel_height, - # user_count_path, - competitor_signal_path, - csv_path, - # grid_4g_source=None, - max_raster_pixels=None, -): - minx, miny, maxx, maxy, pixel_width, pixel_height, width, height, scale_factor = market_raster_layout( - market.geometry.bounds, - pixel_width, - pixel_height, - max_raster_pixels, - ) - raster_fields = ( - EXCELLENT_CELL_FIELD, - RSRP_FIELD, - WEAK_COVER_FIELD, - MOBILE_TOTAL_FIELD, - MOBILE_WEAK_COVER_FIELD, - ) - # user_count_records = {} - competitor_signal_value_sum = np.zeros((height, width), dtype=np.float32) - competitor_signal_value_weight = np.zeros((height, width), dtype=np.uint16) - zero_total_mask = np.zeros((height, width), dtype=bool) - competitor_signal_cells = 0 - zero_total_cells = 0 - exact_geometry_pixels = 0 - exclusion_counts = { - "invalid_fields": 0, - "mobile_weak_ratio": 0, - "competitor_weak_ratio": 0, - "invalid_rsrp": 0, - "no_center_pixels": 0, - } - - # fields = list( - # dict.fromkeys( - # (*CSV_SOURCE_FIELDS, *raster_fields, GRID_ID_FIELD) - # if csv_path is not None - # else (*raster_fields, GRID_ID_FIELD) - # ) - # ) - fields = list(dict.fromkeys((*CSV_SOURCE_FIELDS, *raster_fields) if csv_path is not None else raster_fields)) - if csv_path is None and CLIP_MODE == "center": - fields.extend(field for field in ("longitude", "latitude") if field not in fields) - require_columns(grid_5g_conn, grid_5g_layer.table_name, fields) - table = quote_identifier(grid_5g_layer.table_name) - pk = quote_identifier(grid_5g_layer.pk_col) - geom = quote_identifier(grid_5g_layer.geom_col) - rtree_table = quote_identifier(grid_5g_rtree) - field_sql = ", ".join(f"b.{quote_identifier(field)}" for field in fields) - query = f""" - select b.{pk}, b.{geom}, {field_sql} - from {rtree_table} r - join {table} b on b.{pk} = r."id" - where r."minx" <= ? - and r."maxx" >= ? - and r."miny" <= ? - and r."maxy" >= ? - """ - params = (maxx, minx, maxy, miny) - candidates = 0 - # user_count_5g_clipped_rows = 0 - # user_count_5g_invalid_grid_ids = 0 - csv_rows = 0 - csv_skipped = csv_path is None or (csv_path.exists() and not OVERWRITE) - csv_file = None - csv_writer = None - if not csv_skipped: - csv_file = csv_path.open("w", newline="", encoding=CSV_ENCODING, errors="replace") - csv_writer = csv.writer(csv_file) - csv_writer.writerow(grid_metrics_headers()) - - try: - shapely.prepare(market.geometry) - cursor = grid_5g_conn.execute(query, params) - for batch_rows, geometries, valid_mask in iter_geometry_batches(cursor, 1): - candidates += len(batch_rows) - intersects_mask = valid_mask & shapely.intersects(market.geometry, geometries) - geometry_bounds = shapely.bounds(geometries) - for index, row in enumerate(batch_rows): - values = dict(zip(fields, row[2:])) - numeric_values = {field: to_float(values.get(field)) for field in raster_fields} - - if not valid_mask[index]: - continue - intersects_market = bool(intersects_mask[index]) - if intersects_market and csv_writer is not None: - csv_writer.writerow([market.code, *metric_row(values)]) - csv_rows += 1 - elif intersects_market and csv_path is not None: - csv_rows += 1 - - if CLIP_MODE == "intersects": - if not intersects_market: - continue - window = pixel_window_for_bounds( - geometry_bounds[index], - minx, - maxy, - pixel_width, - pixel_height, - width, - height, - ) - else: - lon = to_float(values.get("longitude")) - lat = to_float(values.get("latitude")) - if lon is None or lat is None or not market.geometry.covers(Point(lon, lat)): - continue - window = pixel_window_from_point(lon, lat, minx, maxy, pixel_width, pixel_height, width, height) - if window is None: - continue - - # if user_count_path is not None: - # user_count_5g_clipped_rows += 1 - # if not merge_user_count_record( - # user_count_records, - # values.get(GRID_ID_FIELD), - # window, - # numeric_values[EXCELLENT_CELL_FIELD], - # "5G", - # prefer_geometry=True, - # ): - # user_count_5g_invalid_grid_ids += 1 - - competitor_total = numeric_values[EXCELLENT_CELL_FIELD] - competitor_rsrp = numeric_values[RSRP_FIELD] - competitor_weak = numeric_values[WEAK_COVER_FIELD] - mobile_total = numeric_values[MOBILE_TOTAL_FIELD] - mobile_weak = numeric_values[MOBILE_WEAK_COVER_FIELD] - exclusion_reason = competitor_signal_filter_reason( - mobile_weak, - mobile_total, - competitor_weak, - competitor_total, - ) - if exclusion_reason is not None: - exclusion_counts[exclusion_reason] += 1 - continue - if competitor_total != 0 and (competitor_rsrp is None or competitor_rsrp > 0): - exclusion_counts["invalid_rsrp"] += 1 - continue - - signal_window = pixel_window_for_bounds( - geometry_bounds[index], - minx, - maxy, - pixel_width, - pixel_height, - width, - height, - ) - if signal_window is None: - exclusion_counts["no_center_pixels"] += 1 - continue - geometry_mask = pixel_center_mask_for_geometry( - geometries[index], - signal_window, - minx, - maxy, - pixel_width, - pixel_height, - ) - geometry_pixel_count = int(np.count_nonzero(geometry_mask)) - if geometry_pixel_count == 0: - exclusion_counts["no_center_pixels"] += 1 - continue - - row_start, row_stop, col_start, col_stop = signal_window - if competitor_total == 0: - zero_total_view = zero_total_mask[row_start:row_stop, col_start:col_stop] - zero_total_view |= geometry_mask - zero_total_cells += 1 - else: - value_sum_view = competitor_signal_value_sum[row_start:row_stop, col_start:col_stop] - value_weight_view = competitor_signal_value_weight[row_start:row_stop, col_start:col_stop] - value_sum_view[geometry_mask] += competitor_rsrp - value_weight_view[geometry_mask] += 1 - competitor_signal_cells += 1 - exact_geometry_pixels += geometry_pixel_count - finally: - if csv_file is not None: - csv_file.close() - shapely.destroy_prepared(market.geometry) - - # user_count_result = None - # if user_count_path is not None: - # if grid_4g_source is None: - # raise ValueError("生成竟对用户量图层时必须提供 Grid_4G 数据源") - # grid_4g_conn, grid_4g_layer, grid_4g_rtree = grid_4g_source - # source_stats = { - # "5G": { - # "candidates": candidates, - # "clipped_rows": user_count_5g_clipped_rows, - # "invalid_grid_ids": user_count_5g_invalid_grid_ids, - # } - # } - # source_stats["4G"] = collect_user_count_source( - # user_count_records, - # grid_4g_conn, - # grid_4g_layer, - # grid_4g_rtree, - # market, - # minx, - # maxy, - # pixel_width, - # pixel_height, - # width, - # height, - # "4G", - # ) - # user_count_state = build_merged_user_count_state(user_count_records, height, width) - # user_count_result = render_ranked_raster( - # user_count_state, - # market, - # user_count_path, - # minx, - # maxy, - # pixel_width, - # pixel_height, - # width, - # height, - # sum(stats["candidates"] for stats in source_stats.values()), - # EXCELLENT_COLORS, - # EXCELLENT_PERCENT_STEPS, - # ) - # user_count_result.update(merged_user_count_metadata(user_count_records, source_stats)) - # del user_count_state - - competitor_signal_state = { - "value_sum": competitor_signal_value_sum, - "value_weight": competitor_signal_value_weight, - "zero_total_mask": zero_total_mask, - "painted_cells": competitor_signal_cells, - "skipped_no_value": sum(exclusion_counts.values()), - } - competitor_signal_result = render_competitor_signal_raster( - competitor_signal_state, - market, - competitor_signal_path, - minx, - maxy, - pixel_width, - pixel_height, - width, - height, - candidates, - ) - competitor_signal_result.update({ - "data_source": str(GRID_5G_GPKG), - "uses_merged_user_count": False, - "geometry_rasterization": "pixel_center_inside_polygon", - "exact_geometry_pixels": exact_geometry_pixels, - "mobile_weak_ratio_formula": f"{MOBILE_WEAK_COVER_FIELD} / {MOBILE_TOTAL_FIELD} * 100", - "mobile_weak_ratio_operator": "<", - "mobile_weak_ratio_threshold": COMPETITOR_SIGNAL_MOBILE_WEAK_RATIO_MAX, - "competitor_total_field": EXCELLENT_CELL_FIELD, - "competitor_weak_ratio_formula": f"{WEAK_COVER_FIELD} / {EXCELLENT_CELL_FIELD} * 100", - "competitor_weak_ratio_operator": ">", - "competitor_weak_ratio_threshold": COMPETITOR_SIGNAL_WEAK_RATIO_MIN, - "zero_competitor_total_is_included": True, - "zero_competitor_total_color": list(COMPETITOR_SIGNAL_RSRP_COLORS[0]), - "zero_competitor_total_cells": zero_total_cells, - "rsrp_field": RSRP_FIELD, - "eligible_cells": competitor_signal_cells, - "exclusion_counts": exclusion_counts, - }) - del ( - competitor_signal_state, - competitor_signal_value_sum, - competitor_signal_value_weight, - zero_total_mask, - ) - - # for result in (user_count_result, competitor_signal_result): - for result in (competitor_signal_result,): - if result is None: - continue - result["raster_extent"] = [ - minx, - maxy - height * pixel_height, - minx + width * pixel_width, - maxy, - ] - result["pixel_width"] = pixel_width - result["pixel_height"] = pixel_height - result["resolution_scale_factor"] = scale_factor - csv_result = None - if csv_path is not None: - csv_result = { - "market_code": market.code, - "market_name": market.name, - "output": str(csv_path), - "candidates": candidates, - "row_count": csv_rows, - "skipped": csv_skipped, - } - return ( - # user_count_result, - competitor_signal_result, - csv_result, - ) - - -def write_excellent_heatmap_legend(output_dir, field): - legend_path = output_dir / "excellent_heatmap_legend.csv" - with legend_path.open("w", newline="", encoding="utf-8-sig") as file: - writer = csv.writer(file) - writer.writerow(["field", "rank_range", "red", "green", "blue", "alpha", "meaning"]) - rank_ranges = ("top_10_percent", "10_to_40_percent", "40_to_70_percent", "bottom_30_percent") - for rank_range, color in zip(rank_ranges, EXCELLENT_COLORS): - writer.writerow([field, rank_range, *color, HEATMAP_ALPHA, "ranked-pixel distribution"]) - writer.writerow([field, "nodata", 0, 0, 0, 0, "transparent no data"]) - return legend_path - - -def write_competitor_signal_legend(output_dir): - legend_path = output_dir / "competitor_signal_legend.csv" - with legend_path.open("w", newline="", encoding="utf-8-sig") as file: - writer = csv.writer(file) - writer.writerow(["field", "rule_or_rsrp_range", "red", "green", "blue", "alpha", "filter"]) - competitor_filter = ( - f"{MOBILE_WEAK_COVER_FIELD}/{MOBILE_TOTAL_FIELD} < {COMPETITOR_SIGNAL_MOBILE_WEAK_RATIO_MAX}%" - f" and ({EXCELLENT_CELL_FIELD} = 0" - f" or {WEAK_COVER_FIELD}/{EXCELLENT_CELL_FIELD} > {COMPETITOR_SIGNAL_WEAK_RATIO_MIN}%)" - ) - writer.writerow([ - EXCELLENT_CELL_FIELD, - "= 0", - *COMPETITOR_SIGNAL_RSRP_COLORS[0], - HEATMAP_ALPHA, - competitor_filter, - ]) - ranges = ( - "< -110", - "[-110, -104)", - "[-104, -98)", - "[-98, -92)", - "[-92, -86)", - "[-86, -80)", - "[-80, -74)", - "[-74, 0]", - ) - for value_range, color in zip(ranges, COMPETITOR_SIGNAL_RSRP_COLORS): - writer.writerow([RSRP_FIELD, value_range, *color, HEATMAP_ALPHA, competitor_filter]) - writer.writerow([RSRP_FIELD, "not_eligible_or_invalid", 0, 0, 0, 0, competitor_filter]) - return legend_path - - -@contextmanager -def open_read_connection(path): - conn = sqlite3.connect(path) - conn.execute("pragma query_only = on") - conn.execute("pragma temp_store = memory") - try: - yield conn - finally: - conn.close() - - -def gpkg_layer_extent(conn, layer): - row = conn.execute( - "select min_x, min_y, max_x, max_y from gpkg_contents where table_name = ?", - (layer.table_name,), - ).fetchone() - if row and all(value is not None for value in row): - return tuple(float(value) for value in row) - rtree = rtree_name(conn, layer) - row = conn.execute( - f"select min(minx), min(miny), max(maxx), max(maxy) from {quote_identifier(rtree)}" - ).fetchone() - return tuple(float(value) for value in row) if row and all(value is not None for value in row) else None - - -def process_market(market, pixel_width, pixel_height, output_dir): - started_at = perf_counter() - output_dir = Path(output_dir) - output_dir.mkdir(parents=True, exist_ok=True) - zip_path = market_zip_output_path(output_dir, market) - if zip_path.exists() and not OVERWRITE: - return { - "market_fid": market.fid, - "market_code": market.code, - "market_name": market.name, - "zip_result": { - "market_code": market.code, - "market_name": market.name, - "output": zip_path.as_posix(), - "skipped": True, - }, - "elapsed_seconds": perf_counter() - started_at, - } - - with ( - open_read_connection(GRID_5G_GPKG) as grid_5g_conn, - # open_read_connection(GRID_4G_GPKG) as grid_4g_conn, - open_read_connection(BUILDING_INFO_GPKG) as building_info_conn, - open_read_connection(AOI_GPKG) as aoi_conn, - ): - grid_5g_layer = resolve_feature_layer(grid_5g_conn, GRID_5G_LAYER) - # grid_4g_layer = resolve_feature_layer(grid_4g_conn, GRID_4G_LAYER) - building_info_layer = resolve_feature_layer(building_info_conn, 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) - building_info_rtree = rtree_name(building_info_conn, building_info_layer) - aoi_layer = resolve_feature_layer(aoi_conn, AOI_LAYER) - aoi_rtree = rtree_name(aoi_conn, aoi_layer) - - with tempfile.TemporaryDirectory(prefix=f"{safe_filename(market.code)}_") as temp_dir: - market_dir = Path(temp_dir) - gis_project_path = market_dir / GIS_PROJECT_OUTPUT_FILENAME - - # user_count_path = market_dir / excellent_heatmap_raster_filename(EXCELLENT_CELL_FIELD) - competitor_signal_path = market_dir / competitor_signal_raster_filename() - grid_started_at = perf_counter() - ( - # user_count_result, - competitor_signal_result, - _, - ) = export_market_grid_outputs( - grid_5g_conn, - grid_5g_layer, - grid_5g_rtree, - market, - pixel_width, - pixel_height, - # user_count_path, - competitor_signal_path, - None, - # (grid_4g_conn, grid_4g_layer, grid_4g_rtree), - ) - grid_elapsed = perf_counter() - grid_started_at - - building_info_path = market_dir / BUILDING_INFO_OUTPUT_FILENAME - building_started_at = perf_counter() - building_info_result = export_market_building_info_gpkg( - building_info_conn, - building_info_layer, - building_info_rtree, - market, - building_info_path, - ) - aoi_result = export_market_aoi_gpkg( - aoi_conn, aoi_layer, aoi_rtree, market, market_dir / AOI_OUTPUT_FILENAME, - ) - gis_project_result = copy_gis_project_to_market( - GIS_PROJECT_SOURCE, - gis_project_path, - market, - building_info_result["extent"], - competitor_signal_result["raster_extent"], - include_cell_data=False, - aoi_result=aoi_result, - ) - building_elapsed = perf_counter() - building_started_at - - zip_result = write_market_zip(market_dir, zip_path, market) - removed_legacy_dir = remove_legacy_market_dir(output_dir, market) - if removed_legacy_dir: - zip_result["removed_legacy_dir"] = str(removed_legacy_dir) - - return { - "market_fid": market.fid, - "market_code": market.code, - "market_name": market.name, - # "excellent_heatmap_result": rewrite_result_for_zip(user_count_result, zip_path, market_dir), - "competitor_signal_result": rewrite_result_for_zip( - competitor_signal_result, - zip_path, - market_dir, - ), - "building_info_result": rewrite_result_for_zip(building_info_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, - "timings": { - "grid_outputs_seconds": grid_elapsed, - "supporting_layers_seconds": building_elapsed, - }, - "elapsed_seconds": perf_counter() - started_at, - } - - -# def process_summary_grid_outputs(markets, pixel_width, pixel_height, output_dir, market_user_thresholds=None): -def process_summary_grid_outputs(markets, pixel_width, pixel_height, output_dir): - started_at = perf_counter() - output_dir = Path(output_dir) - output_dir.mkdir(parents=True, exist_ok=True) - summary_market = build_summary_market(markets) - zip_path = output_dir / SUMMARY_OUTPUT_FILENAME - if zip_path.exists() and not OVERWRITE: - return { - "market_code": summary_market.code, - "zip_result": { - "market_code": summary_market.code, - "market_name": summary_market.name, - "output": zip_path.as_posix(), - "skipped": True, - }, - "skipped": True, - "elapsed_seconds": perf_counter() - started_at, - } - - with ( - open_read_connection(GRID_5G_GPKG) as grid_5g_conn, - # open_read_connection(GRID_4G_GPKG) as grid_4g_conn, - ): - grid_5g_layer = resolve_feature_layer(grid_5g_conn, GRID_5G_LAYER) - # grid_4g_layer = resolve_feature_layer(grid_4g_conn, GRID_4G_LAYER) - 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) - # user_count_path = summary_dir / excellent_heatmap_raster_filename(EXCELLENT_CELL_FIELD) - competitor_signal_path = summary_dir / competitor_signal_raster_filename() - ( - # _, # 原用户量结果 - competitor_signal_result, - _, - ) = export_market_grid_outputs( - grid_5g_conn, - grid_5g_layer, - grid_5g_rtree, - summary_market, - pixel_width, - pixel_height, - # None, # 原 user_count_path - competitor_signal_path, - None, - max_raster_pixels=SUMMARY_MAX_RASTER_PIXELS, - ) - # user_count_result = render_summary_user_count_by_market( - # ( - # ("5G", grid_5g_conn, grid_5g_layer, grid_5g_rtree), - # ("4G", grid_4g_conn, grid_4g_layer, grid_4g_rtree), - # ), - # markets, - # pixel_width, - # pixel_height, - # user_count_path, - # SUMMARY_MAX_RASTER_PIXELS, - # market_user_thresholds, - # ) - building_info_path = summary_dir / BUILDING_INFO_OUTPUT_FILENAME - shutil.copy2(BUILDING_INFO_GPKG, building_info_path) - with open_read_connection(BUILDING_INFO_GPKG) as building_info_conn: - building_info_layer = resolve_feature_layer(building_info_conn, BUILDING_INFO_LAYER) - building_info_extent = gpkg_layer_extent(building_info_conn, building_info_layer) - building_info_result = { - "market_code": summary_market.code, - "market_name": summary_market.name, - "source": str(BUILDING_INFO_GPKG), - "output": str(building_info_path), - "extent": list(building_info_extent) if building_info_extent else None, - "bytes": building_info_path.stat().st_size, - "copied_full_source": True, - "skipped": False, - } - cell_data_path = summary_dir / CELL_DATA_OUTPUT_FILENAME - cell_data_result = copy_full_source_file( - CELL_DATA_GPKG, - cell_data_path, - summary_market, - ) - gis_project_path = summary_dir / GIS_PROJECT_OUTPUT_FILENAME - gis_project_result = copy_gis_project_to_market( - GIS_PROJECT_SOURCE, - gis_project_path, - summary_market, - building_info_extent, - competitor_signal_result["raster_extent"], - include_cell_data=True, - ) - zip_result = write_market_zip(summary_dir, zip_path, summary_market) - legacy_zip_path = output_dir / LEGACY_SUMMARY_OUTPUT_FILENAME - if legacy_zip_path != zip_path and legacy_zip_path.exists(): - remove_file_with_retry(legacy_zip_path) - return { - "market_code": summary_market.code, - # "excellent_heatmap_result": rewrite_result_for_zip(user_count_result, zip_path, summary_dir), - "competitor_signal_result": rewrite_result_for_zip( - competitor_signal_result, - zip_path, - summary_dir, - ), - "building_info_result": rewrite_result_for_zip(building_info_result, zip_path, summary_dir), - "cell_data_result": rewrite_result_for_zip(cell_data_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, - } - - -def main(): - if SCALE <= 0: - raise ValueError("SCALE 必须大于 0") - if MAX_WORKERS <= 0: - raise ValueError("MAX_WORKERS 必须大于 0") - if GEOMETRY_BATCH_SIZE <= 0: - raise ValueError("GEOMETRY_BATCH_SIZE 必须大于 0") - if PROJECT_EXTENT_PADDING_RATIO < 0: - raise ValueError("PROJECT_EXTENT_PADDING_RATIO 不能小于 0") - # validate_smoothing_radius("HEATMAP_SMOOTH_RADIUS", HEATMAP_SMOOTH_RADIUS) - if not 0 <= COMPETITOR_SIGNAL_MOBILE_WEAK_RATIO_MAX <= 100: - raise ValueError("COMPETITOR_SIGNAL_MOBILE_WEAK_RATIO_MAX 必须在 0 到 100 之间") - if not 0 <= COMPETITOR_SIGNAL_WEAK_RATIO_MIN <= 100: - raise ValueError("COMPETITOR_SIGNAL_WEAK_RATIO_MIN 必须在 0 到 100 之间") - if len(COMPETITOR_SIGNAL_RSRP_COLORS) != len(COMPETITOR_SIGNAL_RSRP_BREAKS) + 1: - raise ValueError("竟对信号 RSRP 颜色数量必须比分界点数量多 1") - if any( - left >= right - for left, right in zip( - COMPETITOR_SIGNAL_RSRP_BREAKS, - COMPETITOR_SIGNAL_RSRP_BREAKS[1:], - ) - ): - raise ValueError("COMPETITOR_SIGNAL_RSRP_BREAKS 必须严格递增") - if MAX_RASTER_PIXELS is not None and MAX_RASTER_PIXELS <= 0: - raise ValueError("MAX_RASTER_PIXELS 必须大于 0 或设置为 None") - if SUMMARY_MAX_RASTER_PIXELS is None or SUMMARY_MAX_RASTER_PIXELS <= 0: - raise ValueError("SUMMARY_MAX_RASTER_PIXELS 必须大于 0") - if CLIP_MODE not in {"intersects", "center"}: - raise ValueError("CLIP_MODE 必须是 intersects 或 center") - required_files = ( - MARKET_GPKG, - GRID_5G_GPKG, - # GRID_4G_GPKG, - BUILDING_INFO_GPKG, - CELL_DATA_GPKG, - GIS_PROJECT_SOURCE, - AOI_GPKG, - ) - missing_files = [str(path) for path in required_files if not path.is_file()] - if missing_files: - raise FileNotFoundError(f"缺少输入文件:{', '.join(missing_files)}") - - OUTPUT_DIR.mkdir(parents=True, exist_ok=True) - with ( - open_read_connection(MARKET_GPKG) as market_conn, - open_read_connection(GRID_5G_GPKG) as grid_5g_conn, - # open_read_connection(GRID_4G_GPKG) as grid_4g_conn, - open_read_connection(BUILDING_INFO_GPKG) as building_info_conn, - ): - market_layer = resolve_feature_layer(market_conn, MARKET_LAYER) - grid_5g_layer = resolve_feature_layer(grid_5g_conn, GRID_5G_LAYER) - # grid_4g_layer = resolve_feature_layer(grid_4g_conn, GRID_4G_LAYER) - building_info_layer = resolve_feature_layer(building_info_conn, BUILDING_INFO_LAYER) - if ( - market_layer.srs_id != 4326 - or grid_5g_layer.srs_id != 4326 - # or grid_4g_layer.srs_id != 4326 - ): - raise ValueError("当前脚本只处理 EPSG:4326 的输入图层") - if building_info_layer.srs_id not in BUILDING_INFO_ALLOWED_SRS_IDS: - raise ValueError(f"BuildingInfo 图层坐标系不在允许范围内:{building_info_layer.srs_id}") - - require_columns( - grid_5g_conn, - grid_5g_layer.table_name, - # (*CSV_SOURCE_FIELDS, MOBILE_TOTAL_FIELD, MOBILE_WEAK_COVER_FIELD, GRID_ID_FIELD), - (*CSV_SOURCE_FIELDS, MOBILE_TOTAL_FIELD, MOBILE_WEAK_COVER_FIELD), - ) - # grid_4g_required_fields = [GRID_ID_FIELD, EXCELLENT_CELL_FIELD] - # if CLIP_MODE == "center": - # grid_4g_required_fields.extend(("longitude", "latitude")) - # require_columns(grid_4g_conn, grid_4g_layer.table_name, grid_4g_required_fields) - require_columns(building_info_conn, building_info_layer.table_name, ["name"]) - rtree_name(grid_5g_conn, grid_5g_layer) - # rtree_name(grid_4g_conn, grid_4g_layer) - rtree_name(building_info_conn, building_info_layer) - pixel_width = PIXEL_WIDTH - pixel_height = PIXEL_HEIGHT - if pixel_width is None or pixel_height is None: - estimated_width, estimated_height = estimate_pixel_size( - grid_5g_conn, - grid_5g_layer, - SAMPLE_SIZE, - ) - pixel_width = pixel_width or estimated_width - pixel_height = pixel_height or estimated_height - pixel_width = pixel_width / SCALE - pixel_height = pixel_height / SCALE - - markets = load_market_features( - market_conn, - market_layer, - MARKET_CODE_FIELD, - MARKET_NAME_FIELD, - ) - if LIMIT: - markets = markets[:LIMIT] - layer_names = { - "grid_5g": grid_5g_layer.table_name, - # "grid_4g": grid_4g_layer.table_name, - "building_info": building_info_layer.table_name, - } - - # excellent_legend_path = write_excellent_heatmap_legend(OUTPUT_DIR, EXCELLENT_CELL_FIELD) - competitor_signal_legend_path = write_competitor_signal_legend(OUTPUT_DIR) - worker_count = max(1, min(MAX_WORKERS, len(markets))) if markets else 1 - print(f"市场网格数量:{len(markets)}") - print(f"并行进程数:{worker_count}") - print(f"5G Grid 图层:{layer_names['grid_5g']}") - # print(f"4G Grid 图层:{layer_names['grid_4g']}") - print(f"BuildingInfo 图层:{layer_names['building_info']}") - print(f"像元大小:{pixel_width}, {pixel_height}") - # print(f"用户量图例:{excellent_legend_path}") - print(f"竟对信号图例:{competitor_signal_legend_path}") - - started_at = perf_counter() - outcomes = [] - if worker_count == 1: - for index, market in enumerate(markets, start=1): - outcome = process_market(market, pixel_width, pixel_height, OUTPUT_DIR) - outcomes.append(outcome) - scale_factor = outcome.get("competitor_signal_result", {}).get("resolution_scale_factor", 1.0) - resolution_note = f",分辨率自动调整 x{scale_factor:.2f}" if scale_factor > 1.001 else "" - print( - f"[{index}/{len(markets)}] 完成 {market.code}," - f"耗时 {outcome['elapsed_seconds']:.1f} 秒{resolution_note}" - ) - else: - with ProcessPoolExecutor(max_workers=worker_count) as executor: - future_markets = { - executor.submit(process_market, market, pixel_width, pixel_height, OUTPUT_DIR): market - for market in markets - } - completed = 0 - for future in as_completed(future_markets): - market = future_markets[future] - try: - outcome = future.result() - except Exception as error: - raise RuntimeError(f"市场网格处理失败:{market.code}") from error - outcomes.append(outcome) - completed += 1 - scale_factor = outcome.get("competitor_signal_result", {}).get("resolution_scale_factor", 1.0) - resolution_note = f",分辨率自动调整 x{scale_factor:.2f}" if scale_factor > 1.001 else "" - print( - f"[{completed}/{len(markets)}] 完成 {market.code}," - f"耗时 {outcome['elapsed_seconds']:.1f} 秒{resolution_note}" - ) - - outcomes.sort(key=lambda item: item["market_fid"]) - summary_grid_result = None - if SUMMARY_OUTPUT_ENABLED and markets: - print("开始生成全部市场网格汇总 TIF……") - # market_user_thresholds = { - # outcome["market_code"]: outcome["excellent_heatmap_result"].get("thresholds") - # for outcome in outcomes - # if outcome.get("excellent_heatmap_result") - # } - summary_grid_result = process_summary_grid_outputs( - markets, - pixel_width, - pixel_height, - OUTPUT_DIR, - # market_user_thresholds, - ) - print( - f"汇总 TIF 完成:{summary_grid_result['zip_result']['output']}," - f"耗时 {summary_grid_result['elapsed_seconds']:.1f} 秒" - ) - result_mappings = { - # "excellent_heatmap_results": "excellent_heatmap_result", - "competitor_signal_results": "competitor_signal_result", - "building_info_results": "building_info_result", - "aoi_results": "aoi_result", - "cell_data_results": "cell_data_result", - "gis_project_results": "gis_project_result", - "zip_results": "zip_result", - } - summary = { - "market_gpkg": str(MARKET_GPKG), - "grid_5g_gpkg": str(GRID_5G_GPKG), - # "grid_4g_gpkg": str(GRID_4G_GPKG), - # "user_count_grid_id_field": GRID_ID_FIELD, - # "user_count_merge_rule": "Grid_5G + Grid_4G union by grid20_id and sum mro_total_dl", - "building_info_gpkg": str(BUILDING_INFO_GPKG), - "aoi_gpkg": str(AOI_GPKG), - "aoi_match_field": AOI_MARKET_FIELD, - "cell_data_gpkg": str(CELL_DATA_GPKG), - "gis_project_source": str(GIS_PROJECT_SOURCE), - "rsrp_field": RSRP_FIELD, - "excellent_cell_field": EXCELLENT_CELL_FIELD, - "weak_cover_field": WEAK_COVER_FIELD, - "mobile_total_field": MOBILE_TOTAL_FIELD, - "mobile_weak_cover_field": MOBILE_WEAK_COVER_FIELD, - "competitor_signal_mobile_weak_ratio_formula": ( - f"{MOBILE_WEAK_COVER_FIELD} / {MOBILE_TOTAL_FIELD} * 100" - ), - "competitor_signal_mobile_weak_ratio_rule": ( - f"< {COMPETITOR_SIGNAL_MOBILE_WEAK_RATIO_MAX}" - ), - "competitor_signal_eligibility_rule": ( - f"{EXCELLENT_CELL_FIELD} = 0 or " - f"{WEAK_COVER_FIELD} / {EXCELLENT_CELL_FIELD} * 100 " - f"> {COMPETITOR_SIGNAL_WEAK_RATIO_MIN}" - ), - "competitor_signal_zero_total_color": list(COMPETITOR_SIGNAL_RSRP_COLORS[0]), - "clip_mode": CLIP_MODE, - "scale": SCALE, - "pixel_width": pixel_width, - "pixel_height": pixel_height, - "max_workers": worker_count, - "summary_output_enabled": SUMMARY_OUTPUT_ENABLED, - "total_elapsed_seconds": perf_counter() - started_at, - "market_timings": [ - { - "market_code": outcome["market_code"], - "elapsed_seconds": outcome["elapsed_seconds"], - **outcome.get("timings", {}), - } - for outcome in outcomes - ], - } - for summary_key, outcome_key in result_mappings.items(): - summary[summary_key] = [outcome[outcome_key] for outcome in outcomes if outcome_key in outcome] - summary["summary_grid_result"] = summary_grid_result - - summary_path = OUTPUT_DIR / "summary.json" - temp_summary_path = summary_path.with_name(f".{summary_path.name}.tmp") - try: - temp_summary_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8") - temp_summary_path.replace(summary_path) - except Exception: - if temp_summary_path.exists(): - temp_summary_path.unlink() - raise - print(f"总耗时:{summary['total_elapsed_seconds']:.1f} 秒") - print(f"汇总:{summary_path}") +"""市场网格命令行入口。默认参数见 marketgrid/config.py。""" +from marketgrid.pipeline import main if __name__ == "__main__": diff --git a/marketgrid/__init__.py b/marketgrid/__init__.py new file mode 100644 index 0000000..f71e19c --- /dev/null +++ b/marketgrid/__init__.py @@ -0,0 +1 @@ +"""市场网格数据处理。""" diff --git a/marketgrid/competitor.py b/marketgrid/competitor.py new file mode 100644 index 0000000..b86a7ce --- /dev/null +++ b/marketgrid/competitor.py @@ -0,0 +1,416 @@ +"""竟对信号筛选和精确栅格化。""" +from shapely import Point +import csv +import numpy as np +import shapely +from . import config +from .metrics import grid_metrics_headers +from .gpkg import iter_geometry_batches +from .raster_math import market_raster_layout +from .metrics import metric_row +from .raster_math import pixel_center_mask_for_geometry +from .raster_math import pixel_window_for_bounds +from .raster_math import pixel_window_from_point +from .gpkg import quote_identifier +from .gpkg import require_columns +from .raster_math import to_float +from .raster_math import write_rgba_geotiff + + +def competitor_signal_filter_reason(mobile_weak, mobile_total, competitor_weak, competitor_total): + if mobile_weak is None or mobile_total is None or competitor_total is None: + return "invalid_fields" + if mobile_total <= 0 or mobile_weak < 0 or competitor_total < 0: + return "invalid_fields" + mobile_weak_ratio = mobile_weak / mobile_total * 100.0 + if mobile_weak_ratio >= config.COMPETITOR_SIGNAL_MOBILE_WEAK_RATIO_MAX: + return "mobile_weak_ratio" + if competitor_total == 0: + return None + if competitor_weak is None or competitor_weak < 0: + return "invalid_fields" + competitor_weak_ratio = competitor_weak / competitor_total * 100.0 + if competitor_weak_ratio <= config.COMPETITOR_SIGNAL_WEAK_RATIO_MIN: + return "competitor_weak_ratio" + return None + + +def competitor_signal_is_eligible(mobile_weak, mobile_total, competitor_weak, competitor_total): + return competitor_signal_filter_reason(mobile_weak, mobile_total, competitor_weak, competitor_total) is None + + +def competitor_signal_rsrp_rgb_for_values(values): + values = np.asarray(values, dtype=np.float32) + colors = np.zeros((*values.shape, 3), dtype=np.uint8) + valid_mask = np.isfinite(values) & (values <= 0) + if np.any(valid_mask): + color_indices = np.searchsorted( + np.asarray(config.COMPETITOR_SIGNAL_RSRP_BREAKS, dtype=np.float32), + values[valid_mask], + side="right", + ) + colors[valid_mask] = np.asarray(config.COMPETITOR_SIGNAL_RSRP_COLORS, dtype=np.uint8)[color_indices] + return colors, valid_mask + + +def render_competitor_signal_raster( + state, + market, + output_path, + minx, + maxy, + pixel_width, + pixel_height, + width, + height, + candidates, +): + image = np.full((height, width, 4), config.TRANSPARENT_PIXEL, dtype=np.uint8) + value_sum = state["value_sum"] + value_weight = state["value_weight"] + rsrp_mask = value_weight > 0 + zero_total_mask = state["zero_total_mask"] + data_mask = rsrp_mask | zero_total_mask + class_pixel_counts = [0] * len(config.COMPETITOR_SIGNAL_RSRP_COLORS) + if np.any(rsrp_mask): + value_raster = np.zeros_like(value_sum) + np.divide(value_sum, value_weight, out=value_raster, where=rsrp_mask) + colors, valid_rsrp_mask = competitor_signal_rsrp_rgb_for_values(value_raster) + render_mask = rsrp_mask & valid_rsrp_mask + image[render_mask, :3] = colors[render_mask] + image[zero_total_mask, :3] = config.COMPETITOR_SIGNAL_RSRP_COLORS[0] + image[data_mask, 3] = config.HEATMAP_ALPHA + for index, color in enumerate(config.COMPETITOR_SIGNAL_RSRP_COLORS): + color_mask = data_mask & np.all(image[..., :3] == color, axis=-1) + class_pixel_counts[index] = int(np.count_nonzero(color_mask)) + + write_rgba_geotiff(output_path, image, minx, maxy, pixel_width, pixel_height) + return { + "market_code": market.code, + "market_name": market.name, + "output": str(output_path), + "candidates": candidates, + "painted_cells": state["painted_cells"], + "data_pixels": int(np.count_nonzero(image[..., 3])), + "skipped_no_value": state["skipped_no_value"], + "color_mode": "discrete_competitor_signal", + "rsrp_breaks": list(config.COMPETITOR_SIGNAL_RSRP_BREAKS), + "colors": [list(color) for color in config.COMPETITOR_SIGNAL_RSRP_COLORS], + "class_pixel_counts": class_pixel_counts, + "zero_total_pixels": int(np.count_nonzero(zero_total_mask)), + "smooth_radius": 0, + "width": width, + "height": height, + "skipped": False, + } + + +def export_market_grid_outputs( + grid_5g_conn, + grid_5g_layer, + grid_5g_rtree, + market, + pixel_width, + pixel_height, + # user_count_path, + competitor_signal_path, + csv_path, + # grid_4g_source=None, + max_raster_pixels=None, +): + minx, miny, maxx, maxy, pixel_width, pixel_height, width, height, scale_factor = market_raster_layout( + market.geometry.bounds, + pixel_width, + pixel_height, + max_raster_pixels, + ) + raster_fields = ( + config.EXCELLENT_CELL_FIELD, + config.RSRP_FIELD, + config.WEAK_COVER_FIELD, + config.MOBILE_TOTAL_FIELD, + config.MOBILE_WEAK_COVER_FIELD, + ) + # user_count_records = {} + competitor_signal_value_sum = np.zeros((height, width), dtype=np.float32) + competitor_signal_value_weight = np.zeros((height, width), dtype=np.uint16) + zero_total_mask = np.zeros((height, width), dtype=bool) + competitor_signal_cells = 0 + zero_total_cells = 0 + exact_geometry_pixels = 0 + exclusion_counts = { + "invalid_fields": 0, + "mobile_weak_ratio": 0, + "competitor_weak_ratio": 0, + "invalid_rsrp": 0, + "no_center_pixels": 0, + } + + # fields = list( + # dict.fromkeys( + # (*CSV_SOURCE_FIELDS, *raster_fields, GRID_ID_FIELD) + # if csv_path is not None + # else (*raster_fields, GRID_ID_FIELD) + # ) + # ) + fields = list(dict.fromkeys((*config.CSV_SOURCE_FIELDS, *raster_fields) if csv_path is not None else raster_fields)) + if csv_path is None and config.CLIP_MODE == "center": + fields.extend(field for field in ("longitude", "latitude") if field not in fields) + require_columns(grid_5g_conn, grid_5g_layer.table_name, fields) + table = quote_identifier(grid_5g_layer.table_name) + pk = quote_identifier(grid_5g_layer.pk_col) + geom = quote_identifier(grid_5g_layer.geom_col) + rtree_table = quote_identifier(grid_5g_rtree) + field_sql = ", ".join(f"b.{quote_identifier(field)}" for field in fields) + query = f""" + select b.{pk}, b.{geom}, {field_sql} + from {rtree_table} r + join {table} b on b.{pk} = r."id" + where r."minx" <= ? + and r."maxx" >= ? + and r."miny" <= ? + and r."maxy" >= ? + """ + params = (maxx, minx, maxy, miny) + candidates = 0 + # user_count_5g_clipped_rows = 0 + # user_count_5g_invalid_grid_ids = 0 + csv_rows = 0 + csv_skipped = csv_path is None or (csv_path.exists() and not config.OVERWRITE) + csv_file = None + csv_writer = None + if not csv_skipped: + csv_file = csv_path.open("w", newline="", encoding=config.CSV_ENCODING, errors="replace") + csv_writer = csv.writer(csv_file) + csv_writer.writerow(grid_metrics_headers()) + + try: + shapely.prepare(market.geometry) + cursor = grid_5g_conn.execute(query, params) + for batch_rows, geometries, valid_mask in iter_geometry_batches(cursor, 1): + candidates += len(batch_rows) + intersects_mask = valid_mask & shapely.intersects(market.geometry, geometries) + geometry_bounds = shapely.bounds(geometries) + for index, row in enumerate(batch_rows): + values = dict(zip(fields, row[2:])) + numeric_values = {field: to_float(values.get(field)) for field in raster_fields} + + if not valid_mask[index]: + continue + intersects_market = bool(intersects_mask[index]) + if intersects_market and csv_writer is not None: + csv_writer.writerow([market.code, *metric_row(values)]) + csv_rows += 1 + elif intersects_market and csv_path is not None: + csv_rows += 1 + + if config.CLIP_MODE == "intersects": + if not intersects_market: + continue + window = pixel_window_for_bounds( + geometry_bounds[index], + minx, + maxy, + pixel_width, + pixel_height, + width, + height, + ) + else: + lon = to_float(values.get("longitude")) + lat = to_float(values.get("latitude")) + if lon is None or lat is None or not market.geometry.covers(Point(lon, lat)): + continue + window = pixel_window_from_point(lon, lat, minx, maxy, pixel_width, pixel_height, width, height) + if window is None: + continue + + # if user_count_path is not None: + # user_count_5g_clipped_rows += 1 + # if not merge_user_count_record( + # user_count_records, + # values.get(GRID_ID_FIELD), + # window, + # numeric_values[EXCELLENT_CELL_FIELD], + # "5G", + # prefer_geometry=True, + # ): + # user_count_5g_invalid_grid_ids += 1 + + competitor_total = numeric_values[config.EXCELLENT_CELL_FIELD] + competitor_rsrp = numeric_values[config.RSRP_FIELD] + competitor_weak = numeric_values[config.WEAK_COVER_FIELD] + mobile_total = numeric_values[config.MOBILE_TOTAL_FIELD] + mobile_weak = numeric_values[config.MOBILE_WEAK_COVER_FIELD] + exclusion_reason = competitor_signal_filter_reason( + mobile_weak, + mobile_total, + competitor_weak, + competitor_total, + ) + if exclusion_reason is not None: + exclusion_counts[exclusion_reason] += 1 + continue + if competitor_total != 0 and (competitor_rsrp is None or competitor_rsrp > 0): + exclusion_counts["invalid_rsrp"] += 1 + continue + + signal_window = pixel_window_for_bounds( + geometry_bounds[index], + minx, + maxy, + pixel_width, + pixel_height, + width, + height, + ) + if signal_window is None: + exclusion_counts["no_center_pixels"] += 1 + continue + geometry_mask = pixel_center_mask_for_geometry( + geometries[index], + signal_window, + minx, + maxy, + pixel_width, + pixel_height, + ) + geometry_pixel_count = int(np.count_nonzero(geometry_mask)) + if geometry_pixel_count == 0: + exclusion_counts["no_center_pixels"] += 1 + continue + + row_start, row_stop, col_start, col_stop = signal_window + if competitor_total == 0: + zero_total_view = zero_total_mask[row_start:row_stop, col_start:col_stop] + zero_total_view |= geometry_mask + zero_total_cells += 1 + else: + value_sum_view = competitor_signal_value_sum[row_start:row_stop, col_start:col_stop] + value_weight_view = competitor_signal_value_weight[row_start:row_stop, col_start:col_stop] + value_sum_view[geometry_mask] += competitor_rsrp + value_weight_view[geometry_mask] += 1 + competitor_signal_cells += 1 + exact_geometry_pixels += geometry_pixel_count + finally: + if csv_file is not None: + csv_file.close() + shapely.destroy_prepared(market.geometry) + + # user_count_result = None + # if user_count_path is not None: + # if grid_4g_source is None: + # raise ValueError("生成竟对用户量图层时必须提供 Grid_4G 数据源") + # grid_4g_conn, grid_4g_layer, grid_4g_rtree = grid_4g_source + # source_stats = { + # "5G": { + # "candidates": candidates, + # "clipped_rows": user_count_5g_clipped_rows, + # "invalid_grid_ids": user_count_5g_invalid_grid_ids, + # } + # } + # source_stats["4G"] = collect_user_count_source( + # user_count_records, + # grid_4g_conn, + # grid_4g_layer, + # grid_4g_rtree, + # market, + # minx, + # maxy, + # pixel_width, + # pixel_height, + # width, + # height, + # "4G", + # ) + # user_count_state = build_merged_user_count_state(user_count_records, height, width) + # user_count_result = render_ranked_raster( + # user_count_state, + # market, + # user_count_path, + # minx, + # maxy, + # pixel_width, + # pixel_height, + # width, + # height, + # sum(stats["candidates"] for stats in source_stats.values()), + # EXCELLENT_COLORS, + # EXCELLENT_PERCENT_STEPS, + # ) + # user_count_result.update(merged_user_count_metadata(user_count_records, source_stats)) + # del user_count_state + + competitor_signal_state = { + "value_sum": competitor_signal_value_sum, + "value_weight": competitor_signal_value_weight, + "zero_total_mask": zero_total_mask, + "painted_cells": competitor_signal_cells, + "skipped_no_value": sum(exclusion_counts.values()), + } + competitor_signal_result = render_competitor_signal_raster( + competitor_signal_state, + market, + competitor_signal_path, + minx, + maxy, + pixel_width, + pixel_height, + width, + height, + candidates, + ) + competitor_signal_result.update({ + "data_source": str(config.GRID_5G_GPKG), + "uses_merged_user_count": False, + "geometry_rasterization": "pixel_center_inside_polygon", + "exact_geometry_pixels": exact_geometry_pixels, + "mobile_weak_ratio_formula": f"{config.MOBILE_WEAK_COVER_FIELD} / {config.MOBILE_TOTAL_FIELD} * 100", + "mobile_weak_ratio_operator": "<", + "mobile_weak_ratio_threshold": config.COMPETITOR_SIGNAL_MOBILE_WEAK_RATIO_MAX, + "competitor_total_field": config.EXCELLENT_CELL_FIELD, + "competitor_weak_ratio_formula": f"{config.WEAK_COVER_FIELD} / {config.EXCELLENT_CELL_FIELD} * 100", + "competitor_weak_ratio_operator": ">", + "competitor_weak_ratio_threshold": config.COMPETITOR_SIGNAL_WEAK_RATIO_MIN, + "zero_competitor_total_is_included": True, + "zero_competitor_total_color": list(config.COMPETITOR_SIGNAL_RSRP_COLORS[0]), + "zero_competitor_total_cells": zero_total_cells, + "rsrp_field": config.RSRP_FIELD, + "eligible_cells": competitor_signal_cells, + "exclusion_counts": exclusion_counts, + }) + del ( + competitor_signal_state, + competitor_signal_value_sum, + competitor_signal_value_weight, + zero_total_mask, + ) + + # for result in (user_count_result, competitor_signal_result): + for result in (competitor_signal_result,): + if result is None: + continue + result["raster_extent"] = [ + minx, + maxy - height * pixel_height, + minx + width * pixel_width, + maxy, + ] + result["pixel_width"] = pixel_width + result["pixel_height"] = pixel_height + result["resolution_scale_factor"] = scale_factor + csv_result = None + if csv_path is not None: + csv_result = { + "market_code": market.code, + "market_name": market.name, + "output": str(csv_path), + "candidates": candidates, + "row_count": csv_rows, + "skipped": csv_skipped, + } + return ( + # user_count_result, + competitor_signal_result, + csv_result, + ) diff --git a/marketgrid/config.py b/marketgrid/config.py new file mode 100644 index 0000000..9cf621b --- /dev/null +++ b/marketgrid/config.py @@ -0,0 +1,111 @@ +"""命令行默认配置;界面任务通过独立进程应用自己的配置。""" +from pathlib import Path + +DEFAULT_SOURCE_DIR = Path("source") # 源数据目录,存放 GridMap.gpkg、Grid_5G.gpkg、Grid_4G.gpkg 等输入文件。 +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;竟对信号仅使用该文件。 +# 用户量图层停用;以下原代码以注释保留,便于按需恢复。 +# GRID_4G_GPKG = DEFAULT_SOURCE_DIR / "Grid_4G.gpkg" # 4G Grid;仅参与竟对用户量合并。 +BUILDING_INFO_GPKG = DEFAULT_SOURCE_DIR / "BuildingInfo.gpkg" # 建筑信息 GeoPackage 文件路径,用于结果包 BuildingInfo 分割和楼宇指标 CSV 名称匹配。 +CELL_DATA_GPKG = DEFAULT_SOURCE_DIR / "CellData.gpkg" # 小区数据 GeoPackage;仅完整复制到汇总结果包。 +GIS_PROJECT_SOURCE = DEFAULT_SOURCE_DIR / "GIS.qgz" # 每个市场网格结果包使用的 QGIS 项目模板来源。 +AOI_OUTPUT_FILENAME = "AOI级报表_市场网格匹配.gpkg" +AOI_GPKG = OUTPUT_DIR / AOI_OUTPUT_FILENAME # 已完成市场归属匹配的 AOI 总表。 +AOI_LAYER = "AOI市场网格匹配" +AOI_MARKET_FIELD = "所属市场网格" +RSRP_FIELD = "ssb_rsrp_dl" # 用于生成热力图的电信 RSRP 字段名。 +# EXCELLENT_CELL_FIELD = "mro_total_dl" # 用于生成用户量热力图的字段名,值越大越红。 +EXCELLENT_CELL_FIELD = "mro_total_dl" # 竟对信号筛选仍需使用的 5G 竟对总采样量字段。 +GRID_ID_FIELD = "grid20_id" # 4G/5G 用户量合并去重的唯一索引字段。 +WEAK_COVER_FIELD = "rsrp_lt_neg105_dl" # 用于生成信号差用户量热力图的字段名,值越大越红。 +MOBILE_TOTAL_FIELD = "mro_total_yd" # 移动采样点总数字段,用作移动弱覆盖比例分母。 +MOBILE_WEAK_COVER_FIELD = "rsrp_lt_neg105_yd" # 移动弱覆盖采样点字段,用作目标 Grid 筛选。 +MARKET_LAYER = None # 市场网格图层名;None 表示自动使用 GPKG 中第一个 feature 图层。 +GRID_5G_LAYER = None # 5G Grid 图层名;None 表示自动使用 GPKG 中第一个 feature 图层。 +# GRID_4G_LAYER = None # 4G Grid 图层名;None 表示自动使用 GPKG 中第一个 feature 图层。 +BUILDING_LAYER = None # Building 建筑指标图层名;None 表示自动使用 GPKG 中第一个 feature 图层。 +BUILDING_INFO_LAYER = None # BuildingInfo 建筑信息图层名;None 表示自动使用 GPKG 中第一个 feature 图层。 +MARKET_CODE_FIELD = "fid" # GridMap 市场网格唯一 ID 前缀字段。 +MARKET_NAME_FIELD = "Name" # GridMap 市场网格名称字段。 +MARKET_ID_SEPARATOR = "-" # 市场网格唯一 ID 拼接符,输出为 fid-name,例如 1-城区蓬江。 +BUILDING_INFO_OUTPUT_FILENAME = "BuildingInfo.gpkg" # 每个市场网格结果包内输出的建筑信息拆分文件名。 +CELL_DATA_OUTPUT_FILENAME = "CellData.gpkg" # 汇总结果包内的小区数据文件名。 +BUILDING_METRICS_CSV_FILENAME = "楼宇指标.csv" # 每个市场网格结果包内输出的楼宇指标 CSV 文件名。 +GRID_METRICS_CSV_FILENAME = "栅格指标.csv" # 每个市场网格结果包内输出的栅格指标 CSV 文件名。 +CSV_ENCODING = "gbk" # 指标 CSV 输出编码,供 Excel/传统 GIS 工具直接打开。 +CSV_SOURCE_FIELDS = ("area_type", "area_name", "longitude", "latitude", "mro_total_dl", "rsrp_lt_neg105_dl", "ssb_rsrp_dl", "ssb_rsrp_yd") # 指标 CSV 从源图层提取的字段。 +SIGNAL_BAD_THRESHOLD = -105.0 # 信号等级“较差”的阈值,小于等于该值输出较差。 +SIGNAL_NORMAL_THRESHOLD = -95.0 # 信号等级“一般/正常”的分界,大于该值输出正常。 +GIS_PROJECT_OUTPUT_FILENAME = "GIS.qgz" # 每个市场网格结果包内输出的 QGIS 项目文件名,画布范围按 BuildingInfo 自动更新。 +HEATMAP_SMOOTH_RADIUS = 10 # 热力图平滑半径,数值越大边界感越弱但细节越柔。 +HEATMAP_ALPHA = 191 # 热力图有效像元透明度;191 约等于 75% 不透明度。 +PROJECT_EXTENT_PADDING_RATIO = 0.05 # QGIS 打开后的画布留白比例;0.05 表示在 BuildingInfo 范围四周各增加 5%。 +# USER_COUNT_OUTPUT_FILENAME = "用户量.tif" # 采样点数量热力图输出文件名。 +USER_COUNT_OUTPUT_FILENAME = "用户量.tif" # 保留文件名,以移除旧模板中的用户量图层引用。 +COMPETITOR_SIGNAL_OUTPUT_FILENAME = "竟对信号.tif" # 移动非弱覆盖区域内的竟对 MR 弱覆盖/零采样信号图。 +COMPETITOR_SIGNAL_MOBILE_WEAK_RATIO_MAX = 20.0 # 移动弱覆盖比例必须严格小于该百分比。 +COMPETITOR_SIGNAL_WEAK_RATIO_MIN = 20.0 # 竟对 MR 弱覆盖比例必须严格大于该百分比。 +COMPETITOR_SIGNAL_RSRP_BREAKS = (-110.0, -104.0, -98.0, -92.0, -86.0, -80.0, -74.0) # 八档颜色的七个分界点。 +COMPETITOR_SIGNAL_RSRP_COLORS = ( + (253, 0, 5), # < -110,红色。 + (255, 138, 0), # [-110, -104),橙色。 + (254, 253, 2), # [-104, -98),黄色。 + (214, 251, 199), # [-98, -92),浅绿色。 + (42, 231, 41), # [-92, -86),亮绿色。 + (34, 174, 51), # [-86, -80),深绿色。 + (0, 149, 231), # [-80, -74),蓝色。 + (58, 14, 247), # [-74, 0],紫色。 +) +SUMMARY_OUTPUT_ENABLED = True # 是否额外生成全部市场网格汇总 TIF 结果包。 +# SUMMARY_OUTPUT_FILENAME = "全量网格图层.zip" # 汇总结果包文件名,包含两张 TIF、GIS.qgz、BuildingInfo.gpkg 和 CellData.gpkg。 +SUMMARY_OUTPUT_FILENAME = "全量网格图层.zip" # 包含竟对信号 TIF、GIS.qgz、BuildingInfo.gpkg 和 CellData.gpkg。 +LEGACY_SUMMARY_OUTPUT_FILENAME = "所有网格汇总.zip" # 旧汇总包文件名;新包成功生成后自动清理。 +SUMMARY_MARKET_CODE = "全量网格图层" # 汇总任务在日志和 summary.json 中使用的标识。 +SUMMARY_MAX_RASTER_PIXELS = 100_000_000 # 汇总 TIF 最大像元数;提高该值可增强清晰度,但会增加内存、耗时和文件体积。 +EXCELLENT_PERCENT_STEPS = (0.1, 0.4, 0.7) # 按最终有效像元降序分档:前 10% 红,其余三档各约 30%。 +EXCELLENT_COLORS = ( + (255, 0, 0), # 高值端,红色。 + (255, 255, 0), # 偏高值,黄色。 + (0, 112, 255), # 偏低值,蓝色。 + (0, 176, 80), # 低值端,绿色。 +) +PIXEL_WIDTH = None # 输出像元宽度;None 表示自动按 Grid 单元宽度估算。 +PIXEL_HEIGHT = None # 输出像元高度;None 表示自动按 Grid 单元高度估算。 +SCALE = 5.0 # 分辨率倍数;2.0 表示像元宽高减半,放大查看更清晰。 +SAMPLE_SIZE = 10000 # 自动估算像元大小时抽样读取的 Grid 要素数量。 +LIMIT = None # 限制处理前 N 个市场网格;None 表示处理全部市场网格。 +MAX_WORKERS = 4 # 市场网格并行处理进程数;当前 4 核/32GB 环境实测 4 进程吞吐最佳,内存较小时可降为 2。 +GEOMETRY_BATCH_SIZE = 10000 # Shapely 批量解析和空间判断的每批要素数;增大可减少循环,过大会增加瞬时内存。 +MAX_RASTER_PIXELS = 25_000_000 # 单张 TIF 最大像元数;超限时自动降低该市场分辨率,避免内存溢出。 +CLIP_MODE = "intersects" # 裁切方式:intersects 按几何相交裁切,center 按 Grid 中心点落入裁切。 +BUILDING_ALLOWED_SRS_IDS = (4326, 100000) # Building 允许的经纬度坐标系 ID;100000 是 CRS84。 +BUILDING_INFO_ALLOWED_SRS_IDS = (4326, 100000) # BuildingInfo 允许的经纬度坐标系 ID;100000 是源文件中的 CRS84。 +OVERWRITE = True # 输出文件已存在时是否覆盖。 +TRANSPARENT_PIXEL = (0, 0, 0, 0) # 无数据/背景像元颜色,RGBA 中 alpha=0 表示透明。 + +SELECTED_MARKET_IDS = None +STOP_FILE = None + + +class TaskCancelled(Exception): + """用户请求停止任务。""" + + +def check_cancelled(): + if STOP_FILE and Path(STOP_FILE).exists(): + raise TaskCancelled("任务已停止,已完成的成果保留。") + + +def apply_settings(settings): + """仅在任务独立进程及其子进程中应用配置。""" + for key, value in settings.items(): + if not key.isupper() or key not in globals(): + raise ValueError(f"未知出图配置:{key}") + if isinstance(globals()[key], Path): + value = Path(value) + globals()[key] = value + + +def snapshot(): + return {key: value for key, value in globals().items() if key.isupper()} diff --git a/marketgrid/files.py b/marketgrid/files.py new file mode 100644 index 0000000..dfe906d --- /dev/null +++ b/marketgrid/files.py @@ -0,0 +1,137 @@ +"""成果打包及文件操作。""" +from pathlib import Path +from time import sleep +import re +import shutil +import zipfile +from . import config + + +def safe_filename(value): + text = str(value or "").strip() + text = re.sub(r'[<>:"/\\|?*\s]+', "_", text) + text = text.strip("._") + return text or "unnamed" + + +def market_output_dir(output_dir, market): + return output_dir / safe_filename(market.code) + + +def market_zip_output_path(output_dir, market): + return output_dir / f"{safe_filename(market.code)}.zip" + + +def competitor_signal_raster_filename(): + return config.COMPETITOR_SIGNAL_OUTPUT_FILENAME + + +def zip_member_reference(zip_path, member_path): + return f"{zip_path.as_posix()}/{member_path.as_posix()}" + + +def rewrite_result_for_zip(result, zip_path, workspace_dir): + rewritten = dict(result) + rewritten.pop("market_dir", None) + rewritten["zip_output"] = zip_path.as_posix() + + output = rewritten.get("output") + if output: + output_path = Path(output) + try: + member_path = output_path.resolve().relative_to(workspace_dir.resolve()) + except ValueError: + member_path = Path(output_path.name) + rewritten["output"] = zip_member_reference(zip_path, member_path) + return rewritten + + +def write_market_zip(workspace_dir, zip_path, market): + if zip_path.exists(): + if not config.OVERWRITE: + return { + "market_code": market.code, + "market_name": market.name, + "output": zip_path.as_posix(), + "skipped": True, + } + + entries = sorted(path for path in workspace_dir.rglob("*") if path.is_file()) + temp_zip_path = zip_path.with_name(f".{zip_path.name}.tmp") + if temp_zip_path.exists(): + temp_zip_path.unlink() + try: + with zipfile.ZipFile(temp_zip_path, "w", compression=zipfile.ZIP_DEFLATED) as zip_file: + for path in entries: + zip_file.write(path, path.relative_to(workspace_dir).as_posix()) + replace_file_with_retry(temp_zip_path, zip_path) + except Exception: + if temp_zip_path.exists(): + temp_zip_path.unlink() + raise + + return { + "market_code": market.code, + "market_name": market.name, + "output": zip_path.as_posix(), + "entries": [path.relative_to(workspace_dir).as_posix() for path in entries], + "bytes": zip_path.stat().st_size, + "skipped": False, + } + + +def remove_legacy_market_dir(output_dir, market): + legacy_dir = market_output_dir(output_dir, market) + if not legacy_dir.exists() or not legacy_dir.is_dir(): + return None + + output_root = output_dir.resolve() + target = legacy_dir.resolve() + if output_root not in target.parents: + raise ValueError(f"拒绝删除输出目录之外的路径:{target}") + + shutil.rmtree(target) + return legacy_dir + + +def replace_file_with_retry(source_path, target_path, attempts=20, delay_seconds=0.5): + for attempt in range(attempts): + try: + source_path.replace(target_path) + return + except PermissionError: + if attempt == attempts - 1: + raise + sleep(delay_seconds) + + +def remove_file_with_retry(path, attempts=20, delay_seconds=0.5): + for attempt in range(attempts): + try: + path.unlink(missing_ok=True) + return + except PermissionError: + if attempt == attempts - 1: + raise + sleep(delay_seconds) + + +def copy_full_source_file(source_path, output_path, market): + if output_path.exists() and not config.OVERWRITE: + return { + "market_code": market.code, + "market_name": market.name, + "source": str(source_path), + "output": str(output_path), + "skipped": True, + } + shutil.copy2(source_path, output_path) + return { + "market_code": market.code, + "market_name": market.name, + "source": str(source_path), + "output": str(output_path), + "bytes": output_path.stat().st_size, + "copied_full_source": True, + "skipped": False, + } diff --git a/marketgrid/gpkg.py b/marketgrid/gpkg.py new file mode 100644 index 0000000..c7c513f --- /dev/null +++ b/marketgrid/gpkg.py @@ -0,0 +1,409 @@ +"""GeoPackage 读取、空间筛选与子集导出。""" +from contextlib import contextmanager +from pathlib import Path +from shapely import from_wkb +from shapely.errors import GEOSException +import numpy as np +import shapely +import sqlite3 +from . import config +from .models import LayerInfo +from .models import MarketFeature + + +def quote_identifier(name): + return '"' + str(name).replace('"', '""') + '"' + + +def build_summary_market(markets): + if not markets: + raise ValueError("至少需要一个市场网格才能生成汇总 TIF") + geometries = np.asarray([market.geometry for market in markets], dtype=object) + geometry = shapely.union_all(shapely.make_valid(geometries)) + if geometry.is_empty: + raise ValueError("市场网格合并结果为空,无法生成汇总 TIF") + return MarketFeature(0, config.SUMMARY_MARKET_CODE, config.SUMMARY_MARKET_CODE, geometry) + + +def gpkg_blob_to_wkb(blob): + data = bytes(blob) + if data[:2] != b"GP": + return data + + flags = data[3] + envelope_code = (flags >> 1) & 0b111 + envelope_sizes = { + 0: 0, + 1: 32, + 2: 48, + 3: 48, + 4: 64, + } + return data[8 + envelope_sizes.get(envelope_code, 0):] + + +def iter_geometry_batches(cursor, geom_index): + while True: + config.check_cancelled() + rows = cursor.fetchmany(config.GEOMETRY_BATCH_SIZE) + if not rows: + return + + wkbs = np.empty(len(rows), dtype=object) + for index, row in enumerate(rows): + geom_blob = row[geom_index] + wkbs[index] = gpkg_blob_to_wkb(geom_blob) if geom_blob is not None else None + geometries = from_wkb(wkbs, on_invalid="ignore") + valid_mask = ~shapely.is_missing(geometries) & ~shapely.is_empty(geometries) + yield rows, geometries, valid_mask + + +def gpkg_primary_key(conn, table_name): + for row in conn.execute(f"pragma table_info({quote_identifier(table_name)})"): + if row[5]: + return row[1] + return "fid" + + +def resolve_feature_layer(conn, preferred_table=None): + rows = conn.execute( + """ + select c.table_name, g.column_name, g.srs_id + from gpkg_contents c + join gpkg_geometry_columns g on c.table_name = g.table_name + where c.data_type = 'features' + order by c.table_name + """ + ).fetchall() + if not rows: + raise ValueError("未找到 GeoPackage feature 图层") + + if preferred_table: + for table_name, geom_col, srs_id in rows: + if table_name == preferred_table: + return LayerInfo(table_name, geom_col, gpkg_primary_key(conn, table_name), srs_id) + raise ValueError(f"未找到指定图层:{preferred_table}") + + table_name, geom_col, srs_id = rows[0] + return LayerInfo(table_name, geom_col, gpkg_primary_key(conn, table_name), srs_id) + + +def table_columns(conn, table_name): + return [row[1] for row in conn.execute(f"pragma table_info({quote_identifier(table_name)})")] + + +def require_columns(conn, table_name, columns): + available = set(table_columns(conn, table_name)) + missing = [column for column in columns if column not in available] + if missing: + raise ValueError(f"{table_name} 缺少字段:{', '.join(missing)}") + + +def rtree_name(conn, layer): + candidate = f"rtree_{layer.table_name}_{layer.geom_col}" + found = conn.execute( + "select 1 from sqlite_master where type='table' and name=?", + (candidate,), + ).fetchone() + if not found: + raise ValueError(f"未找到 RTree 空间索引:{candidate}") + return candidate + + +def table_exists(conn, table_name): + return conn.execute( + "select 1 from sqlite_master where type = 'table' and name = ?", + (table_name,), + ).fetchone() is not None + + +def sqlite_create_sql(conn, table_name): + row = conn.execute( + "select sql from sqlite_master where type = 'table' and name = ?", + (table_name,), + ).fetchone() + if not row or not row[0]: + raise ValueError(f"未找到表结构:{table_name}") + return row[0] + + +def copy_all_rows(source_conn, target_conn, table_name): + if not table_exists(source_conn, table_name): + return + + rows = source_conn.execute(f"select * from {quote_identifier(table_name)}").fetchall() + if not rows: + return + + placeholders = ", ".join(["?"] * len(rows[0])) + target_conn.executemany( + f"insert into {quote_identifier(table_name)} values ({placeholders})", + rows, + ) + + +def create_table_like_source(source_conn, target_conn, table_name): + if table_exists(source_conn, table_name): + target_conn.execute(sqlite_create_sql(source_conn, table_name)) + + +def copy_matching_rows(target_conn, table_name, columns, rows): + if not rows: + return + + column_sql = ", ".join(quote_identifier(column) for column in columns) + placeholders = ", ".join(["?"] * len(columns)) + target_conn.executemany( + f"insert into {quote_identifier(table_name)} ({column_sql}) values ({placeholders})", + rows, + ) + + +def copy_gpkg_support_tables(source_conn, target_conn, layer, feature_count, extent): + support_tables = [ + "gpkg_spatial_ref_sys", + "gpkg_contents", + "gpkg_geometry_columns", + "gpkg_ogr_contents", + "gpkg_extensions", + "gpkg_metadata", + "gpkg_metadata_reference", + "gpkg_tile_matrix_set", + "gpkg_tile_matrix", + "layer_styles", + ] + + for table_name in support_tables: + create_table_like_source(source_conn, target_conn, table_name) + + for table_name in support_tables: + copy_all_rows(source_conn, target_conn, table_name) + + minx, miny, maxx, maxy = extent if extent else (None, None, None, None) + target_conn.execute( + """ + update gpkg_contents + set min_x = ?, min_y = ?, max_x = ?, max_y = ? + where table_name = ? + """, + (minx, miny, maxx, maxy, layer.table_name), + ) + if table_exists(target_conn, "gpkg_ogr_contents"): + target_conn.execute( + "update gpkg_ogr_contents set feature_count = ? where table_name = ?", + (feature_count, layer.table_name), + ) + + +def initialize_split_output_gpkg(source_conn, output_path, layer, rtree, feature_count, extent): + if output_path.exists(): + if not config.OVERWRITE: + return None + output_path.unlink() + + target_conn = sqlite3.connect(output_path) + target_conn.execute("pragma foreign_keys = off") + target_conn.execute(f"pragma application_id = {source_conn.execute('pragma application_id').fetchone()[0]}") + target_conn.execute(f"pragma user_version = {source_conn.execute('pragma user_version').fetchone()[0]}") + copy_gpkg_support_tables(source_conn, target_conn, layer, feature_count, extent) + target_conn.execute(sqlite_create_sql(source_conn, layer.table_name)) + target_conn.execute(sqlite_create_sql(source_conn, rtree)) + return target_conn + + +def collect_intersecting_features(source_conn, layer, rtree, market): + table = quote_identifier(layer.table_name) + pk = quote_identifier(layer.pk_col) + rtree_table = quote_identifier(rtree) + columns = table_columns(source_conn, layer.table_name) + column_sql = ", ".join(f"b.{quote_identifier(column)}" for column in columns) + min_market_x, min_market_y, max_market_x, max_market_y = market.geometry.bounds + query = f""" + select {column_sql} + from {rtree_table} r + join {table} b on b.{pk} = r."id" + where r."minx" <= ? + and r."maxx" >= ? + and r."miny" <= ? + and r."maxy" >= ? + """ + + geom_index = columns.index(layer.geom_col) + pk_index = columns.index(layer.pk_col) + rows = [] + rtree_rows = [] + extent = None + candidates = 0 + + cursor = source_conn.execute(query, (max_market_x, min_market_x, max_market_y, min_market_y)) + for batch_rows, geometries, valid_mask in iter_geometry_batches(cursor, geom_index): + candidates += len(batch_rows) + intersects_mask = valid_mask & shapely.intersects(market.geometry, geometries) + matched_indexes = np.flatnonzero(intersects_mask) + if matched_indexes.size == 0: + continue + matched_bounds = shapely.bounds(geometries[matched_indexes]) + for index, bounds in zip(matched_indexes, matched_bounds): + row = batch_rows[int(index)] + minx, miny, maxx, maxy = bounds.tolist() + rows.append(row) + rtree_rows.append((row[pk_index], minx, maxx, miny, maxy)) + if extent is None: + extent = [minx, miny, maxx, maxy] + else: + extent[0] = min(extent[0], minx) + extent[1] = min(extent[1], miny) + extent[2] = max(extent[2], maxx) + extent[3] = max(extent[3], maxy) + + return columns, rows, rtree_rows, tuple(extent) if extent else None, candidates + + +def export_market_building_info_gpkg(source_conn, layer, rtree, market, output_path): + columns, rows, rtree_rows, extent, candidates = collect_intersecting_features( + source_conn, + layer, + rtree, + market, + ) + target_conn = initialize_split_output_gpkg(source_conn, output_path, layer, rtree, len(rows), extent) + if target_conn is None: + return { + "market_code": market.code, + "market_name": market.name, + "output": str(output_path), + "candidates": candidates, + "feature_count": None, + "extent": list(extent) if extent else None, + "skipped": True, + } + + try: + copy_matching_rows(target_conn, layer.table_name, columns, rows) + if rtree_rows: + target_conn.executemany( + f"insert into {quote_identifier(rtree)} values (?, ?, ?, ?, ?)", + rtree_rows, + ) + target_conn.commit() + finally: + target_conn.close() + + return { + "market_code": market.code, + "market_name": market.name, + "output": str(output_path), + "candidates": candidates, + "feature_count": len(rows), + "extent": list(extent) if extent else None, + "skipped": False, + } + + +def export_market_aoi_gpkg(source_conn, layer, rtree, market, output_path): + require_columns(source_conn, layer.table_name, [config.AOI_MARKET_FIELD, "AOI唯一标签", "AOI名称"]) + if layer.srs_id != 4326: + raise ValueError("AOI 图层必须使用 EPSG:4326") + table = quote_identifier(layer.table_name) + owner = quote_identifier(config.AOI_MARKET_FIELD) + pk = quote_identifier(layer.pk_col) + columns = table_columns(source_conn, layer.table_name) + rows = source_conn.execute(f"select * from {table} where {owner} = ? order by {pk}", (market.name,)).fetchall() + rtree_rows = source_conn.execute( + f"select r.* from {quote_identifier(rtree)} r join {table} a on a.{pk} = r.id " + f"where a.{owner} = ? order by r.id", (market.name,), + ).fetchall() + extent = None + if rtree_rows: + extent = (min(row[1] for row in rtree_rows), min(row[3] for row in rtree_rows), + max(row[2] for row in rtree_rows), max(row[4] for row in rtree_rows)) + srs_wkt = source_conn.execute("select definition from gpkg_spatial_ref_sys where srs_id = ?", (layer.srs_id,)).fetchone()[0] + result = { + "market_code": market.code, "market_name": market.name, "output": str(output_path), + "layer_name": layer.table_name, "feature_count": len(rows), "extent": list(extent) if extent else None, + "srs_wkt": srs_wkt, "match_field": config.AOI_MARKET_FIELD, "match_value": market.name, + } + target_conn = initialize_split_output_gpkg(source_conn, output_path, layer, rtree, len(rows), extent) + if target_conn is None: + return {**result, "skipped": True} + try: + copy_matching_rows(target_conn, layer.table_name, columns, rows) + target_conn.executemany(f"insert into {quote_identifier(rtree)} values (?, ?, ?, ?, ?)", rtree_rows) + target_conn.commit() + finally: + target_conn.close() + return {**result, "bytes": output_path.stat().st_size, "skipped": False} + + +def load_market_features(conn, layer, code_field, name_field): + require_columns(conn, layer.table_name, [code_field, name_field]) + table = quote_identifier(layer.table_name) + pk = quote_identifier(layer.pk_col) + geom = quote_identifier(layer.geom_col) + code = quote_identifier(code_field) + name = quote_identifier(name_field) + query = f"select {pk}, {code}, {name}, {geom} from {table} order by {pk}" + + features = [] + for fid, market_code, market_name, geom_blob in conn.execute(query): + if geom_blob is None: + continue + try: + geometry = from_wkb(gpkg_blob_to_wkb(geom_blob)) + except (GEOSException, ValueError): + continue + if not geometry.is_empty: + name = str(market_name or fid).strip() + code_prefix = str(market_code or fid).strip() + market_code_text = f"{code_prefix}{config.MARKET_ID_SEPARATOR}{name}" if name else code_prefix + features.append(MarketFeature(fid, market_code_text, name, geometry)) + return features + + +def estimate_pixel_size(conn, layer, sample_size): + table = quote_identifier(layer.table_name) + geom = quote_identifier(layer.geom_col) + widths = [] + heights = [] + query = f"select {geom} from {table} where {geom} is not null limit ?" + for (geom_blob,) in conn.execute(query, (sample_size,)): + try: + geometry = from_wkb(gpkg_blob_to_wkb(geom_blob)) + except (GEOSException, ValueError): + continue + minx, miny, maxx, maxy = geometry.bounds + width = maxx - minx + height = maxy - miny + if width > 0 and height > 0: + widths.append(width) + heights.append(height) + + if not widths or not heights: + raise ValueError("无法从 Grid 图层估算像元大小") + + return float(np.median(widths)), float(np.median(heights)) + + +@contextmanager +def open_read_connection(path): + conn = sqlite3.connect(Path(path).resolve().as_uri() + "?mode=ro", uri=True) + conn.execute("pragma query_only = on") + conn.execute("pragma temp_store = memory") + try: + yield conn + finally: + conn.close() + + +def gpkg_layer_extent(conn, layer): + row = conn.execute( + "select min_x, min_y, max_x, max_y from gpkg_contents where table_name = ?", + (layer.table_name,), + ).fetchone() + if row and all(value is not None for value in row): + return tuple(float(value) for value in row) + rtree = rtree_name(conn, layer) + row = conn.execute( + f"select min(minx), min(miny), max(maxx), max(maxy) from {quote_identifier(rtree)}" + ).fetchone() + return tuple(float(value) for value in row) if row and all(value is not None for value in row) else None diff --git a/marketgrid/jobs.py b/marketgrid/jobs.py new file mode 100644 index 0000000..203ec2f --- /dev/null +++ b/marketgrid/jobs.py @@ -0,0 +1,243 @@ +"""单市场与汇总成果生成。""" +from pathlib import Path +from time import perf_counter +import shutil +import tempfile +from . import config +from .gpkg import build_summary_market +from .files import competitor_signal_raster_filename +from .files import copy_full_source_file +from .qgis import copy_gis_project_to_market +from .gpkg import export_market_aoi_gpkg +from .gpkg import export_market_building_info_gpkg +from .competitor import export_market_grid_outputs +from .gpkg import gpkg_layer_extent +from .files import market_zip_output_path +from .gpkg import open_read_connection +from .files import remove_file_with_retry +from .files import remove_legacy_market_dir +from .gpkg import resolve_feature_layer +from .files import rewrite_result_for_zip +from .gpkg import rtree_name +from .files import safe_filename +from .files import write_market_zip + + +def process_market(market, pixel_width, pixel_height, output_dir): + config.check_cancelled() + started_at = perf_counter() + output_dir = Path(output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + zip_path = market_zip_output_path(output_dir, market) + if zip_path.exists() and not config.OVERWRITE: + return { + "market_fid": market.fid, + "market_code": market.code, + "market_name": market.name, + "zip_result": { + "market_code": market.code, + "market_name": market.name, + "output": zip_path.as_posix(), + "skipped": True, + }, + "elapsed_seconds": perf_counter() - started_at, + } + + with ( + 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.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) + 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) + building_info_rtree = rtree_name(building_info_conn, building_info_layer) + aoi_layer = resolve_feature_layer(aoi_conn, config.AOI_LAYER) + aoi_rtree = rtree_name(aoi_conn, aoi_layer) + + with tempfile.TemporaryDirectory(prefix=f"{safe_filename(market.code)}_") as temp_dir: + market_dir = Path(temp_dir) + gis_project_path = market_dir / config.GIS_PROJECT_OUTPUT_FILENAME + + # user_count_path = market_dir / excellent_heatmap_raster_filename(EXCELLENT_CELL_FIELD) + competitor_signal_path = market_dir / competitor_signal_raster_filename() + grid_started_at = perf_counter() + ( + # user_count_result, + competitor_signal_result, + _, + ) = export_market_grid_outputs( + grid_5g_conn, + grid_5g_layer, + grid_5g_rtree, + market, + pixel_width, + pixel_height, + # user_count_path, + competitor_signal_path, + None, + # (grid_4g_conn, grid_4g_layer, grid_4g_rtree), + ) + grid_elapsed = perf_counter() - grid_started_at + + building_info_path = market_dir / config.BUILDING_INFO_OUTPUT_FILENAME + building_started_at = perf_counter() + building_info_result = export_market_building_info_gpkg( + building_info_conn, + building_info_layer, + building_info_rtree, + market, + building_info_path, + ) + aoi_result = export_market_aoi_gpkg( + aoi_conn, aoi_layer, aoi_rtree, market, market_dir / config.AOI_OUTPUT_FILENAME, + ) + gis_project_result = copy_gis_project_to_market( + config.GIS_PROJECT_SOURCE, + gis_project_path, + market, + building_info_result["extent"], + competitor_signal_result["raster_extent"], + include_cell_data=False, + aoi_result=aoi_result, + ) + building_elapsed = perf_counter() - building_started_at + + zip_result = write_market_zip(market_dir, zip_path, market) + removed_legacy_dir = remove_legacy_market_dir(output_dir, market) + if removed_legacy_dir: + zip_result["removed_legacy_dir"] = str(removed_legacy_dir) + + return { + "market_fid": market.fid, + "market_code": market.code, + "market_name": market.name, + # "excellent_heatmap_result": rewrite_result_for_zip(user_count_result, zip_path, market_dir), + "competitor_signal_result": rewrite_result_for_zip( + competitor_signal_result, + zip_path, + market_dir, + ), + "building_info_result": rewrite_result_for_zip(building_info_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, + "timings": { + "grid_outputs_seconds": grid_elapsed, + "supporting_layers_seconds": building_elapsed, + }, + "elapsed_seconds": perf_counter() - started_at, + } + + +# def process_summary_grid_outputs(markets, pixel_width, pixel_height, output_dir, market_user_thresholds=None): +def process_summary_grid_outputs(markets, pixel_width, pixel_height, output_dir): + started_at = perf_counter() + output_dir = Path(output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + summary_market = build_summary_market(markets) + zip_path = output_dir / config.SUMMARY_OUTPUT_FILENAME + if zip_path.exists() and not config.OVERWRITE: + return { + "market_code": summary_market.code, + "zip_result": { + "market_code": summary_market.code, + "market_name": summary_market.name, + "output": zip_path.as_posix(), + "skipped": True, + }, + "skipped": True, + "elapsed_seconds": perf_counter() - started_at, + } + + with ( + open_read_connection(config.GRID_5G_GPKG) as grid_5g_conn, + # open_read_connection(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_4G_LAYER) + 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) + # user_count_path = summary_dir / excellent_heatmap_raster_filename(EXCELLENT_CELL_FIELD) + competitor_signal_path = summary_dir / competitor_signal_raster_filename() + ( + # _, # 原用户量结果 + competitor_signal_result, + _, + ) = export_market_grid_outputs( + grid_5g_conn, + grid_5g_layer, + grid_5g_rtree, + summary_market, + pixel_width, + pixel_height, + # None, # 原 user_count_path + competitor_signal_path, + None, + max_raster_pixels=config.SUMMARY_MAX_RASTER_PIXELS, + ) + # user_count_result = render_summary_user_count_by_market( + # ( + # ("5G", grid_5g_conn, grid_5g_layer, grid_5g_rtree), + # ("4G", grid_4g_conn, grid_4g_layer, grid_4g_rtree), + # ), + # markets, + # pixel_width, + # pixel_height, + # user_count_path, + # SUMMARY_MAX_RASTER_PIXELS, + # market_user_thresholds, + # ) + 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: + building_info_layer = resolve_feature_layer(building_info_conn, config.BUILDING_INFO_LAYER) + building_info_extent = gpkg_layer_extent(building_info_conn, building_info_layer) + building_info_result = { + "market_code": summary_market.code, + "market_name": summary_market.name, + "source": str(config.BUILDING_INFO_GPKG), + "output": str(building_info_path), + "extent": list(building_info_extent) if building_info_extent else None, + "bytes": building_info_path.stat().st_size, + "copied_full_source": True, + "skipped": False, + } + cell_data_path = summary_dir / config.CELL_DATA_OUTPUT_FILENAME + cell_data_result = copy_full_source_file( + config.CELL_DATA_GPKG, + cell_data_path, + summary_market, + ) + gis_project_path = summary_dir / config.GIS_PROJECT_OUTPUT_FILENAME + gis_project_result = copy_gis_project_to_market( + config.GIS_PROJECT_SOURCE, + gis_project_path, + summary_market, + building_info_extent, + competitor_signal_result["raster_extent"], + include_cell_data=True, + ) + zip_result = write_market_zip(summary_dir, zip_path, summary_market) + legacy_zip_path = output_dir / config.LEGACY_SUMMARY_OUTPUT_FILENAME + if legacy_zip_path != zip_path and legacy_zip_path.exists(): + remove_file_with_retry(legacy_zip_path) + return { + "market_code": summary_market.code, + # "excellent_heatmap_result": rewrite_result_for_zip(user_count_result, zip_path, summary_dir), + "competitor_signal_result": rewrite_result_for_zip( + competitor_signal_result, + zip_path, + summary_dir, + ), + "building_info_result": rewrite_result_for_zip(building_info_result, zip_path, summary_dir), + "cell_data_result": rewrite_result_for_zip(cell_data_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/legacy_user_count.py b/marketgrid/legacy_user_count.py new file mode 100644 index 0000000..2d86cf9 --- /dev/null +++ b/marketgrid/legacy_user_count.py @@ -0,0 +1,426 @@ +"""已停用用户量算法,保留恢复依据。""" +from shapely import Point +import numpy as np +import shapely +from . import config +from .gpkg import build_summary_market +from .gpkg import iter_geometry_batches +from .raster_math import market_raster_layout +from .raster_math import pixel_window_for_bounds +from .raster_math import pixel_window_from_point +from .gpkg import quote_identifier +from .raster_math import ranked_pixel_rgb_for_values +from .raster_math import ranked_pixel_rgb_for_values_with_thresholds +from .gpkg import require_columns +from .raster_math import smooth_rgb_inside_mask +from .raster_math import to_float +from .raster_math import write_rgba_geotiff + + +def excellent_heatmap_raster_filename(_field): + return config.USER_COUNT_OUTPUT_FILENAME + + +def render_ranked_raster( + state, + market, + output_path, + minx, + maxy, + pixel_width, + pixel_height, + width, + height, + candidates, + colors, + percent_steps, +): + image = np.full((height, width, 4), config.TRANSPARENT_PIXEL, dtype=np.uint8) + value_sum = state["value_sum"] + value_weight = state["value_weight"] + data_mask = value_weight > 0 + thresholds = [] + rank_pixel_counts = [] + if np.any(data_mask): + value_raster = np.zeros_like(value_sum) + np.divide(value_sum, value_weight, out=value_raster, where=data_mask) + ranked_rgb, thresholds, rank_pixel_counts = ranked_pixel_rgb_for_values( + value_raster, + data_mask, + colors, + percent_steps, + ) + smoothed_rgb = smooth_rgb_inside_mask(ranked_rgb, data_mask, config.HEATMAP_SMOOTH_RADIUS) + image[data_mask, :3] = smoothed_rgb[data_mask] + image[data_mask, 3] = config.HEATMAP_ALPHA + + write_rgba_geotiff(output_path, image, minx, maxy, pixel_width, pixel_height) + return { + "market_code": market.code, + "market_name": market.name, + "output": str(output_path), + "candidates": candidates, + "painted_cells": state["painted_cells"], + "data_pixels": int(np.count_nonzero(data_mask)), + "skipped_no_value": state["skipped_no_value"], + "threshold_value_count": int(np.count_nonzero(data_mask)), + "thresholds": thresholds, + "rank_pixel_counts": rank_pixel_counts, + "percent_steps": list(percent_steps), + "width": width, + "height": height, + "skipped": False, + } + + +def normalized_grid_id(value): + if value is None: + return None + if isinstance(value, bytes): + value = value.decode("utf-8", errors="replace") + normalized = str(value).strip() + return normalized or None + + +def merge_user_count_record(records, grid_id, window, value, source_name, prefer_geometry=False): + grid_id = normalized_grid_id(grid_id) + if grid_id is None: + return False + record = records.get(grid_id) + if record is None: + record = { + "window": window, + "value_sum": 0.0, + "has_value": False, + "sources": set(), + } + records[grid_id] = record + elif prefer_geometry: + record["window"] = window + record["sources"].add(source_name) + if value is not None: + record["value_sum"] += value + record["has_value"] = True + return True + + +def collect_user_count_source( + records, + conn, + layer, + rtree, + market, + minx, + maxy, + pixel_width, + pixel_height, + width, + height, + source_name, + prefer_geometry=False, +): + fields = [config.GRID_ID_FIELD, config.EXCELLENT_CELL_FIELD] + if config.CLIP_MODE == "center": + fields.extend(("longitude", "latitude")) + require_columns(conn, layer.table_name, fields) + table = quote_identifier(layer.table_name) + pk = quote_identifier(layer.pk_col) + geom = quote_identifier(layer.geom_col) + rtree_table = quote_identifier(rtree) + field_sql = ", ".join(f"b.{quote_identifier(field)}" for field in fields) + query = f""" + select b.{pk}, b.{geom}, {field_sql} + from {rtree_table} r + join {table} b on b.{pk} = r."id" + where r."minx" <= ? + and r."maxx" >= ? + and r."miny" <= ? + and r."maxy" >= ? + """ + market_minx, market_miny, market_maxx, market_maxy = market.geometry.bounds + params = (market_maxx, market_minx, market_maxy, market_miny) + candidates = 0 + clipped_rows = 0 + invalid_grid_ids = 0 + try: + shapely.prepare(market.geometry) + cursor = conn.execute(query, params) + for batch_rows, geometries, valid_mask in iter_geometry_batches(cursor, 1): + candidates += len(batch_rows) + intersects_mask = valid_mask & shapely.intersects(market.geometry, geometries) + geometry_bounds = shapely.bounds(geometries) + for index, row in enumerate(batch_rows): + if not valid_mask[index]: + continue + values = dict(zip(fields, row[2:])) + if config.CLIP_MODE == "intersects": + if not bool(intersects_mask[index]): + continue + window = pixel_window_for_bounds( + geometry_bounds[index], + minx, + maxy, + pixel_width, + pixel_height, + width, + height, + ) + else: + lon = to_float(values.get("longitude")) + lat = to_float(values.get("latitude")) + if lon is None or lat is None or not market.geometry.covers(Point(lon, lat)): + continue + window = pixel_window_from_point( + lon, + lat, + minx, + maxy, + pixel_width, + pixel_height, + width, + height, + ) + if window is None: + continue + clipped_rows += 1 + if not merge_user_count_record( + records, + values.get(config.GRID_ID_FIELD), + window, + to_float(values.get(config.EXCELLENT_CELL_FIELD)), + source_name, + prefer_geometry, + ): + invalid_grid_ids += 1 + finally: + shapely.destroy_prepared(market.geometry) + return { + "candidates": candidates, + "clipped_rows": clipped_rows, + "invalid_grid_ids": invalid_grid_ids, + } + + +def build_merged_user_count_state(records, height, width, row_offset=0, col_offset=0): + value_sum = np.zeros((height, width), dtype=np.float32) + value_weight = np.zeros((height, width), dtype=np.uint16) + painted_cells = 0 + skipped_no_value = 0 + for record in records.values(): + if not record["has_value"]: + skipped_no_value += 1 + continue + row_start, row_stop, col_start, col_stop = record["window"] + row_start -= row_offset + row_stop -= row_offset + col_start -= col_offset + col_stop -= col_offset + value_sum[row_start:row_stop, col_start:col_stop] += record["value_sum"] + value_weight[row_start:row_stop, col_start:col_stop] += 1 + painted_cells += 1 + return { + "value_sum": value_sum, + "value_weight": value_weight, + "painted_cells": painted_cells, + "skipped_no_value": skipped_no_value, + } + + +def render_merged_user_count_records(records, canvas_height, canvas_width, thresholds=None): + valid_records = [record for record in records.values() if record["has_value"]] + if not valid_records: + empty_mask = np.zeros((0, 0), dtype=bool) + empty_rgb = np.zeros((0, 0, 3), dtype=np.uint8) + return { + "window": (0, 0, 0, 0), + "data_mask": empty_mask, + "rgb": empty_rgb, + "thresholds": [], + "rank_pixel_counts": [], + "painted_cells": 0, + "skipped_no_value": len(records), + } + + row_start = min(record["window"][0] for record in valid_records) + row_stop = max(record["window"][1] for record in valid_records) + col_start = min(record["window"][2] for record in valid_records) + col_stop = max(record["window"][3] for record in valid_records) + padding = config.HEATMAP_SMOOTH_RADIUS + row_start = max(0, row_start - padding) + row_stop = min(canvas_height, row_stop + padding) + col_start = max(0, col_start - padding) + col_stop = min(canvas_width, col_stop + padding) + + state = build_merged_user_count_state( + records, + row_stop - row_start, + col_stop - col_start, + row_offset=row_start, + col_offset=col_start, + ) + value_sum = state["value_sum"] + value_weight = state["value_weight"] + data_mask = value_weight > 0 + value_raster = np.zeros_like(value_sum) + np.divide(value_sum, value_weight, out=value_raster, where=data_mask) + if thresholds: + ranked_rgb, rank_pixel_counts = ranked_pixel_rgb_for_values_with_thresholds( + value_raster, + data_mask, + config.EXCELLENT_COLORS, + thresholds, + ) + applied_thresholds = [float(value) for value in thresholds] + else: + ranked_rgb, applied_thresholds, rank_pixel_counts = ranked_pixel_rgb_for_values( + value_raster, + data_mask, + config.EXCELLENT_COLORS, + config.EXCELLENT_PERCENT_STEPS, + ) + smoothed_rgb = smooth_rgb_inside_mask(ranked_rgb, data_mask, config.HEATMAP_SMOOTH_RADIUS) + return { + "window": (row_start, row_stop, col_start, col_stop), + "data_mask": data_mask, + "rgb": smoothed_rgb, + "thresholds": applied_thresholds, + "rank_pixel_counts": rank_pixel_counts, + "painted_cells": state["painted_cells"], + "skipped_no_value": state["skipped_no_value"], + } + + +def merged_user_count_metadata(records, source_stats): + shared_grids = 0 + five_g_only_grids = 0 + four_g_only_grids = 0 + for record in records.values(): + sources = record["sources"] + if sources == {"5G", "4G"}: + shared_grids += 1 + elif "5G" in sources: + five_g_only_grids += 1 + elif "4G" in sources: + four_g_only_grids += 1 + return { + "data_source_mode": "Grid_5G + Grid_4G sum by grid20_id", + "grid_id_field": config.GRID_ID_FIELD, + "value_field": config.EXCELLENT_CELL_FIELD, + "merge_rule": "union grid20_id; sum mro_total_dl for duplicate ids", + "merged_grid_count": len(records), + "shared_grid_count": shared_grids, + "five_g_only_grid_count": five_g_only_grids, + "four_g_only_grid_count": four_g_only_grids, + "source_stats": source_stats, + } + + +def render_summary_user_count_by_market( + grid_sources, + markets, + pixel_width, + pixel_height, + output_path, + max_raster_pixels, + market_thresholds=None, +): + summary_market = build_summary_market(markets) + minx, miny, maxx, maxy, pixel_width, pixel_height, width, height, scale_factor = market_raster_layout( + summary_market.geometry.bounds, + pixel_width, + pixel_height, + max_raster_pixels, + ) + image = np.full((height, width, 4), config.TRANSPARENT_PIXEL, dtype=np.uint8) + market_results = [] + total_candidates = 0 + total_painted_cells = 0 + total_skipped_no_value = 0 + for market in markets: + records = {} + source_stats = {} + for source_name, conn, layer, rtree in grid_sources: + source_stats[source_name] = collect_user_count_source( + records, + conn, + layer, + rtree, + market, + minx, + maxy, + pixel_width, + pixel_height, + width, + height, + source_name, + prefer_geometry=source_name == "5G", + ) + candidates = sum(stats["candidates"] for stats in source_stats.values()) + render_result = render_merged_user_count_records( + records, + height, + width, + (market_thresholds or {}).get(market.code), + ) + painted_cells = render_result["painted_cells"] + skipped_no_value = render_result["skipped_no_value"] + data_mask = render_result["data_mask"] + thresholds = render_result["thresholds"] + rank_pixel_counts = render_result["rank_pixel_counts"] + data_pixels = int(np.count_nonzero(data_mask)) + if data_pixels: + row_start, row_stop, col_start, col_stop = render_result["window"] + target = image[row_start:row_stop, col_start:col_stop] + target[data_mask, :3] = render_result["rgb"][data_mask] + target[data_mask, 3] = config.HEATMAP_ALPHA + + total_candidates += candidates + total_painted_cells += painted_cells + total_skipped_no_value += skipped_no_value + market_result = { + "market_code": market.code, + "market_name": market.name, + "candidates": candidates, + "painted_cells": painted_cells, + "data_pixels": data_pixels, + "skipped_no_value": skipped_no_value, + "thresholds": thresholds, + "threshold_source": "market_zip" if (market_thresholds or {}).get(market.code) else "summary_raster", + "rank_pixel_counts": rank_pixel_counts, + "render_window": list(render_result["window"]), + "render_buffer_pixels": int(data_mask.size), + } + market_result.update(merged_user_count_metadata(records, source_stats)) + market_results.append(market_result) + + write_rgba_geotiff(output_path, image, minx, maxy, pixel_width, pixel_height) + return { + "market_code": summary_market.code, + "market_name": summary_market.name, + "output": str(output_path), + "candidates": total_candidates, + "painted_cells": total_painted_cells, + "data_pixels": int(np.count_nonzero(image[..., 3])), + "skipped_no_value": total_skipped_no_value, + "threshold_value_count": int(np.count_nonzero(image[..., 3])), + "thresholds": None, + "rank_pixel_counts": None, + "percent_steps": list(config.EXCELLENT_PERCENT_STEPS), + "color_scope": "per_market", + "threshold_source": "market_zip", + "render_scope": "market_local_window", + "render_padding_pixels": config.HEATMAP_SMOOTH_RADIUS, + "market_results": market_results, + "width": width, + "height": height, + "raster_extent": [ + minx, + maxy - height * pixel_height, + minx + width * pixel_width, + maxy, + ], + "pixel_width": pixel_width, + "pixel_height": pixel_height, + "resolution_scale_factor": scale_factor, + "skipped": False, + } diff --git a/marketgrid/legends.py b/marketgrid/legends.py new file mode 100644 index 0000000..5c7e71e --- /dev/null +++ b/marketgrid/legends.py @@ -0,0 +1,48 @@ +"""专题图例导出。""" +import csv +from . import config + + +def write_excellent_heatmap_legend(output_dir, field): + legend_path = output_dir / "excellent_heatmap_legend.csv" + with legend_path.open("w", newline="", encoding="utf-8-sig") as file: + writer = csv.writer(file) + writer.writerow(["field", "rank_range", "red", "green", "blue", "alpha", "meaning"]) + rank_ranges = ("top_10_percent", "10_to_40_percent", "40_to_70_percent", "bottom_30_percent") + for rank_range, color in zip(rank_ranges, config.EXCELLENT_COLORS): + writer.writerow([field, rank_range, *color, config.HEATMAP_ALPHA, "ranked-pixel distribution"]) + writer.writerow([field, "nodata", 0, 0, 0, 0, "transparent no data"]) + return legend_path + + +def write_competitor_signal_legend(output_dir): + legend_path = output_dir / "competitor_signal_legend.csv" + with legend_path.open("w", newline="", encoding="utf-8-sig") as file: + writer = csv.writer(file) + writer.writerow(["field", "rule_or_rsrp_range", "red", "green", "blue", "alpha", "filter"]) + competitor_filter = ( + f"{config.MOBILE_WEAK_COVER_FIELD}/{config.MOBILE_TOTAL_FIELD} < {config.COMPETITOR_SIGNAL_MOBILE_WEAK_RATIO_MAX}%" + f" and ({config.EXCELLENT_CELL_FIELD} = 0" + f" or {config.WEAK_COVER_FIELD}/{config.EXCELLENT_CELL_FIELD} > {config.COMPETITOR_SIGNAL_WEAK_RATIO_MIN}%)" + ) + writer.writerow([ + config.EXCELLENT_CELL_FIELD, + "= 0", + *config.COMPETITOR_SIGNAL_RSRP_COLORS[0], + config.HEATMAP_ALPHA, + competitor_filter, + ]) + ranges = ( + "< -110", + "[-110, -104)", + "[-104, -98)", + "[-98, -92)", + "[-92, -86)", + "[-86, -80)", + "[-80, -74)", + "[-74, 0]", + ) + for value_range, color in zip(ranges, config.COMPETITOR_SIGNAL_RSRP_COLORS): + writer.writerow([config.RSRP_FIELD, value_range, *color, config.HEATMAP_ALPHA, competitor_filter]) + writer.writerow([config.RSRP_FIELD, "not_eligible_or_invalid", 0, 0, 0, 0, competitor_filter]) + return legend_path diff --git a/marketgrid/metrics.py b/marketgrid/metrics.py new file mode 100644 index 0000000..7724823 --- /dev/null +++ b/marketgrid/metrics.py @@ -0,0 +1,250 @@ +"""保留的指标导出算法。""" +from shapely import STRtree +from shapely.errors import GEOSException +import csv +import numpy as np +import shapely +from . import config +from .gpkg import iter_geometry_batches +from .gpkg import quote_identifier +from .gpkg import require_columns +from .raster_math import to_float + + +def csv_text(value): + if value is None: + return "" + return str(value).strip() + + +def signal_level(value): + number = to_float(value) + if number is None: + return "无采集信息" + if number <= config.SIGNAL_BAD_THRESHOLD: + return "较差" + if number <= config.SIGNAL_NORMAL_THRESHOLD: + return "一般" + return "正常" + + +def collect_intersecting_metric_features(source_conn, layer, rtree, market, fields): + require_columns(source_conn, layer.table_name, fields) + table = quote_identifier(layer.table_name) + pk = quote_identifier(layer.pk_col) + geom = quote_identifier(layer.geom_col) + rtree_table = quote_identifier(rtree) + field_sql = ", ".join(f"b.{quote_identifier(field)}" for field in fields) + min_market_x, min_market_y, max_market_x, max_market_y = market.geometry.bounds + query = f""" + select b.{pk}, b.{geom}, {field_sql} + from {rtree_table} r + join {table} b on b.{pk} = r."id" + where r."minx" <= ? + and r."maxx" >= ? + and r."miny" <= ? + and r."maxy" >= ? + """ + + rows = [] + candidates = 0 + cursor = source_conn.execute(query, (max_market_x, min_market_x, max_market_y, min_market_y)) + for batch_rows, geometries, valid_mask in iter_geometry_batches(cursor, 1): + candidates += len(batch_rows) + intersects_mask = valid_mask & shapely.intersects(market.geometry, geometries) + for index in np.flatnonzero(intersects_mask): + row = batch_rows[int(index)] + rows.append((dict(zip(fields, row[2:])), geometries[index])) + + return rows, candidates + + +def load_building_name_index(building_info_conn, layer, rtree, bounds): + geometries = [] + names = [] + if bounds is None: + return None + table = quote_identifier(layer.table_name) + geom = quote_identifier(layer.geom_col) + pk = quote_identifier(layer.pk_col) + rtree_table = quote_identifier(rtree) + minx, miny, maxx, maxy = bounds + query = f""" + select b."name", b.{geom} + from {rtree_table} r + join {table} b on b.{pk} = r."id" + where r."minx" <= ? + and r."maxx" >= ? + and r."miny" <= ? + and r."maxy" >= ? + order by b.{pk} + """ + cursor = building_info_conn.execute(query, (maxx, minx, maxy, miny)) + for batch_rows, batch_geometries, valid_mask in iter_geometry_batches(cursor, 1): + for index in np.flatnonzero(valid_mask): + name = csv_text(batch_rows[int(index)][0]) + if not name: + continue + geometries.append(batch_geometries[index]) + names.append(name) + if not geometries: + return None + return STRtree(geometries), geometries, names + + +def match_building_info_name(name_index, geometry): + if name_index is None: + return "" + tree, geometries, names = name_index + best_name = "" + best_score = -1.0 + for candidate_index in tree.query(geometry, predicate="intersects"): + index = int(candidate_index) + info_geometry = geometries[index] + try: + score = geometry.intersection(info_geometry).area + except GEOSException: + score = 0.0 + if score > best_score: + best_name = names[index] + best_score = score + + return best_name + + +def match_building_info_names(name_index, building_geometries): + if name_index is None or not building_geometries: + return [""] * len(building_geometries) + + tree, info_geometries, names = name_index + building_array = np.asarray(building_geometries, dtype=object) + info_array = np.asarray(info_geometries, dtype=object) + pairs = tree.query(building_array, predicate="intersects") + if pairs.shape[1] == 0: + return [""] * len(building_geometries) + + result = np.full(len(building_geometries), "", dtype=object) + names_array = np.asarray(names, dtype=object) + match_counts = np.bincount(pairs[0], minlength=len(building_geometries)) + single_pair_mask = match_counts[pairs[0]] == 1 + single_pairs = pairs[:, single_pair_mask] + result[single_pairs[0]] = names_array[single_pairs[1]] + + multiple_pairs = pairs[:, ~single_pair_mask] + if multiple_pairs.shape[1]: + try: + areas = shapely.area( + shapely.intersection( + building_array[multiple_pairs[0]], + info_array[multiple_pairs[1]], + ) + ) + except GEOSException: + return [match_building_info_name(name_index, geometry) for geometry in building_geometries] + + pair_positions = np.arange(multiple_pairs.shape[1]) + order = np.lexsort((pair_positions, -areas, multiple_pairs[0])) + ordered_sources = multiple_pairs[0][order] + _, first_positions = np.unique(ordered_sources, return_index=True) + best_pair_positions = order[first_positions] + result[multiple_pairs[0, best_pair_positions]] = names_array[multiple_pairs[1, best_pair_positions]] + + return result.tolist() + + +def write_metric_csv(output_path, headers, rows): + if output_path.exists() and not config.OVERWRITE: + return True + with output_path.open("w", newline="", encoding=config.CSV_ENCODING, errors="replace") as file: + writer = csv.writer(file) + writer.writerow(headers) + writer.writerows(rows) + return False + + +def metric_row(values): + return [ + csv_text(values.get("area_type")), + csv_text(values.get("area_name")), + csv_text(values.get("longitude")), + csv_text(values.get("latitude")), + csv_text(values.get("mro_total_dl")), + csv_text(values.get("rsrp_lt_neg105_dl")), + csv_text(values.get("ssb_rsrp_dl")), + signal_level(values.get("ssb_rsrp_yd")), + signal_level(values.get("ssb_rsrp_dl")), + ] + + +def export_market_building_metrics_csv( + building_conn, + building_layer, + building_rtree, + building_info_conn, + building_info_layer, + building_info_rtree, + market, + output_path, +): + rows, candidates = collect_intersecting_metric_features( + building_conn, + building_layer, + building_rtree, + market, + config.CSV_SOURCE_FIELDS, + ) + building_geometries = [geometry for _values, geometry in rows] + building_bounds = shapely.total_bounds(building_geometries) if building_geometries else None + building_name_index = load_building_name_index( + building_info_conn, + building_info_layer, + building_info_rtree, + building_bounds, + ) + headers = [ + "网格ID", + "区域类型", + "区域名称", + "建筑名称", + "经度", + "纬度", + "竟对采样点总", + "竟对弱覆盖采样点", + "竟对平均信号值", + "移动信号", + "竟对信号", + ] + csv_rows = [] + matched_names = 0 + building_names = match_building_info_names(building_name_index, building_geometries) + for (values, _geometry), building_name in zip(rows, building_names): + if building_name: + matched_names += 1 + common_row = metric_row(values) + csv_rows.append([market.code, common_row[0], common_row[1], building_name, *common_row[2:]]) + + skipped = write_metric_csv(output_path, headers, csv_rows) + return { + "market_code": market.code, + "market_name": market.name, + "output": str(output_path), + "candidates": candidates, + "row_count": len(csv_rows), + "matched_names": matched_names, + "skipped": skipped, + } + + +def grid_metrics_headers(): + return [ + "网格ID", + "区域类型", + "区域名称", + "经度", + "纬度", + "竟对采样点总", + "竟对弱覆盖采样点", + "竟对平均信号值", + "移动信号", + "竟对信号", + ] diff --git a/marketgrid/models.py b/marketgrid/models.py new file mode 100644 index 0000000..5214a94 --- /dev/null +++ b/marketgrid/models.py @@ -0,0 +1,18 @@ +"""空间数据结构。""" +from dataclasses import dataclass + + +@dataclass(frozen=True) +class LayerInfo: + table_name: str + geom_col: str + pk_col: str + srs_id: int + + +@dataclass(frozen=True) +class MarketFeature: + fid: int + code: str + name: str + geometry: object diff --git a/marketgrid/pipeline.py b/marketgrid/pipeline.py new file mode 100644 index 0000000..df355b9 --- /dev/null +++ b/marketgrid/pipeline.py @@ -0,0 +1,284 @@ +"""完整出图流程与并行调度。""" +from concurrent.futures import ProcessPoolExecutor, as_completed +from time import perf_counter +import json +from . import config +from .gpkg import estimate_pixel_size +from .gpkg import load_market_features +from .gpkg import open_read_connection +from .gpkg import require_columns +from .gpkg import resolve_feature_layer +from .gpkg import rtree_name +from .legends import write_competitor_signal_legend + + +from .jobs import process_market, process_summary_grid_outputs + + +def main(settings=None, progress=None): + if settings: + config.apply_settings(settings) + config.check_cancelled() + if config.SCALE <= 0: + raise ValueError("SCALE 必须大于 0") + if config.MAX_WORKERS <= 0: + raise ValueError("MAX_WORKERS 必须大于 0") + if config.GEOMETRY_BATCH_SIZE <= 0: + raise ValueError("GEOMETRY_BATCH_SIZE 必须大于 0") + if config.PROJECT_EXTENT_PADDING_RATIO < 0: + raise ValueError("PROJECT_EXTENT_PADDING_RATIO 不能小于 0") + # validate_smoothing_radius("HEATMAP_SMOOTH_RADIUS", HEATMAP_SMOOTH_RADIUS) + if not 0 <= config.COMPETITOR_SIGNAL_MOBILE_WEAK_RATIO_MAX <= 100: + raise ValueError("COMPETITOR_SIGNAL_MOBILE_WEAK_RATIO_MAX 必须在 0 到 100 之间") + if not 0 <= config.COMPETITOR_SIGNAL_WEAK_RATIO_MIN <= 100: + raise ValueError("COMPETITOR_SIGNAL_WEAK_RATIO_MIN 必须在 0 到 100 之间") + if len(config.COMPETITOR_SIGNAL_RSRP_COLORS) != len(config.COMPETITOR_SIGNAL_RSRP_BREAKS) + 1: + raise ValueError("竟对信号 RSRP 颜色数量必须比分界点数量多 1") + if any( + left >= right + for left, right in zip( + config.COMPETITOR_SIGNAL_RSRP_BREAKS, + config.COMPETITOR_SIGNAL_RSRP_BREAKS[1:], + ) + ): + raise ValueError("COMPETITOR_SIGNAL_RSRP_BREAKS 必须严格递增") + if config.MAX_RASTER_PIXELS is not None and config.MAX_RASTER_PIXELS <= 0: + raise ValueError("MAX_RASTER_PIXELS 必须大于 0 或设置为 None") + if config.SUMMARY_MAX_RASTER_PIXELS is None or config.SUMMARY_MAX_RASTER_PIXELS <= 0: + raise ValueError("SUMMARY_MAX_RASTER_PIXELS 必须大于 0") + if config.CLIP_MODE not in {"intersects", "center"}: + raise ValueError("CLIP_MODE 必须是 intersects 或 center") + required_files = ( + config.MARKET_GPKG, + config.GRID_5G_GPKG, + # GRID_4G_GPKG, + config.BUILDING_INFO_GPKG, + config.GIS_PROJECT_SOURCE, + config.AOI_GPKG, + ) + if config.SUMMARY_OUTPUT_ENABLED: + required_files += (config.CELL_DATA_GPKG,) + missing_files = [str(path) for path in required_files if not path.is_file()] + if missing_files: + raise FileNotFoundError(f"缺少输入文件:{', '.join(missing_files)}") + + config.OUTPUT_DIR.mkdir(parents=True, exist_ok=True) + with ( + open_read_connection(config.MARKET_GPKG) as market_conn, + 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, + ): + market_layer = resolve_feature_layer(market_conn, config.MARKET_LAYER) + 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) + building_info_layer = resolve_feature_layer(building_info_conn, config.BUILDING_INFO_LAYER) + if ( + market_layer.srs_id != 4326 + or grid_5g_layer.srs_id != 4326 + # or grid_4g_layer.srs_id != 4326 + ): + raise ValueError("当前脚本只处理 EPSG:4326 的输入图层") + if building_info_layer.srs_id not in config.BUILDING_INFO_ALLOWED_SRS_IDS: + raise ValueError(f"BuildingInfo 图层坐标系不在允许范围内:{building_info_layer.srs_id}") + + require_columns( + grid_5g_conn, + grid_5g_layer.table_name, + # (*CSV_SOURCE_FIELDS, MOBILE_TOTAL_FIELD, MOBILE_WEAK_COVER_FIELD, GRID_ID_FIELD), + (*config.CSV_SOURCE_FIELDS, config.MOBILE_TOTAL_FIELD, config.MOBILE_WEAK_COVER_FIELD), + ) + # grid_4g_required_fields = [GRID_ID_FIELD, EXCELLENT_CELL_FIELD] + # if CLIP_MODE == "center": + # grid_4g_required_fields.extend(("longitude", "latitude")) + # require_columns(grid_4g_conn, grid_4g_layer.table_name, grid_4g_required_fields) + require_columns(building_info_conn, building_info_layer.table_name, ["name"]) + rtree_name(grid_5g_conn, grid_5g_layer) + # rtree_name(grid_4g_conn, grid_4g_layer) + rtree_name(building_info_conn, building_info_layer) + pixel_width = config.PIXEL_WIDTH + pixel_height = config.PIXEL_HEIGHT + if pixel_width is None or pixel_height is None: + estimated_width, estimated_height = estimate_pixel_size( + grid_5g_conn, + grid_5g_layer, + config.SAMPLE_SIZE, + ) + pixel_width = pixel_width or estimated_width + pixel_height = pixel_height or estimated_height + pixel_width = pixel_width / config.SCALE + pixel_height = pixel_height / config.SCALE + + markets = load_market_features( + market_conn, + market_layer, + config.MARKET_CODE_FIELD, + config.MARKET_NAME_FIELD, + ) + if config.SELECTED_MARKET_IDS is not None: + selected = set(config.SELECTED_MARKET_IDS) + markets = [market for market in markets if market.fid in selected] + if not markets: + raise ValueError("没有可处理的市场网格,请检查市场选择和输入几何。") + if config.LIMIT: + markets = markets[:config.LIMIT] + layer_names = { + "grid_5g": grid_5g_layer.table_name, + # "grid_4g": grid_4g_layer.table_name, + "building_info": building_info_layer.table_name, + } + + # excellent_legend_path = write_excellent_heatmap_legend(OUTPUT_DIR, EXCELLENT_CELL_FIELD) + competitor_signal_legend_path = write_competitor_signal_legend(config.OUTPUT_DIR) + worker_count = max(1, min(config.MAX_WORKERS, len(markets))) if markets else 1 + print(f"市场网格数量:{len(markets)}") + print(f"并行进程数:{worker_count}") + print(f"5G Grid 图层:{layer_names['grid_5g']}") + # print(f"4G Grid 图层:{layer_names['grid_4g']}") + print(f"BuildingInfo 图层:{layer_names['building_info']}") + print(f"像元大小:{pixel_width}, {pixel_height}") + # print(f"用户量图例:{excellent_legend_path}") + print(f"竟对信号图例:{competitor_signal_legend_path}") + + started_at = perf_counter() + outcomes = [] + total_steps = len(markets) + int(config.SUMMARY_OUTPUT_ENABLED) + if progress: + progress(0, total_steps, "开始处理市场网格") + if worker_count == 1: + for index, market in enumerate(markets, start=1): + outcome = process_market(market, pixel_width, pixel_height, config.OUTPUT_DIR) + outcomes.append(outcome) + if progress: + progress(index, total_steps, f"已完成 {market.name}") + config.check_cancelled() + scale_factor = outcome.get("competitor_signal_result", {}).get("resolution_scale_factor", 1.0) + resolution_note = f",分辨率自动调整 x{scale_factor:.2f}" if scale_factor > 1.001 else "" + print( + f"[{index}/{len(markets)}] 完成 {market.code}," + f"耗时 {outcome['elapsed_seconds']:.1f} 秒{resolution_note}" + ) + else: + with ProcessPoolExecutor(max_workers=worker_count, initializer=config.apply_settings, + initargs=(config.snapshot(),)) as executor: + future_markets = { + executor.submit(process_market, market, pixel_width, pixel_height, config.OUTPUT_DIR): market + for market in markets + } + completed = 0 + for future in as_completed(future_markets): + market = future_markets[future] + try: + outcome = future.result() + except config.TaskCancelled: + for pending in future_markets: + pending.cancel() + raise + except Exception as error: + raise RuntimeError(f"市场网格处理失败:{market.code}") from error + outcomes.append(outcome) + completed += 1 + if progress: + progress(completed, total_steps, f"已完成 {market.name}") + config.check_cancelled() + scale_factor = outcome.get("competitor_signal_result", {}).get("resolution_scale_factor", 1.0) + resolution_note = f",分辨率自动调整 x{scale_factor:.2f}" if scale_factor > 1.001 else "" + print( + f"[{completed}/{len(markets)}] 完成 {market.code}," + f"耗时 {outcome['elapsed_seconds']:.1f} 秒{resolution_note}" + ) + + outcomes.sort(key=lambda item: item["market_fid"]) + summary_grid_result = None + if config.SUMMARY_OUTPUT_ENABLED and markets: + config.check_cancelled() + if progress: + progress(len(markets), total_steps, "正在生成全量汇总包") + print("开始生成全部市场网格汇总 TIF……") + # market_user_thresholds = { + # outcome["market_code"]: outcome["excellent_heatmap_result"].get("thresholds") + # for outcome in outcomes + # if outcome.get("excellent_heatmap_result") + # } + summary_grid_result = process_summary_grid_outputs( + markets, + pixel_width, + pixel_height, + config.OUTPUT_DIR, + # market_user_thresholds, + ) + print( + f"汇总 TIF 完成:{summary_grid_result['zip_result']['output']}," + f"耗时 {summary_grid_result['elapsed_seconds']:.1f} 秒" + ) + result_mappings = { + # "excellent_heatmap_results": "excellent_heatmap_result", + "competitor_signal_results": "competitor_signal_result", + "building_info_results": "building_info_result", + "aoi_results": "aoi_result", + "cell_data_results": "cell_data_result", + "gis_project_results": "gis_project_result", + "zip_results": "zip_result", + } + summary = { + "market_gpkg": str(config.MARKET_GPKG), + "grid_5g_gpkg": str(config.GRID_5G_GPKG), + # "grid_4g_gpkg": str(GRID_4G_GPKG), + # "user_count_grid_id_field": GRID_ID_FIELD, + # "user_count_merge_rule": "Grid_5G + Grid_4G union by grid20_id and sum mro_total_dl", + "building_info_gpkg": str(config.BUILDING_INFO_GPKG), + "aoi_gpkg": str(config.AOI_GPKG), + "aoi_match_field": config.AOI_MARKET_FIELD, + "cell_data_gpkg": str(config.CELL_DATA_GPKG), + "gis_project_source": str(config.GIS_PROJECT_SOURCE), + "rsrp_field": config.RSRP_FIELD, + "excellent_cell_field": config.EXCELLENT_CELL_FIELD, + "weak_cover_field": config.WEAK_COVER_FIELD, + "mobile_total_field": config.MOBILE_TOTAL_FIELD, + "mobile_weak_cover_field": config.MOBILE_WEAK_COVER_FIELD, + "competitor_signal_mobile_weak_ratio_formula": ( + f"{config.MOBILE_WEAK_COVER_FIELD} / {config.MOBILE_TOTAL_FIELD} * 100" + ), + "competitor_signal_mobile_weak_ratio_rule": ( + f"< {config.COMPETITOR_SIGNAL_MOBILE_WEAK_RATIO_MAX}" + ), + "competitor_signal_eligibility_rule": ( + f"{config.EXCELLENT_CELL_FIELD} = 0 or " + f"{config.WEAK_COVER_FIELD} / {config.EXCELLENT_CELL_FIELD} * 100 " + f"> {config.COMPETITOR_SIGNAL_WEAK_RATIO_MIN}" + ), + "competitor_signal_zero_total_color": list(config.COMPETITOR_SIGNAL_RSRP_COLORS[0]), + "clip_mode": config.CLIP_MODE, + "scale": config.SCALE, + "pixel_width": pixel_width, + "pixel_height": pixel_height, + "max_workers": worker_count, + "summary_output_enabled": config.SUMMARY_OUTPUT_ENABLED, + "total_elapsed_seconds": perf_counter() - started_at, + "market_timings": [ + { + "market_code": outcome["market_code"], + "elapsed_seconds": outcome["elapsed_seconds"], + **outcome.get("timings", {}), + } + for outcome in outcomes + ], + } + for summary_key, outcome_key in result_mappings.items(): + summary[summary_key] = [outcome[outcome_key] for outcome in outcomes if outcome_key in outcome] + summary["summary_grid_result"] = summary_grid_result + + summary_path = config.OUTPUT_DIR / "summary.json" + temp_summary_path = summary_path.with_name(f".{summary_path.name}.tmp") + try: + temp_summary_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8") + temp_summary_path.replace(summary_path) + except Exception: + if temp_summary_path.exists(): + temp_summary_path.unlink() + raise + print(f"总耗时:{summary['total_elapsed_seconds']:.1f} 秒") + print(f"汇总:{summary_path}") + if progress: + progress(total_steps, total_steps, "成果生成完成") + return summary diff --git a/marketgrid/qgis.py b/marketgrid/qgis.py new file mode 100644 index 0000000..ffd9fb6 --- /dev/null +++ b/marketgrid/qgis.py @@ -0,0 +1,243 @@ +"""QGIS 工程图层与范围更新。""" +from pathlib import Path +import xml.etree.ElementTree as ET +import zipfile +from . import config + + +def set_xml_extent(extent_element, extent): + for tag, value in zip(("xmin", "ymin", "xmax", "ymax"), extent): + child = extent_element.find(tag) + if child is None: + child = ET.SubElement(extent_element, tag) + child.text = format(float(value), ".17g") + + +def padded_extent(extent, padding_ratio): + minx, miny, maxx, maxy = (float(value) for value in extent) + width = maxx - minx + height = maxy - miny + padding_x = width * padding_ratio if width > 0 else (1e-6 if padding_ratio > 0 else 0.0) + padding_y = height * padding_ratio if height > 0 else (1e-6 if padding_ratio > 0 else 0.0) + return minx - padding_x, miny - padding_y, maxx + padding_x, maxy + padding_y + + +def serialize_qgis_project(root, original_data): + bom = b"\xef\xbb\xbf" if original_data.startswith(b"\xef\xbb\xbf") else b"" + payload = original_data[len(bom):] + first_line = payload.splitlines()[0] if payload else b"" + doctype = first_line if first_line.startswith(b" threshold) + flat_result[valid_positions[selected]] = color + rank_counts.append(int(np.count_nonzero(selected))) + remaining &= ~selected + flat_result[valid_positions[remaining]] = colors[-1] + rank_counts.append(int(np.count_nonzero(remaining))) + + return result, thresholds, rank_counts + + +def ranked_pixel_rgb_for_values_with_thresholds(values, data_mask, colors, thresholds): + result = np.zeros((*values.shape, 3), dtype=np.uint8) + valid_positions = np.flatnonzero(data_mask.ravel()) + if valid_positions.size == 0: + return result, [] + if len(thresholds) != len(colors) - 1: + raise ValueError("颜色数量必须比分位阈值数量多 1") + + valid_values = values.ravel()[valid_positions] + flat_result = result.reshape(-1, 3) + remaining = np.ones(valid_values.shape, dtype=bool) + rank_counts = [] + for color, threshold in zip(colors[:-1], thresholds): + selected = remaining & (valid_values > threshold) + flat_result[valid_positions[selected]] = color + rank_counts.append(int(np.count_nonzero(selected))) + remaining &= ~selected + flat_result[valid_positions[remaining]] = colors[-1] + rank_counts.append(int(np.count_nonzero(remaining))) + return result, rank_counts + + +def smooth_rgb_inside_mask(rgb, data_mask, radius): + if radius <= 0: + return rgb + + weight = data_mask.astype(np.float32) + blurred_weight = gaussian_blur(weight, radius) + smoothed = np.zeros_like(rgb, dtype=np.float32) + for channel in range(3): + blurred_channel = gaussian_blur(rgb[..., channel].astype(np.float32) * weight, radius) + np.divide(blurred_channel, blurred_weight, out=smoothed[..., channel], where=blurred_weight > 0) + smoothed[~data_mask] = 0 + return np.clip(smoothed, 0, 255).astype(np.uint8) + + +def gaussian_kernel(radius): + if radius <= 0: + return np.array([1.0], dtype=np.float32) + sigma = max(radius / 2.0, 0.1) + x = np.arange(-radius, radius + 1, dtype=np.float32) + kernel = np.exp(-(x * x) / (2.0 * sigma * sigma)) + return kernel / kernel.sum() + + +def validate_smoothing_radius(name, radius): + if isinstance(radius, bool) or not isinstance(radius, int) or radius < 0: + raise ValueError(f"{name} 必须是非负整数") + + +def convolve_axis(array, kernel, axis): + if kernel.size == 1: + return array + radius = kernel.size // 2 + pad_width = [(0, 0)] * array.ndim + pad_width[axis] = (radius, radius) + padded = np.pad(array, pad_width, mode="edge") + windows = np.lib.stride_tricks.sliding_window_view(padded, kernel.size, axis=axis) + return (windows @ kernel).astype(np.float32, copy=False) + + +def gaussian_blur(array, radius): + kernel = gaussian_kernel(radius) + blurred = convolve_axis(array.astype(np.float32), kernel, axis=0) + return convolve_axis(blurred, kernel, axis=1) + + +def to_float(value): + if value is None: + return None + if isinstance(value, (int, float)): + number = float(value) + return number if math.isfinite(number) else None + try: + text = str(value).strip() + if not text: + return None + number = float(text) + if not math.isfinite(number): + return None + return number + except ValueError: + return None + + +def geotiff_extratags(minx, maxy, pixel_width, pixel_height): + model_pixel_scale = (pixel_width, pixel_height, 0.0) + model_tiepoint = (0.0, 0.0, 0.0, minx, maxy, 0.0) + geo_key_directory = ( + 1, 1, 0, 4, + 1024, 0, 1, 2, + 1025, 0, 1, 1, + 2048, 0, 1, 4326, + 2054, 0, 1, 9102, + ) + return [ + (33550, "d", 3, model_pixel_scale, False), + (33922, "d", 6, model_tiepoint, False), + (34735, "H", len(geo_key_directory), geo_key_directory, False), + ] + + +def write_rgba_geotiff(path, image, minx, maxy, pixel_width, pixel_height): + tifffile.imwrite( + path, + image, + photometric="rgb", + extrasamples=["unassalpha"], + metadata=None, + extratags=geotiff_extratags(minx, maxy, pixel_width, pixel_height), + ) + + +def pixel_window_for_bounds(bounds, minx, maxy, pixel_width, pixel_height, width, height): + geom_minx, geom_miny, geom_maxx, geom_maxy = bounds + col_start = max(0, int(math.floor((geom_minx - minx) / pixel_width))) + col_stop = min(width, int(math.ceil((geom_maxx - minx) / pixel_width))) + row_start = max(0, int(math.floor((maxy - geom_maxy) / pixel_height))) + row_stop = min(height, int(math.ceil((maxy - geom_miny) / pixel_height))) + if row_start >= row_stop or col_start >= col_stop: + return None + return row_start, row_stop, col_start, col_stop + + +def pixel_center_mask_for_geometry(geometry, window, minx, maxy, pixel_width, pixel_height): + row_start, row_stop, col_start, col_stop = window + x_coordinates = minx + (np.arange(col_start, col_stop, dtype=np.float64) + 0.5) * pixel_width + y_coordinates = maxy - (np.arange(row_start, row_stop, dtype=np.float64) + 0.5) * pixel_height + x_grid, y_grid = np.meshgrid(x_coordinates, y_coordinates) + return np.asarray(shapely.contains_xy(geometry, x_grid, y_grid), dtype=bool) + + +def pixel_window_from_point(x, y, minx, maxy, pixel_width, pixel_height, width, height): + col = int((x - minx) / pixel_width) + row = int((maxy - y) / pixel_height) + if 0 <= row < height and 0 <= col < width: + return row, row + 1, col, col + 1 + return None + + +def market_raster_layout(bounds, pixel_width, pixel_height, max_raster_pixels=None): + minx, miny, maxx, maxy = bounds + width = max(1, int(math.ceil((maxx - minx) / pixel_width))) + height = max(1, int(math.ceil((maxy - miny) / pixel_height))) + scale_factor = 1.0 + pixel_limit = config.MAX_RASTER_PIXELS if max_raster_pixels is None else max_raster_pixels + if pixel_limit and width * height > pixel_limit: + scale_factor = math.sqrt((width * height) / pixel_limit) + pixel_width *= scale_factor + pixel_height *= scale_factor + width = max(1, int(math.ceil((maxx - minx) / pixel_width))) + height = max(1, int(math.ceil((maxy - miny) / pixel_height))) + while width * height > pixel_limit: + scale_factor *= 1.001 + pixel_width *= 1.001 + pixel_height *= 1.001 + width = max(1, int(math.ceil((maxx - minx) / pixel_width))) + height = max(1, int(math.ceil((maxy - miny) / pixel_height))) + return minx, miny, maxx, maxy, pixel_width, pixel_height, width, height, scale_factor diff --git a/requirements-ui.txt b/requirements-ui.txt new file mode 100644 index 0000000..f13da0f --- /dev/null +++ b/requirements-ui.txt @@ -0,0 +1,6 @@ +-r requirements.txt +-r requirements-nr-buildings.txt +streamlit==1.64.0 +filelock==3.32.7 +psutil==7.2.2 +Pillow==12.3.0 diff --git a/start-ui.cmd b/start-ui.cmd new file mode 100644 index 0000000..549279a --- /dev/null +++ b/start-ui.cmd @@ -0,0 +1,3 @@ +@echo off +powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0start-ui.ps1" +if errorlevel 1 pause diff --git a/start-ui.ps1 b/start-ui.ps1 new file mode 100644 index 0000000..884b597 --- /dev/null +++ b/start-ui.ps1 @@ -0,0 +1,21 @@ +$ErrorActionPreference = 'Stop' +Set-Location -LiteralPath $PSScriptRoot +$env:PYTHONIOENCODING = 'utf-8' +if (Get-Command uv -ErrorAction SilentlyContinue) { + if (-not (Test-Path '.venv-ui/Scripts/python.exe')) { + uv venv .venv-ui --python 3.13 + if ($LASTEXITCODE -ne 0) { throw '创建 Python 环境失败。' } + } + uv pip install --python .venv-ui/Scripts/python.exe -r requirements-ui.txt + if ($LASTEXITCODE -ne 0) { throw '安装依赖失败。' } + & .venv-ui/Scripts/python.exe -m streamlit run app.py +} else { + if (-not (Test-Path '.venv-ui/Scripts/python.exe')) { + python -m venv .venv-ui + if ($LASTEXITCODE -ne 0) { throw '创建 Python 环境失败。' } + } + & .venv-ui/Scripts/python.exe -m pip install -r requirements-ui.txt + if ($LASTEXITCODE -ne 0) { throw '安装依赖失败。' } + & .venv-ui/Scripts/python.exe -m streamlit run app.py +} +exit $LASTEXITCODE diff --git a/tests/test_main.py b/tests/test_main.py index c0646f8..e145c91 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -12,66 +12,66 @@ import tifffile from shapely import STRtree from shapely.geometry import Polygon, box -import main +from marketgrid import competitor, config, files, gpkg, legacy_user_count, metrics, models, qgis, raster_math class SignalRulesTest(unittest.TestCase): def test_signal_level_boundaries(self): - self.assertEqual(main.signal_level(None), "无采集信息") - self.assertEqual(main.signal_level(-105), "较差") - self.assertEqual(main.signal_level(-95), "一般") - self.assertEqual(main.signal_level(-94.9), "正常") + self.assertEqual(metrics.signal_level(None), "无采集信息") + self.assertEqual(metrics.signal_level(-105), "较差") + self.assertEqual(metrics.signal_level(-95), "一般") + self.assertEqual(metrics.signal_level(-94.9), "正常") class RankedHeatmapTest(unittest.TestCase): def test_equal_values_are_not_split_between_colors(self): values = np.array([[10.0, 0.0, 0.0], [0.0, 0.0, 0.0]], dtype=np.float32) mask = np.ones(values.shape, dtype=bool) - result, thresholds, counts = main.ranked_pixel_rgb_for_values( + result, thresholds, counts = raster_math.ranked_pixel_rgb_for_values( values, mask, - main.EXCELLENT_COLORS, - main.EXCELLENT_PERCENT_STEPS, + config.EXCELLENT_COLORS, + config.EXCELLENT_PERCENT_STEPS, ) self.assertEqual(thresholds, [0.0, 0.0, 0.0]) self.assertEqual(counts, [1, 0, 0, 5]) - self.assertTrue(np.all(result[values == 0] == main.EXCELLENT_COLORS[-1])) - self.assertTrue(np.all(result[values == 10] == main.EXCELLENT_COLORS[0])) + self.assertTrue(np.all(result[values == 0] == config.EXCELLENT_COLORS[-1])) + self.assertTrue(np.all(result[values == 10] == config.EXCELLENT_COLORS[0])) def test_invalid_color_threshold_configuration_fails(self): values = np.array([[1.0]], dtype=np.float32) mask = np.ones(values.shape, dtype=bool) with self.assertRaises(ValueError): - main.ranked_pixel_rgb_for_values(values, mask, ((255, 0, 0),), (0.5,)) + raster_math.ranked_pixel_rgb_for_values(values, mask, ((255, 0, 0),), (0.5,)) def test_ranked_colors_can_reuse_existing_thresholds(self): values = np.array([[20.0, 10.0, 5.0, 1.0]], dtype=np.float32) mask = np.ones(values.shape, dtype=bool) - result, counts = main.ranked_pixel_rgb_for_values_with_thresholds( + result, counts = raster_math.ranked_pixel_rgb_for_values_with_thresholds( values, mask, - main.EXCELLENT_COLORS, + config.EXCELLENT_COLORS, [15.0, 7.5, 2.5], ) self.assertEqual(counts, [1, 1, 1, 1]) - self.assertEqual(result[0, 0].tolist(), list(main.EXCELLENT_COLORS[0])) - self.assertEqual(result[0, 1].tolist(), list(main.EXCELLENT_COLORS[1])) - self.assertEqual(result[0, 2].tolist(), list(main.EXCELLENT_COLORS[2])) - self.assertEqual(result[0, 3].tolist(), list(main.EXCELLENT_COLORS[3])) + self.assertEqual(result[0, 0].tolist(), list(config.EXCELLENT_COLORS[0])) + self.assertEqual(result[0, 1].tolist(), list(config.EXCELLENT_COLORS[1])) + self.assertEqual(result[0, 2].tolist(), list(config.EXCELLENT_COLORS[2])) + self.assertEqual(result[0, 3].tolist(), list(config.EXCELLENT_COLORS[3])) class UserCountMergeTest(unittest.TestCase): def test_4g_and_5g_counts_are_summed_by_grid20_id_without_duplicates(self): records = {} - self.assertTrue(main.merge_user_count_record(records, "shared", (0, 1, 0, 1), 10.0, "5G", True)) - self.assertTrue(main.merge_user_count_record(records, "shared", (0, 1, 1, 2), 5.0, "4G")) - self.assertTrue(main.merge_user_count_record(records, "4g-only", (0, 1, 1, 2), 7.0, "4G")) - self.assertTrue(main.merge_user_count_record(records, "5g-only", (0, 1, 2, 3), 3.0, "5G", True)) - self.assertFalse(main.merge_user_count_record(records, " ", (0, 1, 0, 1), 99.0, "4G")) + self.assertTrue(legacy_user_count.merge_user_count_record(records, "shared", (0, 1, 0, 1), 10.0, "5G", True)) + self.assertTrue(legacy_user_count.merge_user_count_record(records, "shared", (0, 1, 1, 2), 5.0, "4G")) + self.assertTrue(legacy_user_count.merge_user_count_record(records, "4g-only", (0, 1, 1, 2), 7.0, "4G")) + self.assertTrue(legacy_user_count.merge_user_count_record(records, "5g-only", (0, 1, 2, 3), 3.0, "5G", True)) + self.assertFalse(legacy_user_count.merge_user_count_record(records, " ", (0, 1, 0, 1), 99.0, "4G")) - state = main.build_merged_user_count_state(records, 1, 3) - metadata = main.merged_user_count_metadata(records, {"5G": {}, "4G": {}}) + state = legacy_user_count.build_merged_user_count_state(records, 1, 3) + metadata = legacy_user_count.merged_user_count_metadata(records, {"5G": {}, "4G": {}}) self.assertEqual(state["value_sum"].tolist(), [[15.0, 7.0, 3.0]]) self.assertEqual(state["value_weight"].tolist(), [[1, 1, 1]]) @@ -83,12 +83,12 @@ class UserCountMergeTest(unittest.TestCase): def test_local_summary_render_matches_full_canvas_colors(self): records = {} - main.merge_user_count_record(records, "a", (24, 27, 24, 27), 20.0, "5G", True) - main.merge_user_count_record(records, "b", (28, 31, 28, 31), 10.0, "5G", True) - main.merge_user_count_record(records, "c", (32, 35, 32, 35), 5.0, "4G") + legacy_user_count.merge_user_count_record(records, "a", (24, 27, 24, 27), 20.0, "5G", True) + legacy_user_count.merge_user_count_record(records, "b", (28, 31, 28, 31), 10.0, "5G", True) + legacy_user_count.merge_user_count_record(records, "c", (32, 35, 32, 35), 5.0, "4G") thresholds = [15.0, 7.5, 2.5] - full_state = main.build_merged_user_count_state(records, 64, 64) + full_state = legacy_user_count.build_merged_user_count_state(records, 64, 64) full_mask = full_state["value_weight"] > 0 full_values = np.zeros((64, 64), dtype=np.float32) np.divide( @@ -97,15 +97,15 @@ class UserCountMergeTest(unittest.TestCase): out=full_values, where=full_mask, ) - full_ranked, _ = main.ranked_pixel_rgb_for_values_with_thresholds( + full_ranked, _ = raster_math.ranked_pixel_rgb_for_values_with_thresholds( full_values, full_mask, - main.EXCELLENT_COLORS, + config.EXCELLENT_COLORS, thresholds, ) - expected = main.smooth_rgb_inside_mask(full_ranked, full_mask, main.HEATMAP_SMOOTH_RADIUS) + expected = raster_math.smooth_rgb_inside_mask(full_ranked, full_mask, config.HEATMAP_SMOOTH_RADIUS) - local = main.render_merged_user_count_records(records, 64, 64, thresholds) + local = legacy_user_count.render_merged_user_count_records(records, 64, 64, thresholds) actual = np.zeros_like(expected) row_start, row_stop, col_start, col_stop = local["window"] actual[row_start:row_stop, col_start:col_stop] = local["rgb"] @@ -126,23 +126,23 @@ class CompetitorSignalTest(unittest.TestCase): conn.execute("insert into grid values (?, ?, ?, ?, ?, 100, 10)", (index + 1, box(index, 0, index + 1, 1).wkb, total, rsrp, weak)) conn.execute("insert into grid_rtree values (?, ?, ?, 0, 1)", (index + 1, index, index + 1)) - output = Path(temp_dir) / main.COMPETITOR_SIGNAL_OUTPUT_FILENAME - result, csv_result = main.export_market_grid_outputs( - conn, main.LayerInfo("grid", "geom", "fid", 4326), "grid_rtree", - main.MarketFeature(1, "1-test", "test", box(0, 0, 3, 1)), 1, 1, output, None, + output = Path(temp_dir) / config.COMPETITOR_SIGNAL_OUTPUT_FILENAME + result, csv_result = competitor.export_market_grid_outputs( + conn, models.LayerInfo("grid", "geom", "fid", 4326), "grid_rtree", + models.MarketFeature(1, "1-test", "test", box(0, 0, 3, 1)), 1, 1, output, None, ) pixels = tifffile.imread(output) - self.assertEqual(pixels[0, :, 3].tolist(), [main.HEATMAP_ALPHA, main.HEATMAP_ALPHA, 0]) - self.assertEqual(pixels[0, 1, :3].tolist(), list(main.COMPETITOR_SIGNAL_RSRP_COLORS[0])) + self.assertEqual(pixels[0, :, 3].tolist(), [config.HEATMAP_ALPHA, config.HEATMAP_ALPHA, 0]) + self.assertEqual(pixels[0, 1, :3].tolist(), list(config.COMPETITOR_SIGNAL_RSRP_COLORS[0])) self.assertEqual(result["raster_extent"], [0, 0, 3, 1]) self.assertIsNone(csv_result) - self.assertEqual([item.name for item in Path(temp_dir).iterdir()], [main.COMPETITOR_SIGNAL_OUTPUT_FILENAME]) + self.assertEqual([item.name for item in Path(temp_dir).iterdir()], [config.COMPETITOR_SIGNAL_OUTPUT_FILENAME]) def test_filter_accepts_weak_coverage_or_zero_competitor_samples(self): - self.assertTrue(main.competitor_signal_is_eligible(199.0, 1000.0, 1.0, 1.0)) - self.assertTrue(main.competitor_signal_is_eligible(199.0, 1000.0, None, 0.0)) - self.assertFalse(main.competitor_signal_is_eligible(200.0, 1000.0, 1.0, 1.0)) - self.assertFalse(main.competitor_signal_is_eligible(199.0, 1000.0, 20.0, 100.0)) + self.assertTrue(competitor.competitor_signal_is_eligible(199.0, 1000.0, 1.0, 1.0)) + self.assertTrue(competitor.competitor_signal_is_eligible(199.0, 1000.0, None, 0.0)) + self.assertFalse(competitor.competitor_signal_is_eligible(200.0, 1000.0, 1.0, 1.0)) + self.assertFalse(competitor.competitor_signal_is_eligible(199.0, 1000.0, 20.0, 100.0)) def test_filter_rejects_invalid_ratio_fields(self): invalid_cases = ( @@ -155,25 +155,25 @@ class CompetitorSignalTest(unittest.TestCase): ) for values in invalid_cases: with self.subTest(values=values): - self.assertEqual(main.competitor_signal_filter_reason(*values), "invalid_fields") + self.assertEqual(competitor.competitor_signal_filter_reason(*values), "invalid_fields") def test_competitor_signal_uses_eight_discrete_color_classes(self): values = np.array( [[-200.0, -110.1, -110.0, -104.0, -98.0, -92.0, -86.0, -80.0, -74.0, 0.0, 0.1, np.nan]], dtype=np.float32, ) - colors, valid_mask = main.competitor_signal_rsrp_rgb_for_values(values) + colors, valid_mask = competitor.competitor_signal_rsrp_rgb_for_values(values) expected_colors = [ - main.COMPETITOR_SIGNAL_RSRP_COLORS[0], - main.COMPETITOR_SIGNAL_RSRP_COLORS[0], - main.COMPETITOR_SIGNAL_RSRP_COLORS[1], - main.COMPETITOR_SIGNAL_RSRP_COLORS[2], - main.COMPETITOR_SIGNAL_RSRP_COLORS[3], - main.COMPETITOR_SIGNAL_RSRP_COLORS[4], - main.COMPETITOR_SIGNAL_RSRP_COLORS[5], - main.COMPETITOR_SIGNAL_RSRP_COLORS[6], - main.COMPETITOR_SIGNAL_RSRP_COLORS[7], - main.COMPETITOR_SIGNAL_RSRP_COLORS[7], + config.COMPETITOR_SIGNAL_RSRP_COLORS[0], + config.COMPETITOR_SIGNAL_RSRP_COLORS[0], + config.COMPETITOR_SIGNAL_RSRP_COLORS[1], + config.COMPETITOR_SIGNAL_RSRP_COLORS[2], + config.COMPETITOR_SIGNAL_RSRP_COLORS[3], + config.COMPETITOR_SIGNAL_RSRP_COLORS[4], + config.COMPETITOR_SIGNAL_RSRP_COLORS[5], + config.COMPETITOR_SIGNAL_RSRP_COLORS[6], + config.COMPETITOR_SIGNAL_RSRP_COLORS[7], + config.COMPETITOR_SIGNAL_RSRP_COLORS[7], ] self.assertEqual(colors[0, :10].tolist(), [list(color) for color in expected_colors]) self.assertEqual(valid_mask.tolist(), [[True] * 10 + [False, False]]) @@ -190,9 +190,9 @@ class CompetitorSignalTest(unittest.TestCase): } left_geometry = box(0, 0, 1, 1) right_geometry = box(1, 0, 2, 1) - left_window = main.pixel_window_for_bounds(left_geometry.bounds, **canvas) - right_window = main.pixel_window_for_bounds(right_geometry.bounds, **canvas) - left_mask = main.pixel_center_mask_for_geometry( + left_window = raster_math.pixel_window_for_bounds(left_geometry.bounds, **canvas) + right_window = raster_math.pixel_window_for_bounds(right_geometry.bounds, **canvas) + left_mask = raster_math.pixel_center_mask_for_geometry( left_geometry, left_window, canvas["minx"], @@ -200,7 +200,7 @@ class CompetitorSignalTest(unittest.TestCase): canvas["pixel_width"], canvas["pixel_height"], ) - right_mask = main.pixel_center_mask_for_geometry( + right_mask = raster_math.pixel_center_mask_for_geometry( right_geometry, right_window, canvas["minx"], @@ -227,10 +227,10 @@ class CompetitorSignalTest(unittest.TestCase): "painted_cells": 2, "skipped_no_value": 0, } - market = main.MarketFeature(1, "1-test", "test", box(0, 0, 2, 1)) + market = models.MarketFeature(1, "1-test", "test", box(0, 0, 2, 1)) with tempfile.TemporaryDirectory() as temp_dir: - output_path = Path(temp_dir) / main.COMPETITOR_SIGNAL_OUTPUT_FILENAME - result = main.render_competitor_signal_raster( + output_path = Path(temp_dir) / config.COMPETITOR_SIGNAL_OUTPUT_FILENAME + result = competitor.render_competitor_signal_raster( state, market, output_path, @@ -244,37 +244,37 @@ class CompetitorSignalTest(unittest.TestCase): ) image = tifffile.imread(output_path) - self.assertEqual(image[0, 1, :3].tolist(), list(main.COMPETITOR_SIGNAL_RSRP_COLORS[0])) - self.assertEqual(image[0, 1, 3], main.HEATMAP_ALPHA) + self.assertEqual(image[0, 1, :3].tolist(), list(config.COMPETITOR_SIGNAL_RSRP_COLORS[0])) + self.assertEqual(image[0, 1, 3], config.HEATMAP_ALPHA) self.assertEqual(result["zero_total_pixels"], 1) def test_smoothing_radius_must_be_a_nonnegative_integer(self): - main.validate_smoothing_radius("radius", 0) - main.validate_smoothing_radius("radius", 10) + raster_math.validate_smoothing_radius("radius", 0) + raster_math.validate_smoothing_radius("radius", 10) for value in (-1, 1.5, True): with self.subTest(value=value): with self.assertRaises(ValueError): - main.validate_smoothing_radius("radius", value) + raster_math.validate_smoothing_radius("radius", value) class SpatialNameIndexTest(unittest.TestCase): def test_largest_intersection_wins(self): geometries = [box(0, 0, 1, 1), box(0, 0, 2, 2)] index = (STRtree(geometries), geometries, ["小建筑", "大建筑"]) - self.assertEqual(main.match_building_info_name(index, box(0, 0, 1.5, 1.5)), "大建筑") + self.assertEqual(metrics.match_building_info_name(index, box(0, 0, 1.5, 1.5)), "大建筑") def test_batch_matching_matches_scalar_results(self): info_geometries = [box(0, 0, 1, 1), box(0, 0, 2, 2), box(5, 5, 6, 6)] index = (STRtree(info_geometries), info_geometries, ["小建筑", "大建筑", "远端建筑"]) buildings = [box(0, 0, 1.5, 1.5), box(5.2, 5.2, 5.8, 5.8), box(10, 10, 11, 11)] - expected = [main.match_building_info_name(index, geometry) for geometry in buildings] - self.assertEqual(main.match_building_info_names(index, buildings), expected) + expected = [metrics.match_building_info_name(index, geometry) for geometry in buildings] + self.assertEqual(metrics.match_building_info_names(index, buildings), expected) class GaussianBlurTest(unittest.TestCase): def test_batch_convolution_matches_scalar_reference(self): array = np.arange(30, dtype=np.float32).reshape(5, 6) - kernel = main.gaussian_kernel(2) + kernel = raster_math.gaussian_kernel(2) radius = kernel.size // 2 padded = np.pad(array, ((radius, radius), (0, 0)), mode="edge") moved = np.moveaxis(padded, 0, 0) @@ -282,7 +282,7 @@ class GaussianBlurTest(unittest.TestCase): for index in range(expected.shape[0]): expected[index] = np.tensordot(kernel, moved[index:index + kernel.size], axes=(0, 0)) - actual = main.convolve_axis(array, kernel, axis=0) + actual = raster_math.convolve_axis(array, kernel, axis=0) np.testing.assert_allclose(actual, expected, rtol=1e-6, atol=1e-6) padded = np.pad(array, ((0, 0), (radius, radius)), mode="edge") @@ -291,46 +291,46 @@ class GaussianBlurTest(unittest.TestCase): for index in range(expected.shape[0]): expected[index] = np.tensordot(kernel, moved[index:index + kernel.size], axes=(0, 0)) - actual = main.convolve_axis(array, kernel, axis=1) + actual = raster_math.convolve_axis(array, kernel, axis=1) np.testing.assert_allclose(actual, np.moveaxis(expected, 0, 1), rtol=1e-6, atol=1e-6) class OutputSafetyTest(unittest.TestCase): def test_summary_market_unions_all_market_geometries(self): markets = [ - main.MarketFeature(1, "1-a", "a", box(0, 0, 1, 1)), - main.MarketFeature(2, "2-b", "b", box(2, 0, 3, 1)), + models.MarketFeature(1, "1-a", "a", box(0, 0, 1, 1)), + models.MarketFeature(2, "2-b", "b", box(2, 0, 3, 1)), ] - summary_market = main.build_summary_market(markets) - self.assertEqual(summary_market.code, main.SUMMARY_MARKET_CODE) + summary_market = gpkg.build_summary_market(markets) + self.assertEqual(summary_market.code, config.SUMMARY_MARKET_CODE) self.assertEqual(summary_market.geometry.bounds, (0.0, 0.0, 3.0, 1.0)) self.assertEqual(summary_market.geometry.area, 2.0) def test_summary_market_requires_input(self): with self.assertRaises(ValueError): - main.build_summary_market([]) + gpkg.build_summary_market([]) def test_summary_market_repairs_invalid_geometry(self): invalid_geometry = Polygon([(0, 0), (1, 1), (1, 0), (0, 1), (0, 0)]) self.assertFalse(invalid_geometry.is_valid) - summary_market = main.build_summary_market( - [main.MarketFeature(1, "1-a", "a", invalid_geometry)] + summary_market = gpkg.build_summary_market( + [models.MarketFeature(1, "1-a", "a", invalid_geometry)] ) self.assertTrue(summary_market.geometry.is_valid) self.assertFalse(summary_market.geometry.is_empty) def test_raster_layout_respects_pixel_limit(self): - original_limit = main.MAX_RASTER_PIXELS - main.MAX_RASTER_PIXELS = 100 + original_limit = config.MAX_RASTER_PIXELS + config.MAX_RASTER_PIXELS = 100 try: - layout = main.market_raster_layout((0, 0, 10, 10), 0.1, 0.1) + layout = raster_math.market_raster_layout((0, 0, 10, 10), 0.1, 0.1) finally: - main.MAX_RASTER_PIXELS = original_limit + config.MAX_RASTER_PIXELS = original_limit self.assertLessEqual(layout[6] * layout[7], 100) self.assertGreater(layout[8], 1.0) def test_summary_raster_layout_uses_independent_pixel_limit(self): - layout = main.market_raster_layout((0, 0, 10, 10), 0.1, 0.1, 400) + layout = raster_math.market_raster_layout((0, 0, 10, 10), 0.1, 0.1, 400) self.assertLessEqual(layout[6] * layout[7], 400) self.assertEqual((layout[6], layout[7]), (20, 20)) @@ -342,8 +342,8 @@ class OutputSafetyTest(unittest.TestCase): (workspace / "a.txt").write_text("a", encoding="utf-8") (workspace / "b.txt").write_text("b", encoding="utf-8") zip_path = root / "market.zip" - market = main.MarketFeature(1, "1-test", "test", box(0, 0, 1, 1)) - result = main.write_market_zip(workspace, zip_path, market) + market = models.MarketFeature(1, "1-test", "test", box(0, 0, 1, 1)) + result = files.write_market_zip(workspace, zip_path, market) with zipfile.ZipFile(zip_path) as archive: self.assertEqual(sorted(archive.namelist()), ["a.txt", "b.txt"]) self.assertEqual(result["entries"], ["a.txt", "b.txt"]) @@ -356,8 +356,8 @@ class OutputSafetyTest(unittest.TestCase): output = root / "result" / "CellData.gpkg" output.parent.mkdir() source.write_bytes(b"cell-data") - market = main.MarketFeature(1, "1-test", "test", box(0, 0, 1, 1)) - result = main.copy_full_source_file(source, output, market) + market = models.MarketFeature(1, "1-test", "test", box(0, 0, 1, 1)) + result = files.copy_full_source_file(source, output, market) self.assertEqual(output.read_bytes(), b"cell-data") self.assertTrue(result["copied_full_source"]) @@ -392,12 +392,12 @@ class AoiLayerTest(unittest.TestCase): self.conn.execute("insert into aoi values (?, ?, ?, ?, ?, ?)", (fid, geometry, owner, f"aoi-{fid}", f"Area {fid}", fid + 0.5)) self.conn.execute("insert into rtree_aoi_geom values (?, ?, ?, 0, 1)", (fid, start, start + 1)) - self.layer = main.LayerInfo("aoi", "geom", "fid", 4326) + self.layer = models.LayerInfo("aoi", "geom", "fid", 4326) def export(self, name): - market = main.MarketFeature(1, f"1-{name}", name, box(0, 0, 2, 1)) - path = Path(self.temp.name) / main.AOI_OUTPUT_FILENAME - result = main.export_market_aoi_gpkg(self.conn, self.layer, "rtree_aoi_geom", market, path) + market = models.MarketFeature(1, f"1-{name}", name, box(0, 0, 2, 1)) + path = Path(self.temp.name) / config.AOI_OUTPUT_FILENAME + result = gpkg.export_market_aoi_gpkg(self.conn, self.layer, "rtree_aoi_geom", market, path) return market, path, result def test_export_uses_assigned_market_not_intersection(self): @@ -424,18 +424,18 @@ class AoiLayerTest(unittest.TestCase): def test_project_shows_aoi_outline_above_signal_without_duplicates(self): market, _, result = self.export("A") path = Path(self.temp.name) / "GIS.qgz" - metadata = main.copy_gis_project_to_market(main.GIS_PROJECT_SOURCE, path, market, None, + metadata = qgis.copy_gis_project_to_market(config.GIS_PROJECT_SOURCE, path, market, None, include_cell_data=False, aoi_result=result) self.assertTrue(metadata["includes_aoi"]) with zipfile.ZipFile(path) as archive: root = ET.fromstring(archive.read("GIS.qgs")) - main.add_market_aoi_layer(root, result, market.geometry.bounds) + qgis.add_market_aoi_layer(root, result, market.geometry.bounds) tree = root.findall("./layer-tree-group/layer-tree-layer") - self.assertEqual(tree[0].get("name"), main.AOI_LAYER) + self.assertEqual(tree[0].get("name"), config.AOI_LAYER) self.assertEqual(tree[0].get("checked"), "Qt::Checked") - self.assertEqual(sum(item.get("name") == main.AOI_LAYER for item in tree), 1) + self.assertEqual(sum(item.get("name") == config.AOI_LAYER for item in tree), 1) layer = root.find("./projectlayers/maplayer[id='market_aoi_matched']") - self.assertEqual(layer.findtext("datasource"), f"./{main.AOI_OUTPUT_FILENAME}|layername=aoi") + self.assertEqual(layer.findtext("datasource"), f"./{config.AOI_OUTPUT_FILENAME}|layername=aoi") self.assertEqual(layer.findtext("provider"), "ogr") options = {item.get("name"): item.get("value") for item in layer.findall("./renderer-v2/symbols/symbol/layer/Option/Option")} self.assertEqual(options["style"], "no") @@ -469,8 +469,8 @@ class QgisProjectTest(unittest.TestCase): archive.writestr("GIS.qgs", project_xml) archive.writestr("styles.db", b"style-data") - market = main.MarketFeature(1, "1-test", "test", box(0, 0, 1, 1)) - result = main.copy_gis_project_to_market( + market = models.MarketFeature(1, "1-test", "test", box(0, 0, 1, 1)) + result = qgis.copy_gis_project_to_market( source_path, output_path, market, @@ -494,13 +494,13 @@ class QgisProjectTest(unittest.TestCase): # user_count_layer = next( # layer # for layer in project.findall(".//projectlayers/maplayer") - # if layer.findtext("datasource") == f"./{main.USER_COUNT_OUTPUT_FILENAME}" + # if layer.findtext("datasource") == f"./{config.USER_COUNT_OUTPUT_FILENAME}" # ) - self.assertNotIn(main.USER_COUNT_OUTPUT_FILENAME, updated_xml.decode("utf-8")) + self.assertNotIn(config.USER_COUNT_OUTPUT_FILENAME, updated_xml.decode("utf-8")) competitor_signal_layer = next( layer for layer in project.findall(".//projectlayers/maplayer") - if layer.findtext("datasource") == f"./{main.COMPETITOR_SIGNAL_OUTPUT_FILENAME}" + if layer.findtext("datasource") == f"./{config.COMPETITOR_SIGNAL_OUTPUT_FILENAME}" ) self.assertNotIn("CellData.gpkg", updated_xml.decode("utf-8")) self.assertEqual(read_extent(canvas), (9, 19, 31, 41)) @@ -517,8 +517,8 @@ class QgisProjectTest(unittest.TestCase): # def test_repository_template_contains_only_two_thematic_rasters(self): def test_repository_template_contains_only_competitor_signal(self): - self.assertEqual(main.GIS_PROJECT_SOURCE, main.DEFAULT_SOURCE_DIR / "GIS.qgz") - with zipfile.ZipFile(main.GIS_PROJECT_SOURCE) as archive: + self.assertEqual(config.GIS_PROJECT_SOURCE, config.DEFAULT_SOURCE_DIR / "GIS.qgz") + with zipfile.ZipFile(config.GIS_PROJECT_SOURCE) as archive: self.assertIsNone(archive.testzip()) qgs_members = [name for name in archive.namelist() if name.lower().endswith(".qgs")] self.assertEqual(len(qgs_members), 1) @@ -527,9 +527,9 @@ class QgisProjectTest(unittest.TestCase): layer = next( item for item in project.findall(".//projectlayers/maplayer") - if item.findtext("layername") == Path(main.COMPETITOR_SIGNAL_OUTPUT_FILENAME).stem + if item.findtext("layername") == Path(config.COMPETITOR_SIGNAL_OUTPUT_FILENAME).stem ) - self.assertEqual(layer.findtext("datasource"), f"./{main.COMPETITOR_SIGNAL_OUTPUT_FILENAME}") + self.assertEqual(layer.findtext("datasource"), f"./{config.COMPETITOR_SIGNAL_OUTPUT_FILENAME}") layer_id = layer.findtext("id") tree_layer = next( item @@ -544,16 +544,16 @@ class QgisProjectTest(unittest.TestCase): ] self.assertEqual( {item.get("name") for item in raster_tree_layers}, - # {"用户量", Path(main.COMPETITOR_SIGNAL_OUTPUT_FILENAME).stem}, - {Path(main.COMPETITOR_SIGNAL_OUTPUT_FILENAME).stem}, + # {"用户量", Path(config.COMPETITOR_SIGNAL_OUTPUT_FILENAME).stem}, + {Path(config.COMPETITOR_SIGNAL_OUTPUT_FILENAME).stem}, ) # user_count_tree = next(item for item in raster_tree_layers if item.get("name") == "用户量") # self.assertEqual(user_count_tree.get("checked"), "Qt::Unchecked") tree_layers = project.findall("./layer-tree-group/layer-tree-layer") self.assertEqual( [item.get("name") for item in tree_layers], - # ["CellData", Path(main.COMPETITOR_SIGNAL_OUTPUT_FILENAME).stem, "用户量", "BuildInfo", "GoogleCN", "必应地图"], - ["CellData", Path(main.COMPETITOR_SIGNAL_OUTPUT_FILENAME).stem, "BuildInfo", "GoogleCN", "必应地图"], + # ["CellData", Path(config.COMPETITOR_SIGNAL_OUTPUT_FILENAME).stem, "用户量", "BuildInfo", "GoogleCN", "必应地图"], + ["CellData", Path(config.COMPETITOR_SIGNAL_OUTPUT_FILENAME).stem, "BuildInfo", "GoogleCN", "必应地图"], ) self.assertEqual(tree_layers[-2].get("checked"), "Qt::Checked") self.assertEqual(tree_layers[-1].get("checked"), "Qt::Unchecked") @@ -570,17 +570,17 @@ class QgisProjectTest(unittest.TestCase): for include_cell_data in (False, True): with self.subTest(include_cell_data=include_cell_data): output = Path(temp_dir) / f"GIS-{include_cell_data}.qgz" - main.copy_gis_project_to_market( - main.GIS_PROJECT_SOURCE, output, - main.MarketFeature(1, "1-test", "test", box(0, 0, 1, 1)), + qgis.copy_gis_project_to_market( + config.GIS_PROJECT_SOURCE, output, + models.MarketFeature(1, "1-test", "test", box(0, 0, 1, 1)), None, include_cell_data=include_cell_data, ) with zipfile.ZipFile(output) as archive: xml = archive.read("GIS.qgs") - self.assertNotIn(main.USER_COUNT_OUTPUT_FILENAME, xml.decode("utf-8")) + self.assertNotIn(config.USER_COUNT_OUTPUT_FILENAME, xml.decode("utf-8")) names = [item.get("name") for item in ET.fromstring(xml).iter("layer-tree-layer")] self.assertEqual("CellData" in names, include_cell_data) - self.assertIn(Path(main.COMPETITOR_SIGNAL_OUTPUT_FILENAME).stem, names) + self.assertIn(Path(config.COMPETITOR_SIGNAL_OUTPUT_FILENAME).stem, names) self.assertEqual(names[-2:], ["GoogleCN", "必应地图"]) diff --git a/tests/test_toolbox.py b/tests/test_toolbox.py new file mode 100644 index 0000000..4e7e278 --- /dev/null +++ b/tests/test_toolbox.py @@ -0,0 +1,219 @@ +"""真实子进程验证任务隔离、Windows spawn 配置和停止/持久化。""" +import csv +from contextlib import closing +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import io +import json +from pathlib import Path +import sqlite3 +import tempfile +import threading +import time +import unittest +from unittest.mock import patch +import zipfile + +from shapely.geometry import box +from toolbox import tasks +from marketgrid import config +from marketgrid import gpkg + + +def create_gpkg(path, table, columns, records): + with closing(sqlite3.connect(path)) as conn, conn: + conn.executescript(''' + create table gpkg_spatial_ref_sys (srs_id integer primary key, definition text); + create table gpkg_contents (table_name text primary key, data_type text, min_x real, min_y real, + max_x real, max_y real, srs_id integer); + create table gpkg_geometry_columns (table_name text, column_name text, geometry_type_name text, + srs_id integer, z integer, m integer); + create table gpkg_ogr_contents (table_name text primary key, feature_count integer); + ''') + conn.execute('insert into gpkg_spatial_ref_sys values (4326, ?)', ('GEOGCS["WGS 84"]',)) + conn.execute('insert into gpkg_contents values (?, "features", 112, 22, 113, 23, 4326)', (table,)) + conn.execute('insert into gpkg_geometry_columns values (?, "geom", "POLYGON", 4326, 0, 0)', (table,)) + conn.execute('insert into gpkg_ogr_contents values (?, ?)', (table, len(records))) + conn.execute(f'create table "{table}" (fid integer primary key, geom blob, {columns})') + conn.execute(f'create virtual table "rtree_{table}_geom" using rtree(id,minx,maxx,miny,maxy)') + for fid, geometry, values in records: + row = [fid, geometry.wkb, *values] + conn.execute(f'insert into "{table}" values ({",".join("?" for _ in row)})', row) + x1, y1, x2, y2 = geometry.bounds + conn.execute(f'insert into "rtree_{table}_geom" values (?,?,?,?,?)', (fid, x1, x2, y1, y2)) + + +class TaskIntegrationTest(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory(prefix="toolbox_'中文_") + self.root = Path(self.temp.name) + self.patch = patch.object(tasks, "TASKS", self.root / "tasks") + self.patch.start() + self.addCleanup(self.patch.stop) + self.addCleanup(self.temp.cleanup) + self.input = self.root / "坐标.csv" + with self.input.open("w", encoding="utf-8-sig", newline="") as output: + writer = csv.writer(output) + writer.writerow(["序号", "经度", "维度"]) + writer.writerows((i, 112+i/1000, 22) for i in range(30)) + self.params = {"INPUT_CSV": str(self.input), "INPUT_ENCODING": "utf-8-sig", "START_ROW": 1, + "LIMIT": 30, "CONCURRENCY": 2, "TIMEOUT": 5, "MAX_RETRIES": 0, "REQUEST_INTERVAL": 0} + + def wait_for(self, task_id, condition, timeout=30): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + state = tasks.read_task(tasks.TASKS / task_id) + if condition(state): + if state["status"] not in tasks.ACTIVE: + while tasks.alive(state) and time.monotonic() < deadline: + time.sleep(0.05) + return state + time.sleep(0.05) + self.fail(f"任务超时:{tasks.tail_log(tasks.TASKS / task_id)}") + + def server(self, delay=0, status=200): + class Handler(BaseHTTPRequestHandler): + def do_GET(self): + time.sleep(delay) + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(json.dumps({"type": "FeatureCollection", "features": [{"id": "one", "properties": {"楼名": "测试楼"}}]}).encode()) + def log_message(self, *args): + pass + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + self.addCleanup(server.server_close) + self.addCleanup(server.shutdown) + return {"URL": f"http://127.0.0.1:{server.server_port}/wfs?ak=test-private-key", + "COOKIES": "private-cookie-for-test", "REFERER": ""} + + def test_query_persists_results_without_persisting_credentials(self): + params = {**self.params, "LIMIT": 3} + credentials = self.server() + task_id = tasks.start_task("buildings", params, credentials) + state = self.wait_for(task_id, lambda s: s["status"] not in tasks.ACTIVE) + self.assertEqual(state["status"], "success", state) + self.assertEqual(state["counts"]["查询坐标"], 3) + with (Path(state["output"]) / "NRBuildingsData.csv").open(encoding="utf-8-sig") as source: + self.assertEqual(len(list(csv.DictReader(source))), 3) + history = (tasks.TASKS / task_id / "state.json").read_text(encoding="utf-8") + tasks.tail_log(tasks.TASKS / task_id) + self.assertNotIn(credentials["COOKIES"], history) + self.assertNotIn("test-private-key", history) + + def test_single_task_lock_and_graceful_stop(self): + task_id = tasks.start_task("buildings", self.params, self.server(delay=0.2)) + with self.assertRaisesRegex(ValueError, "已有任务"): + tasks.start_task("buildings", self.params) + self.wait_for(task_id, lambda s: s.get("done", 0) > 0) + tasks.stop_task(task_id) + state = self.wait_for(task_id, lambda s: s["status"] not in tasks.ACTIVE) + self.assertEqual(state["status"], "cancelled", state) + self.assertLess(state["done"], 30) + self.assertGreater(state["done"], 0) + with (Path(state["output"]) / "NRBuildingsData.csv").open(encoding="utf-8-sig") as source: + self.assertEqual(len(list(csv.DictReader(source))), state["done"]) + + def test_authentication_failure_is_not_success(self): + task_id = tasks.start_task("buildings", self.params, self.server(status=401)) + state = self.wait_for(task_id, lambda s: s["status"] not in tasks.ACTIVE) + self.assertEqual(state["status"], "failed") + self.assertGreater(state["counts"]["失败坐标"], 0) + + def test_dead_process_is_reported_as_interrupted(self): + folder = tasks.TASKS / "old" + folder.mkdir(parents=True) + tasks.write_json(folder / "state.json", {"status": "running", "created": 0, "pid": -1, "process_created": 0}) + self.assertEqual(tasks.read_task(folder)["status"], "interrupted") + + def test_invalid_input_path_does_not_create_a_database(self): + missing = self.root / "missing.gpkg" + with self.assertRaises(sqlite3.OperationalError): + with gpkg.open_read_connection(missing): + pass + self.assertFalse(missing.exists()) + + 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])) + 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 / "buildings.gpkg", "BuildingInfo", '"name" text', [(1, a, ["建筑甲"]), (2, 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"), + "BUILDING_INFO_GPKG": str(self.root / "buildings.gpkg"), "AOI_GPKG": str(self.root / "aoi.gpkg"), + "CELL_DATA_GPKG": str(self.root / "buildings.gpkg"), + "GIS_PROJECT_SOURCE": str(tasks.ROOT / "source/GIS.qgz"), "MAX_WORKERS": 2, + "SCALE": 1, "MAX_RASTER_PIXELS": 64, "SUMMARY_MAX_RASTER_PIXELS": 64, + "SUMMARY_OUTPUT_ENABLED": True, "SELECTED_MARKET_IDS": [31, 42]} + task_id = tasks.start_task("market", params) + state = self.wait_for(task_id, lambda s: s["status"] not in tasks.ACTIVE) + self.assertEqual(state["status"], "success", tasks.tail_log(tasks.TASKS / task_id)) + out = Path(state["output"]) + summary = json.loads((out / "summary.json").read_text(encoding="utf-8")) + self.assertEqual([r["market_code"] for r in summary["zip_results"]], ["31-甲", "42-乙"]) + for row in summary["competitor_signal_results"]: + self.assertLessEqual(row["width"] * row["height"], 64) + for name in ["31-甲.zip", "42-乙.zip", "全量网格图层.zip"]: + with zipfile.ZipFile(out / name) as archive: + self.assertIsNone(archive.testzip()) + self.assertNotIn("用户量.tif", archive.namelist()) + + +class PageTest(unittest.TestCase): + def test_result_previews_render_summary_csv_raster_and_geometry(self): + from streamlit.testing.v1 import AppTest + import numpy as np + from marketgrid.raster_math import write_rgba_geotiff + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "summary.json").write_text(json.dumps({"market_timings": [ + {"market_code": "甲", "elapsed_seconds": 1.5}, {"market_code": "乙", "elapsed_seconds": 2.5} + ]}), encoding="utf-8") + (root / "data.csv").write_text("序号,结果\n1,成功\n", encoding="utf-8-sig") + write_rgba_geotiff(root / "signal.tif", np.zeros((2, 3, 4), dtype=np.uint8), 112, 22, 0.1, 0.1) + create_gpkg(root / "data.gpkg", "test", '"name" text', [(1, box(112, 22, 112.01, 22.01), ["测试"] )]) + for path in [*root.iterdir(), tasks.ROOT / "source/GIS.qgz"]: + with self.subTest(file=path.name): + at = AppTest.from_string( + f"from pathlib import Path\nfrom ui.results_page import preview\npreview(Path({str(path)!r}))" + ).run(timeout=30) + self.assertFalse(at.exception, at.exception) + + def test_uploaded_file_is_stored_once_with_exact_bytes(self): + from streamlit.testing.v1 import AppTest + from ui import inputs + content = b"id,longitude,latitude\n1,112,22\n" + uploaded = io.BytesIO(content) + uploaded.name, uploaded.size, uploaded.file_id = "坐标.csv", len(content), "test-upload" + with tempfile.TemporaryDirectory() as directory, patch.object(inputs, "ROOT", Path(directory)), \ + patch("streamlit.file_uploader", return_value=uploaded): + at = AppTest.from_string( + "from ui.inputs import file_input\n" + "file_input('坐标', 'missing.csv', 'csv', 'test')" + ).run() + at.radio[0].set_value("拖拽上传").run() + self.assertFalse(at.exception) + saved = list(Path(directory).rglob("坐标.csv")) + self.assertEqual(len(saved), 1) + self.assertEqual(saved[0].read_bytes(), content) + at.run() + self.assertEqual(len(list(Path(directory).rglob("坐标.csv"))), 1) + + def test_home_and_each_functional_page_render(self): + from streamlit.testing.v1 import AppTest + at = AppTest.from_file(str(tasks.ROOT / "app.py")).run(timeout=30) + self.assertFalse(at.exception, at.exception) + for module in ("market_page", "building_page", "tasks_page", "results_page"): + with self.subTest(page=module): + at = AppTest.from_string(f"from ui.{module} import render\nrender()").run(timeout=30) + self.assertFalse(at.exception, at.exception) + + +if __name__ == "__main__": + unittest.main() diff --git a/toolbox/__init__.py b/toolbox/__init__.py new file mode 100644 index 0000000..2b60356 --- /dev/null +++ b/toolbox/__init__.py @@ -0,0 +1 @@ +"""本地工具箱任务与成果服务。""" diff --git a/toolbox/artifacts.py b/toolbox/artifacts.py new file mode 100644 index 0000000..0d98ff7 --- /dev/null +++ b/toolbox/artifacts.py @@ -0,0 +1,87 @@ +"""按需读取成果;大栅格通过磁盘映射降采样预览。""" +from contextlib import contextmanager +import csv +import json +from pathlib import Path +import shutil +import tempfile +import xml.etree.ElementTree as ET +import zipfile + +import numpy as np +from PIL import Image +import shapely +import tifffile +from marketgrid import gpkg + + +def csv_preview(path, encoding="utf-8-sig", limit=500): + with Path(path).open(encoding=encoding, newline="") as source: + reader = csv.DictReader(source) + rows = [] + for index, row in enumerate(reader): + if index >= limit: + return rows, True + rows.append(row) + return rows, False + + +def qgis_layers(path): + with zipfile.ZipFile(path) as archive: + projects = [n for n in archive.namelist() if n.lower().endswith(".qgs")] + if len(projects) != 1: + raise ValueError("QGZ 必须包含一个 .qgs 工程。") + name = projects[0] + root = ET.fromstring(archive.read(name)) + checked = {n.get("id"): n.get("checked") for n in root.findall(".//layer-tree-layer")} + return [{"图层": layer.findtext("layername"), "类型": layer.get("type"), + "默认显示": checked.get(layer.findtext("id")) == "Qt::Checked"} + for layer in root.findall("./projectlayers/maplayer")] + + +def raster_preview(path, max_side=1400): + with tifffile.TiffFile(path) as source: + page = source.pages[0] + height, width = page.shape[:2] + metadata = {"宽": width, "高": height, "数据类型": str(page.dtype), "通道": page.samplesperpixel} + for name in ("ModelPixelScaleTag", "ModelTiepointTag", "GeoKeyDirectoryTag"): + if name in page.tags: + metadata[name] = list(page.tags[name].value) + # 当前生成的 TIFF 未压缩,可以直接 memmap,不把原图完整载入内存。 + data = tifffile.memmap(path, mode="r") + step = max(1, int(np.ceil(max(height, width) / max_side))) + image = Image.fromarray(np.array(data[::step, ::step])) + del data + return image, metadata + + +def gpkg_preview(path, limit=300): + with gpkg.open_read_connection(Path(path)) as conn: + layer = gpkg.resolve_feature_layer(conn) + table = gpkg.quote_identifier(layer.table_name) + total = conn.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0] + columns = gpkg.table_columns(conn, layer.table_name) + rows = conn.execute(f"SELECT * FROM {table} LIMIT ?", (limit,)).fetchall() + records, features = [], [] + for row in rows: + record = dict(zip(columns, row)) + blob = record.pop(layer.geom_col) + records.append({k: str(v) if isinstance(v, bytes) else v for k, v in record.items()}) + if blob: + geometry = shapely.from_wkb(gpkg.gpkg_blob_to_wkb(blob)) + if not geometry.is_empty: + features.append({"type": "Feature", "geometry": json.loads(shapely.to_geojson(geometry)), + "properties": {"名称": str(record.get("name", record.get("AOI名称", record.get("Name", ""))))}}) + return records, features, {"图层": layer.table_name, "总要素": total, "坐标系": layer.srs_id, "预览上限": limit} + + +@contextmanager +def zip_member(path, member): + with zipfile.ZipFile(path) as archive, tempfile.TemporaryDirectory(prefix="marketgrid_preview_") as temp: + info = archive.getinfo(member) + if info.file_size > 1024**3: + raise ValueError("该成员超过 1 GB,请下载后使用 QGIS 查看。") + target = Path(temp) / Path(member).name + with archive.open(info) as source, target.open("wb") as output: + shutil.copyfileobj(source, output, length=8 * 1024 * 1024) + yield target diff --git a/toolbox/tasks.py b/toolbox/tasks.py new file mode 100644 index 0000000..4efbc57 --- /dev/null +++ b/toolbox/tasks.py @@ -0,0 +1,122 @@ +"""文件持久化任务记录;任务进程独立于浏览器会话。""" +import json +import os +from pathlib import Path +import subprocess +import sys +import threading +import time +import uuid + +from filelock import FileLock +import psutil + +ROOT = Path(__file__).resolve().parents[1] +TASKS = ROOT / "output" / "toolbox" / "tasks" +ACTIVE = {"queued", "running"} +LABELS = {"queued": "启动中", "running": "运行中", "success": "已完成", + "failed": "失败", "cancelled": "已停止", "interrupted": "意外中断"} +KINDS = {"market": "市场网格出图", "buildings": "楼宇数据查询"} + + +def write_json(path, value): + path = Path(path) + temporary = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp") + try: + temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding="utf-8") + for attempt in range(20): + try: + temporary.replace(path) + break + except PermissionError: + if attempt == 19: + raise + time.sleep(0.05) + finally: + temporary.unlink(missing_ok=True) + + +def alive(state): + try: + process = psutil.Process(state["pid"]) + return (abs(process.create_time() - state["process_created"]) < 0.1 + and process.is_running() and process.status() != psutil.STATUS_ZOMBIE) + except (KeyError, ValueError, psutil.Error): + return False + + +def read_task(directory): + directory = Path(directory) + state = json.loads((directory / "state.json").read_text(encoding="utf-8")) + if state["status"] in ACTIVE and not alive(state): + if time.time() - state["created"] > 15: + # 不写回,避免与刚完成的 worker 原子更新发生竞争。 + state = {**state, "status": "interrupted", "message": "任务进程已退出,已完成文件保留。"} + state["stop_requested"] = (directory / "stop").exists() + return state + + +def list_tasks(): + if not TASKS.exists(): + return [] + return [read_task(p.parent) for p in sorted(TASKS.glob("*/state.json"), reverse=True)] + + +def start_task(kind, params, credentials=None): + from .validation import validate + validate(kind, params) + TASKS.mkdir(parents=True, exist_ok=True) + with FileLock(str(TASKS / ".launch.lock"), timeout=10): + if any(t["status"] in ACTIVE for t in list_tasks()): + raise ValueError("已有任务正在运行,请等待完成或到任务中心停止它。") + task_id = time.strftime("%Y%m%d-%H%M%S") + "-" + uuid.uuid4().hex[:8] + directory = TASKS / task_id + directory.mkdir() + output = directory / "results" + output.mkdir() + state = {"id": task_id, "kind": kind, "status": "queued", "created": time.time(), + "output": str(output), "params": params, "done": 0, "total": 0, + "message": "正在启动", "directory": str(directory)} + write_json(directory / "state.json", state) + process = None + try: + env = {**os.environ, "PYTHONIOENCODING": "utf-8", "PYTHONUNBUFFERED": "1"} + flags = subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0 + with (directory / "task.log").open("wb") as log: + process = subprocess.Popen( + [sys.executable, "-u", "-m", "toolbox.worker", str(directory)], + cwd=ROOT, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT, + env=env, creationflags=flags, + ) + state.update(pid=process.pid, process_created=psutil.Process(process.pid).create_time()) + write_json(directory / "state.json", state) + # 凭据只经标准输入传给独立任务进程,不写配置文件或命令行。 + process.stdin.write(json.dumps(credentials or {}).encode("utf-8")) + process.stdin.close() + threading.Thread(target=process.wait, daemon=True, name=f"wait-{task_id}").start() + except Exception: + if process is not None: + if process.stdin and not process.stdin.closed: + process.stdin.close() + if process.poll() is None: + process.terminate() + process.wait(timeout=10) + state.update(status="failed", message="任务进程启动失败", finished=time.time()) + write_json(directory / "state.json", state) + raise + return task_id + + +def stop_task(task_id): + directory = TASKS / task_id + if read_task(directory)["status"] in ACTIVE: + (directory / "stop").touch() + + +def tail_log(directory, max_bytes=24000): + path = Path(directory) / "task.log" + if not path.exists(): + return "等待任务输出……" + with path.open("rb") as source: + source.seek(max(0, path.stat().st_size - max_bytes)) + return source.read().decode("utf-8", errors="replace") diff --git a/toolbox/validation.py b/toolbox/validation.py new file mode 100644 index 0000000..f2d9abc --- /dev/null +++ b/toolbox/validation.py @@ -0,0 +1,70 @@ +"""界面启动前验证输入,避免无效任务覆盖现有数据。""" +import csv +from pathlib import Path +import zipfile + +from marketgrid import config, gpkg + +SOURCES = { + "MARKET_GPKG": ("市场边界", "source/GridMap.gpkg", "gpkg"), + "GRID_5G_GPKG": ("5G Grid", "source/Grid_5G.gpkg", "gpkg"), + "BUILDING_INFO_GPKG": ("建筑信息", "source/BuildingInfo.gpkg", "gpkg"), + "AOI_GPKG": ("已匹配市场的 AOI", "output/AOI级报表_市场网格匹配.gpkg", "gpkg"), + "CELL_DATA_GPKG": ("小区数据(汇总包使用)", "source/CellData.gpkg", "gpkg"), + "GIS_PROJECT_SOURCE": ("QGIS 工程模板", "source/GIS.qgz", "qgz"), +} + + +def market_options(path): + with gpkg.open_read_connection(Path(path)) as conn: + layer = gpkg.resolve_feature_layer(conn) + gpkg.require_columns(conn, layer.table_name, [config.MARKET_CODE_FIELD, config.MARKET_NAME_FIELD]) + return [(int(row[0]), str(row[1])) for row in conn.execute( + f'SELECT "fid", "Name" FROM {gpkg.quote_identifier(layer.table_name)} ORDER BY "fid"')] + + +def validate(kind, params): + if kind == "market": + for key, (label, _, suffix) in SOURCES.items(): + if key == "CELL_DATA_GPKG" and not params["SUMMARY_OUTPUT_ENABLED"]: + continue + path = Path(params[key]) + if not path.is_file(): + raise ValueError(f"{label}文件不存在:{path}") + if suffix == "gpkg": + with gpkg.open_read_connection(path) as conn: + layer = gpkg.resolve_feature_layer(conn, config.AOI_LAYER if key == "AOI_GPKG" else None) + if key != "CELL_DATA_GPKG": + 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", "AOI_GPKG"}: + gpkg.rtree_name(conn, layer) + fields = { + "MARKET_GPKG": ["fid", "Name"], "BUILDING_INFO_GPKG": ["name"], + "AOI_GPKG": [config.AOI_MARKET_FIELD, "AOI唯一标签", "AOI名称"], + "GRID_5G_GPKG": [*config.CSV_SOURCE_FIELDS, config.MOBILE_TOTAL_FIELD, config.MOBILE_WEAK_COVER_FIELD], + }.get(key, []) + gpkg.require_columns(conn, layer.table_name, fields) + else: + with zipfile.ZipFile(path) as archive: + if len([n for n in archive.namelist() if n.lower().endswith(".qgs")]) != 1: + raise ValueError("QGIS 模板必须包含一个 .qgs 工程。") + if not params.get("SELECTED_MARKET_IDS"): + raise ValueError("请至少选择一个市场网格。") + if not set(params["SELECTED_MARKET_IDS"]) <= {i for i, _ in market_options(params["MARKET_GPKG"])}: + raise ValueError("市场选择已过期,请重新选择。") + for key in ("SCALE", "MAX_WORKERS", "MAX_RASTER_PIXELS", "SUMMARY_MAX_RASTER_PIXELS"): + if params[key] <= 0: + raise ValueError(f"{key} 必须大于零。") + elif kind == "buildings": + if params["START_ROW"] < 1 or (params["LIMIT"] is not None and params["LIMIT"] < 1): + raise ValueError("起始行和查询数量必须大于零。") + if params["CONCURRENCY"] < 1 or params["TIMEOUT"] <= 0 or params["MAX_RETRIES"] < 0 or params["REQUEST_INTERVAL"] < 0: + raise ValueError("查询参数无效。") + with Path(params["INPUT_CSV"]).open(encoding=params["INPUT_ENCODING"], newline="") as source: + reader = csv.DictReader(source) + if not {"序号", "经度", "维度"} <= set(reader.fieldnames or []): + raise ValueError("坐标 CSV 必须包含:序号、经度、维度。") + else: + raise ValueError("未知工具。") diff --git a/toolbox/worker.py b/toolbox/worker.py new file mode 100644 index 0000000..92ffd10 --- /dev/null +++ b/toolbox/worker.py @@ -0,0 +1,78 @@ +"""独立任务入口。刷新界面或切换页面不会重新启动计算。""" +import asyncio +import json +from pathlib import Path +import sys +import time + +from .tasks import write_json +from marketgrid.config import TaskCancelled + + +def run(directory, credentials): + directory = Path(directory) + path = directory / "state.json" + state = json.loads(path.read_text(encoding="utf-8")) + state.update(status="running", message="开始处理", started=time.time()) + write_json(path, state) + def progress(done, total, message, **extra): + state.update(done=done, total=total, message=message, **extra) + write_json(path, state) + def stopping(): + return (directory / "stop").exists() + try: + if stopping(): + raise TaskCancelled("启动前已停止。") + if state["kind"] == "market": + from marketgrid.pipeline import main + settings = {**state["params"], "OUTPUT_DIR": state["output"], + "STOP_FILE": str(directory / "stop"), "OVERWRITE": True, "LIMIT": None} + main(settings, progress) + else: + import GetNRBuildingsData as query + for key, value in state["params"].items(): + setattr(query, key, value) + for key in ("URL", "COOKIES", "REFERER"): + if key in credentials: + setattr(query, key, credentials[key]) + query.OUTPUT_CSV = Path(state["output"]) / "NRBuildingsData.csv" + last = 0 + def report(counts): + nonlocal last + now = time.monotonic() + state["counts"] = counts + state["done"] = counts["查询坐标"] + if now - last >= 0.5: + progress(counts["查询坐标"], query.LIMIT or 0, "正在查询楼宇", counts=counts) + last = now + result = asyncio.run(query.async_main(handle_signals=False, should_stop=stopping, progress=report)) + if stopping(): + raise TaskCancelled("已停止领取新坐标,进行中的查询和写入已完成。") + if result: + raise ValueError("部分查询失败或认证失效,已保存返回结果,请查看日志和 CSV 状态列。") + state["total"] = state["done"] + state.update(status="success", message="处理完成") + except TaskCancelled as error: + state.update(status="cancelled", message=str(error)) + except Exception as error: + # 不输出堆栈局部变量;外部输入中的凭据也不进入日志。 + chain = [] + current = error + while current is not None: + chain.append(str(current)) + current = current.__cause__ + message = ":".join(chain) + for value in credentials.values(): + if value: + message = message.replace(value, "[已隐藏]") + print(f"任务失败:{message}", flush=True) + state.update(status="failed", message=message) + finally: + state["finished"] = time.time() + write_json(path, state) + return 0 if state["status"] in {"success", "cancelled"} else 1 + + +if __name__ == "__main__": + credentials = json.loads(sys.stdin.buffer.read().decode("utf-8")) + raise SystemExit(run(sys.argv[1], credentials)) diff --git a/ui/__init__.py b/ui/__init__.py new file mode 100644 index 0000000..84f203c --- /dev/null +++ b/ui/__init__.py @@ -0,0 +1 @@ +"""Streamlit 页面与交互组件。""" diff --git a/ui/building_page.py b/ui/building_page.py new file mode 100644 index 0000000..9e7e7d4 --- /dev/null +++ b/ui/building_page.py @@ -0,0 +1,42 @@ +import streamlit as st +from toolbox.tasks import start_task +from .inputs import file_input +from .task_panel import show_started, task_panel + + +def render(): + st.title("楼宇数据查询") + st.write("根据坐标 CSV 查询楼宇 WFS,返回后即时写入,保留未命中和失败记录。") + source = file_input("坐标清单", "source/NRBuildingsPoint.csv", "csv", "building_csv") + st.caption("输入列名必须包含:序号、经度、维度。输出采用 UTF-8 BOM,方便 Excel 打开。") + with st.form("building_run"): + c1, c2, c3 = st.columns(3) + start = c1.number_input("起始数据行(不含表头)", 1, value=1) + limit = c2.number_input("查询数量(0 表示剩余全部)", 0, value=1000) + concurrency = c3.number_input("并发请求数", 1, 32, 8) + encoding = st.selectbox("输入编码", ["gb18030", "utf-8-sig"]) + with st.expander("请求参数"): + timeout = st.number_input("单次请求超时(秒)", 1, 300, 30) + retries = st.number_input("失败重试次数", 0, 10, 2) + interval = st.number_input("每协程请求间隔(秒)", 0.0, 60.0, 0.2, 0.1) + override = st.checkbox("本次使用新的连接配置", value=False) + st.caption("默认使用现有脚本中的本地连接配置;下方临时配置不会写入任务历史。") + url = st.text_input("完整 WFS URL", type="password") + cookies = st.text_input("Cookies", type="password") + referer = st.text_input("Referer(可留空)") + submitted = st.form_submit_button("开始查询", type="primary") + if submitted: + try: + if not source: + raise ValueError("请先导入坐标 CSV。") + if override and (not url.startswith(("http://", "https://")) or not cookies.strip()): + raise ValueError("请填写完整 WFS URL 和 Cookies。") + params = {"INPUT_CSV": source, "INPUT_ENCODING": encoding, "START_ROW": start, + "LIMIT": limit or None, "CONCURRENCY": concurrency, "TIMEOUT": timeout, + "MAX_RETRIES": retries, "REQUEST_INTERVAL": interval} + credentials = {"URL": url.strip(), "COOKIES": cookies.strip(), "REFERER": referer.strip()} if override else None + show_started(start_task("buildings", params, credentials)) + except (OSError, ValueError, UnicodeError) as error: + st.error(str(error)) + if st.session_state.get("last_task"): + task_panel(st.session_state["last_task"]) diff --git a/ui/home_page.py b/ui/home_page.py new file mode 100644 index 0000000..7e2554c --- /dev/null +++ b/ui/home_page.py @@ -0,0 +1,36 @@ +import json +import streamlit as st +from toolbox.tasks import ROOT, list_tasks, ACTIVE +from toolbox.validation import SOURCES + + +def render(): + st.title("MarketGrid 工具箱") + st.write("从空间数据到可交付成果,集中完成出图、查询与结果检查。") + tasks = list_tasks() + output = ROOT / "output" + cols = st.columns(3) + cols[0].metric("正在运行", sum(t["status"] in ACTIVE for t in tasks)) + cols[1].metric("任务记录", len(tasks)) + cols[2].metric("现有 ZIP 成果", len(list(output.glob("*.zip")))) + st.subheader("选择工具") + left, right = st.columns(2) + with left, st.container(border=True): + st.markdown("### 🗺️ 市场网格出图") + st.write("六类数据源导入,完整运行专题渲染、空间分包和 QGIS 打包流程。") + st.page_link(st.session_state["pages"]["market"], label="进入出图流程", icon="➡️") + with right, st.container(border=True): + st.markdown("### 🏢 楼宇数据查询") + st.write("导入坐标清单,批量查询楼宇并实时生成 CSV。") + st.page_link(st.session_state["pages"]["buildings"], label="进入楼宇查询", icon="➡️") + st.subheader("默认数据源") + st.dataframe([{"数据源": label, "状态": "已就绪" if (ROOT / file).is_file() else "缺失", + "文件": file, "大小 MB": round((ROOT / file).stat().st_size / 1024**2, 1) if (ROOT / file).is_file() else 0} + for label, file, _ in SOURCES.values()], hide_index=True, width="stretch") + summary_path = output / "summary.json" + if summary_path.exists(): + try: + data = json.loads(summary_path.read_text(encoding="utf-8")) + st.caption(f"现有正式成果:{len(data.get('zip_results', []))} 个市场包。") + except (OSError, ValueError) as error: + st.warning(f"现有汇总记录无法读取:{error}") diff --git a/ui/inputs.py b/ui/inputs.py new file mode 100644 index 0000000..a997941 --- /dev/null +++ b/ui/inputs.py @@ -0,0 +1,41 @@ +"""按数据源独立选择本地文件或拖拽上传。""" +from pathlib import Path +import uuid +import streamlit as st +from toolbox.tasks import ROOT + + +def file_input(label, default, extension, key): + with st.container(border=True): + st.markdown(f"**{label}**") + mode = st.radio("导入方式", ["本地路径", "拖拽上传"], horizontal=True, + key=f"{key}_mode", label_visibility="collapsed") + if mode == "本地路径": + value = st.text_input("文件路径", str(ROOT / default), key=f"{key}_path") + value = value.strip().strip('"') + path = Path(value).expanduser() + if not path.is_absolute(): + path = ROOT / path + else: + uploaded = st.file_uploader("拖拽文件到这里,或点击选择", type=[extension], key=f"{key}_upload") + if uploaded is None: + st.caption(f"请选择 .{extension} 文件") + return None + identity = (uploaded.file_id, uploaded.size) + cached = st.session_state.get(f"{key}_stored") + if cached and cached[0] == identity and Path(cached[1]).exists(): + path = Path(cached[1]) + else: + folder = ROOT / "output" / "toolbox" / "imports" / uuid.uuid4().hex + folder.mkdir(parents=True) + path = folder / Path(uploaded.name).name + uploaded.seek(0) + with path.open("wb") as target: + while chunk := uploaded.read(8 * 1024 * 1024): + target.write(chunk) + st.session_state[f"{key}_stored"] = (identity, str(path)) + if path.is_file(): + st.caption(f"已就绪 · {path.stat().st_size / 1024 / 1024:,.1f} MB") + else: + st.caption("文件不存在,请选择或输入有效路径。") + return str(path.resolve()) diff --git a/ui/market_page.py b/ui/market_page.py new file mode 100644 index 0000000..281a824 --- /dev/null +++ b/ui/market_page.py @@ -0,0 +1,56 @@ +"""完整市场出图流程页面,不把流水线拆成零散工具。""" +import sqlite3 +import zipfile +import streamlit as st +from toolbox.tasks import start_task +from toolbox.validation import SOURCES, market_options +from .inputs import file_input +from .task_panel import show_started, task_panel + + +def render(): + st.title("市场网格出图") + st.write("导入六类数据,一次完成竟对信号渲染、建筑与 AOI 分包、QGIS 工程和全量汇总。") + st.caption("大体积 GeoPackage 推荐直接填写本地路径,避免上传时额外占用内存。上传副本和新成果均保存在 output/toolbox。") + st.subheader("1 · 导入数据源") + params = {} + columns = st.columns(2) + for index, (key, (label, default, extension)) in enumerate(SOURCES.items()): + with columns[index % 2]: + params[key] = file_input(label, default, extension, key) + st.caption("AOI 使用已完成归属匹配的总表;此流程按“所属市场网格”分包,不重新计算归属。") + options = [] + if params["MARKET_GPKG"]: + try: + options = market_options(params["MARKET_GPKG"]) + except (OSError, sqlite3.Error, ValueError) as error: + st.warning(f"市场边界暂不可用:{error}") + st.subheader("2 · 选择市场与输出参数") + with st.form("market_run"): + all_markets = st.checkbox("处理全部市场", value=True) + labels = {fid: f"{fid} · {name}" for fid, name in options} + chosen = st.multiselect("指定市场(取消全部市场后生效)", list(labels), format_func=labels.get) + c1, c2, c3 = st.columns(3) + params["MAX_WORKERS"] = c1.number_input("并行进程数", 1, 16, 4) + params["SCALE"] = c2.number_input("分辨率倍数", 0.1, 20.0, 5.0, 0.5) + params["SUMMARY_OUTPUT_ENABLED"] = c3.checkbox("生成全量汇总包", value=True) + with st.expander("栅格与显示参数"): + params["MAX_RASTER_PIXELS"] = int(st.number_input("单市场像元上限(百万)", 1, 100, 25) * 1_000_000) + params["SUMMARY_MAX_RASTER_PIXELS"] = int(st.number_input("汇总像元上限(百万)", 1, 200, 100) * 1_000_000) + params["CLIP_MODE"] = st.selectbox("Grid 纳入方式", ["intersects", "center"], + format_func=lambda v: {"intersects": "与市场相交(含边界触碰)", "center": "中心点位于市场内"}[v]) + params["PROJECT_EXTENT_PADDING_RATIO"] = st.number_input("QGIS 画布留白比例", 0.0, 1.0, 0.05, 0.01) + st.caption("每次任务生成独立目录,不覆盖现有正式成果。竟对信号采用当前八档图例和严格 20% 筛选规则。") + submitted = st.form_submit_button("开始生成成果", type="primary", disabled=not options) + if submitted: + params["SELECTED_MARKET_IDS"] = list(labels) if all_markets else chosen + try: + if any(value is None for key, value in params.items() if key in SOURCES and (key != "CELL_DATA_GPKG" or params["SUMMARY_OUTPUT_ENABLED"])): + raise ValueError("请完成所需数据源的导入。") + if params["CELL_DATA_GPKG"] is None: + params.pop("CELL_DATA_GPKG") + show_started(start_task("market", params)) + except (OSError, sqlite3.Error, ValueError, zipfile.BadZipFile) as error: + st.error(str(error)) + if st.session_state.get("last_task"): + task_panel(st.session_state["last_task"]) diff --git a/ui/results_page.py b/ui/results_page.py new file mode 100644 index 0000000..0830de1 --- /dev/null +++ b/ui/results_page.py @@ -0,0 +1,93 @@ +import json +import os +from pathlib import Path +import sqlite3 +import zipfile + +import pydeck as pdk +import streamlit as st +from toolbox import artifacts +from toolbox.tasks import ROOT, KINDS, LABELS, list_tasks + + +def preview(path): + suffix = path.suffix.lower() + if suffix == ".csv": + encoding = st.selectbox("预览编码", ["utf-8-sig", "gb18030"], key="preview_encoding") + rows, truncated = artifacts.csv_preview(path, encoding) + st.dataframe(rows, width="stretch", hide_index=True) + st.caption("仅显示前 500 行。" if truncated else f"共 {len(rows)} 行。") + elif suffix == ".json": + data = json.loads(path.read_text(encoding="utf-8")) + if isinstance(data, dict) and data.get("market_timings"): + st.subheader("市场处理耗时(秒)") + st.bar_chart([{"市场": item["market_code"], "耗时秒": item["elapsed_seconds"]} + for item in data["market_timings"]], x="市场", y="耗时秒") + st.json(data, expanded=False) + elif suffix == ".qgz": + st.dataframe(artifacts.qgis_layers(path), hide_index=True, width="stretch") + elif suffix in {".tif", ".tiff"}: + image, metadata = artifacts.raster_preview(path) + st.image(image, caption="按比例降采样预览;完整地理信息保留在原始 TIFF 中。") + st.json(metadata, expanded=False) + elif suffix == ".gpkg": + rows, features, metadata = artifacts.gpkg_preview(path) + st.write(metadata) + st.dataframe(rows, hide_index=True, width="stretch") + if features and metadata["坐标系"] in {4326, 100000}: + import shapely + geometry = shapely.from_geojson(json.dumps({"type": "FeatureCollection", "features": features})) + minx, miny, maxx, maxy = geometry.bounds + st.pydeck_chart(pdk.Deck( + map_style=None, + initial_view_state=pdk.ViewState(longitude=(minx+maxx)/2, latitude=(miny+maxy)/2, zoom=10), + layers=[pdk.Layer("GeoJsonLayer", {"type": "FeatureCollection", "features": features}, + get_fill_color=[13, 130, 122, 60], get_line_color=[13, 130, 122, 255], + line_width_min_pixels=1, pickable=True)], + tooltip={"text": "{名称}"}, + )) + st.caption("离线几何预览,仅显示上述抽样要素;可拖动和缩放。完整地图请打开成果中的 QGIS 工程。") + else: + st.info("此文件可下载或在本地打开。") + + +def render(): + st.title("成果浏览") + st.write("查看既有成果或新任务结果,预览数据表、空间图层、QGIS 图层配置和专题栅格。") + tasks = list_tasks() + roots = {"现有正式成果": ROOT / "output"} + roots.update({f"{t['id']} · {KINDS[t['kind']]} · {LABELS[t['status']]}": Path(t["output"]) for t in tasks}) + selected = st.selectbox("成果来源", list(roots)) + directory = roots[selected] + st.caption(str(directory)) + if os.name == "nt" and st.button("在资源管理器中打开目录"): + os.startfile(directory) + files = sorted(p for p in directory.iterdir() if p.is_file() and not p.name.startswith(".")) if directory.exists() else [] + if not files: + st.info("该任务尚未生成文件,稍后可刷新页面。") + return + st.dataframe([{"文件": p.name, "大小 MB": round(p.stat().st_size/1024**2, 2)} for p in files], + hide_index=True, width="stretch") + name = st.selectbox("选择文件", [p.name for p in files]) + path = directory / name + # 下载按需加载,避免首次进入页面把所有大 ZIP 都读进内存。 + if path.stat().st_size <= 128 * 1024**2: + if st.checkbox("准备下载所选文件", key=f"download_{path}"): + with path.open("rb") as source: + st.download_button("下载文件", source, file_name=path.name) + else: + st.caption("文件大于 128 MB,请使用上方本地目录直接复制,避免浏览器占用大量内存。") + try: + if path.suffix.lower() == ".zip": + with zipfile.ZipFile(path) as archive: + entries = [info for info in archive.infolist() if not info.is_dir()] + st.dataframe([{"成员": e.filename, "原始大小 MB": round(e.file_size/1024**2, 2)} for e in entries], + hide_index=True, width="stretch") + member = st.selectbox("包内文件", [e.filename for e in entries]) + if st.checkbox("加载包内预览", key=f"preview_{path}_{member}"): + with st.spinner("读取成果预览……"), artifacts.zip_member(path, member) as target: + preview(target) + elif st.checkbox("加载文件预览", key=f"preview_{path}"): + preview(path) + except (OSError, ValueError, sqlite3.Error, zipfile.BadZipFile, KeyError) as error: + st.error(f"无法预览此文件:{error}") diff --git a/ui/task_panel.py b/ui/task_panel.py new file mode 100644 index 0000000..ac71491 --- /dev/null +++ b/ui/task_panel.py @@ -0,0 +1,41 @@ +from datetime import datetime +import streamlit as st +from toolbox.tasks import ACTIVE, KINDS, LABELS, list_tasks, stop_task, tail_log + + +@st.fragment(run_every="2s") +def task_panel(task_id=None, recent=False): + tasks = list_tasks() + if task_id: + tasks = [task for task in tasks if task["id"] == task_id] + elif recent: + tasks = tasks[:1] + if not tasks: + st.info("暂无任务。启动工具后可在这里查看进度和成果。") + return + for task in tasks: + with st.container(border=True): + st.markdown(f"**{KINDS[task['kind']]} · {LABELS[task['status']]}**") + st.caption(f"{task['id']} · {datetime.fromtimestamp(task['created']):%Y-%m-%d %H:%M:%S}") + st.write(task["message"]) + if task.get("total"): + ratio = min(task.get("done", 0) / task["total"], 1.0) + st.progress(ratio, text=f"{task.get('done', 0)} / {task['total']}") + elif task.get("done"): + st.write(f"已处理 {task['done']} 个坐标") + if task.get("counts"): + st.write(task["counts"]) + if task["status"] in ACTIVE: + if task["stop_requested"]: + st.info("已请求停止,等待当前批次或正在进行的请求完成写入。") + elif st.button("停止任务", key=f"stop_{task['id']}"): + stop_task(task["id"]) + st.rerun(scope="fragment") + st.caption(f"成果目录:{task['output']}") + with st.expander("运行日志", expanded=bool(task_id)): + st.code(tail_log(task["directory"]), language="text") + + +def show_started(task_id): + st.session_state["last_task"] = task_id + st.success("任务已启动。可以切换页面,进度和结果保存在任务中心。") diff --git a/ui/tasks_page.py b/ui/tasks_page.py new file mode 100644 index 0000000..3bb2537 --- /dev/null +++ b/ui/tasks_page.py @@ -0,0 +1,8 @@ +import streamlit as st +from .task_panel import task_panel + + +def render(): + st.title("任务中心") + st.caption("进度每两秒刷新。关闭浏览器不会中断任务;停止请求会保留已完成成果。") + task_panel()