diff --git a/.gitignore b/.gitignore index ebb1759..6f2ec5e 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ __pycache__/ # Local data artifacts source/ output/ +output_*/ diff --git a/README.md b/README.md index 901365e..b7a6445 100644 --- a/README.md +++ b/README.md @@ -95,6 +95,8 @@ BuildingInfo.gpkg 每个市场网格的数据范围不同,所以四等分阈值是动态计算的。运行后可在 `output/summary.json` 的 `excellent_heatmap_results.thresholds` 查看对应市场的阈值记录。 +相同数值的像元始终归入同一颜色档位,不会为了强制凑满 25% 而按空间位置拆分,因此实际各档像元占比可能因重复值而偏离严格四等分。 + ### 信号差用户量.tif 来源字段:`grid.gpkg` 的 `rsrp_lt_neg105_dl` @@ -112,7 +114,7 @@ BuildingInfo.gpkg 每个市场网格的数据范围不同,所以三等分阈值是动态计算的。运行后可在 `output/summary.json` 的 `weak_cover_heatmap_results.thresholds` 查看对应市场的阈值记录。 -注意:该图层仍会做平滑处理,所以视觉上可能出现红、黄、绿之间的过渡色,但不再使用蓝色档位。 +相同数值的像元始终归入同一颜色档位。弱覆盖数据中大量 `0` 会统一归入低值绿色档,不再按像元位置强行拆分到黄、绿两档,因此可避免人为形成大块空间分层。该图层仍会做平滑处理,所以视觉上可能出现红、黄、绿之间的过渡色,但不再使用蓝色档位。 ## CSV 指标表 @@ -178,8 +180,27 @@ CSV 中的 `移动信号` 和 `竟对信号` 使用同一套文字等级: | --- | --- | --- | | `OUTPUT_DIR` | `output` | 输出目录 | | `LIMIT` | `None` | `None` 表示处理全部市场网格 | +| `MAX_WORKERS` | `2` | 市场网格并行处理进程数;内存和磁盘充足时可尝试 `3` 或 `4` | +| `MAX_RASTER_PIXELS` | `25000000` | 单张 TIF 最大像元数;超限市场自动降低分辨率,防止内存溢出 | | `SCALE` | `5.0` | 分辨率倍数,越大输出越清晰,文件也越大 | | `CLIP_MODE` | `intersects` | Grid 热力图裁切模式 | | `HEATMAP_BAD_RSRP` | `-105.0` | RSRP 红色端 | | `HEATMAP_MID_RSRP` | `-95.0` | RSRP 黄色/绿色分界 | | `HEATMAP_ALPHA` | `191` | 热力图有效像元透明度,约 75% 不透明 | + +## 性能优化 + +当前处理流程已做以下加速: + +- 同一市场的 Grid 数据只执行一次 RTree 查询和几何相交判断,同时缓存像元窗口并写出 `栅格指标.csv`;三张 TIF 顺序复用栅格矩阵内存。 +- 楼宇名称匹配使用市场内 STRtree 内存空间索引,避免逐栋楼宇重复查询 BuildingInfo 数据库。 +- 不同市场网格使用独立进程并行处理,每个进程自行打开只读 GeoPackage 连接并写入独立 zip。 +- 单市场范围过大时按 `MAX_RASTER_PIXELS` 自动调整像元大小,结果中记录实际像元尺寸和分辨率调整系数。 +- zip 和 `summary.json` 使用临时文件完成后原子替换,处理中断时不会先删除已有成果。 +- `output/summary.json` 会记录总耗时、实际并发数以及每个市场的 Grid/Building 分阶段耗时。 + +并发建议: + +- 普通办公电脑建议 `MAX_WORKERS = 2`。 +- 内存充足且数据位于 SSD 时可尝试 `3` 或 `4`。 +- 如果出现内存占用过高或磁盘持续满负载,应降低并发数。 diff --git a/aidocs/project_context.md b/aidocs/project_context.md index 265ddb7..e42c9eb 100644 --- a/aidocs/project_context.md +++ b/aidocs/project_context.md @@ -68,3 +68,15 @@ - `楼宇指标.csv` 来源为 `source/Building.gpkg`,并通过 `source/BuildingInfo.gpkg` 的 `BuildingInfo.name` 做空间匹配补回建筑名称;匹配时优先取与 Building 要素相交面积最大的 BuildingInfo 名称,匹配不到则建筑名称留空。 - 两个指标 CSV 使用统一字段口径:第一列为 `网格ID`,填入当前市场网格编码,后续字段为区域类型、区域名称、经度、纬度、竟对采样点总、竟对弱覆盖采样点、竟对平均信号值、移动信号、竟对信号;楼宇指标额外包含建筑名称。`ssb_rsrp_yd` 和 `ssb_rsrp_dl` 会按 `<= -105` 较差、`<= -95` 一般、`> -95` 正常转换为中文信号等级,空值输出 `无采集信息`。 - 当前新版 MarketMap 测试市场 `1-城区蓬江` 已验证:临时输出包名为 `1-城区蓬江.zip`,两个 CSV 均可用 GBK 解码,表头首列为 `网格ID` 且数据行填入 `1-城区蓬江`。 + +## 2026-07-18 +- Grid 处理已改为单次 RTree 查询和单次几何相交判断,同时生成 `信号.tif`、`用户量.tif`、`信号差用户量.tif` 和 `栅格指标.csv`,删除旧的重复扫描路径。 +- 楼宇名称匹配已改为按市场 Building 联合范围一次加载 BuildingInfo 候选并构建 Shapely STRtree,避免逐栋楼宇查询 SQLite;边界外但与楼宇相交的 BuildingInfo 仍会纳入候选,保证结果与旧逻辑一致。 +- 新增 `MAX_WORKERS = 2` 市场级多进程配置;每个 worker 独立打开只读 GeoPackage 连接并生成独立 zip,主进程负责进度和 summary 汇总。 +- `summary.json` 新增 `max_workers`、`total_elapsed_seconds` 和 `market_timings`,记录总耗时及 Grid/Building 分阶段耗时。 +- 性能基准:新版市场 `1-城区蓬江` 完整生成由约 70 秒降至 33 秒;两个市场使用 2 个进程总耗时约 36 秒,相比串行估算约 60 秒以上进一步缩短。 +- 排名热力图修复重复值分层伪影:相同值像元不再为强制凑比例而按栅格位置拆色,统一进入同一颜色档;弱覆盖阈值 `[6.5, 0]` 的测试市场不再出现由大量 `0` 值稳定排序造成的空间大块分层。 +- Grid 单次查询后改为缓存紧凑像元窗口,三张 TIF 顺序复用矩阵内存;新增 `MAX_RASTER_PIXELS = 25000000`,超限市场自动降低分辨率并在结果中记录调整系数。 +- 最大范围市场 `16-台山海宴` 从原规划约 3.99 亿像元自动调整为约 2495 万像元,分辨率调整系数约 4.0,69 秒完成全部 7 个包内文件;BuildingInfo 要素数和 RTree 均为 12490,完整性检查为 `ok`。 +- zip 和 `summary.json` 改为临时文件写完后原子替换,避免异常中断时先删除已有成果;worker 会自行创建输出目录,所有输入文件会在启动前显式校验。 +- 优化前后 `信号.tif`、两个 CSV 和 BuildingInfo 结果保持一致;`用户量.tif`、`信号差用户量.tif` 因同值同色修复按预期发生变化。新增 7 个标准库单元测试覆盖信号边界、同值分类、STRtree、像元上限和 zip 完整性。 diff --git a/main.py b/main.py index 8f8b8a3..ffc5fde 100644 --- a/main.py +++ b/main.py @@ -6,12 +6,15 @@ import shutil import sqlite3 import tempfile 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 import numpy as np import tifffile -from shapely import Point, from_wkb +from shapely import Point, STRtree, from_wkb from shapely.errors import GEOSException from shapely.prepared import prep @@ -34,7 +37,7 @@ BUILDING_INFO_LAYER = None # BuildingInfo 建筑信息图层名;None 表示 MARKET_CODE_FIELD = "fid" # 市场网格唯一 ID 前缀字段,新版 MarketMap 使用 fid。 MARKET_NAME_FIELD = "Name" # 市场网格名称字段,新版 MarketMap 使用 Name。 MARKET_ID_SEPARATOR = "-" # 市场网格唯一 ID 拼接符,输出为 fid-name,例如 1-城区蓬江。 -SIGNAL_OUTPUT_FILENAME = "信号.tif" # RSRP 连续热力图输出文件名。 +SIGNAL_OUTPUT_FILENAME = "信号.tif" # RSRP 三色信号图输出文件名。 BUILDING_INFO_OUTPUT_FILENAME = "BuildingInfo.gpkg" # 每个市场网格结果包内输出的建筑信息拆分文件名。 BUILDING_METRICS_CSV_FILENAME = "楼宇指标.csv" # 每个市场网格结果包内输出的楼宇指标 CSV 文件名。 GRID_METRICS_CSV_FILENAME = "栅格指标.csv" # 每个市场网格结果包内输出的栅格指标 CSV 文件名。 @@ -67,6 +70,8 @@ PIXEL_HEIGHT = None # 输出像元高度;None 表示自动按 Grid 单元高 SCALE = 5.0 # 分辨率倍数;2.0 表示像元宽高减半,放大查看更清晰。 SAMPLE_SIZE = 10000 # 自动估算像元大小时抽样读取的 Grid 要素数量。 LIMIT = None # 限制处理前 N 个市场网格;None 表示处理全部市场网格。 +MAX_WORKERS = 2 # 市场网格并行处理进程数;1 表示串行,建议根据内存和磁盘性能设置为 2~4。 +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。 @@ -171,12 +176,20 @@ def write_market_zip(workspace_dir, zip_path, market): "output": zip_path.as_posix(), "skipped": True, } - zip_path.unlink() entries = sorted(path for path in workspace_dir.rglob("*") if path.is_file()) - with zipfile.ZipFile(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()) + 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()) + temp_zip_path.replace(zip_path) + except Exception: + if temp_zip_path.exists(): + temp_zip_path.unlink() + raise return { "market_code": market.code, @@ -516,39 +529,58 @@ def collect_intersecting_metric_features(source_conn, layer, rtree, market, fiel return rows, candidates -def match_building_info_name(building_info_conn, building_info_layer, building_info_rtree, geometry): - table = quote_identifier(building_info_layer.table_name) - geom = quote_identifier(building_info_layer.geom_col) - rtree_table = quote_identifier(building_info_rtree) - minx, miny, maxx, maxy = geometry.bounds +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.{quote_identifier(building_info_layer.pk_col)} = r."id" + join {table} b on b.{pk} = r."id" where r."minx" <= ? and r."maxx" >= ? and r."miny" <= ? and r."maxy" >= ? + order by b.{pk} """ - - best_name = "" - best_score = -1.0 for raw_name, geom_blob in building_info_conn.execute(query, (maxx, minx, maxy, miny)): name = csv_text(raw_name) if not name or geom_blob is None: continue try: - info_geometry = from_wkb(gpkg_blob_to_wkb(geom_blob)) + geometry = from_wkb(gpkg_blob_to_wkb(geom_blob)) except (GEOSException, ValueError): continue - if info_geometry.is_empty or not geometry.intersects(info_geometry): + if geometry.is_empty: continue + geometries.append(geometry) + 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 = name + best_name = names[index] best_score = score return best_name @@ -595,6 +627,22 @@ def export_market_building_metrics_csv( market, CSV_SOURCE_FIELDS, ) + building_bounds = None + for _values, geometry in rows: + minx, miny, maxx, maxy = geometry.bounds + if building_bounds is None: + building_bounds = [minx, miny, maxx, maxy] + else: + building_bounds[0] = min(building_bounds[0], minx) + building_bounds[1] = min(building_bounds[1], miny) + building_bounds[2] = max(building_bounds[2], maxx) + building_bounds[3] = max(building_bounds[3], maxy) + building_name_index = load_building_name_index( + building_info_conn, + building_info_layer, + building_info_rtree, + building_bounds, + ) headers = [ "网格ID", "区域类型", @@ -611,7 +659,7 @@ def export_market_building_metrics_csv( csv_rows = [] matched_names = 0 for values, geometry in rows: - building_name = match_building_info_name(building_info_conn, building_info_layer, building_info_rtree, geometry) + building_name = match_building_info_name(building_name_index, geometry) if building_name: matched_names += 1 common_row = metric_row(values) @@ -629,38 +677,6 @@ def export_market_building_metrics_csv( } -def export_market_grid_metrics_csv(grid_conn, grid_layer, grid_rtree, market, output_path): - rows, candidates = collect_intersecting_metric_features( - grid_conn, - grid_layer, - grid_rtree, - market, - CSV_SOURCE_FIELDS, - ) - headers = [ - "网格ID", - "区域类型", - "区域名称", - "经度", - "纬度", - "竟对采样点总", - "竟对弱覆盖采样点", - "竟对平均信号值", - "移动信号", - "竟对信号", - ] - csv_rows = [[market.code, *metric_row(values)] for values, _geometry in rows] - 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), - "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) @@ -740,19 +756,22 @@ def ranked_pixel_rgb_for_values(values, data_mask, colors, percent_steps): 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] - order = np.argsort(-valid_values, kind="mergesort") - sorted_positions = valid_positions[order] - rank_groups = np.array_split(sorted_positions, len(colors)) - flat_result = result.reshape(-1, 3) - rank_counts = [] - for color, group in zip(colors, rank_groups): - if group.size: - flat_result[group] = color - rank_counts.append(int(group.size)) - 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 @@ -843,14 +862,6 @@ def write_rgba_geotiff(path, image, minx, maxy, pixel_width, pixel_height): ) -def create_canvas(bounds, pixel_width, pixel_height): - 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))) - image = np.full((height, width, 4), TRANSPARENT_PIXEL, dtype=np.uint8) - return image, minx, maxy - - 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))) @@ -870,89 +881,45 @@ def pixel_window_from_point(x, y, minx, maxy, pixel_width, pixel_height, width, return None -def export_market_heatmap_tif(grid_conn, grid_layer, rtree, market, field, pixel_width, pixel_height, output_path): - image, minx, maxy = create_canvas(market.geometry.bounds, pixel_width, pixel_height) - height, width = image.shape[:2] - value_sum = np.zeros((height, width), dtype=np.float32) - value_weight = np.zeros((height, width), dtype=np.float32) - prepared_market = prep(market.geometry) - table = quote_identifier(grid_layer.table_name) - geom = quote_identifier(grid_layer.geom_col) - pk = quote_identifier(grid_layer.pk_col) - rtree_table = quote_identifier(rtree) - field_expr = quote_identifier(field) - lon_expr = quote_identifier("longitude") - lat_expr = quote_identifier("latitude") - min_market_x, min_market_y, max_market_x, max_market_y = market.geometry.bounds +def grid_metrics_headers(): + return [ + "网格ID", + "区域类型", + "区域名称", + "经度", + "纬度", + "竟对采样点总", + "竟对弱覆盖采样点", + "竟对平均信号值", + "移动信号", + "竟对信号", + ] - query = f""" - select b.{pk}, b.{geom}, b.{field_expr}, b.{lon_expr}, b.{lat_expr} - 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 = (max_market_x, min_market_x, max_market_y, min_market_y) - total = 0 - painted = 0 - skipped_no_value = 0 - for _fid, geom_blob, raw_value, raw_lon, raw_lat in grid_conn.execute(query, params): - total += 1 - value = to_float(raw_value) - if value is None: - skipped_no_value += 1 - continue +def market_raster_layout(bounds, pixel_width, pixel_height): + 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 + if MAX_RASTER_PIXELS and width * height > MAX_RASTER_PIXELS: + scale_factor = math.sqrt((width * height) / MAX_RASTER_PIXELS) + 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 > MAX_RASTER_PIXELS: + 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 - lon = to_float(raw_lon) - lat = to_float(raw_lat) - target_point = None - if lon is not None and lat is not None: - target_point = (lon, lat) - - if CLIP_MODE == "intersects": - if geom_blob is None: - continue - try: - grid_geom = from_wkb(gpkg_blob_to_wkb(geom_blob)) - except (GEOSException, ValueError): - continue - if not prepared_market.intersects(grid_geom): - continue - window = pixel_window_for_bounds( - grid_geom.bounds, - minx, - maxy, - pixel_width, - pixel_height, - width, - height, - ) - else: - if target_point is None: - continue - if not prepared_market.covers(Point(target_point)): - continue - window = pixel_window_from_point( - target_point[0], - target_point[1], - minx, - maxy, - pixel_width, - pixel_height, - width, - height, - ) - if window is None: - continue - - row_start, row_stop, col_start, col_stop = window - value_sum[row_start:row_stop, col_start:col_stop] += value - value_weight[row_start:row_stop, col_start:col_stop] += 1.0 - painted += 1 +def render_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"] data_mask = value_weight > 0 if np.any(data_mask): smoothed_sum = gaussian_blur(value_sum, HEATMAP_SMOOTH_RADIUS) @@ -967,110 +934,34 @@ def export_market_heatmap_tif(grid_conn, grid_layer, rtree, market, field, pixel "market_code": market.code, "market_name": market.name, "output": str(output_path), - "candidates": total, - "painted_pixels": painted, + "candidates": candidates, + "painted_pixels": state["painted_cells"], "data_pixels": int(np.count_nonzero(data_mask)), - "skipped_no_value": skipped_no_value, + "skipped_no_value": state["skipped_no_value"], "smooth_radius": HEATMAP_SMOOTH_RADIUS, "width": width, "height": height, + "skipped": False, } -def export_market_excellent_heatmap_tif( - grid_conn, - grid_layer, - rtree, +def render_ranked_raster( + state, market, - field, + output_path, + minx, + maxy, pixel_width, pixel_height, - output_path, - colors=EXCELLENT_COLORS, - percent_steps=EXCELLENT_PERCENT_STEPS, + width, + height, + candidates, + colors, + percent_steps, ): - image, minx, maxy = create_canvas(market.geometry.bounds, pixel_width, pixel_height) - height, width = image.shape[:2] - value_sum = np.zeros((height, width), dtype=np.float32) - value_weight = np.zeros((height, width), dtype=np.float32) - prepared_market = prep(market.geometry) - table = quote_identifier(grid_layer.table_name) - geom = quote_identifier(grid_layer.geom_col) - pk = quote_identifier(grid_layer.pk_col) - rtree_table = quote_identifier(rtree) - field_expr = quote_identifier(field) - lon_expr = quote_identifier("longitude") - lat_expr = quote_identifier("latitude") - min_market_x, min_market_y, max_market_x, max_market_y = market.geometry.bounds - - query = f""" - select b.{pk}, b.{geom}, b.{field_expr}, b.{lon_expr}, b.{lat_expr} - 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 = (max_market_x, min_market_x, max_market_y, min_market_y) - candidates = 0 - matched_cells = 0 - skipped_no_value = 0 - - for _fid, geom_blob, raw_value, raw_lon, raw_lat in grid_conn.execute(query, params): - candidates += 1 - value = to_float(raw_value) - if value is None: - skipped_no_value += 1 - continue - - lon = to_float(raw_lon) - lat = to_float(raw_lat) - target_point = None - if lon is not None and lat is not None: - target_point = (lon, lat) - - if CLIP_MODE == "intersects": - if geom_blob is None: - continue - try: - grid_geom = from_wkb(gpkg_blob_to_wkb(geom_blob)) - except (GEOSException, ValueError): - continue - if not prepared_market.intersects(grid_geom): - continue - window = pixel_window_for_bounds( - grid_geom.bounds, - minx, - maxy, - pixel_width, - pixel_height, - width, - height, - ) - else: - if target_point is None: - continue - if not prepared_market.covers(Point(target_point)): - continue - window = pixel_window_from_point( - target_point[0], - target_point[1], - minx, - maxy, - pixel_width, - pixel_height, - width, - height, - ) - if window is None: - continue - - row_start, row_stop, col_start, col_stop = window - value_sum[row_start:row_stop, col_start:col_stop] += value - value_weight[row_start:row_stop, col_start:col_stop] += 1.0 - matched_cells += 1 - + 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 = [] @@ -1093,18 +984,204 @@ def export_market_excellent_heatmap_tif( "market_name": market.name, "output": str(output_path), "candidates": candidates, - "painted_cells": matched_cells, - "data_pixels": int(np.count_nonzero(image[..., 3] > 0)), - "skipped_no_value": skipped_no_value, + "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 export_market_grid_outputs( + grid_conn, + grid_layer, + rtree, + market, + pixel_width, + pixel_height, + signal_path, + user_count_path, + weak_cover_path, + csv_path, +): + minx, miny, maxx, maxy, pixel_width, pixel_height, width, height, scale_factor = market_raster_layout( + market.geometry.bounds, + pixel_width, + pixel_height, + ) + raster_fields = (RSRP_FIELD, EXCELLENT_CELL_FIELD, WEAK_COVER_FIELD) + skipped_no_value = {field: 0 for field in raster_fields} + painted_cells = {field: 0 for field in raster_fields} + raster_cells = [] + + fields = list(dict.fromkeys(CSV_SOURCE_FIELDS)) + require_columns(grid_conn, grid_layer.table_name, fields) + table = quote_identifier(grid_layer.table_name) + pk = quote_identifier(grid_layer.pk_col) + geom = quote_identifier(grid_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" >= ? + """ + params = (maxx, minx, maxy, miny) + prepared_market = prep(market.geometry) + candidates = 0 + csv_rows = 0 + csv_skipped = 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: + for row in grid_conn.execute(query, params): + candidates += 1 + geom_blob = row[1] + values = dict(zip(fields, row[2:])) + numeric_values = {field: to_float(values.get(field)) for field in raster_fields} + for field, value in numeric_values.items(): + if value is None: + skipped_no_value[field] += 1 + + if geom_blob is None: + continue + try: + grid_geometry = from_wkb(gpkg_blob_to_wkb(geom_blob)) + except (GEOSException, ValueError): + continue + if grid_geometry.is_empty: + continue + + intersects_market = prepared_market.intersects(grid_geometry) + if intersects_market and csv_writer is not None: + csv_writer.writerow([market.code, *metric_row(values)]) + csv_rows += 1 + elif intersects_market: + csv_rows += 1 + + if CLIP_MODE == "intersects": + if not intersects_market: + continue + window = pixel_window_for_bounds( + grid_geometry.bounds, + 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 prepared_market.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 + + row_start, row_stop, col_start, col_stop = window + for field, value in numeric_values.items(): + if value is not None: + painted_cells[field] += 1 + raster_cells.append( + ( + row_start, + row_stop, + col_start, + col_stop, + numeric_values[RSRP_FIELD], + numeric_values[EXCELLENT_CELL_FIELD], + numeric_values[WEAK_COVER_FIELD], + ) + ) + finally: + if csv_file is not None: + csv_file.close() + + def build_state(field, value_index): + value_sum = np.zeros((height, width), dtype=np.float32) + value_weight = np.zeros((height, width), dtype=np.uint16) + for cell in raster_cells: + row_start, row_stop, col_start, col_stop = cell[:4] + value = cell[4 + value_index] + if value is None: + continue + value_sum[row_start:row_stop, col_start:col_stop] += value + value_weight[row_start:row_stop, col_start:col_stop] += 1 + return { + "value_sum": value_sum, + "value_weight": value_weight, + "painted_cells": painted_cells[field], + "skipped_no_value": skipped_no_value[field], + } + + signal_state = build_state(RSRP_FIELD, 0) + signal_result = render_signal_raster( + signal_state, market, signal_path, minx, maxy, pixel_width, pixel_height, width, height, candidates + ) + del signal_state + user_count_state = build_state(EXCELLENT_CELL_FIELD, 1) + user_count_result = render_ranked_raster( + user_count_state, + market, + user_count_path, + minx, + maxy, + pixel_width, + pixel_height, + width, + height, + candidates, + EXCELLENT_COLORS, + EXCELLENT_PERCENT_STEPS, + ) + del user_count_state + weak_cover_state = build_state(WEAK_COVER_FIELD, 2) + weak_cover_result = render_ranked_raster( + weak_cover_state, + market, + weak_cover_path, + minx, + maxy, + pixel_width, + pixel_height, + width, + height, + candidates, + WEAK_COVER_COLORS, + WEAK_COVER_PERCENT_STEPS, + ) + del weak_cover_state + for result in (signal_result, user_count_result, weak_cover_result): + result["pixel_width"] = pixel_width + result["pixel_height"] = pixel_height + result["resolution_scale_factor"] = scale_factor + csv_result = { + "market_code": market.code, + "market_name": market.name, + "output": str(csv_path), + "candidates": candidates, + "row_count": csv_rows, + "skipped": csv_skipped, + } + return signal_result, user_count_result, weak_cover_result, csv_result + + def write_heatmap_legend(output_dir, field): legend_path = output_dir / "heatmap_legend.csv" with legend_path.open("w", newline="", encoding="utf-8-sig") as file: @@ -1141,21 +1218,139 @@ def write_weak_cover_heatmap_legend(output_dir, field): 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 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_GPKG) as grid_conn, + open_read_connection(BUILDING_GPKG) as building_conn, + open_read_connection(BUILDING_INFO_GPKG) as building_info_conn, + ): + grid_layer = resolve_feature_layer(grid_conn, GRID_LAYER) + building_layer = resolve_feature_layer(building_conn, BUILDING_LAYER) + building_info_layer = resolve_feature_layer(building_info_conn, BUILDING_INFO_LAYER) + grid_rtree = rtree_name(grid_conn, grid_layer) + building_rtree = rtree_name(building_conn, building_layer) + building_info_rtree = rtree_name(building_info_conn, building_info_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 + gis_project_result = copy_gis_project_to_market(GIS_PROJECT_SOURCE, gis_project_path, market) + + signal_path = market_dir / heatmap_raster_filename(RSRP_FIELD) + user_count_path = market_dir / excellent_heatmap_raster_filename(EXCELLENT_CELL_FIELD) + weak_cover_path = market_dir / weak_cover_heatmap_raster_filename(WEAK_COVER_FIELD) + grid_metrics_path = market_dir / GRID_METRICS_CSV_FILENAME + grid_started_at = perf_counter() + signal_result, user_count_result, weak_cover_result, grid_metrics_result = export_market_grid_outputs( + grid_conn, + grid_layer, + grid_rtree, + market, + pixel_width, + pixel_height, + signal_path, + user_count_path, + weak_cover_path, + grid_metrics_path, + ) + 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, + ) + building_metrics_path = market_dir / BUILDING_METRICS_CSV_FILENAME + building_metrics_result = export_market_building_metrics_csv( + building_conn, + building_layer, + building_rtree, + building_info_conn, + building_info_layer, + building_info_rtree, + market, + building_metrics_path, + ) + 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, + "heatmap_result": rewrite_result_for_zip(signal_result, zip_path, market_dir), + "excellent_heatmap_result": rewrite_result_for_zip(user_count_result, zip_path, market_dir), + "weak_cover_heatmap_result": rewrite_result_for_zip(weak_cover_result, zip_path, market_dir), + "building_info_result": rewrite_result_for_zip(building_info_result, zip_path, market_dir), + "building_metrics_csv_result": rewrite_result_for_zip(building_metrics_result, zip_path, market_dir), + "grid_metrics_csv_result": rewrite_result_for_zip(grid_metrics_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, + "building_outputs_seconds": building_elapsed, + }, + "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 MAX_RASTER_PIXELS is not None and MAX_RASTER_PIXELS <= 0: + raise ValueError("MAX_RASTER_PIXELS 必须大于 0 或设置为 None") if CLIP_MODE not in {"intersects", "center"}: raise ValueError("CLIP_MODE 必须是 intersects 或 center") - if not GIS_PROJECT_SOURCE.is_file(): - raise FileNotFoundError(f"未找到 QGIS 项目文件:{GIS_PROJECT_SOURCE}") + required_files = (MARKET_GPKG, GRID_GPKG, BUILDING_GPKG, BUILDING_INFO_GPKG, GIS_PROJECT_SOURCE) + 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 ( - sqlite3.connect(MARKET_GPKG) as market_conn, - sqlite3.connect(GRID_GPKG) as grid_conn, - sqlite3.connect(BUILDING_GPKG) as building_conn, - sqlite3.connect(BUILDING_INFO_GPKG) as building_info_conn, + open_read_connection(MARKET_GPKG) as market_conn, + open_read_connection(GRID_GPKG) as grid_conn, + open_read_connection(BUILDING_GPKG) as building_conn, + open_read_connection(BUILDING_INFO_GPKG) as building_info_conn, ): market_layer = resolve_feature_layer(market_conn, MARKET_LAYER) grid_layer = resolve_feature_layer(grid_conn, GRID_LAYER) @@ -1171,12 +1366,12 @@ def main(): require_columns( grid_conn, grid_layer.table_name, - [RSRP_FIELD, EXCELLENT_CELL_FIELD, WEAK_COVER_FIELD, "longitude", "latitude"], + CSV_SOURCE_FIELDS, ) require_columns(building_info_conn, building_info_layer.table_name, ["name"]) - grid_rtree = rtree_name(grid_conn, grid_layer) - building_rtree = rtree_name(building_conn, building_layer) - building_info_rtree = rtree_name(building_info_conn, building_info_layer) + rtree_name(grid_conn, grid_layer) + rtree_name(building_conn, building_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: @@ -1194,191 +1389,109 @@ def main(): ) if LIMIT: markets = markets[:LIMIT] - - heatmap_legend_path = write_heatmap_legend(OUTPUT_DIR, RSRP_FIELD) - excellent_legend_path = write_excellent_heatmap_legend(OUTPUT_DIR, EXCELLENT_CELL_FIELD) - weak_cover_legend_path = write_weak_cover_heatmap_legend(OUTPUT_DIR, WEAK_COVER_FIELD) - heatmap_results = [] - excellent_heatmap_results = [] - weak_cover_heatmap_results = [] - building_info_results = [] - building_metrics_csv_results = [] - grid_metrics_csv_results = [] - gis_project_results = [] - zip_results = [] - print(f"市场网格数量:{len(markets)}") - print(f"Grid 图层:{grid_layer.table_name}") - print(f"Building 图层:{building_layer.table_name}") - print(f"BuildingInfo 名称匹配图层:{building_info_layer.table_name}") - print(f"QGIS 项目文件:{GIS_PROJECT_SOURCE}") - print(f"RSRP 字段:{RSRP_FIELD}") - print(f"采样点字段:{EXCELLENT_CELL_FIELD}") - print(f"信号差用户量字段:{WEAK_COVER_FIELD}") - print(f"分辨率倍数:{SCALE}") - print(f"像元大小:{pixel_width}, {pixel_height}") - print(f"热力图图例:{heatmap_legend_path}") - print(f"采样点热力图图例:{excellent_legend_path}") - print(f"信号差用户量热力图图例:{weak_cover_legend_path}") - - for index, market in enumerate(markets, start=1): - zip_path = market_zip_output_path(OUTPUT_DIR, market) - if zip_path.exists() and not OVERWRITE: - print(f"[{index}/{len(markets)}] 跳过已存在结果包:{zip_path}") - zip_results.append( - { - "market_code": market.code, - "market_name": market.name, - "output": zip_path.as_posix(), - "skipped": True, - } - ) - continue - - 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 - gis_project_result = copy_gis_project_to_market(GIS_PROJECT_SOURCE, gis_project_path, market) - gis_project_results.append(rewrite_result_for_zip(gis_project_result, zip_path, market_dir)) - print(f"[{index}/{len(markets)}] 复制 QGIS 项目:{market.code}/{gis_project_path.name}") - - heatmap_path = market_dir / heatmap_raster_filename(RSRP_FIELD) - print(f"[{index}/{len(markets)}] 导出热力图:{market.code} {market.name}") - heatmap_result = export_market_heatmap_tif( - grid_conn, - grid_layer, - grid_rtree, - market, - RSRP_FIELD, - pixel_width, - pixel_height, - heatmap_path, - ) - heatmap_result["skipped"] = False - heatmap_results.append(rewrite_result_for_zip(heatmap_result, zip_path, market_dir)) - print( - f" 热力图像素:{heatmap_result['width']}x{heatmap_result['height']}," - f"有效像素:{heatmap_result['data_pixels']}" - ) - - excellent_path = market_dir / excellent_heatmap_raster_filename(EXCELLENT_CELL_FIELD) - print(f" 导出采样点热力图:{excellent_path.name}") - excellent_result = export_market_excellent_heatmap_tif( - grid_conn, - grid_layer, - grid_rtree, - market, - EXCELLENT_CELL_FIELD, - pixel_width, - pixel_height, - excellent_path, - ) - excellent_result["skipped"] = False - excellent_heatmap_results.append(rewrite_result_for_zip(excellent_result, zip_path, market_dir)) - print( - f" 采样点热力图像素:{excellent_result['width']}x{excellent_result['height']}," - f"阈值:{excellent_result['thresholds']}" - ) - - weak_cover_path = market_dir / weak_cover_heatmap_raster_filename(WEAK_COVER_FIELD) - print(f" 导出信号差用户量热力图:{weak_cover_path.name}") - weak_cover_result = export_market_excellent_heatmap_tif( - grid_conn, - grid_layer, - grid_rtree, - market, - WEAK_COVER_FIELD, - pixel_width, - pixel_height, - weak_cover_path, - WEAK_COVER_COLORS, - WEAK_COVER_PERCENT_STEPS, - ) - weak_cover_result["skipped"] = False - weak_cover_heatmap_results.append(rewrite_result_for_zip(weak_cover_result, zip_path, market_dir)) - print( - f" 信号差用户量热力图像素:{weak_cover_result['width']}x{weak_cover_result['height']}," - f"阈值:{weak_cover_result['thresholds']}" - ) - - building_info_path = market_dir / BUILDING_INFO_OUTPUT_FILENAME - print(f" 拆分 BuildingInfo:{building_info_path.name}") - building_info_result = export_market_building_info_gpkg( - building_info_conn, - building_info_layer, - building_info_rtree, - market, - building_info_path, - ) - building_info_result["skipped"] = False - building_info_results.append(rewrite_result_for_zip(building_info_result, zip_path, market_dir)) - print( - f" BuildingInfo 要素:{building_info_result['feature_count']}," - f"候选:{building_info_result['candidates']}" - ) - - building_metrics_path = market_dir / BUILDING_METRICS_CSV_FILENAME - print(f" 导出楼宇指标 CSV:{building_metrics_path.name}") - building_metrics_result = export_market_building_metrics_csv( - building_conn, - building_layer, - building_rtree, - building_info_conn, - building_info_layer, - building_info_rtree, - market, - building_metrics_path, - ) - building_metrics_csv_results.append(rewrite_result_for_zip(building_metrics_result, zip_path, market_dir)) - print( - f" 楼宇指标行数:{building_metrics_result['row_count']}," - f"匹配建筑名称:{building_metrics_result['matched_names']}" - ) - - grid_metrics_path = market_dir / GRID_METRICS_CSV_FILENAME - print(f" 导出栅格指标 CSV:{grid_metrics_path.name}") - grid_metrics_result = export_market_grid_metrics_csv( - grid_conn, - grid_layer, - grid_rtree, - market, - grid_metrics_path, - ) - grid_metrics_csv_results.append(rewrite_result_for_zip(grid_metrics_result, zip_path, market_dir)) - print(f" 栅格指标行数:{grid_metrics_result['row_count']}") - - 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) - zip_results.append(zip_result) - print(f" 结果包:{zip_path},文件数:{len(zip_result['entries'])}") - - summary_path = OUTPUT_DIR / "summary.json" - summary = { - "market_gpkg": str(MARKET_GPKG), - "grid_gpkg": str(GRID_GPKG), - "building_gpkg": str(BUILDING_GPKG), - "building_info_gpkg": str(BUILDING_INFO_GPKG), - "gis_project_source": str(GIS_PROJECT_SOURCE), - "rsrp_field": RSRP_FIELD, - "excellent_cell_field": EXCELLENT_CELL_FIELD, - "weak_cover_field": WEAK_COVER_FIELD, - "clip_mode": CLIP_MODE, - "scale": SCALE, - "pixel_width": pixel_width, - "pixel_height": pixel_height, - "heatmap_results": heatmap_results, - "excellent_heatmap_results": excellent_heatmap_results, - "weak_cover_heatmap_results": weak_cover_heatmap_results, - "building_info_results": building_info_results, - "building_metrics_csv_results": building_metrics_csv_results, - "grid_metrics_csv_results": grid_metrics_csv_results, - "gis_project_results": gis_project_results, - "zip_results": zip_results, + layer_names = { + "grid": grid_layer.table_name, + "building": building_layer.table_name, + "building_info": building_info_layer.table_name, } - summary_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8") - print(f"汇总:{summary_path}") + + heatmap_legend_path = write_heatmap_legend(OUTPUT_DIR, RSRP_FIELD) + excellent_legend_path = write_excellent_heatmap_legend(OUTPUT_DIR, EXCELLENT_CELL_FIELD) + weak_cover_legend_path = write_weak_cover_heatmap_legend(OUTPUT_DIR, WEAK_COVER_FIELD) + worker_count = max(1, min(MAX_WORKERS, len(markets))) if markets else 1 + print(f"市场网格数量:{len(markets)}") + print(f"并行进程数:{worker_count}") + print(f"Grid 图层:{layer_names['grid']}") + print(f"Building 图层:{layer_names['building']}") + print(f"BuildingInfo 图层:{layer_names['building_info']}") + print(f"像元大小:{pixel_width}, {pixel_height}") + print(f"热力图图例:{heatmap_legend_path}") + print(f"用户量图例:{excellent_legend_path}") + print(f"信号差用户量图例:{weak_cover_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("heatmap_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("heatmap_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"]) + result_mappings = { + "heatmap_results": "heatmap_result", + "excellent_heatmap_results": "excellent_heatmap_result", + "weak_cover_heatmap_results": "weak_cover_heatmap_result", + "building_info_results": "building_info_result", + "building_metrics_csv_results": "building_metrics_csv_result", + "grid_metrics_csv_results": "grid_metrics_csv_result", + "gis_project_results": "gis_project_result", + "zip_results": "zip_result", + } + summary = { + "market_gpkg": str(MARKET_GPKG), + "grid_gpkg": str(GRID_GPKG), + "building_gpkg": str(BUILDING_GPKG), + "building_info_gpkg": str(BUILDING_INFO_GPKG), + "gis_project_source": str(GIS_PROJECT_SOURCE), + "rsrp_field": RSRP_FIELD, + "excellent_cell_field": EXCELLENT_CELL_FIELD, + "weak_cover_field": WEAK_COVER_FIELD, + "clip_mode": CLIP_MODE, + "scale": SCALE, + "pixel_width": pixel_width, + "pixel_height": pixel_height, + "max_workers": worker_count, + "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_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}") if __name__ == "__main__": diff --git a/tests/test_main.py b/tests/test_main.py new file mode 100644 index 0000000..f25e8fe --- /dev/null +++ b/tests/test_main.py @@ -0,0 +1,84 @@ +import tempfile +import unittest +import zipfile +from pathlib import Path + +import numpy as np +from shapely import STRtree +from shapely.geometry import box + +import main + + +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), "正常") + + def test_signal_raster_colors(self): + values = np.array([[-106.0, -105.0, -100.0, -95.0, -94.0]], dtype=np.float32) + colors = main.heatmap_rgb_for_values(values) + self.assertEqual(colors.tolist(), [[[255, 0, 0], [255, 0, 0], [255, 255, 0], [255, 255, 0], [0, 176, 80]]]) + + +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( + values, + mask, + main.WEAK_COVER_COLORS, + main.WEAK_COVER_PERCENT_STEPS, + ) + + self.assertEqual(thresholds, [0.0, 0.0]) + self.assertEqual(counts, [1, 0, 5]) + self.assertTrue(np.all(result[values == 0] == main.WEAK_COVER_COLORS[-1])) + self.assertTrue(np.all(result[values == 10] == main.WEAK_COVER_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,)) + + +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)), "大建筑") + + +class OutputSafetyTest(unittest.TestCase): + def test_raster_layout_respects_pixel_limit(self): + original_limit = main.MAX_RASTER_PIXELS + main.MAX_RASTER_PIXELS = 100 + try: + layout = main.market_raster_layout((0, 0, 10, 10), 0.1, 0.1) + finally: + main.MAX_RASTER_PIXELS = original_limit + self.assertLessEqual(layout[6] * layout[7], 100) + self.assertGreater(layout[8], 1.0) + + def test_zip_output_is_complete(self): + with tempfile.TemporaryDirectory() as temp_dir: + root = Path(temp_dir) + workspace = root / "workspace" + workspace.mkdir() + (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) + with zipfile.ZipFile(zip_path) as archive: + self.assertEqual(sorted(archive.namelist()), ["a.txt", "b.txt"]) + self.assertEqual(result["entries"], ["a.txt", "b.txt"]) + self.assertFalse((root / ".market.zip.tmp").exists()) + + +if __name__ == "__main__": + unittest.main()