diff --git a/aidocs/project_context.md b/aidocs/project_context.md index 5e0763c..1bf3c17 100644 --- a/aidocs/project_context.md +++ b/aidocs/project_context.md @@ -27,3 +27,9 @@ - 热力图使用红-黄-绿连续渐变:`HEATMAP_BAD_RSRP` 对应红色,`HEATMAP_MID_RSRP` 对应黄色,`HEATMAP_GOOD_RSRP` 对应绿色,并通过 `HEATMAP_SMOOTH_RADIUS` 控制平滑半径以弱化格网边界感。 - 测试阶段 `LIMIT = 1`,当前 `python main.py` 只处理第一个市场网格;确认效果后将 `LIMIT` 改回 `None` 即可全量生成。 - `summary.json` 新增 `heatmap_results`,当前测试输出含 1 条 tif、1 条 heatmap、1 条 build 结果。 + +## 2026-07-15 +- 按当前测试需求,`main.py` 已收敛为仅生成真正的连续热力图,不再生成分级 tif,也不再拆分 `build.gpkg`。 +- 当前 `python main.py` 只读取 `source/MarketMap.gpkg` 和 `source/grid.gpkg`,按市场网格与 Grid 相交关系生成 `output/JMXXXX/ssb_rsrp_dx_heatmap.tif`。 +- 输出目录已清理为热力图测试结构:当前仅保留 `output/JM010404/ssb_rsrp_dx_heatmap.tif`、`output/heatmap_legend.csv` 和 `output/summary.json`。 +- `LIMIT = 1` 仍保留为测试阶段配置,后续确认字段和效果后再改回 `None` 全量生成。 diff --git a/main.py b/main.py index 538cd89..f23510e 100644 --- a/main.py +++ b/main.py @@ -17,16 +17,12 @@ 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 文件路径。 -BUILD_GPKG = DEFAULT_SOURCE_DIR / "build.gpkg" # 建筑物/Build 指标 GeoPackage 文件路径。 -RSRP_FIELD = "ssb_rsrp_dx" # 用于着色的电信 RSRP 字段名。 +RSRP_FIELD = "ssb_rsrp_dx" # 用于生成热力图的电信 RSRP 字段名。 MARKET_LAYER = None # 市场网格图层名;None 表示自动使用 GPKG 中第一个 feature 图层。 GRID_LAYER = None # Grid 指标图层名;None 表示自动使用 GPKG 中第一个 feature 图层。 -BUILD_LAYER = None # Build 图层名;None 表示自动使用 GPKG 中第一个 feature 图层。 MARKET_CODE_FIELD = "micro_grid" # 市场网格编码字段,用于输出文件夹名,例如 JM010404。 MARKET_NAME_FIELD = "micro_gr_1" # 市场网格名称字段,用于日志和汇总信息。 -BUILD_OUTPUT_FILENAME = "build.gpkg" # 每个市场网格目录内输出的 Build 拆分文件名。 HEATMAP_OUTPUT_SUFFIX = "_heatmap" # 连续热力图文件名后缀,例如 ssb_rsrp_dx_heatmap.tif。 -EXPORT_HEATMAP = True # 是否额外导出绿黄红连续渐变热力图。 HEATMAP_GOOD_RSRP = -80.0 # 热力图绿色端阈值;RSRP 大于等于该值视为信号好。 HEATMAP_MID_RSRP = -95.0 # 热力图黄色中间阈值。 HEATMAP_BAD_RSRP = -110.0 # 热力图红色端阈值;RSRP 小于等于该值视为信号差。 @@ -40,15 +36,6 @@ CLIP_MODE = "intersects" # 裁切方式:intersects 按几何相交裁切,ce OVERWRITE = True # 输出文件已存在时是否覆盖。 TRANSPARENT_PIXEL = (0, 0, 0, 0) # 无数据/背景像元颜色,RGBA 中 alpha=0 表示透明。 -COLOR_BREAKS = [ - (-80.0, (26, 152, 80), ">= -80"), # RSRP >= -80,信号最强,绿色。 - (-90.0, (102, 189, 99), "[-90, -80)"), # -90 到 -80,较强信号,浅绿色。 - (-100.0, (217, 239, 139), "[-100, -90)"), # -100 到 -90,中等信号,黄绿色。 - (-105.0, (254, 224, 139), "[-105, -100)"), # -105 到 -100,偏弱信号,黄色。 - (-110.0, (244, 109, 67), "[-110, -105)"), # -110 到 -105,弱信号,橙红色。 - (-math.inf, (94, 79, 162), "< -110"), # RSRP < -110,最弱信号,紫色。 -] - @dataclass(frozen=True) class LayerInfo: @@ -81,18 +68,10 @@ def market_output_dir(output_dir, market): return output_dir / safe_filename(market.code) -def raster_filename(field): - return f"{safe_filename(field)}.tif" - - def heatmap_raster_filename(field): return f"{safe_filename(field)}{HEATMAP_OUTPUT_SUFFIX}.tif" -def build_output_path(output_dir, market): - return market_output_dir(output_dir, market) / BUILD_OUTPUT_FILENAME - - def gpkg_blob_to_wkb(blob): data = bytes(blob) if data[:2] != b"GP": @@ -208,13 +187,6 @@ def estimate_pixel_size(conn, layer, sample_size): return float(np.median(widths)), float(np.median(heights)) -def color_for_value(value): - for threshold, color, _label in COLOR_BREAKS: - if value >= threshold: - return (*color, 255) - return (*COLOR_BREAKS[-1][1], 255) - - def interpolate_color(start_color, end_color, ratio): ratio = np.clip(ratio, 0.0, 1.0)[..., np.newaxis] start = np.array(start_color, dtype=np.float32) @@ -336,102 +308,7 @@ def pixel_window_from_point(x, y, minx, maxy, pixel_width, pixel_height, width, return None -def export_market_tif(grid_conn, grid_layer, rtree, market, field, pixel_width, pixel_height, output_path, clip_mode): - image, minx, maxy = create_canvas(market.geometry.bounds, pixel_width, pixel_height) - height, width = image.shape[:2] - prepared_market = prep(market.geometry) - table = quote_identifier(grid_layer.table_name) - geom = quote_identifier(grid_layer.geom_col) - pk = quote_identifier(grid_layer.pk_col) - rtree_table = quote_identifier(rtree) - field_expr = quote_identifier(field) - lon_expr = quote_identifier("longitude") - lat_expr = quote_identifier("latitude") - min_market_x, min_market_y, max_market_x, max_market_y = market.geometry.bounds - - query = f""" - select b.{pk}, b.{geom}, b.{field_expr}, b.{lon_expr}, b.{lat_expr} - from {rtree_table} r - join {table} b on b.{pk} = r."id" - where r."minx" <= ? - and r."maxx" >= ? - and r."miny" <= ? - and r."maxy" >= ? - """ - params = (max_market_x, min_market_x, max_market_y, min_market_y) - total = 0 - painted = 0 - skipped_no_value = 0 - - for _fid, geom_blob, raw_value, raw_lon, raw_lat in grid_conn.execute(query, params): - total += 1 - value = to_float(raw_value) - if value is None: - skipped_no_value += 1 - continue - - lon = to_float(raw_lon) - lat = to_float(raw_lat) - target_point = None - if lon is not None and lat is not None: - target_point = (lon, lat) - - if clip_mode == "intersects": - if geom_blob is None: - continue - try: - grid_geom = from_wkb(gpkg_blob_to_wkb(geom_blob)) - except (GEOSException, ValueError): - continue - if not prepared_market.intersects(grid_geom): - continue - if target_point is None: - target_point = grid_geom.representative_point().coords[0] - window = pixel_window_for_bounds( - grid_geom.bounds, - minx, - maxy, - pixel_width, - pixel_height, - width, - height, - ) - else: - if target_point is None: - continue - if not prepared_market.covers(Point(target_point)): - continue - window = pixel_window_from_point( - target_point[0], - target_point[1], - minx, - maxy, - pixel_width, - pixel_height, - width, - height, - ) - if window is None: - continue - - row_start, row_stop, col_start, col_stop = window - image[row_start:row_stop, col_start:col_stop] = color_for_value(value) - painted += 1 - - 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": total, - "painted_pixels": painted, - "skipped_no_value": skipped_no_value, - "width": width, - "height": height, - } - - -def export_market_heatmap_tif(grid_conn, grid_layer, rtree, market, field, pixel_width, pixel_height, output_path, clip_mode): +def export_market_heatmap_tif(grid_conn, grid_layer, rtree, market, field, pixel_width, pixel_height, output_path): image, minx, maxy = create_canvas(market.geometry.bounds, pixel_width, pixel_height) height, width = image.shape[:2] value_sum = np.zeros((height, width), dtype=np.float32) @@ -473,7 +350,7 @@ def export_market_heatmap_tif(grid_conn, grid_layer, rtree, market, field, pixel if lon is not None and lat is not None: target_point = (lon, lat) - if clip_mode == "intersects": + if CLIP_MODE == "intersects": if geom_blob is None: continue try: @@ -539,227 +416,6 @@ def export_market_heatmap_tif(grid_conn, grid_layer, rtree, market, field, pixel } -def sqlite_create_sql(conn, name): - row = conn.execute( - "select sql from sqlite_master where type = 'table' and name = ?", - (name,), - ).fetchone() - if not row or not row[0]: - raise ValueError(f"未找到表结构:{name}") - return row[0] - - -def copy_all_rows(source_conn, target_conn, table_name): - 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 write_gpkg_contents(source_conn, target_conn, layer, feature_count, extent): - row = source_conn.execute( - "select table_name, data_type, identifier, description, last_change, min_x, min_y, max_x, max_y, srs_id " - "from gpkg_contents where table_name = ?", - (layer.table_name,), - ).fetchone() - if not row: - raise ValueError(f"gpkg_contents 缺少图层记录:{layer.table_name}") - - minx, miny, maxx, maxy = extent if extent else (None, None, None, None) - 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - """, - (row[0], row[1], row[2], row[3], row[4], minx, miny, maxx, maxy, row[9]), - ) - - geometry_row = source_conn.execute( - "select table_name, column_name, geometry_type_name, srs_id, z, m " - "from gpkg_geometry_columns where table_name = ? and column_name = ?", - (layer.table_name, layer.geom_col), - ).fetchone() - if not geometry_row: - raise ValueError(f"gpkg_geometry_columns 缺少图层记录:{layer.table_name}") - target_conn.execute( - "insert into gpkg_geometry_columns values (?, ?, ?, ?, ?, ?)", - geometry_row, - ) - - has_ogr_contents = source_conn.execute( - "select 1 from sqlite_master where type = 'table' and name = 'gpkg_ogr_contents'", - ).fetchone() - if has_ogr_contents: - target_conn.execute( - "insert into gpkg_ogr_contents (table_name, feature_count) values (?, ?)", - (layer.table_name, feature_count), - ) - - -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(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]}") - - metadata_tables = [ - "gpkg_spatial_ref_sys", - "gpkg_contents", - "gpkg_geometry_columns", - "gpkg_ogr_contents", - "gpkg_extensions", - ] - for table_name in metadata_tables: - if source_conn.execute( - "select 1 from sqlite_master where type = 'table' and name = ?", - (table_name,), - ).fetchone(): - target_conn.execute(sqlite_create_sql(source_conn, table_name)) - - target_conn.execute(sqlite_create_sql(source_conn, layer.table_name)) - rtree = rtree_name(source_conn, layer) - target_conn.execute(sqlite_create_sql(source_conn, rtree)) - copy_all_rows(source_conn, target_conn, "gpkg_spatial_ref_sys") - write_gpkg_contents(source_conn, target_conn, layer, feature_count, extent) - - if source_conn.execute( - "select 1 from sqlite_master where type = 'table' and name = 'gpkg_extensions'", - ).fetchone(): - extension_rows = source_conn.execute( - "select * from gpkg_extensions where table_name = ?", - (layer.table_name,), - ).fetchall() - if extension_rows: - placeholders = ", ".join(["?"] * len(extension_rows[0])) - target_conn.executemany( - f"insert into gpkg_extensions values ({placeholders})", - extension_rows, - ) - return target_conn - - -def collect_intersecting_features(source_conn, layer, rtree, market): - table = quote_identifier(layer.table_name) - geom = quote_identifier(layer.geom_col) - 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_build_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 write_legend(output_dir, field): - legend_path = output_dir / "legend.csv" - with legend_path.open("w", newline="", encoding="utf-8-sig") as file: - writer = csv.writer(file) - writer.writerow(["field", "range", "red", "green", "blue", "alpha", "meaning"]) - for _threshold, color, label in COLOR_BREAKS: - writer.writerow([field, label, color[0], color[1], color[2], 255, "strong-to-weak RSRP"]) - writer.writerow([field, "nodata", 0, 0, 0, 0, "transparent no data"]) - return legend_path - - def write_heatmap_legend(output_dir, field): legend_path = output_dir / "heatmap_legend.csv" with legend_path.open("w", newline="", encoding="utf-8-sig") as file: @@ -780,20 +436,14 @@ 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, - sqlite3.connect(BUILD_GPKG) as build_conn, - ): + with sqlite3.connect(MARKET_GPKG) as market_conn, sqlite3.connect(GRID_GPKG) as grid_conn: market_layer = resolve_feature_layer(market_conn, MARKET_LAYER) grid_layer = resolve_feature_layer(grid_conn, GRID_LAYER) - build_layer = resolve_feature_layer(build_conn, BUILD_LAYER) - if market_layer.srs_id != 4326 or grid_layer.srs_id != 4326 or build_layer.srs_id != 4326: + if market_layer.srs_id != 4326 or grid_layer.srs_id != 4326: raise ValueError("当前脚本只处理 EPSG:4326 的输入图层") require_columns(grid_conn, grid_layer.table_name, [RSRP_FIELD, "longitude", "latitude"]) grid_rtree = rtree_name(grid_conn, grid_layer) - build_rtree = rtree_name(build_conn, build_layer) pixel_width = PIXEL_WIDTH pixel_height = PIXEL_HEIGHT if pixel_width is None or pixel_height is None: @@ -812,114 +462,61 @@ def main(): if LIMIT: markets = markets[:LIMIT] - legend_path = write_legend(OUTPUT_DIR, RSRP_FIELD) - heatmap_legend_path = write_heatmap_legend(OUTPUT_DIR, RSRP_FIELD) if EXPORT_HEATMAP else None - tif_results = [] + heatmap_legend_path = write_heatmap_legend(OUTPUT_DIR, RSRP_FIELD) heatmap_results = [] - build_results = [] print(f"市场网格数量:{len(markets)}") print(f"Grid 图层:{grid_layer.table_name}") - print(f"Build 图层:{build_layer.table_name}") print(f"RSRP 字段:{RSRP_FIELD}") print(f"分辨率倍数:{SCALE}") print(f"像元大小:{pixel_width}, {pixel_height}") - print(f"图例:{legend_path}") - if heatmap_legend_path: - print(f"热力图图例:{heatmap_legend_path}") + print(f"热力图图例:{heatmap_legend_path}") for index, market in enumerate(markets, start=1): market_dir = market_output_dir(OUTPUT_DIR, market) market_dir.mkdir(parents=True, exist_ok=True) - output_path = market_dir / raster_filename(RSRP_FIELD) - if output_path.exists() and not OVERWRITE: - print(f"[{index}/{len(markets)}] 跳过已存在:{market.code}/{output_path.name}") - tif_results.append( + heatmap_path = market_dir / heatmap_raster_filename(RSRP_FIELD) + if heatmap_path.exists() and not OVERWRITE: + print(f"[{index}/{len(markets)}] 跳过已存在热力图:{market.code}/{heatmap_path.name}") + heatmap_results.append( { "market_code": market.code, "market_name": market.name, "market_dir": str(market_dir), - "output": str(output_path), + "output": str(heatmap_path), "skipped": True, } ) - else: - print(f"[{index}/{len(markets)}] 导出:{market.code} {market.name}") - result = export_market_tif( - grid_conn, - grid_layer, - grid_rtree, - market, - RSRP_FIELD, - pixel_width, - pixel_height, - output_path, - CLIP_MODE, - ) - result["market_dir"] = str(market_dir) - result["skipped"] = False - tif_results.append(result) - print(f" 像素:{result['width']}x{result['height']},已着色:{result['painted_pixels']}") + continue - if EXPORT_HEATMAP: - heatmap_path = market_dir / heatmap_raster_filename(RSRP_FIELD) - if heatmap_path.exists() and not OVERWRITE: - print(f" 跳过已存在热力图:{heatmap_path.name}") - heatmap_results.append( - { - "market_code": market.code, - "market_name": market.name, - "market_dir": str(market_dir), - "output": str(heatmap_path), - "skipped": True, - } - ) - else: - print(f" 导出连续热力图:{heatmap_path.name}") - heatmap_result = export_market_heatmap_tif( - grid_conn, - grid_layer, - grid_rtree, - market, - RSRP_FIELD, - pixel_width, - pixel_height, - heatmap_path, - CLIP_MODE, - ) - 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']}" - ) - - build_path = build_output_path(OUTPUT_DIR, market) - print(f" 拆分 Build:{build_path.name}") - build_result = export_market_build_gpkg( - build_conn, - build_layer, - build_rtree, + print(f"[{index}/{len(markets)}] 导出热力图:{market.code} {market.name}") + heatmap_result = export_market_heatmap_tif( + grid_conn, + grid_layer, + grid_rtree, market, - build_path, + 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']}" ) - build_result["market_dir"] = str(market_dir) - build_results.append(build_result) - print(f" Build 要素:{build_result['feature_count']},候选:{build_result['candidates']}") summary_path = OUTPUT_DIR / "summary.json" summary = { "market_gpkg": str(MARKET_GPKG), "grid_gpkg": str(GRID_GPKG), - "build_gpkg": str(BUILD_GPKG), "field": RSRP_FIELD, "clip_mode": CLIP_MODE, "scale": SCALE, "pixel_width": pixel_width, "pixel_height": pixel_height, - "tif_results": tif_results, "heatmap_results": heatmap_results, - "build_results": build_results, } summary_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8") print(f"汇总:{summary_path}")