diff --git a/aidocs/project_context.md b/aidocs/project_context.md index f9a95e8..7e96620 100644 --- a/aidocs/project_context.md +++ b/aidocs/project_context.md @@ -43,3 +43,8 @@ - 当前测试市场 `JM010404` 的 `mr_dl_lt105_weak_cover_rate_dl` 去重分位阈值为 `[30.43, 16.95, 9.47]`,输出验证为 889 种有效颜色加透明背景。 - 字段口径已切换为 DL:`信号.tif` 使用 `ssb_rsrp_dl`,`用户量.tif` 使用 `mro_total_dl`,`信号差用户量.tif` 使用 `rsrp_lt_neg105_dl`。 - 当前测试市场 `JM010404` 新字段阈值:`mro_total_dl` 为 `[2583.0, 1428.0, 871.0]`,`rsrp_lt_neg105_dl` 为 `[389.0, 219.0, 138.0]`。 +- `main.py` 已重新纳入 `source/BuildingInfo.gpkg` 拆分流程,仍通过 `python main.py` 一次运行完成三张热力图和 BuildingInfo 拆分。 +- BuildingInfo 输出路径为 `output/JMXXXX/BuildingInfo.gpkg`,匹配规则沿用 `intersects`:建筑面只要与市场网格相交或边界触碰,就会写入对应市场目录,几何和属性行保持原样不裁剪。 +- BuildingInfo 拆分会复制源 GeoPackage 的 `layer_styles`、`gpkg_metadata`、`gpkg_metadata_reference`、`gpkg_extensions`、`gpkg_ogr_contents`、`gpkg_spatial_ref_sys` 等支撑表,并重建输出 RTree;避免复制依赖 SpatiaLite 函数的 RTree 触发器。 +- `source/BuildingInfo.gpkg` 的图层 `srs_id` 为 `100000`(CRS84,经纬度坐标值可与市场网格相交判断),因此 `BUILDING_INFO_ALLOWED_SRS_IDS` 默认允许 `(4326, 100000)`。 +- 当前测试市场 `JM010404` 已生成 `BuildingInfo.gpkg`,包含 9495 个建筑要素,RTree 和 `gpkg_ogr_contents.feature_count` 均为 9495;`layer_styles.styleQML` 与 `gpkg_metadata.metadata` 已验证与源文件完全一致。 diff --git a/main.py b/main.py index 9ff1096..3af1954 100644 --- a/main.py +++ b/main.py @@ -17,14 +17,17 @@ DEFAULT_SOURCE_DIR = Path("source") # 源数据目录,存放 MarketMap.gpkg OUTPUT_DIR = Path("output") # 输出根目录,每个市场网格会在这里生成一个 JMXXXX 文件夹。 MARKET_GPKG = DEFAULT_SOURCE_DIR / "MarketMap.gpkg" # 市场网格 GeoPackage 文件路径。 GRID_GPKG = DEFAULT_SOURCE_DIR / "grid.gpkg" # Grid 栅格指标 GeoPackage 文件路径。 +BUILDING_INFO_GPKG = DEFAULT_SOURCE_DIR / "BuildingInfo.gpkg" # 建筑信息 GeoPackage 文件路径,拆分时保留原始图层和 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_INFO_LAYER = None # BuildingInfo 图层名;None 表示自动使用 GPKG 中第一个 feature 图层。 MARKET_CODE_FIELD = "micro_grid" # 市场网格编码字段,用于输出文件夹名,例如 JM010404。 MARKET_NAME_FIELD = "micro_gr_1" # 市场网格名称字段,用于日志和汇总信息。 SIGNAL_OUTPUT_FILENAME = "信号.tif" # RSRP 连续热力图输出文件名。 +BUILDING_INFO_OUTPUT_FILENAME = "BuildingInfo.gpkg" # 每个市场网格目录内输出的建筑信息拆分文件名。 HEATMAP_GOOD_RSRP = -80.0 # 热力图绿色端阈值;RSRP 大于等于该值视为信号好。 HEATMAP_MID_RSRP = -95.0 # 热力图黄色中间阈值。 HEATMAP_BAD_RSRP = -110.0 # 热力图红色端阈值;RSRP 小于等于该值视为信号差。 @@ -45,6 +48,7 @@ SCALE = 5.0 # 分辨率倍数;2.0 表示像元宽高减半,放大查看更 SAMPLE_SIZE = 10000 # 自动估算像元大小时抽样读取的 Grid 要素数量。 LIMIT = 1 # 限制处理前 N 个市场网格;None 表示处理全部市场网格。 CLIP_MODE = "intersects" # 裁切方式:intersects 按几何相交裁切,center 按 Grid 中心点落入裁切。 +BUILDING_INFO_ALLOWED_SRS_IDS = (4326, 100000) # BuildingInfo 允许的经纬度坐标系 ID;100000 是源文件中的 CRS84。 OVERWRITE = True # 输出文件已存在时是否覆盖。 TRANSPARENT_PIXEL = (0, 0, 0, 0) # 无数据/背景像元颜色,RGBA 中 alpha=0 表示透明。 @@ -92,6 +96,10 @@ def weak_cover_heatmap_raster_filename(_field): return WEAK_COVER_OUTPUT_FILENAME +def building_info_output_path(output_dir, market): + return market_output_dir(output_dir, market) / BUILDING_INFO_OUTPUT_FILENAME + + def gpkg_blob_to_wkb(blob): data = bytes(blob) if data[:2] != b"GP": @@ -161,6 +169,198 @@ def rtree_name(conn, layer): 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 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 create_source_table_schema(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_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_source_table_schema(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_output_gpkg(source_conn, output_path, layer, 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_name(source_conn, layer))) + 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) + prepared_market = prep(market.geometry) + rows = [] + rtree_rows = [] + extent = None + candidates = 0 + + for row in source_conn.execute(query, (max_market_x, min_market_x, max_market_y, min_market_y)): + candidates += 1 + geom_blob = row[geom_index] + if geom_blob is None: + continue + try: + geometry = from_wkb(gpkg_blob_to_wkb(geom_blob)) + except (GEOSException, ValueError): + continue + if geometry.is_empty or not prepared_market.intersects(geometry): + continue + + minx, miny, maxx, maxy = geometry.bounds + 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_output_gpkg(source_conn, output_path, layer, 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, + "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), + "skipped": False, + } + + def load_market_features(conn, layer, code_field, name_field): require_columns(conn, layer.table_name, [code_field, name_field]) table = quote_identifier(layer.table_name) @@ -644,11 +844,18 @@ def main(): OUTPUT_DIR.mkdir(parents=True, exist_ok=True) - with sqlite3.connect(MARKET_GPKG) as market_conn, sqlite3.connect(GRID_GPKG) as grid_conn: + with ( + sqlite3.connect(MARKET_GPKG) as market_conn, + sqlite3.connect(GRID_GPKG) as grid_conn, + sqlite3.connect(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_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_info_layer.srs_id not in BUILDING_INFO_ALLOWED_SRS_IDS: + raise ValueError(f"BuildingInfo 图层坐标系不在允许范围内:{building_info_layer.srs_id}") require_columns( grid_conn, @@ -656,6 +863,7 @@ def main(): [RSRP_FIELD, EXCELLENT_CELL_FIELD, WEAK_COVER_FIELD, "longitude", "latitude"], ) grid_rtree = rtree_name(grid_conn, grid_layer) + building_info_rtree = 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: @@ -680,8 +888,10 @@ def main(): heatmap_results = [] excellent_heatmap_results = [] weak_cover_heatmap_results = [] + building_info_results = [] print(f"市场网格数量:{len(markets)}") print(f"Grid 图层:{grid_layer.table_name}") + print(f"BuildingInfo 图层:{building_info_layer.table_name}") print(f"RSRP 字段:{RSRP_FIELD}") print(f"采样点字段:{EXCELLENT_CELL_FIELD}") print(f"信号差用户量字段:{WEAK_COVER_FIELD}") @@ -706,26 +916,25 @@ def main(): "skipped": True, } ) - continue - - print(f"[{index}/{len(markets)}] 导出热力图:{market.code} {market.name}") - heatmap_result = export_market_heatmap_tif( - grid_conn, - grid_layer, - grid_rtree, - market, - RSRP_FIELD, - pixel_width, - pixel_height, - heatmap_path, - ) - heatmap_result["market_dir"] = str(market_dir) - heatmap_result["skipped"] = False - heatmap_results.append(heatmap_result) - print( - f" 热力图像素:{heatmap_result['width']}x{heatmap_result['height']}," - f"有效像素:{heatmap_result['data_pixels']}" - ) + else: + print(f"[{index}/{len(markets)}] 导出热力图:{market.code} {market.name}") + heatmap_result = export_market_heatmap_tif( + grid_conn, + grid_layer, + grid_rtree, + market, + RSRP_FIELD, + pixel_width, + pixel_height, + heatmap_path, + ) + heatmap_result["market_dir"] = str(market_dir) + heatmap_result["skipped"] = False + heatmap_results.append(heatmap_result) + print( + f" 热力图像素:{heatmap_result['width']}x{heatmap_result['height']}," + f"有效像素:{heatmap_result['data_pixels']}" + ) excellent_path = market_dir / excellent_heatmap_raster_filename(EXCELLENT_CELL_FIELD) if excellent_path.exists() and not OVERWRITE: @@ -739,26 +948,25 @@ def main(): "skipped": True, } ) - continue - - print(f" 导出采样点热力图:{excellent_path.name}") - excellent_result = export_market_excellent_heatmap_tif( - grid_conn, - grid_layer, - grid_rtree, - market, - EXCELLENT_CELL_FIELD, - pixel_width, - pixel_height, - excellent_path, - ) - excellent_result["market_dir"] = str(market_dir) - excellent_result["skipped"] = False - excellent_heatmap_results.append(excellent_result) - print( - f" 采样点热力图像素:{excellent_result['width']}x{excellent_result['height']}," - f"阈值:{excellent_result['thresholds']}" - ) + else: + print(f" 导出采样点热力图:{excellent_path.name}") + excellent_result = export_market_excellent_heatmap_tif( + grid_conn, + grid_layer, + grid_rtree, + market, + EXCELLENT_CELL_FIELD, + pixel_width, + pixel_height, + excellent_path, + ) + excellent_result["market_dir"] = str(market_dir) + excellent_result["skipped"] = False + excellent_heatmap_results.append(excellent_result) + print( + f" 采样点热力图像素:{excellent_result['width']}x{excellent_result['height']}," + f"阈值:{excellent_result['thresholds']}" + ) weak_cover_path = market_dir / weak_cover_heatmap_raster_filename(WEAK_COVER_FIELD) if weak_cover_path.exists() and not OVERWRITE: @@ -772,31 +980,47 @@ def main(): "skipped": True, } ) - continue + else: + print(f" 导出信号差用户量热力图:{weak_cover_path.name}") + weak_cover_result = export_market_excellent_heatmap_tif( + grid_conn, + grid_layer, + grid_rtree, + market, + WEAK_COVER_FIELD, + pixel_width, + pixel_height, + weak_cover_path, + ) + weak_cover_result["market_dir"] = str(market_dir) + weak_cover_result["skipped"] = False + weak_cover_heatmap_results.append(weak_cover_result) + print( + f" 信号差用户量热力图像素:{weak_cover_result['width']}x{weak_cover_result['height']}," + f"阈值:{weak_cover_result['thresholds']}" + ) - print(f" 导出信号差用户量热力图:{weak_cover_path.name}") - weak_cover_result = export_market_excellent_heatmap_tif( - grid_conn, - grid_layer, - grid_rtree, + building_info_path = building_info_output_path(OUTPUT_DIR, market) + print(f" 拆分 BuildingInfo:{building_info_path.name}") + building_info_result = export_market_building_info_gpkg( + building_info_conn, + building_info_layer, + building_info_rtree, market, - WEAK_COVER_FIELD, - pixel_width, - pixel_height, - weak_cover_path, + building_info_path, ) - weak_cover_result["market_dir"] = str(market_dir) - weak_cover_result["skipped"] = False - weak_cover_heatmap_results.append(weak_cover_result) + building_info_result["market_dir"] = str(market_dir) + building_info_results.append(building_info_result) print( - f" 信号差用户量热力图像素:{weak_cover_result['width']}x{weak_cover_result['height']}," - f"阈值:{weak_cover_result['thresholds']}" + f" BuildingInfo 要素:{building_info_result['feature_count']}," + f"候选:{building_info_result['candidates']}" ) summary_path = OUTPUT_DIR / "summary.json" summary = { "market_gpkg": str(MARKET_GPKG), "grid_gpkg": str(GRID_GPKG), + "building_info_gpkg": str(BUILDING_INFO_GPKG), "rsrp_field": RSRP_FIELD, "excellent_cell_field": EXCELLENT_CELL_FIELD, "weak_cover_field": WEAK_COVER_FIELD, @@ -807,6 +1031,7 @@ def main(): "heatmap_results": heatmap_results, "excellent_heatmap_results": excellent_heatmap_results, "weak_cover_heatmap_results": weak_cover_heatmap_results, + "building_info_results": building_info_results, } summary_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8") print(f"汇总:{summary_path}")