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") # 源数据目录,存放 MarketMap.gpkg、grid.gpkg 等输入文件。 OUTPUT_DIR = Path("output") # 输出根目录,每个市场网格会在这里生成一个 JMXXXX.zip 结果包。 MARKET_GPKG = DEFAULT_SOURCE_DIR / "MarketMap.gpkg" # 市场网格 GeoPackage 文件路径。 GRID_GPKG = DEFAULT_SOURCE_DIR / "grid.gpkg" # Grid 栅格指标 GeoPackage 文件路径。 BUILDING_GPKG = DEFAULT_SOURCE_DIR / "Building.gpkg" # 建筑指标 GeoPackage 文件路径,用于生成楼宇指标 CSV。 BUILDING_INFO_GPKG = DEFAULT_SOURCE_DIR / "BuildingInfo.gpkg" # 建筑信息 GeoPackage 文件路径,用于结果包 BuildingInfo 分割和楼宇指标 CSV 名称匹配。 MAP_PARK_DIR = DEFAULT_SOURCE_DIR / "MapPark" # QGIS 项目模板目录,里面的 GIS.qgz 用于生成各市场网格项目。 GIS_PROJECT_SOURCE = MAP_PARK_DIR / "GIS.qgz" # 每个市场网格结果包要使用的 QGIS 项目模板来源。 RSRP_FIELD = "ssb_rsrp_dl" # 用于生成热力图的电信 RSRP 字段名。 EXCELLENT_CELL_FIELD = "mro_total_dl" # 用于生成用户量热力图的字段名,值越大越红。 WEAK_COVER_FIELD = "rsrp_lt_neg105_dl" # 用于生成信号差用户量热力图的字段名,值越大越红。 MARKET_LAYER = None # 市场网格图层名;None 表示自动使用 GPKG 中第一个 feature 图层。 GRID_LAYER = None # Grid 指标图层名;None 表示自动使用 GPKG 中第一个 feature 图层。 BUILDING_LAYER = None # Building 建筑指标图层名;None 表示自动使用 GPKG 中第一个 feature 图层。 BUILDING_INFO_LAYER = None # BuildingInfo 建筑信息图层名;None 表示自动使用 GPKG 中第一个 feature 图层。 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 连续红黄绿热力图输出文件名。 BUILDING_INFO_OUTPUT_FILENAME = "BuildingInfo.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_MID_RSRP = -95.0 # 热力图黄色中间阈值。 HEATMAP_BAD_RSRP = -105.0 # 热力图红色端阈值;RSRP 小于等于该值视为信号差。 HEATMAP_GOOD_RSRP = -80.0 # 热力图绿色端阈值;RSRP 大于等于该值使用纯绿色。 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" # 采样点数量热力图输出文件名。 WEAK_COVER_OUTPUT_FILENAME = "信号差用户量.tif" # 信号差用户量热力图输出文件名。 WEAK_COVER_RATIO_OUTPUT_FILENAME = "弱覆盖占比.tif" # 弱覆盖采样点占总采样点比例的分级 TIF 输出文件名。 WEAK_COVER_RATIO_GREEN_MAX = 5.0 # 弱覆盖占比小于等于该百分比时使用绿色。 WEAK_COVER_RATIO_YELLOW_MIN = 10.0 # 弱覆盖占比大于等于该百分比时由蓝色进入黄色。 WEAK_COVER_RATIO_RED_MIN = 20.0 # 弱覆盖占比大于等于该百分比时使用红色。 WEAK_COVER_RATIO_GREEN = (0, 176, 80) # 弱覆盖占比低值档颜色。 WEAK_COVER_RATIO_BLUE = (0, 112, 255) # 弱覆盖占比偏低档颜色。 WEAK_COVER_RATIO_YELLOW = (255, 255, 0) # 弱覆盖占比偏高档颜色。 WEAK_COVER_RATIO_RED = (255, 0, 0) # 弱覆盖占比高值档颜色。 SUMMARY_OUTPUT_ENABLED = True # 是否额外生成全部市场网格汇总 TIF 结果包。 SUMMARY_OUTPUT_FILENAME = "所有网格汇总.zip" # 汇总结果包文件名,包含四张 TIF、GIS.qgz 和完整 BuildingInfo.gpkg。 SUMMARY_MARKET_CODE = "所有网格汇总" # 汇总任务在日志和 summary.json 中使用的标识。 SUMMARY_MAX_RASTER_PIXELS = 100_000_000 # 汇总 TIF 最大像元数;提高该值可增强清晰度,但会增加内存、耗时和文件体积。 EXCELLENT_PERCENT_STEPS = (0.25, 0.5, 0.75) # 按最终有效像元降序四等分,取 25%、50%、75% 位置作为结果记录阈值。 EXCELLENT_COLORS = ( (255, 0, 0), # 高值端,红色。 (255, 255, 0), # 偏高值,黄色。 (0, 112, 255), # 偏低值,蓝色。 (0, 176, 80), # 低值端,绿色。 ) CONTINUOUS_HEATMAP_RED = (255, 0, 0) # 连续热力图高风险端颜色。 CONTINUOUS_HEATMAP_YELLOW = (255, 255, 0) # 连续热力图中间颜色。 CONTINUOUS_HEATMAP_GREEN = (0, 176, 80) # 连续热力图低风险端颜色。 WEAK_COVER_YELLOW_PERCENTILE = 0.75 # 信号差用户量黄色锚点百分位;0.75 使红色集中在最高值约 25% 区域。 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 heatmap_raster_filename(_field): return SIGNAL_OUTPUT_FILENAME def excellent_heatmap_raster_filename(_field): return USER_COUNT_OUTPUT_FILENAME def weak_cover_heatmap_raster_filename(_field): return WEAK_COVER_OUTPUT_FILENAME def weak_cover_ratio_raster_filename(): return WEAK_COVER_RATIO_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 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 continuous_heatmap_rgb_for_scores(scores, yellow_score=0.5): if not 0 < yellow_score < 1: raise ValueError("yellow_score 必须大于 0 且小于 1") normalized = np.clip(np.asarray(scores, dtype=np.float32), 0.0, 1.0) result = np.empty((*normalized.shape, 3), dtype=np.float32) green = np.asarray(CONTINUOUS_HEATMAP_GREEN, dtype=np.float32) yellow = np.asarray(CONTINUOUS_HEATMAP_YELLOW, dtype=np.float32) red = np.asarray(CONTINUOUS_HEATMAP_RED, dtype=np.float32) lower_mask = normalized <= yellow_score lower_weight = (normalized[lower_mask] / yellow_score)[..., None] result[lower_mask] = green + (yellow - green) * lower_weight upper_mask = ~lower_mask upper_weight = ((normalized[upper_mask] - yellow_score) / (1.0 - yellow_score))[..., None] result[upper_mask] = yellow + (red - yellow) * upper_weight return np.rint(np.clip(result, 0, 255)).astype(np.uint8) def heatmap_rgb_for_values(values): values = np.asarray(values, dtype=np.float32) scores = np.empty(values.shape, dtype=np.float32) scores[values <= HEATMAP_BAD_RSRP] = 1.0 middle_mask = (values > HEATMAP_BAD_RSRP) & (values <= HEATMAP_MID_RSRP) scores[middle_mask] = 1.0 - 0.5 * ( (values[middle_mask] - HEATMAP_BAD_RSRP) / (HEATMAP_MID_RSRP - HEATMAP_BAD_RSRP) ) good_mask = (values > HEATMAP_MID_RSRP) & (values < HEATMAP_GOOD_RSRP) scores[good_mask] = 0.5 * ( (HEATMAP_GOOD_RSRP - values[good_mask]) / (HEATMAP_GOOD_RSRP - HEATMAP_MID_RSRP) ) scores[values >= HEATMAP_GOOD_RSRP] = 0.0 return continuous_heatmap_rgb_for_scores(scores) def weak_cover_ratio_rgb_for_values(values): values = np.asarray(values, dtype=np.float32) colors = np.empty((*values.shape, 3), dtype=np.uint8) colors[:] = WEAK_COVER_RATIO_GREEN colors[(values > WEAK_COVER_RATIO_GREEN_MAX) & (values < WEAK_COVER_RATIO_YELLOW_MIN)] = WEAK_COVER_RATIO_BLUE colors[(values >= WEAK_COVER_RATIO_YELLOW_MIN) & (values < WEAK_COVER_RATIO_RED_MIN)] = WEAK_COVER_RATIO_YELLOW colors[values >= WEAK_COVER_RATIO_RED_MIN] = WEAK_COVER_RATIO_RED return colors def percentile_scores_for_values(values, data_mask, anchor_scores=(0.0, 0.5, 1.0)): scores = np.zeros(values.shape, dtype=np.float32) valid_values = values[data_mask] if valid_values.size == 0: return scores, [] unique_values, inverse, counts = np.unique(valid_values, return_inverse=True, return_counts=True) if unique_values.size == 1: return scores, [float(unique_values[0])] * len(anchor_scores) cumulative_before = np.cumsum(counts, dtype=np.int64) - counts rank_scores = cumulative_before.astype(np.float32) / float(cumulative_before[-1]) scores[data_mask] = rank_scores[inverse] anchor_values = [] for anchor_score in anchor_scores: index = min(int(np.searchsorted(rank_scores, anchor_score, side="left")), unique_values.size - 1) anchor_values.append(float(unique_values[index])) return scores, anchor_values 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) - 1) 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 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 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_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 smooth_weighted_values(value_sum, value_weight): data_mask = value_weight > 0 smoothed_value = np.zeros_like(value_sum) if np.any(data_mask): smoothed_sum = gaussian_blur(value_sum, HEATMAP_SMOOTH_RADIUS) smoothed_weight = gaussian_blur(value_weight, HEATMAP_SMOOTH_RADIUS) np.divide(smoothed_sum, smoothed_weight, out=smoothed_value, where=smoothed_weight > 0) return smoothed_value, data_mask 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) smoothed_value, data_mask = smooth_weighted_values(state["value_sum"], state["value_weight"]) if np.any(data_mask): image[data_mask, :3] = heatmap_rgb_for_values(smoothed_value)[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_pixels": state["painted_cells"], "data_pixels": int(np.count_nonzero(data_mask)), "skipped_no_value": state["skipped_no_value"], "color_mode": "continuous_fixed_rsrp", "color_anchors": { "red": HEATMAP_BAD_RSRP, "yellow": HEATMAP_MID_RSRP, "green": HEATMAP_GOOD_RSRP, }, "smooth_radius": HEATMAP_SMOOTH_RADIUS, "width": width, "height": height, "skipped": False, } 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 render_percentile_heatmap_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) smoothed_value, data_mask = smooth_weighted_values(state["value_sum"], state["value_weight"]) anchor_values = [] if np.any(data_mask): anchor_scores = (0.0, WEAK_COVER_YELLOW_PERCENTILE, 1.0) scores, anchor_values = percentile_scores_for_values(smoothed_value, data_mask, anchor_scores) image[data_mask, :3] = continuous_heatmap_rgb_for_scores( scores, yellow_score=WEAK_COVER_YELLOW_PERCENTILE, )[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"], "color_mode": "continuous_percentile", "yellow_percentile": WEAK_COVER_YELLOW_PERCENTILE, "color_anchor_values": { "green": anchor_values[0], "yellow": anchor_values[1], "red": anchor_values[2], } if anchor_values else None, "smooth_radius": HEATMAP_SMOOTH_RADIUS, "width": width, "height": height, "skipped": False, } def render_weak_cover_ratio_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) smoothed_value, data_mask = smooth_weighted_values(state["value_sum"], state["value_weight"]) if np.any(data_mask): image[data_mask, :3] = weak_cover_ratio_rgb_for_values(smoothed_value)[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"], "color_mode": "fixed_weak_cover_ratio_classes", "percentage_thresholds": { "green_max": WEAK_COVER_RATIO_GREEN_MAX, "yellow_min": WEAK_COVER_RATIO_YELLOW_MIN, "red_min": WEAK_COVER_RATIO_RED_MIN, }, "smooth_radius": HEATMAP_SMOOTH_RADIUS, "width": width, "height": height, "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 export_market_grid_outputs( grid_conn, grid_layer, rtree, market, pixel_width, pixel_height, signal_path, user_count_path, weak_cover_path, weak_cover_ratio_path, csv_path, 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 = (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 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_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) candidates = 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_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} for field, value in numeric_values.items(): if value is None: skipped_no_value[field] += 1 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 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_percentile_heatmap_raster( weak_cover_state, market, weak_cover_path, minx, maxy, pixel_width, pixel_height, width, height, candidates, ) del weak_cover_state ratio_value_sum = np.zeros((height, width), dtype=np.float32) ratio_value_weight = np.zeros((height, width), dtype=np.uint16) ratio_painted_cells = 0 ratio_skipped_no_value = 0 for cell in raster_cells: row_start, row_stop, col_start, col_stop = cell[:4] total = cell[5] weak_cover = cell[6] if total is None or total <= 0 or weak_cover is None or weak_cover < 0: ratio_skipped_no_value += 1 continue ratio = weak_cover / total * 100.0 ratio_value_sum[row_start:row_stop, col_start:col_stop] += ratio ratio_value_weight[row_start:row_stop, col_start:col_stop] += 1 ratio_painted_cells += 1 ratio_state = { "value_sum": ratio_value_sum, "value_weight": ratio_value_weight, "painted_cells": ratio_painted_cells, "skipped_no_value": ratio_skipped_no_value, } weak_cover_ratio_result = render_weak_cover_ratio_raster( ratio_state, market, weak_cover_ratio_path, minx, maxy, pixel_width, pixel_height, width, height, candidates, ) del ratio_state, ratio_value_sum, ratio_value_weight for result in (signal_result, user_count_result, weak_cover_result, weak_cover_ratio_result): 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 signal_result, user_count_result, weak_cover_result, weak_cover_ratio_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: writer = csv.writer(file) writer.writerow(["field", "rsrp_anchor", "red", "green", "blue", "alpha", "meaning"]) writer.writerow([field, f"<= {HEATMAP_BAD_RSRP}", *CONTINUOUS_HEATMAP_RED, HEATMAP_ALPHA, "bad signal red endpoint"]) writer.writerow([field, HEATMAP_MID_RSRP, *CONTINUOUS_HEATMAP_YELLOW, HEATMAP_ALPHA, "continuous yellow anchor"]) writer.writerow([field, f">= {HEATMAP_GOOD_RSRP}", *CONTINUOUS_HEATMAP_GREEN, HEATMAP_ALPHA, "good signal green endpoint"]) writer.writerow([field, "nodata", 0, 0, 0, 0, "transparent no data"]) return legend_path 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_25_percent", "25_to_50_percent", "50_to_75_percent", "bottom_25_percent") for rank_range, color in zip(rank_ranges, EXCELLENT_COLORS): writer.writerow([field, rank_range, *color, HEATMAP_ALPHA, "ranked-pixel quartile"]) writer.writerow([field, "nodata", 0, 0, 0, 0, "transparent no data"]) return legend_path def write_weak_cover_heatmap_legend(output_dir, field): legend_path = output_dir / "weak_cover_heatmap_legend.csv" with legend_path.open("w", newline="", encoding="utf-8-sig") as file: writer = csv.writer(file) writer.writerow(["field", "percentile_anchor", "red", "green", "blue", "alpha", "meaning"]) writer.writerow([field, "highest_value", *CONTINUOUS_HEATMAP_RED, HEATMAP_ALPHA, "most weak-cover users"]) writer.writerow([field, f"percentile_{WEAK_COVER_YELLOW_PERCENTILE}", *CONTINUOUS_HEATMAP_YELLOW, HEATMAP_ALPHA, "continuous yellow anchor"]) writer.writerow([field, "lowest_value", *CONTINUOUS_HEATMAP_GREEN, HEATMAP_ALPHA, "fewest weak-cover users"]) writer.writerow([field, "nodata", 0, 0, 0, 0, "transparent no data"]) return legend_path def write_weak_cover_ratio_legend(output_dir): legend_path = output_dir / "weak_cover_ratio_legend.csv" with legend_path.open("w", newline="", encoding="utf-8-sig") as file: writer = csv.writer(file) writer.writerow(["formula", "percentage_range", "red", "green", "blue", "alpha", "meaning"]) formula = f"{WEAK_COVER_FIELD} / {EXCELLENT_CELL_FIELD} * 100" writer.writerow([formula, f">= {WEAK_COVER_RATIO_RED_MIN}%", *WEAK_COVER_RATIO_RED, HEATMAP_ALPHA, "high weak-cover ratio"]) writer.writerow([formula, f">= {WEAK_COVER_RATIO_YELLOW_MIN}% and < {WEAK_COVER_RATIO_RED_MIN}%", *WEAK_COVER_RATIO_YELLOW, HEATMAP_ALPHA, "medium-high weak-cover ratio"]) writer.writerow([formula, f"> {WEAK_COVER_RATIO_GREEN_MAX}% and < {WEAK_COVER_RATIO_YELLOW_MIN}%", *WEAK_COVER_RATIO_BLUE, HEATMAP_ALPHA, "medium-low weak-cover ratio"]) writer.writerow([formula, f"<= {WEAK_COVER_RATIO_GREEN_MAX}%", *WEAK_COVER_RATIO_GREEN, HEATMAP_ALPHA, "low weak-cover ratio"]) writer.writerow([formula, "no valid total", 0, 0, 0, 0, "transparent no data"]) 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_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 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) weak_cover_ratio_path = market_dir / weak_cover_ratio_raster_filename() grid_metrics_path = market_dir / GRID_METRICS_CSV_FILENAME grid_started_at = perf_counter() signal_result, user_count_result, weak_cover_result, weak_cover_ratio_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, weak_cover_ratio_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, ) gis_project_result = copy_gis_project_to_market( GIS_PROJECT_SOURCE, gis_project_path, market, building_info_result["extent"], ) 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), "weak_cover_ratio_result": rewrite_result_for_zip(weak_cover_ratio_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 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_GPKG) as grid_conn: grid_layer = resolve_feature_layer(grid_conn, GRID_LAYER) grid_rtree = rtree_name(grid_conn, grid_layer) with tempfile.TemporaryDirectory(prefix="market_grid_summary_") as temp_dir: summary_dir = Path(temp_dir) signal_path = summary_dir / heatmap_raster_filename(RSRP_FIELD) user_count_path = summary_dir / excellent_heatmap_raster_filename(EXCELLENT_CELL_FIELD) weak_cover_path = summary_dir / weak_cover_heatmap_raster_filename(WEAK_COVER_FIELD) weak_cover_ratio_path = summary_dir / weak_cover_ratio_raster_filename() signal_result, user_count_result, weak_cover_result, weak_cover_ratio_result, _ = export_market_grid_outputs( grid_conn, grid_layer, grid_rtree, summary_market, pixel_width, pixel_height, signal_path, user_count_path, weak_cover_path, weak_cover_ratio_path, None, SUMMARY_MAX_RASTER_PIXELS, ) 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, } 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, ) zip_result = write_market_zip(summary_dir, zip_path, summary_market) return { "market_code": summary_market.code, "heatmap_result": rewrite_result_for_zip(signal_result, zip_path, summary_dir), "excellent_heatmap_result": rewrite_result_for_zip(user_count_result, zip_path, summary_dir), "weak_cover_heatmap_result": rewrite_result_for_zip(weak_cover_result, zip_path, summary_dir), "weak_cover_ratio_result": rewrite_result_for_zip(weak_cover_ratio_result, zip_path, summary_dir), "building_info_result": rewrite_result_for_zip(building_info_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") if not HEATMAP_BAD_RSRP < HEATMAP_MID_RSRP < HEATMAP_GOOD_RSRP: raise ValueError("RSRP 热力图阈值必须满足 HEATMAP_BAD_RSRP < HEATMAP_MID_RSRP < HEATMAP_GOOD_RSRP") if not 0 < WEAK_COVER_YELLOW_PERCENTILE < 1: raise ValueError("WEAK_COVER_YELLOW_PERCENTILE 必须大于 0 且小于 1") if not 0 <= WEAK_COVER_RATIO_GREEN_MAX < WEAK_COVER_RATIO_YELLOW_MIN < WEAK_COVER_RATIO_RED_MIN: raise ValueError("弱覆盖占比阈值必须满足 0 <= GREEN_MAX < YELLOW_MIN < RED_MIN") 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_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 ( 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) building_layer = resolve_feature_layer(building_conn, BUILDING_LAYER) building_info_layer = resolve_feature_layer(building_info_conn, BUILDING_INFO_LAYER) if market_layer.srs_id != 4326 or grid_layer.srs_id != 4326: raise ValueError("当前脚本只处理 EPSG:4326 的输入图层") if building_layer.srs_id not in BUILDING_ALLOWED_SRS_IDS: raise ValueError(f"Building 图层坐标系不在允许范围内:{building_layer.srs_id}") 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_conn, grid_layer.table_name, CSV_SOURCE_FIELDS, ) require_columns(building_info_conn, building_info_layer.table_name, ["name"]) 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: estimated_width, estimated_height = estimate_pixel_size(grid_conn, grid_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": grid_layer.table_name, "building": building_layer.table_name, "building_info": building_info_layer.table_name, } 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) weak_cover_ratio_legend_path = write_weak_cover_ratio_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"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}") print(f"弱覆盖占比图例:{weak_cover_ratio_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"]) summary_grid_result = None if SUMMARY_OUTPUT_ENABLED and markets: print("开始生成全部市场网格汇总 TIF……") summary_grid_result = process_summary_grid_outputs(markets, pixel_width, pixel_height, OUTPUT_DIR) print( f"汇总 TIF 完成:{summary_grid_result['zip_result']['output']}," f"耗时 {summary_grid_result['elapsed_seconds']:.1f} 秒" ) result_mappings = { "heatmap_results": "heatmap_result", "excellent_heatmap_results": "excellent_heatmap_result", "weak_cover_heatmap_results": "weak_cover_heatmap_result", "weak_cover_ratio_results": "weak_cover_ratio_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, "weak_cover_ratio_formula": f"{WEAK_COVER_FIELD} / {EXCELLENT_CELL_FIELD} * 100", "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}") if __name__ == "__main__": main()