diff --git a/aidocs/project_context.md b/aidocs/project_context.md index 8129ba4..e05090d 100644 --- a/aidocs/project_context.md +++ b/aidocs/project_context.md @@ -49,3 +49,10 @@ - 当前测试市场 `JM010404` 已生成 `BuildingInfo.gpkg`,包含 9495 个建筑要素,RTree 和 `gpkg_ogr_contents.feature_count` 均为 9495;`layer_styles.styleQML` 与 `gpkg_metadata.metadata` 已验证与源文件完全一致。 - 每个市场网格结果包会额外复制 `source/MapPark/GIS.qgz` 为 `GIS.qgz`,复制过程不修改 QGIS 项目文件;当前测试市场 `JM010404` 已通过 SHA256 对比确认输出文件与源文件一致。 - 市场网格结果改为 zip 包输出:`python main.py` 会先在系统临时目录生成结果,再写入 `output/JMXXXX.zip`,zip 根目录直接包含 `GIS.qgz`、`信号.tif`、`用户量.tif`、`信号差用户量.tif`、`BuildingInfo.gpkg`,不再保留 `output/JMXXXX/` 文件夹。 + +## 2026-07-17 +- 建筑信息输出不再依赖 `source/BuildingInfo.gpkg`,改为从 `source/Building.gpkg` 按市场网格相交关系抽取建筑要素,并在结果包内生成兼容 QGIS 项目的 `BuildingInfo.gpkg`。 +- 结果包内建筑图层名固定为 `BuildingInfo`,字段固定为 `fid`、`geom`、`name`、`floor`、`height`;`name` 按 `building_name`、`building_id`、`area_name` 顺序取第一个非空值,`height` 来自源 `height` 字段,`floor` 默认按 `height / 3.0` 估算。 +- 输出 `BuildingInfo.gpkg` 会写入 GeoPackage 基础元数据、`gpkg_geometry_columns`、`gpkg_ogr_contents` 和 `rtree_BuildingInfo_geom`,以保持 `source/MapPark/GIS.qgz` 中 `./BuildingInfo.gpkg|layername=BuildingInfo` 的引用可用。 +- 当前测试市场 `JM010404` 已验证:zip 内包含 `BuildingInfo.gpkg`、`GIS.qgz`、`信号.tif`、`用户量.tif`、`信号差用户量.tif`;`BuildingInfo` 要素数和 RTree 数量均为 11215,`pragma integrity_check` 为 `ok`。 +- RSRP 红色端阈值已按用户手动配置纳入当前版本:`HEATMAP_BAD_RSRP = -105.0`。 diff --git a/main.py b/main.py index 7db09ce..3172043 100644 --- a/main.py +++ b/main.py @@ -20,7 +20,7 @@ DEFAULT_SOURCE_DIR = Path("source") # 源数据目录,存放 MarketMap.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_INFO_GPKG = DEFAULT_SOURCE_DIR / "BuildingInfo.gpkg" # 建筑信息 GeoPackage 文件路径,拆分时保留原始图层和 QGIS 样式。 +BUILDING_GPKG = DEFAULT_SOURCE_DIR / "Building.gpkg" # 建筑指标 GeoPackage 文件路径,拆分时只抽取当前 BuildingInfo 图层需要的字段。 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 字段名。 @@ -28,15 +28,19 @@ 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 图层。 +BUILDING_LAYER = None # Building 建筑指标图层名;None 表示自动使用 GPKG 中第一个 feature 图层。 MARKET_CODE_FIELD = "micro_grid" # 市场网格编码字段,用于输出 zip 文件名,例如 JM010404.zip。 MARKET_NAME_FIELD = "micro_gr_1" # 市场网格名称字段,用于日志和汇总信息。 SIGNAL_OUTPUT_FILENAME = "信号.tif" # RSRP 连续热力图输出文件名。 BUILDING_INFO_OUTPUT_FILENAME = "BuildingInfo.gpkg" # 每个市场网格结果包内输出的建筑信息拆分文件名。 +BUILDING_INFO_OUTPUT_LAYER = "BuildingInfo" # 输出给 GIS.qgz 使用的图层名,需保持 BuildingInfo 不变。 +BUILDING_NAME_FIELDS = ("building_name", "building_id", "area_name") # 输出 name 字段来源,按顺序取第一个非空值。 +BUILDING_HEIGHT_FIELD = "height" # 输出 height 字段来源。 +BUILDING_FLOOR_HEIGHT_METERS = 3.0 # 输出 floor 字段按 height 估算时使用的单层高度。 GIS_PROJECT_OUTPUT_FILENAME = "GIS.qgz" # 每个市场网格结果包内输出的 QGIS 项目文件名,内容不修改直接复制。 HEATMAP_GOOD_RSRP = -80.0 # 热力图绿色端阈值;RSRP 大于等于该值视为信号好。 HEATMAP_MID_RSRP = -95.0 # 热力图黄色中间阈值。 -HEATMAP_BAD_RSRP = -110.0 # 热力图红色端阈值;RSRP 小于等于该值视为信号差。 +HEATMAP_BAD_RSRP = -105.0 # 热力图红色端阈值;RSRP 小于等于该值视为信号差。 HEATMAP_SMOOTH_RADIUS = 10 # 热力图平滑半径,数值越大边界感越弱但细节越柔。 HEATMAP_ALPHA = 191 # 热力图有效像元透明度;191 约等于 75% 不透明度。 USER_COUNT_OUTPUT_FILENAME = "用户量.tif" # 采样点数量热力图输出文件名。 @@ -54,7 +58,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。 +BUILDING_ALLOWED_SRS_IDS = (4326, 100000) # Building 允许的经纬度坐标系 ID;100000 是 CRS84。 OVERWRITE = True # 输出文件已存在时是否覆盖。 TRANSPARENT_PIXEL = (0, 0, 0, 0) # 无数据/背景像元颜色,RGBA 中 alpha=0 表示透明。 @@ -288,60 +292,20 @@ def copy_all_rows(source_conn, target_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 create_source_table_schema(source_conn, target_conn, table_name): +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_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 source_layer_geometry_type(source_conn, layer): + row = source_conn.execute( + "select geometry_type_name from gpkg_geometry_columns where table_name = ? and column_name = ?", + (layer.table_name, layer.geom_col), + ).fetchone() + return row[0] if row else "MULTIPOLYGON" -def initialize_output_gpkg(source_conn, output_path, layer, feature_count, extent): +def initialize_building_info_output_gpkg(source_conn, output_path, source_layer, feature_count, extent): if output_path.exists(): if not OVERWRITE: return None @@ -352,21 +316,91 @@ def initialize_output_gpkg(source_conn, output_path, layer, feature_count, exten 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))) + for table_name in ("gpkg_spatial_ref_sys", "gpkg_contents", "gpkg_geometry_columns", "gpkg_ogr_contents", "gpkg_extensions"): + create_table_like_source(source_conn, target_conn, table_name) + copy_all_rows(source_conn, target_conn, "gpkg_spatial_ref_sys") + + target_conn.execute( + f""" + create table {quote_identifier(BUILDING_INFO_OUTPUT_LAYER)} ( + "fid" integer primary key autoincrement not null, + "geom" {source_layer_geometry_type(source_conn, source_layer)}, + "name" text, + "floor" mediumint, + "height" real + ) + """ + ) + + minx, miny, maxx, maxy = extent if extent else (None, None, None, None) + source_contents = source_conn.execute( + "select description, last_change, srs_id from gpkg_contents where table_name = ?", + (source_layer.table_name,), + ).fetchone() + description, last_change, srs_id = source_contents if source_contents else ("", None, source_layer.srs_id) + target_conn.execute( + """ + insert into gpkg_contents + (table_name, data_type, identifier, description, last_change, min_x, min_y, max_x, max_y, srs_id) + values (?, 'features', ?, ?, coalesce(?, strftime('%Y-%m-%dT%H:%M:%fZ','now')), ?, ?, ?, ?, ?) + """, + (BUILDING_INFO_OUTPUT_LAYER, BUILDING_INFO_OUTPUT_LAYER, description, last_change, minx, miny, maxx, maxy, srs_id), + ) + target_conn.execute( + "insert into gpkg_geometry_columns values (?, ?, ?, ?, ?, ?)", + ( + BUILDING_INFO_OUTPUT_LAYER, + "geom", + source_layer_geometry_type(source_conn, source_layer), + srs_id, + 0, + 0, + ), + ) + if table_exists(target_conn, "gpkg_ogr_contents"): + target_conn.execute( + "insert into gpkg_ogr_contents (table_name, feature_count) values (?, ?)", + (BUILDING_INFO_OUTPUT_LAYER, feature_count), + ) + + output_rtree = f"rtree_{BUILDING_INFO_OUTPUT_LAYER}_geom" + target_conn.execute(f"create virtual table {quote_identifier(output_rtree)} using rtree(id, minx, maxx, miny, maxy)") + if table_exists(target_conn, "gpkg_extensions"): + target_conn.execute( + """ + insert into gpkg_extensions (table_name, column_name, extension_name, definition, scope) + values (?, 'geom', 'gpkg_rtree_index', 'http://www.geopackage.org/spec120/#extension_rtree', 'write-only') + """, + (BUILDING_INFO_OUTPUT_LAYER,), + ) return target_conn -def collect_intersecting_features(source_conn, layer, rtree, market): +def first_non_empty(values): + for value in values: + if value is not None and str(value).strip(): + return str(value).strip() + return None + + +def estimate_floor_from_height(height): + value = to_float(height) + if value is None or value <= 0: + return None + return max(1, int(round(value / BUILDING_FLOOR_HEIGHT_METERS))) + + +def collect_intersecting_building_info(source_conn, layer, rtree, market): + source_fields = [field for field in (*BUILDING_NAME_FIELDS, BUILDING_HEIGHT_FIELD) if field] + require_columns(source_conn, layer.table_name, source_fields) table = quote_identifier(layer.table_name) pk = quote_identifier(layer.pk_col) + geom = quote_identifier(layer.geom_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) + field_sql = ", ".join(f"b.{quote_identifier(field)}" for field in source_fields) min_market_x, min_market_y, max_market_x, max_market_y = market.geometry.bounds query = f""" - select {column_sql} + select b.{pk}, b.{geom}, {field_sql} from {rtree_table} r join {table} b on b.{pk} = r."id" where r."minx" <= ? @@ -375,8 +409,6 @@ def collect_intersecting_features(source_conn, layer, rtree, market): 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 = [] @@ -385,7 +417,8 @@ def collect_intersecting_features(source_conn, layer, rtree, market): 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] + source_fid = row[0] + geom_blob = row[1] if geom_blob is None: continue try: @@ -396,8 +429,12 @@ def collect_intersecting_features(source_conn, layer, rtree, market): continue minx, miny, maxx, maxy = geometry.bounds - rows.append(row) - rtree_rows.append((row[pk_index], minx, maxx, miny, maxy)) + source_values = dict(zip(source_fields, row[2:])) + building_name = first_non_empty(source_values.get(field) for field in BUILDING_NAME_FIELDS) + height = to_float(source_values.get(BUILDING_HEIGHT_FIELD)) + floor = estimate_floor_from_height(height) + rows.append((source_fid, geom_blob, building_name, floor, height)) + rtree_rows.append((source_fid, minx, maxx, miny, maxy)) if extent is None: extent = [minx, miny, maxx, maxy] else: @@ -406,17 +443,17 @@ def collect_intersecting_features(source_conn, layer, rtree, market): extent[2] = max(extent[2], maxx) extent[3] = max(extent[3], maxy) - return columns, rows, rtree_rows, tuple(extent) if extent else None, candidates + return 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( + rows, rtree_rows, extent, candidates = collect_intersecting_building_info( source_conn, layer, rtree, market, ) - target_conn = initialize_output_gpkg(source_conn, output_path, layer, len(rows), extent) + target_conn = initialize_building_info_output_gpkg(source_conn, output_path, layer, len(rows), extent) if target_conn is None: return { "market_code": market.code, @@ -428,10 +465,17 @@ def export_market_building_info_gpkg(source_conn, layer, rtree, market, output_p } try: - copy_matching_rows(target_conn, layer.table_name, columns, rows) + target_conn.executemany( + f""" + insert into {quote_identifier(BUILDING_INFO_OUTPUT_LAYER)} + ("fid", "geom", "name", "floor", "height") + values (?, ?, ?, ?, ?) + """, + rows, + ) if rtree_rows: target_conn.executemany( - f"insert into {quote_identifier(rtree)} values (?, ?, ?, ?, ?)", + f"insert into {quote_identifier(f'rtree_{BUILDING_INFO_OUTPUT_LAYER}_geom')} values (?, ?, ?, ?, ?)", rtree_rows, ) target_conn.commit() @@ -945,15 +989,15 @@ def main(): with ( sqlite3.connect(MARKET_GPKG) as market_conn, sqlite3.connect(GRID_GPKG) as grid_conn, - sqlite3.connect(BUILDING_INFO_GPKG) as building_info_conn, + sqlite3.connect(BUILDING_GPKG) as building_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) + building_layer = resolve_feature_layer(building_conn, BUILDING_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}") + if building_layer.srs_id not in BUILDING_ALLOWED_SRS_IDS: + raise ValueError(f"Building 图层坐标系不在允许范围内:{building_layer.srs_id}") require_columns( grid_conn, @@ -961,7 +1005,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) + building_rtree = rtree_name(building_conn, building_layer) pixel_width = PIXEL_WIDTH pixel_height = PIXEL_HEIGHT if pixel_width is None or pixel_height is None: @@ -991,7 +1035,7 @@ def main(): zip_results = [] print(f"市场网格数量:{len(markets)}") print(f"Grid 图层:{grid_layer.table_name}") - print(f"BuildingInfo 图层:{building_info_layer.table_name}") + print(f"Building 图层:{building_layer.table_name}") print(f"QGIS 项目文件:{GIS_PROJECT_SOURCE}") print(f"RSRP 字段:{RSRP_FIELD}") print(f"采样点字段:{EXCELLENT_CELL_FIELD}") @@ -1084,9 +1128,9 @@ def main(): building_info_path = market_dir / BUILDING_INFO_OUTPUT_FILENAME print(f" 拆分 BuildingInfo:{building_info_path.name}") building_info_result = export_market_building_info_gpkg( - building_info_conn, - building_info_layer, - building_info_rtree, + building_conn, + building_layer, + building_rtree, market, building_info_path, ) @@ -1108,7 +1152,7 @@ def main(): summary = { "market_gpkg": str(MARKET_GPKG), "grid_gpkg": str(GRID_GPKG), - "building_info_gpkg": str(BUILDING_INFO_GPKG), + "building_gpkg": str(BUILDING_GPKG), "gis_project_source": str(GIS_PROJECT_SOURCE), "rsrp_field": RSRP_FIELD, "excellent_cell_field": EXCELLENT_CELL_FIELD,