import csv import json import math import re import shutil import sqlite3 import tempfile import xml.etree.ElementTree as ET import zipfile from concurrent.futures import ProcessPoolExecutor, as_completed from contextlib import contextmanager from dataclasses import dataclass from pathlib import Path from time import perf_counter, sleep import numpy as np import shapely import tifffile from shapely import Point, STRtree, from_wkb from shapely.errors import GEOSException DEFAULT_SOURCE_DIR = Path("source") # 源数据目录,存放 GridMap.gpkg、Grid_5G.gpkg、Grid_4G.gpkg 等输入文件。 OUTPUT_DIR = Path("output") # 输出根目录,每个市场网格会在这里生成一个 JMXXXX.zip 结果包。 MARKET_GPKG = DEFAULT_SOURCE_DIR / "GridMap.gpkg" # 市场网格 GeoPackage 文件路径。 GRID_5G_GPKG = DEFAULT_SOURCE_DIR / "Grid_5G.gpkg" # 5G Grid;竟对信号仅使用该文件。 # 用户量图层停用;以下原代码以注释保留,便于按需恢复。 # GRID_4G_GPKG = DEFAULT_SOURCE_DIR / "Grid_4G.gpkg" # 4G Grid;仅参与竟对用户量合并。 BUILDING_INFO_GPKG = DEFAULT_SOURCE_DIR / "BuildingInfo.gpkg" # 建筑信息 GeoPackage 文件路径,用于结果包 BuildingInfo 分割和楼宇指标 CSV 名称匹配。 CELL_DATA_GPKG = DEFAULT_SOURCE_DIR / "CellData.gpkg" # 小区数据 GeoPackage;仅完整复制到汇总结果包。 GIS_PROJECT_SOURCE = DEFAULT_SOURCE_DIR / "GIS.qgz" # 每个市场网格结果包使用的 QGIS 项目模板来源。 AOI_OUTPUT_FILENAME = "AOI级报表_市场网格匹配.gpkg" AOI_GPKG = OUTPUT_DIR / AOI_OUTPUT_FILENAME # 已完成市场归属匹配的 AOI 总表。 AOI_LAYER = "AOI市场网格匹配" AOI_MARKET_FIELD = "所属市场网格" RSRP_FIELD = "ssb_rsrp_dl" # 用于生成热力图的电信 RSRP 字段名。 # EXCELLENT_CELL_FIELD = "mro_total_dl" # 用于生成用户量热力图的字段名,值越大越红。 EXCELLENT_CELL_FIELD = "mro_total_dl" # 竟对信号筛选仍需使用的 5G 竟对总采样量字段。 GRID_ID_FIELD = "grid20_id" # 4G/5G 用户量合并去重的唯一索引字段。 WEAK_COVER_FIELD = "rsrp_lt_neg105_dl" # 用于生成信号差用户量热力图的字段名,值越大越红。 MOBILE_TOTAL_FIELD = "mro_total_yd" # 移动采样点总数字段,用作移动弱覆盖比例分母。 MOBILE_WEAK_COVER_FIELD = "rsrp_lt_neg105_yd" # 移动弱覆盖采样点字段,用作目标 Grid 筛选。 MARKET_LAYER = None # 市场网格图层名;None 表示自动使用 GPKG 中第一个 feature 图层。 GRID_5G_LAYER = None # 5G Grid 图层名;None 表示自动使用 GPKG 中第一个 feature 图层。 # GRID_4G_LAYER = None # 4G Grid 图层名;None 表示自动使用 GPKG 中第一个 feature 图层。 BUILDING_LAYER = None # Building 建筑指标图层名;None 表示自动使用 GPKG 中第一个 feature 图层。 BUILDING_INFO_LAYER = None # BuildingInfo 建筑信息图层名;None 表示自动使用 GPKG 中第一个 feature 图层。 MARKET_CODE_FIELD = "fid" # GridMap 市场网格唯一 ID 前缀字段。 MARKET_NAME_FIELD = "Name" # GridMap 市场网格名称字段。 MARKET_ID_SEPARATOR = "-" # 市场网格唯一 ID 拼接符,输出为 fid-name,例如 1-城区蓬江。 BUILDING_INFO_OUTPUT_FILENAME = "BuildingInfo.gpkg" # 每个市场网格结果包内输出的建筑信息拆分文件名。 CELL_DATA_OUTPUT_FILENAME = "CellData.gpkg" # 汇总结果包内的小区数据文件名。 BUILDING_METRICS_CSV_FILENAME = "楼宇指标.csv" # 每个市场网格结果包内输出的楼宇指标 CSV 文件名。 GRID_METRICS_CSV_FILENAME = "栅格指标.csv" # 每个市场网格结果包内输出的栅格指标 CSV 文件名。 CSV_ENCODING = "gbk" # 指标 CSV 输出编码,供 Excel/传统 GIS 工具直接打开。 CSV_SOURCE_FIELDS = ("area_type", "area_name", "longitude", "latitude", "mro_total_dl", "rsrp_lt_neg105_dl", "ssb_rsrp_dl", "ssb_rsrp_yd") # 指标 CSV 从源图层提取的字段。 SIGNAL_BAD_THRESHOLD = -105.0 # 信号等级“较差”的阈值,小于等于该值输出较差。 SIGNAL_NORMAL_THRESHOLD = -95.0 # 信号等级“一般/正常”的分界,大于该值输出正常。 GIS_PROJECT_OUTPUT_FILENAME = "GIS.qgz" # 每个市场网格结果包内输出的 QGIS 项目文件名,画布范围按 BuildingInfo 自动更新。 HEATMAP_SMOOTH_RADIUS = 10 # 热力图平滑半径,数值越大边界感越弱但细节越柔。 HEATMAP_ALPHA = 191 # 热力图有效像元透明度;191 约等于 75% 不透明度。 PROJECT_EXTENT_PADDING_RATIO = 0.05 # QGIS 打开后的画布留白比例;0.05 表示在 BuildingInfo 范围四周各增加 5%。 # USER_COUNT_OUTPUT_FILENAME = "用户量.tif" # 采样点数量热力图输出文件名。 USER_COUNT_OUTPUT_FILENAME = "用户量.tif" # 保留文件名,以移除旧模板中的用户量图层引用。 COMPETITOR_SIGNAL_OUTPUT_FILENAME = "竟对信号.tif" # 移动非弱覆盖区域内的竟对 MR 弱覆盖/零采样信号图。 COMPETITOR_SIGNAL_MOBILE_WEAK_RATIO_MAX = 20.0 # 移动弱覆盖比例必须严格小于该百分比。 COMPETITOR_SIGNAL_WEAK_RATIO_MIN = 20.0 # 竟对 MR 弱覆盖比例必须严格大于该百分比。 COMPETITOR_SIGNAL_RSRP_BREAKS = (-110.0, -104.0, -98.0, -92.0, -86.0, -80.0, -74.0) # 八档颜色的七个分界点。 COMPETITOR_SIGNAL_RSRP_COLORS = ( (253, 0, 5), # < -110,红色。 (255, 138, 0), # [-110, -104),橙色。 (254, 253, 2), # [-104, -98),黄色。 (214, 251, 199), # [-98, -92),浅绿色。 (42, 231, 41), # [-92, -86),亮绿色。 (34, 174, 51), # [-86, -80),深绿色。 (0, 149, 231), # [-80, -74),蓝色。 (58, 14, 247), # [-74, 0],紫色。 ) SUMMARY_OUTPUT_ENABLED = True # 是否额外生成全部市场网格汇总 TIF 结果包。 # SUMMARY_OUTPUT_FILENAME = "全量网格图层.zip" # 汇总结果包文件名,包含两张 TIF、GIS.qgz、BuildingInfo.gpkg 和 CellData.gpkg。 SUMMARY_OUTPUT_FILENAME = "全量网格图层.zip" # 包含竟对信号 TIF、GIS.qgz、BuildingInfo.gpkg 和 CellData.gpkg。 LEGACY_SUMMARY_OUTPUT_FILENAME = "所有网格汇总.zip" # 旧汇总包文件名;新包成功生成后自动清理。 SUMMARY_MARKET_CODE = "全量网格图层" # 汇总任务在日志和 summary.json 中使用的标识。 SUMMARY_MAX_RASTER_PIXELS = 100_000_000 # 汇总 TIF 最大像元数;提高该值可增强清晰度,但会增加内存、耗时和文件体积。 EXCELLENT_PERCENT_STEPS = (0.1, 0.4, 0.7) # 按最终有效像元降序分档:前 10% 红,其余三档各约 30%。 EXCELLENT_COLORS = ( (255, 0, 0), # 高值端,红色。 (255, 255, 0), # 偏高值,黄色。 (0, 112, 255), # 偏低值,蓝色。 (0, 176, 80), # 低值端,绿色。 ) PIXEL_WIDTH = None # 输出像元宽度;None 表示自动按 Grid 单元宽度估算。 PIXEL_HEIGHT = None # 输出像元高度;None 表示自动按 Grid 单元高度估算。 SCALE = 5.0 # 分辨率倍数;2.0 表示像元宽高减半,放大查看更清晰。 SAMPLE_SIZE = 10000 # 自动估算像元大小时抽样读取的 Grid 要素数量。 LIMIT = None # 限制处理前 N 个市场网格;None 表示处理全部市场网格。 MAX_WORKERS = 4 # 市场网格并行处理进程数;当前 4 核/32GB 环境实测 4 进程吞吐最佳,内存较小时可降为 2。 GEOMETRY_BATCH_SIZE = 10000 # Shapely 批量解析和空间判断的每批要素数;增大可减少循环,过大会增加瞬时内存。 MAX_RASTER_PIXELS = 25_000_000 # 单张 TIF 最大像元数;超限时自动降低该市场分辨率,避免内存溢出。 CLIP_MODE = "intersects" # 裁切方式:intersects 按几何相交裁切,center 按 Grid 中心点落入裁切。 BUILDING_ALLOWED_SRS_IDS = (4326, 100000) # Building 允许的经纬度坐标系 ID;100000 是 CRS84。 BUILDING_INFO_ALLOWED_SRS_IDS = (4326, 100000) # BuildingInfo 允许的经纬度坐标系 ID;100000 是源文件中的 CRS84。 OVERWRITE = True # 输出文件已存在时是否覆盖。 TRANSPARENT_PIXEL = (0, 0, 0, 0) # 无数据/背景像元颜色,RGBA 中 alpha=0 表示透明。 @dataclass(frozen=True) class LayerInfo: table_name: str geom_col: str pk_col: str srs_id: int @dataclass(frozen=True) class MarketFeature: fid: int code: str name: str geometry: object def quote_identifier(name): return '"' + str(name).replace('"', '""') + '"' def safe_filename(value): text = str(value or "").strip() text = re.sub(r'[<>:"/\\|?*\s]+', "_", text) text = text.strip("._") return text or "unnamed" def market_output_dir(output_dir, market): return output_dir / safe_filename(market.code) def market_zip_output_path(output_dir, market): return output_dir / f"{safe_filename(market.code)}.zip" def build_summary_market(markets): if not markets: raise ValueError("至少需要一个市场网格才能生成汇总 TIF") geometries = np.asarray([market.geometry for market in markets], dtype=object) geometry = shapely.union_all(shapely.make_valid(geometries)) if geometry.is_empty: raise ValueError("市场网格合并结果为空,无法生成汇总 TIF") return MarketFeature(0, SUMMARY_MARKET_CODE, SUMMARY_MARKET_CODE, geometry) def excellent_heatmap_raster_filename(_field): return USER_COUNT_OUTPUT_FILENAME def competitor_signal_raster_filename(): return COMPETITOR_SIGNAL_OUTPUT_FILENAME def set_xml_extent(extent_element, extent): for tag, value in zip(("xmin", "ymin", "xmax", "ymax"), extent): child = extent_element.find(tag) if child is None: child = ET.SubElement(extent_element, tag) child.text = format(float(value), ".17g") def padded_extent(extent, padding_ratio): minx, miny, maxx, maxy = (float(value) for value in extent) width = maxx - minx height = maxy - miny padding_x = width * padding_ratio if width > 0 else (1e-6 if padding_ratio > 0 else 0.0) padding_y = height * padding_ratio if height > 0 else (1e-6 if padding_ratio > 0 else 0.0) return minx - padding_x, miny - padding_y, maxx + padding_x, maxy + padding_y def serialize_qgis_project(root, original_data): bom = b"\xef\xbb\xbf" if original_data.startswith(b"\xef\xbb\xbf") else b"" payload = original_data[len(bom):] first_line = payload.splitlines()[0] if payload else b"" doctype = first_line if first_line.startswith(b"> 1) & 0b111 envelope_sizes = { 0: 0, 1: 32, 2: 48, 3: 48, 4: 64, } return data[8 + envelope_sizes.get(envelope_code, 0):] def iter_geometry_batches(cursor, geom_index): while True: rows = cursor.fetchmany(GEOMETRY_BATCH_SIZE) if not rows: return wkbs = np.empty(len(rows), dtype=object) for index, row in enumerate(rows): geom_blob = row[geom_index] wkbs[index] = gpkg_blob_to_wkb(geom_blob) if geom_blob is not None else None geometries = from_wkb(wkbs, on_invalid="ignore") valid_mask = ~shapely.is_missing(geometries) & ~shapely.is_empty(geometries) yield rows, geometries, valid_mask def gpkg_primary_key(conn, table_name): for row in conn.execute(f"pragma table_info({quote_identifier(table_name)})"): if row[5]: return row[1] return "fid" def resolve_feature_layer(conn, preferred_table=None): rows = conn.execute( """ select c.table_name, g.column_name, g.srs_id from gpkg_contents c join gpkg_geometry_columns g on c.table_name = g.table_name where c.data_type = 'features' order by c.table_name """ ).fetchall() if not rows: raise ValueError("未找到 GeoPackage feature 图层") if preferred_table: for table_name, geom_col, srs_id in rows: if table_name == preferred_table: return LayerInfo(table_name, geom_col, gpkg_primary_key(conn, table_name), srs_id) raise ValueError(f"未找到指定图层:{preferred_table}") table_name, geom_col, srs_id = rows[0] return LayerInfo(table_name, geom_col, gpkg_primary_key(conn, table_name), srs_id) def table_columns(conn, table_name): return [row[1] for row in conn.execute(f"pragma table_info({quote_identifier(table_name)})")] def require_columns(conn, table_name, columns): available = set(table_columns(conn, table_name)) missing = [column for column in columns if column not in available] if missing: raise ValueError(f"{table_name} 缺少字段:{', '.join(missing)}") def rtree_name(conn, layer): candidate = f"rtree_{layer.table_name}_{layer.geom_col}" found = conn.execute( "select 1 from sqlite_master where type='table' and name=?", (candidate,), ).fetchone() if not found: raise ValueError(f"未找到 RTree 空间索引:{candidate}") return candidate def table_exists(conn, table_name): return conn.execute( "select 1 from sqlite_master where type = 'table' and name = ?", (table_name,), ).fetchone() is not None def sqlite_create_sql(conn, table_name): row = conn.execute( "select sql from sqlite_master where type = 'table' and name = ?", (table_name,), ).fetchone() if not row or not row[0]: raise ValueError(f"未找到表结构:{table_name}") return row[0] def copy_all_rows(source_conn, target_conn, table_name): if not table_exists(source_conn, table_name): return rows = source_conn.execute(f"select * from {quote_identifier(table_name)}").fetchall() if not rows: return placeholders = ", ".join(["?"] * len(rows[0])) target_conn.executemany( f"insert into {quote_identifier(table_name)} values ({placeholders})", rows, ) def create_table_like_source(source_conn, target_conn, table_name): if table_exists(source_conn, table_name): target_conn.execute(sqlite_create_sql(source_conn, table_name)) def copy_matching_rows(target_conn, table_name, columns, rows): if not rows: return column_sql = ", ".join(quote_identifier(column) for column in columns) placeholders = ", ".join(["?"] * len(columns)) target_conn.executemany( f"insert into {quote_identifier(table_name)} ({column_sql}) values ({placeholders})", rows, ) def copy_gpkg_support_tables(source_conn, target_conn, layer, feature_count, extent): support_tables = [ "gpkg_spatial_ref_sys", "gpkg_contents", "gpkg_geometry_columns", "gpkg_ogr_contents", "gpkg_extensions", "gpkg_metadata", "gpkg_metadata_reference", "gpkg_tile_matrix_set", "gpkg_tile_matrix", "layer_styles", ] for table_name in support_tables: create_table_like_source(source_conn, target_conn, table_name) for table_name in support_tables: copy_all_rows(source_conn, target_conn, table_name) minx, miny, maxx, maxy = extent if extent else (None, None, None, None) target_conn.execute( """ update gpkg_contents set min_x = ?, min_y = ?, max_x = ?, max_y = ? where table_name = ? """, (minx, miny, maxx, maxy, layer.table_name), ) if table_exists(target_conn, "gpkg_ogr_contents"): target_conn.execute( "update gpkg_ogr_contents set feature_count = ? where table_name = ?", (feature_count, layer.table_name), ) def initialize_split_output_gpkg(source_conn, output_path, layer, rtree, feature_count, extent): if output_path.exists(): if not OVERWRITE: return None output_path.unlink() target_conn = sqlite3.connect(output_path) target_conn.execute("pragma foreign_keys = off") target_conn.execute(f"pragma application_id = {source_conn.execute('pragma application_id').fetchone()[0]}") target_conn.execute(f"pragma user_version = {source_conn.execute('pragma user_version').fetchone()[0]}") copy_gpkg_support_tables(source_conn, target_conn, layer, feature_count, extent) target_conn.execute(sqlite_create_sql(source_conn, layer.table_name)) target_conn.execute(sqlite_create_sql(source_conn, rtree)) return target_conn def collect_intersecting_features(source_conn, layer, rtree, market): table = quote_identifier(layer.table_name) pk = quote_identifier(layer.pk_col) rtree_table = quote_identifier(rtree) columns = table_columns(source_conn, layer.table_name) column_sql = ", ".join(f"b.{quote_identifier(column)}" for column in columns) min_market_x, min_market_y, max_market_x, max_market_y = market.geometry.bounds query = f""" select {column_sql} from {rtree_table} r join {table} b on b.{pk} = r."id" where r."minx" <= ? and r."maxx" >= ? and r."miny" <= ? and r."maxy" >= ? """ geom_index = columns.index(layer.geom_col) pk_index = columns.index(layer.pk_col) rows = [] rtree_rows = [] extent = None candidates = 0 cursor = source_conn.execute(query, (max_market_x, min_market_x, max_market_y, min_market_y)) for batch_rows, geometries, valid_mask in iter_geometry_batches(cursor, geom_index): candidates += len(batch_rows) intersects_mask = valid_mask & shapely.intersects(market.geometry, geometries) matched_indexes = np.flatnonzero(intersects_mask) if matched_indexes.size == 0: continue matched_bounds = shapely.bounds(geometries[matched_indexes]) for index, bounds in zip(matched_indexes, matched_bounds): row = batch_rows[int(index)] minx, miny, maxx, maxy = bounds.tolist() rows.append(row) rtree_rows.append((row[pk_index], minx, maxx, miny, maxy)) if extent is None: extent = [minx, miny, maxx, maxy] else: extent[0] = min(extent[0], minx) extent[1] = min(extent[1], miny) extent[2] = max(extent[2], maxx) extent[3] = max(extent[3], maxy) return columns, rows, rtree_rows, tuple(extent) if extent else None, candidates def export_market_building_info_gpkg(source_conn, layer, rtree, market, output_path): columns, rows, rtree_rows, extent, candidates = collect_intersecting_features( source_conn, layer, rtree, market, ) target_conn = initialize_split_output_gpkg(source_conn, output_path, layer, rtree, len(rows), extent) if target_conn is None: return { "market_code": market.code, "market_name": market.name, "output": str(output_path), "candidates": candidates, "feature_count": None, "extent": list(extent) if extent else None, "skipped": True, } try: copy_matching_rows(target_conn, layer.table_name, columns, rows) if rtree_rows: target_conn.executemany( f"insert into {quote_identifier(rtree)} values (?, ?, ?, ?, ?)", rtree_rows, ) target_conn.commit() finally: target_conn.close() return { "market_code": market.code, "market_name": market.name, "output": str(output_path), "candidates": candidates, "feature_count": len(rows), "extent": list(extent) if extent else None, "skipped": False, } def export_market_aoi_gpkg(source_conn, layer, rtree, market, output_path): require_columns(source_conn, layer.table_name, [AOI_MARKET_FIELD, "AOI唯一标签", "AOI名称"]) if layer.srs_id != 4326: raise ValueError("AOI 图层必须使用 EPSG:4326") table = quote_identifier(layer.table_name) owner = quote_identifier(AOI_MARKET_FIELD) pk = quote_identifier(layer.pk_col) columns = table_columns(source_conn, layer.table_name) rows = source_conn.execute(f"select * from {table} where {owner} = ? order by {pk}", (market.name,)).fetchall() rtree_rows = source_conn.execute( f"select r.* from {quote_identifier(rtree)} r join {table} a on a.{pk} = r.id " f"where a.{owner} = ? order by r.id", (market.name,), ).fetchall() extent = None if rtree_rows: extent = (min(row[1] for row in rtree_rows), min(row[3] for row in rtree_rows), max(row[2] for row in rtree_rows), max(row[4] for row in rtree_rows)) srs_wkt = source_conn.execute("select definition from gpkg_spatial_ref_sys where srs_id = ?", (layer.srs_id,)).fetchone()[0] result = { "market_code": market.code, "market_name": market.name, "output": str(output_path), "layer_name": layer.table_name, "feature_count": len(rows), "extent": list(extent) if extent else None, "srs_wkt": srs_wkt, "match_field": AOI_MARKET_FIELD, "match_value": market.name, } target_conn = initialize_split_output_gpkg(source_conn, output_path, layer, rtree, len(rows), extent) if target_conn is None: return {**result, "skipped": True} try: copy_matching_rows(target_conn, layer.table_name, columns, rows) target_conn.executemany(f"insert into {quote_identifier(rtree)} values (?, ?, ?, ?, ?)", rtree_rows) target_conn.commit() finally: target_conn.close() return {**result, "bytes": output_path.stat().st_size, "skipped": False} def csv_text(value): if value is None: return "" return str(value).strip() def signal_level(value): number = to_float(value) if number is None: return "无采集信息" if number <= SIGNAL_BAD_THRESHOLD: return "较差" if number <= SIGNAL_NORMAL_THRESHOLD: return "一般" return "正常" def collect_intersecting_metric_features(source_conn, layer, rtree, market, fields): require_columns(source_conn, layer.table_name, fields) table = quote_identifier(layer.table_name) pk = quote_identifier(layer.pk_col) geom = quote_identifier(layer.geom_col) rtree_table = quote_identifier(rtree) field_sql = ", ".join(f"b.{quote_identifier(field)}" for field in fields) min_market_x, min_market_y, max_market_x, max_market_y = market.geometry.bounds query = f""" select b.{pk}, b.{geom}, {field_sql} from {rtree_table} r join {table} b on b.{pk} = r."id" where r."minx" <= ? and r."maxx" >= ? and r."miny" <= ? and r."maxy" >= ? """ rows = [] candidates = 0 cursor = source_conn.execute(query, (max_market_x, min_market_x, max_market_y, min_market_y)) for batch_rows, geometries, valid_mask in iter_geometry_batches(cursor, 1): candidates += len(batch_rows) intersects_mask = valid_mask & shapely.intersects(market.geometry, geometries) for index in np.flatnonzero(intersects_mask): row = batch_rows[int(index)] rows.append((dict(zip(fields, row[2:])), geometries[index])) return rows, candidates def load_building_name_index(building_info_conn, layer, rtree, bounds): geometries = [] names = [] if bounds is None: return None table = quote_identifier(layer.table_name) geom = quote_identifier(layer.geom_col) pk = quote_identifier(layer.pk_col) rtree_table = quote_identifier(rtree) minx, miny, maxx, maxy = bounds query = f""" select b."name", b.{geom} from {rtree_table} r join {table} b on b.{pk} = r."id" where r."minx" <= ? and r."maxx" >= ? and r."miny" <= ? and r."maxy" >= ? order by b.{pk} """ cursor = building_info_conn.execute(query, (maxx, minx, maxy, miny)) for batch_rows, batch_geometries, valid_mask in iter_geometry_batches(cursor, 1): for index in np.flatnonzero(valid_mask): name = csv_text(batch_rows[int(index)][0]) if not name: continue geometries.append(batch_geometries[index]) names.append(name) if not geometries: return None return STRtree(geometries), geometries, names def match_building_info_name(name_index, geometry): if name_index is None: return "" tree, geometries, names = name_index best_name = "" best_score = -1.0 for candidate_index in tree.query(geometry, predicate="intersects"): index = int(candidate_index) info_geometry = geometries[index] try: score = geometry.intersection(info_geometry).area except GEOSException: score = 0.0 if score > best_score: best_name = names[index] best_score = score return best_name def match_building_info_names(name_index, building_geometries): if name_index is None or not building_geometries: return [""] * len(building_geometries) tree, info_geometries, names = name_index building_array = np.asarray(building_geometries, dtype=object) info_array = np.asarray(info_geometries, dtype=object) pairs = tree.query(building_array, predicate="intersects") if pairs.shape[1] == 0: return [""] * len(building_geometries) result = np.full(len(building_geometries), "", dtype=object) names_array = np.asarray(names, dtype=object) match_counts = np.bincount(pairs[0], minlength=len(building_geometries)) single_pair_mask = match_counts[pairs[0]] == 1 single_pairs = pairs[:, single_pair_mask] result[single_pairs[0]] = names_array[single_pairs[1]] multiple_pairs = pairs[:, ~single_pair_mask] if multiple_pairs.shape[1]: try: areas = shapely.area( shapely.intersection( building_array[multiple_pairs[0]], info_array[multiple_pairs[1]], ) ) except GEOSException: return [match_building_info_name(name_index, geometry) for geometry in building_geometries] pair_positions = np.arange(multiple_pairs.shape[1]) order = np.lexsort((pair_positions, -areas, multiple_pairs[0])) ordered_sources = multiple_pairs[0][order] _, first_positions = np.unique(ordered_sources, return_index=True) best_pair_positions = order[first_positions] result[multiple_pairs[0, best_pair_positions]] = names_array[multiple_pairs[1, best_pair_positions]] return result.tolist() def write_metric_csv(output_path, headers, rows): if output_path.exists() and not OVERWRITE: return True with output_path.open("w", newline="", encoding=CSV_ENCODING, errors="replace") as file: writer = csv.writer(file) writer.writerow(headers) writer.writerows(rows) return False def metric_row(values): return [ csv_text(values.get("area_type")), csv_text(values.get("area_name")), csv_text(values.get("longitude")), csv_text(values.get("latitude")), csv_text(values.get("mro_total_dl")), csv_text(values.get("rsrp_lt_neg105_dl")), csv_text(values.get("ssb_rsrp_dl")), signal_level(values.get("ssb_rsrp_yd")), signal_level(values.get("ssb_rsrp_dl")), ] def export_market_building_metrics_csv( building_conn, building_layer, building_rtree, building_info_conn, building_info_layer, building_info_rtree, market, output_path, ): rows, candidates = collect_intersecting_metric_features( building_conn, building_layer, building_rtree, market, CSV_SOURCE_FIELDS, ) building_geometries = [geometry for _values, geometry in rows] building_bounds = shapely.total_bounds(building_geometries) if building_geometries else None building_name_index = load_building_name_index( building_info_conn, building_info_layer, building_info_rtree, building_bounds, ) headers = [ "网格ID", "区域类型", "区域名称", "建筑名称", "经度", "纬度", "竟对采样点总", "竟对弱覆盖采样点", "竟对平均信号值", "移动信号", "竟对信号", ] csv_rows = [] matched_names = 0 building_names = match_building_info_names(building_name_index, building_geometries) for (values, _geometry), building_name in zip(rows, building_names): if building_name: matched_names += 1 common_row = metric_row(values) csv_rows.append([market.code, common_row[0], common_row[1], building_name, *common_row[2:]]) skipped = write_metric_csv(output_path, headers, csv_rows) return { "market_code": market.code, "market_name": market.name, "output": str(output_path), "candidates": candidates, "row_count": len(csv_rows), "matched_names": matched_names, "skipped": skipped, } def load_market_features(conn, layer, code_field, name_field): require_columns(conn, layer.table_name, [code_field, name_field]) table = quote_identifier(layer.table_name) pk = quote_identifier(layer.pk_col) geom = quote_identifier(layer.geom_col) code = quote_identifier(code_field) name = quote_identifier(name_field) query = f"select {pk}, {code}, {name}, {geom} from {table} order by {pk}" features = [] for fid, market_code, market_name, geom_blob in conn.execute(query): if geom_blob is None: continue try: geometry = from_wkb(gpkg_blob_to_wkb(geom_blob)) except (GEOSException, ValueError): continue if not geometry.is_empty: name = str(market_name or fid).strip() code_prefix = str(market_code or fid).strip() market_code_text = f"{code_prefix}{MARKET_ID_SEPARATOR}{name}" if name else code_prefix features.append(MarketFeature(fid, market_code_text, name, geometry)) return features def estimate_pixel_size(conn, layer, sample_size): table = quote_identifier(layer.table_name) geom = quote_identifier(layer.geom_col) widths = [] heights = [] query = f"select {geom} from {table} where {geom} is not null limit ?" for (geom_blob,) in conn.execute(query, (sample_size,)): try: geometry = from_wkb(gpkg_blob_to_wkb(geom_blob)) except (GEOSException, ValueError): continue minx, miny, maxx, maxy = geometry.bounds width = maxx - minx height = maxy - miny if width > 0 and height > 0: widths.append(width) heights.append(height) if not widths or not heights: raise ValueError("无法从 Grid 图层估算像元大小") return float(np.median(widths)), float(np.median(heights)) def percentile_thresholds_from_values(values, percent_steps): sorted_values = np.sort(np.asarray(values, dtype=np.float32))[::-1] sorted_values = sorted_values[np.isfinite(sorted_values)] if sorted_values.size == 0: return [] thresholds = [] for percent in percent_steps: index = max(0, math.ceil(sorted_values.size * percent)) index = min(index, sorted_values.size - 1) thresholds.append(float(sorted_values[index])) return thresholds def ranked_pixel_rgb_for_values(values, data_mask, colors, percent_steps): result = np.zeros((*values.shape, 3), dtype=np.uint8) valid_positions = np.flatnonzero(data_mask.ravel()) if valid_positions.size == 0: return result, [], [] if len(percent_steps) != len(colors) - 1: raise ValueError("颜色数量必须比分位阈值数量多 1") valid_values = values.ravel()[valid_positions] thresholds = percentile_thresholds_from_values(valid_values, percent_steps) flat_result = result.reshape(-1, 3) remaining = np.ones(valid_values.shape, dtype=bool) rank_counts = [] for color, threshold in zip(colors[:-1], thresholds): selected = remaining & (valid_values > threshold) flat_result[valid_positions[selected]] = color rank_counts.append(int(np.count_nonzero(selected))) remaining &= ~selected flat_result[valid_positions[remaining]] = colors[-1] rank_counts.append(int(np.count_nonzero(remaining))) return result, thresholds, rank_counts def ranked_pixel_rgb_for_values_with_thresholds(values, data_mask, colors, thresholds): result = np.zeros((*values.shape, 3), dtype=np.uint8) valid_positions = np.flatnonzero(data_mask.ravel()) if valid_positions.size == 0: return result, [] if len(thresholds) != len(colors) - 1: raise ValueError("颜色数量必须比分位阈值数量多 1") valid_values = values.ravel()[valid_positions] flat_result = result.reshape(-1, 3) remaining = np.ones(valid_values.shape, dtype=bool) rank_counts = [] for color, threshold in zip(colors[:-1], thresholds): selected = remaining & (valid_values > threshold) flat_result[valid_positions[selected]] = color rank_counts.append(int(np.count_nonzero(selected))) remaining &= ~selected flat_result[valid_positions[remaining]] = colors[-1] rank_counts.append(int(np.count_nonzero(remaining))) return result, rank_counts def smooth_rgb_inside_mask(rgb, data_mask, radius): if radius <= 0: return rgb weight = data_mask.astype(np.float32) blurred_weight = gaussian_blur(weight, radius) smoothed = np.zeros_like(rgb, dtype=np.float32) for channel in range(3): blurred_channel = gaussian_blur(rgb[..., channel].astype(np.float32) * weight, radius) np.divide(blurred_channel, blurred_weight, out=smoothed[..., channel], where=blurred_weight > 0) smoothed[~data_mask] = 0 return np.clip(smoothed, 0, 255).astype(np.uint8) def gaussian_kernel(radius): if radius <= 0: return np.array([1.0], dtype=np.float32) sigma = max(radius / 2.0, 0.1) x = np.arange(-radius, radius + 1, dtype=np.float32) kernel = np.exp(-(x * x) / (2.0 * sigma * sigma)) return kernel / kernel.sum() def validate_smoothing_radius(name, radius): if isinstance(radius, bool) or not isinstance(radius, int) or radius < 0: raise ValueError(f"{name} 必须是非负整数") def convolve_axis(array, kernel, axis): if kernel.size == 1: return array radius = kernel.size // 2 pad_width = [(0, 0)] * array.ndim pad_width[axis] = (radius, radius) padded = np.pad(array, pad_width, mode="edge") windows = np.lib.stride_tricks.sliding_window_view(padded, kernel.size, axis=axis) return (windows @ kernel).astype(np.float32, copy=False) def gaussian_blur(array, radius): kernel = gaussian_kernel(radius) blurred = convolve_axis(array.astype(np.float32), kernel, axis=0) return convolve_axis(blurred, kernel, axis=1) def to_float(value): if value is None: return None if isinstance(value, (int, float)): number = float(value) return number if math.isfinite(number) else None try: text = str(value).strip() if not text: return None number = float(text) if not math.isfinite(number): return None return number except ValueError: return None def competitor_signal_filter_reason(mobile_weak, mobile_total, competitor_weak, competitor_total): if mobile_weak is None or mobile_total is None or competitor_total is None: return "invalid_fields" if mobile_total <= 0 or mobile_weak < 0 or competitor_total < 0: return "invalid_fields" mobile_weak_ratio = mobile_weak / mobile_total * 100.0 if mobile_weak_ratio >= COMPETITOR_SIGNAL_MOBILE_WEAK_RATIO_MAX: return "mobile_weak_ratio" if competitor_total == 0: return None if competitor_weak is None or competitor_weak < 0: return "invalid_fields" competitor_weak_ratio = competitor_weak / competitor_total * 100.0 if competitor_weak_ratio <= COMPETITOR_SIGNAL_WEAK_RATIO_MIN: return "competitor_weak_ratio" return None def competitor_signal_is_eligible(mobile_weak, mobile_total, competitor_weak, competitor_total): return competitor_signal_filter_reason(mobile_weak, mobile_total, competitor_weak, competitor_total) is None def competitor_signal_rsrp_rgb_for_values(values): values = np.asarray(values, dtype=np.float32) colors = np.zeros((*values.shape, 3), dtype=np.uint8) valid_mask = np.isfinite(values) & (values <= 0) if np.any(valid_mask): color_indices = np.searchsorted( np.asarray(COMPETITOR_SIGNAL_RSRP_BREAKS, dtype=np.float32), values[valid_mask], side="right", ) colors[valid_mask] = np.asarray(COMPETITOR_SIGNAL_RSRP_COLORS, dtype=np.uint8)[color_indices] return colors, valid_mask def geotiff_extratags(minx, maxy, pixel_width, pixel_height): model_pixel_scale = (pixel_width, pixel_height, 0.0) model_tiepoint = (0.0, 0.0, 0.0, minx, maxy, 0.0) geo_key_directory = ( 1, 1, 0, 4, 1024, 0, 1, 2, 1025, 0, 1, 1, 2048, 0, 1, 4326, 2054, 0, 1, 9102, ) return [ (33550, "d", 3, model_pixel_scale, False), (33922, "d", 6, model_tiepoint, False), (34735, "H", len(geo_key_directory), geo_key_directory, False), ] def write_rgba_geotiff(path, image, minx, maxy, pixel_width, pixel_height): tifffile.imwrite( path, image, photometric="rgb", extrasamples=["unassalpha"], metadata=None, extratags=geotiff_extratags(minx, maxy, pixel_width, pixel_height), ) def pixel_window_for_bounds(bounds, minx, maxy, pixel_width, pixel_height, width, height): geom_minx, geom_miny, geom_maxx, geom_maxy = bounds col_start = max(0, int(math.floor((geom_minx - minx) / pixel_width))) col_stop = min(width, int(math.ceil((geom_maxx - minx) / pixel_width))) row_start = max(0, int(math.floor((maxy - geom_maxy) / pixel_height))) row_stop = min(height, int(math.ceil((maxy - geom_miny) / pixel_height))) if row_start >= row_stop or col_start >= col_stop: return None return row_start, row_stop, col_start, col_stop def pixel_center_mask_for_geometry(geometry, window, minx, maxy, pixel_width, pixel_height): row_start, row_stop, col_start, col_stop = window x_coordinates = minx + (np.arange(col_start, col_stop, dtype=np.float64) + 0.5) * pixel_width y_coordinates = maxy - (np.arange(row_start, row_stop, dtype=np.float64) + 0.5) * pixel_height x_grid, y_grid = np.meshgrid(x_coordinates, y_coordinates) return np.asarray(shapely.contains_xy(geometry, x_grid, y_grid), dtype=bool) def pixel_window_from_point(x, y, minx, maxy, pixel_width, pixel_height, width, height): col = int((x - minx) / pixel_width) row = int((maxy - y) / pixel_height) if 0 <= row < height and 0 <= col < width: return row, row + 1, col, col + 1 return None def grid_metrics_headers(): return [ "网格ID", "区域类型", "区域名称", "经度", "纬度", "竟对采样点总", "竟对弱覆盖采样点", "竟对平均信号值", "移动信号", "竟对信号", ] def market_raster_layout(bounds, pixel_width, pixel_height, max_raster_pixels=None): minx, miny, maxx, maxy = bounds width = max(1, int(math.ceil((maxx - minx) / pixel_width))) height = max(1, int(math.ceil((maxy - miny) / pixel_height))) scale_factor = 1.0 pixel_limit = MAX_RASTER_PIXELS if max_raster_pixels is None else max_raster_pixels if pixel_limit and width * height > pixel_limit: scale_factor = math.sqrt((width * height) / pixel_limit) pixel_width *= scale_factor pixel_height *= scale_factor width = max(1, int(math.ceil((maxx - minx) / pixel_width))) height = max(1, int(math.ceil((maxy - miny) / pixel_height))) while width * height > pixel_limit: scale_factor *= 1.001 pixel_width *= 1.001 pixel_height *= 1.001 width = max(1, int(math.ceil((maxx - minx) / pixel_width))) height = max(1, int(math.ceil((maxy - miny) / pixel_height))) return minx, miny, maxx, maxy, pixel_width, pixel_height, width, height, scale_factor def replace_file_with_retry(source_path, target_path, attempts=20, delay_seconds=0.5): for attempt in range(attempts): try: source_path.replace(target_path) return except PermissionError: if attempt == attempts - 1: raise sleep(delay_seconds) def remove_file_with_retry(path, attempts=20, delay_seconds=0.5): for attempt in range(attempts): try: path.unlink(missing_ok=True) return except PermissionError: if attempt == attempts - 1: raise sleep(delay_seconds) def copy_full_source_file(source_path, output_path, market): if output_path.exists() and not OVERWRITE: return { "market_code": market.code, "market_name": market.name, "source": str(source_path), "output": str(output_path), "skipped": True, } shutil.copy2(source_path, output_path) return { "market_code": market.code, "market_name": market.name, "source": str(source_path), "output": str(output_path), "bytes": output_path.stat().st_size, "copied_full_source": True, "skipped": False, } def render_ranked_raster( state, market, output_path, minx, maxy, pixel_width, pixel_height, width, height, candidates, colors, percent_steps, ): image = np.full((height, width, 4), TRANSPARENT_PIXEL, dtype=np.uint8) value_sum = state["value_sum"] value_weight = state["value_weight"] data_mask = value_weight > 0 thresholds = [] rank_pixel_counts = [] if np.any(data_mask): value_raster = np.zeros_like(value_sum) np.divide(value_sum, value_weight, out=value_raster, where=data_mask) ranked_rgb, thresholds, rank_pixel_counts = ranked_pixel_rgb_for_values( value_raster, data_mask, colors, percent_steps, ) smoothed_rgb = smooth_rgb_inside_mask(ranked_rgb, data_mask, HEATMAP_SMOOTH_RADIUS) image[data_mask, :3] = smoothed_rgb[data_mask] image[data_mask, 3] = HEATMAP_ALPHA write_rgba_geotiff(output_path, image, minx, maxy, pixel_width, pixel_height) return { "market_code": market.code, "market_name": market.name, "output": str(output_path), "candidates": candidates, "painted_cells": state["painted_cells"], "data_pixels": int(np.count_nonzero(data_mask)), "skipped_no_value": state["skipped_no_value"], "threshold_value_count": int(np.count_nonzero(data_mask)), "thresholds": thresholds, "rank_pixel_counts": rank_pixel_counts, "percent_steps": list(percent_steps), "width": width, "height": height, "skipped": False, } def normalized_grid_id(value): if value is None: return None if isinstance(value, bytes): value = value.decode("utf-8", errors="replace") normalized = str(value).strip() return normalized or None def merge_user_count_record(records, grid_id, window, value, source_name, prefer_geometry=False): grid_id = normalized_grid_id(grid_id) if grid_id is None: return False record = records.get(grid_id) if record is None: record = { "window": window, "value_sum": 0.0, "has_value": False, "sources": set(), } records[grid_id] = record elif prefer_geometry: record["window"] = window record["sources"].add(source_name) if value is not None: record["value_sum"] += value record["has_value"] = True return True def collect_user_count_source( records, conn, layer, rtree, market, minx, maxy, pixel_width, pixel_height, width, height, source_name, prefer_geometry=False, ): fields = [GRID_ID_FIELD, EXCELLENT_CELL_FIELD] if CLIP_MODE == "center": fields.extend(("longitude", "latitude")) require_columns(conn, layer.table_name, fields) table = quote_identifier(layer.table_name) pk = quote_identifier(layer.pk_col) geom = quote_identifier(layer.geom_col) rtree_table = quote_identifier(rtree) field_sql = ", ".join(f"b.{quote_identifier(field)}" for field in fields) query = f""" select b.{pk}, b.{geom}, {field_sql} from {rtree_table} r join {table} b on b.{pk} = r."id" where r."minx" <= ? and r."maxx" >= ? and r."miny" <= ? and r."maxy" >= ? """ market_minx, market_miny, market_maxx, market_maxy = market.geometry.bounds params = (market_maxx, market_minx, market_maxy, market_miny) candidates = 0 clipped_rows = 0 invalid_grid_ids = 0 try: shapely.prepare(market.geometry) cursor = conn.execute(query, params) for batch_rows, geometries, valid_mask in iter_geometry_batches(cursor, 1): candidates += len(batch_rows) intersects_mask = valid_mask & shapely.intersects(market.geometry, geometries) geometry_bounds = shapely.bounds(geometries) for index, row in enumerate(batch_rows): if not valid_mask[index]: continue values = dict(zip(fields, row[2:])) if CLIP_MODE == "intersects": if not bool(intersects_mask[index]): continue window = pixel_window_for_bounds( geometry_bounds[index], minx, maxy, pixel_width, pixel_height, width, height, ) else: lon = to_float(values.get("longitude")) lat = to_float(values.get("latitude")) if lon is None or lat is None or not market.geometry.covers(Point(lon, lat)): continue window = pixel_window_from_point( lon, lat, minx, maxy, pixel_width, pixel_height, width, height, ) if window is None: continue clipped_rows += 1 if not merge_user_count_record( records, values.get(GRID_ID_FIELD), window, to_float(values.get(EXCELLENT_CELL_FIELD)), source_name, prefer_geometry, ): invalid_grid_ids += 1 finally: shapely.destroy_prepared(market.geometry) return { "candidates": candidates, "clipped_rows": clipped_rows, "invalid_grid_ids": invalid_grid_ids, } def build_merged_user_count_state(records, height, width, row_offset=0, col_offset=0): value_sum = np.zeros((height, width), dtype=np.float32) value_weight = np.zeros((height, width), dtype=np.uint16) painted_cells = 0 skipped_no_value = 0 for record in records.values(): if not record["has_value"]: skipped_no_value += 1 continue row_start, row_stop, col_start, col_stop = record["window"] row_start -= row_offset row_stop -= row_offset col_start -= col_offset col_stop -= col_offset value_sum[row_start:row_stop, col_start:col_stop] += record["value_sum"] value_weight[row_start:row_stop, col_start:col_stop] += 1 painted_cells += 1 return { "value_sum": value_sum, "value_weight": value_weight, "painted_cells": painted_cells, "skipped_no_value": skipped_no_value, } def render_merged_user_count_records(records, canvas_height, canvas_width, thresholds=None): valid_records = [record for record in records.values() if record["has_value"]] if not valid_records: empty_mask = np.zeros((0, 0), dtype=bool) empty_rgb = np.zeros((0, 0, 3), dtype=np.uint8) return { "window": (0, 0, 0, 0), "data_mask": empty_mask, "rgb": empty_rgb, "thresholds": [], "rank_pixel_counts": [], "painted_cells": 0, "skipped_no_value": len(records), } row_start = min(record["window"][0] for record in valid_records) row_stop = max(record["window"][1] for record in valid_records) col_start = min(record["window"][2] for record in valid_records) col_stop = max(record["window"][3] for record in valid_records) padding = HEATMAP_SMOOTH_RADIUS row_start = max(0, row_start - padding) row_stop = min(canvas_height, row_stop + padding) col_start = max(0, col_start - padding) col_stop = min(canvas_width, col_stop + padding) state = build_merged_user_count_state( records, row_stop - row_start, col_stop - col_start, row_offset=row_start, col_offset=col_start, ) value_sum = state["value_sum"] value_weight = state["value_weight"] data_mask = value_weight > 0 value_raster = np.zeros_like(value_sum) np.divide(value_sum, value_weight, out=value_raster, where=data_mask) if thresholds: ranked_rgb, rank_pixel_counts = ranked_pixel_rgb_for_values_with_thresholds( value_raster, data_mask, EXCELLENT_COLORS, thresholds, ) applied_thresholds = [float(value) for value in thresholds] else: ranked_rgb, applied_thresholds, rank_pixel_counts = ranked_pixel_rgb_for_values( value_raster, data_mask, EXCELLENT_COLORS, EXCELLENT_PERCENT_STEPS, ) smoothed_rgb = smooth_rgb_inside_mask(ranked_rgb, data_mask, HEATMAP_SMOOTH_RADIUS) return { "window": (row_start, row_stop, col_start, col_stop), "data_mask": data_mask, "rgb": smoothed_rgb, "thresholds": applied_thresholds, "rank_pixel_counts": rank_pixel_counts, "painted_cells": state["painted_cells"], "skipped_no_value": state["skipped_no_value"], } def merged_user_count_metadata(records, source_stats): shared_grids = 0 five_g_only_grids = 0 four_g_only_grids = 0 for record in records.values(): sources = record["sources"] if sources == {"5G", "4G"}: shared_grids += 1 elif "5G" in sources: five_g_only_grids += 1 elif "4G" in sources: four_g_only_grids += 1 return { "data_source_mode": "Grid_5G + Grid_4G sum by grid20_id", "grid_id_field": GRID_ID_FIELD, "value_field": EXCELLENT_CELL_FIELD, "merge_rule": "union grid20_id; sum mro_total_dl for duplicate ids", "merged_grid_count": len(records), "shared_grid_count": shared_grids, "five_g_only_grid_count": five_g_only_grids, "four_g_only_grid_count": four_g_only_grids, "source_stats": source_stats, } def render_summary_user_count_by_market( grid_sources, markets, pixel_width, pixel_height, output_path, max_raster_pixels, market_thresholds=None, ): summary_market = build_summary_market(markets) minx, miny, maxx, maxy, pixel_width, pixel_height, width, height, scale_factor = market_raster_layout( summary_market.geometry.bounds, pixel_width, pixel_height, max_raster_pixels, ) image = np.full((height, width, 4), TRANSPARENT_PIXEL, dtype=np.uint8) market_results = [] total_candidates = 0 total_painted_cells = 0 total_skipped_no_value = 0 for market in markets: records = {} source_stats = {} for source_name, conn, layer, rtree in grid_sources: source_stats[source_name] = collect_user_count_source( records, conn, layer, rtree, market, minx, maxy, pixel_width, pixel_height, width, height, source_name, prefer_geometry=source_name == "5G", ) candidates = sum(stats["candidates"] for stats in source_stats.values()) render_result = render_merged_user_count_records( records, height, width, (market_thresholds or {}).get(market.code), ) painted_cells = render_result["painted_cells"] skipped_no_value = render_result["skipped_no_value"] data_mask = render_result["data_mask"] thresholds = render_result["thresholds"] rank_pixel_counts = render_result["rank_pixel_counts"] data_pixels = int(np.count_nonzero(data_mask)) if data_pixels: row_start, row_stop, col_start, col_stop = render_result["window"] target = image[row_start:row_stop, col_start:col_stop] target[data_mask, :3] = render_result["rgb"][data_mask] target[data_mask, 3] = HEATMAP_ALPHA total_candidates += candidates total_painted_cells += painted_cells total_skipped_no_value += skipped_no_value market_result = { "market_code": market.code, "market_name": market.name, "candidates": candidates, "painted_cells": painted_cells, "data_pixels": data_pixels, "skipped_no_value": skipped_no_value, "thresholds": thresholds, "threshold_source": "market_zip" if (market_thresholds or {}).get(market.code) else "summary_raster", "rank_pixel_counts": rank_pixel_counts, "render_window": list(render_result["window"]), "render_buffer_pixels": int(data_mask.size), } market_result.update(merged_user_count_metadata(records, source_stats)) market_results.append(market_result) write_rgba_geotiff(output_path, image, minx, maxy, pixel_width, pixel_height) return { "market_code": summary_market.code, "market_name": summary_market.name, "output": str(output_path), "candidates": total_candidates, "painted_cells": total_painted_cells, "data_pixels": int(np.count_nonzero(image[..., 3])), "skipped_no_value": total_skipped_no_value, "threshold_value_count": int(np.count_nonzero(image[..., 3])), "thresholds": None, "rank_pixel_counts": None, "percent_steps": list(EXCELLENT_PERCENT_STEPS), "color_scope": "per_market", "threshold_source": "market_zip", "render_scope": "market_local_window", "render_padding_pixels": HEATMAP_SMOOTH_RADIUS, "market_results": market_results, "width": width, "height": height, "raster_extent": [ minx, maxy - height * pixel_height, minx + width * pixel_width, maxy, ], "pixel_width": pixel_width, "pixel_height": pixel_height, "resolution_scale_factor": scale_factor, "skipped": False, } def render_competitor_signal_raster( state, market, output_path, minx, maxy, pixel_width, pixel_height, width, height, candidates, ): image = np.full((height, width, 4), TRANSPARENT_PIXEL, dtype=np.uint8) value_sum = state["value_sum"] value_weight = state["value_weight"] rsrp_mask = value_weight > 0 zero_total_mask = state["zero_total_mask"] data_mask = rsrp_mask | zero_total_mask class_pixel_counts = [0] * len(COMPETITOR_SIGNAL_RSRP_COLORS) if np.any(rsrp_mask): value_raster = np.zeros_like(value_sum) np.divide(value_sum, value_weight, out=value_raster, where=rsrp_mask) colors, valid_rsrp_mask = competitor_signal_rsrp_rgb_for_values(value_raster) render_mask = rsrp_mask & valid_rsrp_mask image[render_mask, :3] = colors[render_mask] image[zero_total_mask, :3] = COMPETITOR_SIGNAL_RSRP_COLORS[0] image[data_mask, 3] = HEATMAP_ALPHA for index, color in enumerate(COMPETITOR_SIGNAL_RSRP_COLORS): color_mask = data_mask & np.all(image[..., :3] == color, axis=-1) class_pixel_counts[index] = int(np.count_nonzero(color_mask)) write_rgba_geotiff(output_path, image, minx, maxy, pixel_width, pixel_height) return { "market_code": market.code, "market_name": market.name, "output": str(output_path), "candidates": candidates, "painted_cells": state["painted_cells"], "data_pixels": int(np.count_nonzero(image[..., 3])), "skipped_no_value": state["skipped_no_value"], "color_mode": "discrete_competitor_signal", "rsrp_breaks": list(COMPETITOR_SIGNAL_RSRP_BREAKS), "colors": [list(color) for color in COMPETITOR_SIGNAL_RSRP_COLORS], "class_pixel_counts": class_pixel_counts, "zero_total_pixels": int(np.count_nonzero(zero_total_mask)), "smooth_radius": 0, "width": width, "height": height, "skipped": False, } def export_market_grid_outputs( grid_5g_conn, grid_5g_layer, grid_5g_rtree, market, pixel_width, pixel_height, # user_count_path, competitor_signal_path, csv_path, # grid_4g_source=None, max_raster_pixels=None, ): minx, miny, maxx, maxy, pixel_width, pixel_height, width, height, scale_factor = market_raster_layout( market.geometry.bounds, pixel_width, pixel_height, max_raster_pixels, ) raster_fields = ( EXCELLENT_CELL_FIELD, RSRP_FIELD, WEAK_COVER_FIELD, MOBILE_TOTAL_FIELD, MOBILE_WEAK_COVER_FIELD, ) # user_count_records = {} competitor_signal_value_sum = np.zeros((height, width), dtype=np.float32) competitor_signal_value_weight = np.zeros((height, width), dtype=np.uint16) zero_total_mask = np.zeros((height, width), dtype=bool) competitor_signal_cells = 0 zero_total_cells = 0 exact_geometry_pixels = 0 exclusion_counts = { "invalid_fields": 0, "mobile_weak_ratio": 0, "competitor_weak_ratio": 0, "invalid_rsrp": 0, "no_center_pixels": 0, } # fields = list( # dict.fromkeys( # (*CSV_SOURCE_FIELDS, *raster_fields, GRID_ID_FIELD) # if csv_path is not None # else (*raster_fields, GRID_ID_FIELD) # ) # ) fields = list(dict.fromkeys((*CSV_SOURCE_FIELDS, *raster_fields) if csv_path is not None else raster_fields)) if csv_path is None and CLIP_MODE == "center": fields.extend(field for field in ("longitude", "latitude") if field not in fields) require_columns(grid_5g_conn, grid_5g_layer.table_name, fields) table = quote_identifier(grid_5g_layer.table_name) pk = quote_identifier(grid_5g_layer.pk_col) geom = quote_identifier(grid_5g_layer.geom_col) rtree_table = quote_identifier(grid_5g_rtree) field_sql = ", ".join(f"b.{quote_identifier(field)}" for field in fields) query = f""" select b.{pk}, b.{geom}, {field_sql} from {rtree_table} r join {table} b on b.{pk} = r."id" where r."minx" <= ? and r."maxx" >= ? and r."miny" <= ? and r."maxy" >= ? """ params = (maxx, minx, maxy, miny) candidates = 0 # user_count_5g_clipped_rows = 0 # user_count_5g_invalid_grid_ids = 0 csv_rows = 0 csv_skipped = csv_path is None or (csv_path.exists() and not OVERWRITE) csv_file = None csv_writer = None if not csv_skipped: csv_file = csv_path.open("w", newline="", encoding=CSV_ENCODING, errors="replace") csv_writer = csv.writer(csv_file) csv_writer.writerow(grid_metrics_headers()) try: shapely.prepare(market.geometry) cursor = grid_5g_conn.execute(query, params) for batch_rows, geometries, valid_mask in iter_geometry_batches(cursor, 1): candidates += len(batch_rows) intersects_mask = valid_mask & shapely.intersects(market.geometry, geometries) geometry_bounds = shapely.bounds(geometries) for index, row in enumerate(batch_rows): values = dict(zip(fields, row[2:])) numeric_values = {field: to_float(values.get(field)) for field in raster_fields} if not valid_mask[index]: continue intersects_market = bool(intersects_mask[index]) if intersects_market and csv_writer is not None: csv_writer.writerow([market.code, *metric_row(values)]) csv_rows += 1 elif intersects_market and csv_path is not None: csv_rows += 1 if CLIP_MODE == "intersects": if not intersects_market: continue window = pixel_window_for_bounds( geometry_bounds[index], minx, maxy, pixel_width, pixel_height, width, height, ) else: lon = to_float(values.get("longitude")) lat = to_float(values.get("latitude")) if lon is None or lat is None or not market.geometry.covers(Point(lon, lat)): continue window = pixel_window_from_point(lon, lat, minx, maxy, pixel_width, pixel_height, width, height) if window is None: continue # if user_count_path is not None: # user_count_5g_clipped_rows += 1 # if not merge_user_count_record( # user_count_records, # values.get(GRID_ID_FIELD), # window, # numeric_values[EXCELLENT_CELL_FIELD], # "5G", # prefer_geometry=True, # ): # user_count_5g_invalid_grid_ids += 1 competitor_total = numeric_values[EXCELLENT_CELL_FIELD] competitor_rsrp = numeric_values[RSRP_FIELD] competitor_weak = numeric_values[WEAK_COVER_FIELD] mobile_total = numeric_values[MOBILE_TOTAL_FIELD] mobile_weak = numeric_values[MOBILE_WEAK_COVER_FIELD] exclusion_reason = competitor_signal_filter_reason( mobile_weak, mobile_total, competitor_weak, competitor_total, ) if exclusion_reason is not None: exclusion_counts[exclusion_reason] += 1 continue if competitor_total != 0 and (competitor_rsrp is None or competitor_rsrp > 0): exclusion_counts["invalid_rsrp"] += 1 continue signal_window = pixel_window_for_bounds( geometry_bounds[index], minx, maxy, pixel_width, pixel_height, width, height, ) if signal_window is None: exclusion_counts["no_center_pixels"] += 1 continue geometry_mask = pixel_center_mask_for_geometry( geometries[index], signal_window, minx, maxy, pixel_width, pixel_height, ) geometry_pixel_count = int(np.count_nonzero(geometry_mask)) if geometry_pixel_count == 0: exclusion_counts["no_center_pixels"] += 1 continue row_start, row_stop, col_start, col_stop = signal_window if competitor_total == 0: zero_total_view = zero_total_mask[row_start:row_stop, col_start:col_stop] zero_total_view |= geometry_mask zero_total_cells += 1 else: value_sum_view = competitor_signal_value_sum[row_start:row_stop, col_start:col_stop] value_weight_view = competitor_signal_value_weight[row_start:row_stop, col_start:col_stop] value_sum_view[geometry_mask] += competitor_rsrp value_weight_view[geometry_mask] += 1 competitor_signal_cells += 1 exact_geometry_pixels += geometry_pixel_count finally: if csv_file is not None: csv_file.close() shapely.destroy_prepared(market.geometry) # user_count_result = None # if user_count_path is not None: # if grid_4g_source is None: # raise ValueError("生成竟对用户量图层时必须提供 Grid_4G 数据源") # grid_4g_conn, grid_4g_layer, grid_4g_rtree = grid_4g_source # source_stats = { # "5G": { # "candidates": candidates, # "clipped_rows": user_count_5g_clipped_rows, # "invalid_grid_ids": user_count_5g_invalid_grid_ids, # } # } # source_stats["4G"] = collect_user_count_source( # user_count_records, # grid_4g_conn, # grid_4g_layer, # grid_4g_rtree, # market, # minx, # maxy, # pixel_width, # pixel_height, # width, # height, # "4G", # ) # user_count_state = build_merged_user_count_state(user_count_records, height, width) # user_count_result = render_ranked_raster( # user_count_state, # market, # user_count_path, # minx, # maxy, # pixel_width, # pixel_height, # width, # height, # sum(stats["candidates"] for stats in source_stats.values()), # EXCELLENT_COLORS, # EXCELLENT_PERCENT_STEPS, # ) # user_count_result.update(merged_user_count_metadata(user_count_records, source_stats)) # del user_count_state competitor_signal_state = { "value_sum": competitor_signal_value_sum, "value_weight": competitor_signal_value_weight, "zero_total_mask": zero_total_mask, "painted_cells": competitor_signal_cells, "skipped_no_value": sum(exclusion_counts.values()), } competitor_signal_result = render_competitor_signal_raster( competitor_signal_state, market, competitor_signal_path, minx, maxy, pixel_width, pixel_height, width, height, candidates, ) competitor_signal_result.update({ "data_source": str(GRID_5G_GPKG), "uses_merged_user_count": False, "geometry_rasterization": "pixel_center_inside_polygon", "exact_geometry_pixels": exact_geometry_pixels, "mobile_weak_ratio_formula": f"{MOBILE_WEAK_COVER_FIELD} / {MOBILE_TOTAL_FIELD} * 100", "mobile_weak_ratio_operator": "<", "mobile_weak_ratio_threshold": COMPETITOR_SIGNAL_MOBILE_WEAK_RATIO_MAX, "competitor_total_field": EXCELLENT_CELL_FIELD, "competitor_weak_ratio_formula": f"{WEAK_COVER_FIELD} / {EXCELLENT_CELL_FIELD} * 100", "competitor_weak_ratio_operator": ">", "competitor_weak_ratio_threshold": COMPETITOR_SIGNAL_WEAK_RATIO_MIN, "zero_competitor_total_is_included": True, "zero_competitor_total_color": list(COMPETITOR_SIGNAL_RSRP_COLORS[0]), "zero_competitor_total_cells": zero_total_cells, "rsrp_field": RSRP_FIELD, "eligible_cells": competitor_signal_cells, "exclusion_counts": exclusion_counts, }) del ( competitor_signal_state, competitor_signal_value_sum, competitor_signal_value_weight, zero_total_mask, ) # for result in (user_count_result, competitor_signal_result): for result in (competitor_signal_result,): if result is None: continue result["raster_extent"] = [ minx, maxy - height * pixel_height, minx + width * pixel_width, maxy, ] result["pixel_width"] = pixel_width result["pixel_height"] = pixel_height result["resolution_scale_factor"] = scale_factor csv_result = None if csv_path is not None: csv_result = { "market_code": market.code, "market_name": market.name, "output": str(csv_path), "candidates": candidates, "row_count": csv_rows, "skipped": csv_skipped, } return ( # user_count_result, competitor_signal_result, csv_result, ) def write_excellent_heatmap_legend(output_dir, field): legend_path = output_dir / "excellent_heatmap_legend.csv" with legend_path.open("w", newline="", encoding="utf-8-sig") as file: writer = csv.writer(file) writer.writerow(["field", "rank_range", "red", "green", "blue", "alpha", "meaning"]) rank_ranges = ("top_10_percent", "10_to_40_percent", "40_to_70_percent", "bottom_30_percent") for rank_range, color in zip(rank_ranges, EXCELLENT_COLORS): writer.writerow([field, rank_range, *color, HEATMAP_ALPHA, "ranked-pixel distribution"]) writer.writerow([field, "nodata", 0, 0, 0, 0, "transparent no data"]) return legend_path def write_competitor_signal_legend(output_dir): legend_path = output_dir / "competitor_signal_legend.csv" with legend_path.open("w", newline="", encoding="utf-8-sig") as file: writer = csv.writer(file) writer.writerow(["field", "rule_or_rsrp_range", "red", "green", "blue", "alpha", "filter"]) competitor_filter = ( f"{MOBILE_WEAK_COVER_FIELD}/{MOBILE_TOTAL_FIELD} < {COMPETITOR_SIGNAL_MOBILE_WEAK_RATIO_MAX}%" f" and ({EXCELLENT_CELL_FIELD} = 0" f" or {WEAK_COVER_FIELD}/{EXCELLENT_CELL_FIELD} > {COMPETITOR_SIGNAL_WEAK_RATIO_MIN}%)" ) writer.writerow([ EXCELLENT_CELL_FIELD, "= 0", *COMPETITOR_SIGNAL_RSRP_COLORS[0], HEATMAP_ALPHA, competitor_filter, ]) ranges = ( "< -110", "[-110, -104)", "[-104, -98)", "[-98, -92)", "[-92, -86)", "[-86, -80)", "[-80, -74)", "[-74, 0]", ) for value_range, color in zip(ranges, COMPETITOR_SIGNAL_RSRP_COLORS): writer.writerow([RSRP_FIELD, value_range, *color, HEATMAP_ALPHA, competitor_filter]) writer.writerow([RSRP_FIELD, "not_eligible_or_invalid", 0, 0, 0, 0, competitor_filter]) return legend_path @contextmanager def open_read_connection(path): conn = sqlite3.connect(path) conn.execute("pragma query_only = on") conn.execute("pragma temp_store = memory") try: yield conn finally: conn.close() def gpkg_layer_extent(conn, layer): row = conn.execute( "select min_x, min_y, max_x, max_y from gpkg_contents where table_name = ?", (layer.table_name,), ).fetchone() if row and all(value is not None for value in row): return tuple(float(value) for value in row) rtree = rtree_name(conn, layer) row = conn.execute( f"select min(minx), min(miny), max(maxx), max(maxy) from {quote_identifier(rtree)}" ).fetchone() return tuple(float(value) for value in row) if row and all(value is not None for value in row) else None def process_market(market, pixel_width, pixel_height, output_dir): started_at = perf_counter() output_dir = Path(output_dir) output_dir.mkdir(parents=True, exist_ok=True) zip_path = market_zip_output_path(output_dir, market) if zip_path.exists() and not OVERWRITE: return { "market_fid": market.fid, "market_code": market.code, "market_name": market.name, "zip_result": { "market_code": market.code, "market_name": market.name, "output": zip_path.as_posix(), "skipped": True, }, "elapsed_seconds": perf_counter() - started_at, } with ( open_read_connection(GRID_5G_GPKG) as grid_5g_conn, # open_read_connection(GRID_4G_GPKG) as grid_4g_conn, open_read_connection(BUILDING_INFO_GPKG) as building_info_conn, open_read_connection(AOI_GPKG) as aoi_conn, ): grid_5g_layer = resolve_feature_layer(grid_5g_conn, GRID_5G_LAYER) # grid_4g_layer = resolve_feature_layer(grid_4g_conn, GRID_4G_LAYER) building_info_layer = resolve_feature_layer(building_info_conn, BUILDING_INFO_LAYER) grid_5g_rtree = rtree_name(grid_5g_conn, grid_5g_layer) # grid_4g_rtree = rtree_name(grid_4g_conn, grid_4g_layer) building_info_rtree = rtree_name(building_info_conn, building_info_layer) aoi_layer = resolve_feature_layer(aoi_conn, AOI_LAYER) aoi_rtree = rtree_name(aoi_conn, aoi_layer) with tempfile.TemporaryDirectory(prefix=f"{safe_filename(market.code)}_") as temp_dir: market_dir = Path(temp_dir) gis_project_path = market_dir / GIS_PROJECT_OUTPUT_FILENAME # user_count_path = market_dir / excellent_heatmap_raster_filename(EXCELLENT_CELL_FIELD) competitor_signal_path = market_dir / competitor_signal_raster_filename() grid_started_at = perf_counter() ( # user_count_result, competitor_signal_result, _, ) = export_market_grid_outputs( grid_5g_conn, grid_5g_layer, grid_5g_rtree, market, pixel_width, pixel_height, # user_count_path, competitor_signal_path, None, # (grid_4g_conn, grid_4g_layer, grid_4g_rtree), ) grid_elapsed = perf_counter() - grid_started_at building_info_path = market_dir / BUILDING_INFO_OUTPUT_FILENAME building_started_at = perf_counter() building_info_result = export_market_building_info_gpkg( building_info_conn, building_info_layer, building_info_rtree, market, building_info_path, ) aoi_result = export_market_aoi_gpkg( aoi_conn, aoi_layer, aoi_rtree, market, market_dir / AOI_OUTPUT_FILENAME, ) gis_project_result = copy_gis_project_to_market( GIS_PROJECT_SOURCE, gis_project_path, market, building_info_result["extent"], competitor_signal_result["raster_extent"], include_cell_data=False, aoi_result=aoi_result, ) building_elapsed = perf_counter() - building_started_at zip_result = write_market_zip(market_dir, zip_path, market) removed_legacy_dir = remove_legacy_market_dir(output_dir, market) if removed_legacy_dir: zip_result["removed_legacy_dir"] = str(removed_legacy_dir) return { "market_fid": market.fid, "market_code": market.code, "market_name": market.name, # "excellent_heatmap_result": rewrite_result_for_zip(user_count_result, zip_path, market_dir), "competitor_signal_result": rewrite_result_for_zip( competitor_signal_result, zip_path, market_dir, ), "building_info_result": rewrite_result_for_zip(building_info_result, zip_path, market_dir), "aoi_result": rewrite_result_for_zip(aoi_result, zip_path, market_dir), "gis_project_result": rewrite_result_for_zip(gis_project_result, zip_path, market_dir), "zip_result": zip_result, "timings": { "grid_outputs_seconds": grid_elapsed, "supporting_layers_seconds": building_elapsed, }, "elapsed_seconds": perf_counter() - started_at, } # def process_summary_grid_outputs(markets, pixel_width, pixel_height, output_dir, market_user_thresholds=None): def process_summary_grid_outputs(markets, pixel_width, pixel_height, output_dir): started_at = perf_counter() output_dir = Path(output_dir) output_dir.mkdir(parents=True, exist_ok=True) summary_market = build_summary_market(markets) zip_path = output_dir / SUMMARY_OUTPUT_FILENAME if zip_path.exists() and not OVERWRITE: return { "market_code": summary_market.code, "zip_result": { "market_code": summary_market.code, "market_name": summary_market.name, "output": zip_path.as_posix(), "skipped": True, }, "skipped": True, "elapsed_seconds": perf_counter() - started_at, } with ( open_read_connection(GRID_5G_GPKG) as grid_5g_conn, # open_read_connection(GRID_4G_GPKG) as grid_4g_conn, ): grid_5g_layer = resolve_feature_layer(grid_5g_conn, GRID_5G_LAYER) # grid_4g_layer = resolve_feature_layer(grid_4g_conn, GRID_4G_LAYER) grid_5g_rtree = rtree_name(grid_5g_conn, grid_5g_layer) # grid_4g_rtree = rtree_name(grid_4g_conn, grid_4g_layer) with tempfile.TemporaryDirectory(prefix="market_grid_summary_") as temp_dir: summary_dir = Path(temp_dir) # user_count_path = summary_dir / excellent_heatmap_raster_filename(EXCELLENT_CELL_FIELD) competitor_signal_path = summary_dir / competitor_signal_raster_filename() ( # _, # 原用户量结果 competitor_signal_result, _, ) = export_market_grid_outputs( grid_5g_conn, grid_5g_layer, grid_5g_rtree, summary_market, pixel_width, pixel_height, # None, # 原 user_count_path competitor_signal_path, None, max_raster_pixels=SUMMARY_MAX_RASTER_PIXELS, ) # user_count_result = render_summary_user_count_by_market( # ( # ("5G", grid_5g_conn, grid_5g_layer, grid_5g_rtree), # ("4G", grid_4g_conn, grid_4g_layer, grid_4g_rtree), # ), # markets, # pixel_width, # pixel_height, # user_count_path, # SUMMARY_MAX_RASTER_PIXELS, # market_user_thresholds, # ) building_info_path = summary_dir / BUILDING_INFO_OUTPUT_FILENAME shutil.copy2(BUILDING_INFO_GPKG, building_info_path) with open_read_connection(BUILDING_INFO_GPKG) as building_info_conn: building_info_layer = resolve_feature_layer(building_info_conn, BUILDING_INFO_LAYER) building_info_extent = gpkg_layer_extent(building_info_conn, building_info_layer) building_info_result = { "market_code": summary_market.code, "market_name": summary_market.name, "source": str(BUILDING_INFO_GPKG), "output": str(building_info_path), "extent": list(building_info_extent) if building_info_extent else None, "bytes": building_info_path.stat().st_size, "copied_full_source": True, "skipped": False, } cell_data_path = summary_dir / CELL_DATA_OUTPUT_FILENAME cell_data_result = copy_full_source_file( CELL_DATA_GPKG, cell_data_path, summary_market, ) gis_project_path = summary_dir / GIS_PROJECT_OUTPUT_FILENAME gis_project_result = copy_gis_project_to_market( GIS_PROJECT_SOURCE, gis_project_path, summary_market, building_info_extent, competitor_signal_result["raster_extent"], include_cell_data=True, ) zip_result = write_market_zip(summary_dir, zip_path, summary_market) legacy_zip_path = output_dir / LEGACY_SUMMARY_OUTPUT_FILENAME if legacy_zip_path != zip_path and legacy_zip_path.exists(): remove_file_with_retry(legacy_zip_path) return { "market_code": summary_market.code, # "excellent_heatmap_result": rewrite_result_for_zip(user_count_result, zip_path, summary_dir), "competitor_signal_result": rewrite_result_for_zip( competitor_signal_result, zip_path, summary_dir, ), "building_info_result": rewrite_result_for_zip(building_info_result, zip_path, summary_dir), "cell_data_result": rewrite_result_for_zip(cell_data_result, zip_path, summary_dir), "gis_project_result": rewrite_result_for_zip(gis_project_result, zip_path, summary_dir), "zip_result": zip_result, "elapsed_seconds": perf_counter() - started_at, } def main(): if SCALE <= 0: raise ValueError("SCALE 必须大于 0") if MAX_WORKERS <= 0: raise ValueError("MAX_WORKERS 必须大于 0") if GEOMETRY_BATCH_SIZE <= 0: raise ValueError("GEOMETRY_BATCH_SIZE 必须大于 0") if PROJECT_EXTENT_PADDING_RATIO < 0: raise ValueError("PROJECT_EXTENT_PADDING_RATIO 不能小于 0") # validate_smoothing_radius("HEATMAP_SMOOTH_RADIUS", HEATMAP_SMOOTH_RADIUS) if not 0 <= COMPETITOR_SIGNAL_MOBILE_WEAK_RATIO_MAX <= 100: raise ValueError("COMPETITOR_SIGNAL_MOBILE_WEAK_RATIO_MAX 必须在 0 到 100 之间") if not 0 <= COMPETITOR_SIGNAL_WEAK_RATIO_MIN <= 100: raise ValueError("COMPETITOR_SIGNAL_WEAK_RATIO_MIN 必须在 0 到 100 之间") if len(COMPETITOR_SIGNAL_RSRP_COLORS) != len(COMPETITOR_SIGNAL_RSRP_BREAKS) + 1: raise ValueError("竟对信号 RSRP 颜色数量必须比分界点数量多 1") if any( left >= right for left, right in zip( COMPETITOR_SIGNAL_RSRP_BREAKS, COMPETITOR_SIGNAL_RSRP_BREAKS[1:], ) ): raise ValueError("COMPETITOR_SIGNAL_RSRP_BREAKS 必须严格递增") if MAX_RASTER_PIXELS is not None and MAX_RASTER_PIXELS <= 0: raise ValueError("MAX_RASTER_PIXELS 必须大于 0 或设置为 None") if SUMMARY_MAX_RASTER_PIXELS is None or SUMMARY_MAX_RASTER_PIXELS <= 0: raise ValueError("SUMMARY_MAX_RASTER_PIXELS 必须大于 0") if CLIP_MODE not in {"intersects", "center"}: raise ValueError("CLIP_MODE 必须是 intersects 或 center") required_files = ( MARKET_GPKG, GRID_5G_GPKG, # GRID_4G_GPKG, BUILDING_INFO_GPKG, CELL_DATA_GPKG, GIS_PROJECT_SOURCE, AOI_GPKG, ) missing_files = [str(path) for path in required_files if not path.is_file()] if missing_files: raise FileNotFoundError(f"缺少输入文件:{', '.join(missing_files)}") OUTPUT_DIR.mkdir(parents=True, exist_ok=True) with ( open_read_connection(MARKET_GPKG) as market_conn, open_read_connection(GRID_5G_GPKG) as grid_5g_conn, # open_read_connection(GRID_4G_GPKG) as grid_4g_conn, open_read_connection(BUILDING_INFO_GPKG) as building_info_conn, ): market_layer = resolve_feature_layer(market_conn, MARKET_LAYER) grid_5g_layer = resolve_feature_layer(grid_5g_conn, GRID_5G_LAYER) # grid_4g_layer = resolve_feature_layer(grid_4g_conn, GRID_4G_LAYER) building_info_layer = resolve_feature_layer(building_info_conn, BUILDING_INFO_LAYER) if ( market_layer.srs_id != 4326 or grid_5g_layer.srs_id != 4326 # or grid_4g_layer.srs_id != 4326 ): raise ValueError("当前脚本只处理 EPSG:4326 的输入图层") if building_info_layer.srs_id not in BUILDING_INFO_ALLOWED_SRS_IDS: raise ValueError(f"BuildingInfo 图层坐标系不在允许范围内:{building_info_layer.srs_id}") require_columns( grid_5g_conn, grid_5g_layer.table_name, # (*CSV_SOURCE_FIELDS, MOBILE_TOTAL_FIELD, MOBILE_WEAK_COVER_FIELD, GRID_ID_FIELD), (*CSV_SOURCE_FIELDS, MOBILE_TOTAL_FIELD, MOBILE_WEAK_COVER_FIELD), ) # grid_4g_required_fields = [GRID_ID_FIELD, EXCELLENT_CELL_FIELD] # if CLIP_MODE == "center": # grid_4g_required_fields.extend(("longitude", "latitude")) # require_columns(grid_4g_conn, grid_4g_layer.table_name, grid_4g_required_fields) require_columns(building_info_conn, building_info_layer.table_name, ["name"]) rtree_name(grid_5g_conn, grid_5g_layer) # rtree_name(grid_4g_conn, grid_4g_layer) rtree_name(building_info_conn, building_info_layer) pixel_width = PIXEL_WIDTH pixel_height = PIXEL_HEIGHT if pixel_width is None or pixel_height is None: estimated_width, estimated_height = estimate_pixel_size( grid_5g_conn, grid_5g_layer, SAMPLE_SIZE, ) pixel_width = pixel_width or estimated_width pixel_height = pixel_height or estimated_height pixel_width = pixel_width / SCALE pixel_height = pixel_height / SCALE markets = load_market_features( market_conn, market_layer, MARKET_CODE_FIELD, MARKET_NAME_FIELD, ) if LIMIT: markets = markets[:LIMIT] layer_names = { "grid_5g": grid_5g_layer.table_name, # "grid_4g": grid_4g_layer.table_name, "building_info": building_info_layer.table_name, } # excellent_legend_path = write_excellent_heatmap_legend(OUTPUT_DIR, EXCELLENT_CELL_FIELD) competitor_signal_legend_path = write_competitor_signal_legend(OUTPUT_DIR) worker_count = max(1, min(MAX_WORKERS, len(markets))) if markets else 1 print(f"市场网格数量:{len(markets)}") print(f"并行进程数:{worker_count}") print(f"5G Grid 图层:{layer_names['grid_5g']}") # print(f"4G Grid 图层:{layer_names['grid_4g']}") print(f"BuildingInfo 图层:{layer_names['building_info']}") print(f"像元大小:{pixel_width}, {pixel_height}") # print(f"用户量图例:{excellent_legend_path}") print(f"竟对信号图例:{competitor_signal_legend_path}") started_at = perf_counter() outcomes = [] if worker_count == 1: for index, market in enumerate(markets, start=1): outcome = process_market(market, pixel_width, pixel_height, OUTPUT_DIR) outcomes.append(outcome) scale_factor = outcome.get("competitor_signal_result", {}).get("resolution_scale_factor", 1.0) resolution_note = f",分辨率自动调整 x{scale_factor:.2f}" if scale_factor > 1.001 else "" print( f"[{index}/{len(markets)}] 完成 {market.code}," f"耗时 {outcome['elapsed_seconds']:.1f} 秒{resolution_note}" ) else: with ProcessPoolExecutor(max_workers=worker_count) as executor: future_markets = { executor.submit(process_market, market, pixel_width, pixel_height, OUTPUT_DIR): market for market in markets } completed = 0 for future in as_completed(future_markets): market = future_markets[future] try: outcome = future.result() except Exception as error: raise RuntimeError(f"市场网格处理失败:{market.code}") from error outcomes.append(outcome) completed += 1 scale_factor = outcome.get("competitor_signal_result", {}).get("resolution_scale_factor", 1.0) resolution_note = f",分辨率自动调整 x{scale_factor:.2f}" if scale_factor > 1.001 else "" print( f"[{completed}/{len(markets)}] 完成 {market.code}," f"耗时 {outcome['elapsed_seconds']:.1f} 秒{resolution_note}" ) outcomes.sort(key=lambda item: item["market_fid"]) summary_grid_result = None if SUMMARY_OUTPUT_ENABLED and markets: print("开始生成全部市场网格汇总 TIF……") # market_user_thresholds = { # outcome["market_code"]: outcome["excellent_heatmap_result"].get("thresholds") # for outcome in outcomes # if outcome.get("excellent_heatmap_result") # } summary_grid_result = process_summary_grid_outputs( markets, pixel_width, pixel_height, OUTPUT_DIR, # market_user_thresholds, ) print( f"汇总 TIF 完成:{summary_grid_result['zip_result']['output']}," f"耗时 {summary_grid_result['elapsed_seconds']:.1f} 秒" ) result_mappings = { # "excellent_heatmap_results": "excellent_heatmap_result", "competitor_signal_results": "competitor_signal_result", "building_info_results": "building_info_result", "aoi_results": "aoi_result", "cell_data_results": "cell_data_result", "gis_project_results": "gis_project_result", "zip_results": "zip_result", } summary = { "market_gpkg": str(MARKET_GPKG), "grid_5g_gpkg": str(GRID_5G_GPKG), # "grid_4g_gpkg": str(GRID_4G_GPKG), # "user_count_grid_id_field": GRID_ID_FIELD, # "user_count_merge_rule": "Grid_5G + Grid_4G union by grid20_id and sum mro_total_dl", "building_info_gpkg": str(BUILDING_INFO_GPKG), "aoi_gpkg": str(AOI_GPKG), "aoi_match_field": AOI_MARKET_FIELD, "cell_data_gpkg": str(CELL_DATA_GPKG), "gis_project_source": str(GIS_PROJECT_SOURCE), "rsrp_field": RSRP_FIELD, "excellent_cell_field": EXCELLENT_CELL_FIELD, "weak_cover_field": WEAK_COVER_FIELD, "mobile_total_field": MOBILE_TOTAL_FIELD, "mobile_weak_cover_field": MOBILE_WEAK_COVER_FIELD, "competitor_signal_mobile_weak_ratio_formula": ( f"{MOBILE_WEAK_COVER_FIELD} / {MOBILE_TOTAL_FIELD} * 100" ), "competitor_signal_mobile_weak_ratio_rule": ( f"< {COMPETITOR_SIGNAL_MOBILE_WEAK_RATIO_MAX}" ), "competitor_signal_eligibility_rule": ( f"{EXCELLENT_CELL_FIELD} = 0 or " f"{WEAK_COVER_FIELD} / {EXCELLENT_CELL_FIELD} * 100 " f"> {COMPETITOR_SIGNAL_WEAK_RATIO_MIN}" ), "competitor_signal_zero_total_color": list(COMPETITOR_SIGNAL_RSRP_COLORS[0]), "clip_mode": CLIP_MODE, "scale": SCALE, "pixel_width": pixel_width, "pixel_height": pixel_height, "max_workers": worker_count, "summary_output_enabled": SUMMARY_OUTPUT_ENABLED, "total_elapsed_seconds": perf_counter() - started_at, "market_timings": [ { "market_code": outcome["market_code"], "elapsed_seconds": outcome["elapsed_seconds"], **outcome.get("timings", {}), } for outcome in outcomes ], } for summary_key, outcome_key in result_mappings.items(): summary[summary_key] = [outcome[outcome_key] for outcome in outcomes if outcome_key in outcome] summary["summary_grid_result"] = summary_grid_result summary_path = OUTPUT_DIR / "summary.json" temp_summary_path = summary_path.with_name(f".{summary_path.name}.tmp") try: temp_summary_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8") temp_summary_path.replace(summary_path) except Exception: if temp_summary_path.exists(): temp_summary_path.unlink() raise print(f"总耗时:{summary['total_elapsed_seconds']:.1f} 秒") print(f"汇总:{summary_path}") if __name__ == "__main__": main()