feat: 增加采样点数量热力图
This commit is contained in:
@@ -34,3 +34,7 @@
|
||||
- 输出目录已清理为热力图测试结构:当前仅保留 `output/JM010404/ssb_rsrp_dx_heatmap.tif`、`output/heatmap_legend.csv` 和 `output/summary.json`。
|
||||
- `LIMIT = 1` 仍保留为测试阶段配置,后续确认字段和效果后再改回 `None` 全量生成。
|
||||
- 热力图红色端已改回纯红 `(255, 0, 0)`,有效像元统一使用 `HEATMAP_ALPHA = 191`(约 75% 不透明度),无数据区域仍为 alpha=0;当前测试配置为 `SCALE = 5.0`、`HEATMAP_SMOOTH_RADIUS = 10`、`SAMPLE_SIZE = 10000`。
|
||||
- 新增 `mr_dl_excellent_cell_dl` 采样点数量热力图,输出为 `output/JMXXXX/mr_dl_excellent_cell_dl_excellent_heatmap.tif`。
|
||||
- 采样点数量热力图按每个市场网格内相交 Grid 的字段值去重后降序排列,使用 `EXCELLENT_PERCENT_STEPS = (0.2, 0.4, 0.6)` 计算阈值;默认规则为 `>20%阈值` 红、`>40%阈值` 黄、`>60%阈值` 蓝、其余绿。
|
||||
- 采样点数量热力图颜色由 `EXCELLENT_COLORS` 配置,图例写入 `output/excellent_heatmap_legend.csv`,每个市场的实际阈值写入 `summary.json` 的 `excellent_heatmap_results`。
|
||||
- 当前测试市场 `JM010404` 的 `mr_dl_excellent_cell_dl` 去重分位阈值为 `[1204.0, 749.0, 471.0]`,输出验证为四种有效颜色加透明背景。
|
||||
|
||||
@@ -18,6 +18,7 @@ OUTPUT_DIR = Path("output") # 输出根目录,每个市场网格会在这里
|
||||
MARKET_GPKG = DEFAULT_SOURCE_DIR / "MarketMap.gpkg" # 市场网格 GeoPackage 文件路径。
|
||||
GRID_GPKG = DEFAULT_SOURCE_DIR / "grid.gpkg" # Grid 栅格指标 GeoPackage 文件路径。
|
||||
RSRP_FIELD = "ssb_rsrp_dx" # 用于生成热力图的电信 RSRP 字段名。
|
||||
EXCELLENT_CELL_FIELD = "mr_dl_excellent_cell_dl" # 用于生成采样点数量热力图的字段名,值越大越红。
|
||||
MARKET_LAYER = None # 市场网格图层名;None 表示自动使用 GPKG 中第一个 feature 图层。
|
||||
GRID_LAYER = None # Grid 指标图层名;None 表示自动使用 GPKG 中第一个 feature 图层。
|
||||
MARKET_CODE_FIELD = "micro_grid" # 市场网格编码字段,用于输出文件夹名,例如 JM010404。
|
||||
@@ -28,6 +29,14 @@ HEATMAP_MID_RSRP = -95.0 # 热力图黄色中间阈值。
|
||||
HEATMAP_BAD_RSRP = -110.0 # 热力图红色端阈值;RSRP 小于等于该值视为信号差。
|
||||
HEATMAP_SMOOTH_RADIUS = 10 # 热力图平滑半径,数值越大边界感越弱但细节越柔。
|
||||
HEATMAP_ALPHA = 191 # 热力图有效像元透明度;191 约等于 75% 不透明度。
|
||||
EXCELLENT_HEATMAP_OUTPUT_SUFFIX = "_excellent_heatmap" # 采样点数量热力图文件名后缀。
|
||||
EXCELLENT_PERCENT_STEPS = (0.2, 0.4, 0.6) # 去重值降序分位阈值,默认按前 20%、40%、60% 分四档。
|
||||
EXCELLENT_COLORS = (
|
||||
(255, 0, 0), # 高于前 20% 阈值,红色。
|
||||
(255, 255, 0), # 高于前 40% 阈值,黄色。
|
||||
(0, 112, 255), # 高于前 60% 阈值,蓝色。
|
||||
(0, 176, 80), # 其余较低值,绿色。
|
||||
)
|
||||
PIXEL_WIDTH = None # 输出像元宽度;None 表示自动按 Grid 单元宽度估算。
|
||||
PIXEL_HEIGHT = None # 输出像元高度;None 表示自动按 Grid 单元高度估算。
|
||||
SCALE = 5.0 # 分辨率倍数;2.0 表示像元宽高减半,放大查看更清晰。
|
||||
@@ -73,6 +82,10 @@ def heatmap_raster_filename(field):
|
||||
return f"{safe_filename(field)}{HEATMAP_OUTPUT_SUFFIX}.tif"
|
||||
|
||||
|
||||
def excellent_heatmap_raster_filename(field):
|
||||
return f"{safe_filename(field)}{EXCELLENT_HEATMAP_OUTPUT_SUFFIX}.tif"
|
||||
|
||||
|
||||
def gpkg_blob_to_wkb(blob):
|
||||
data = bytes(blob)
|
||||
if data[:2] != b"GP":
|
||||
@@ -212,6 +225,29 @@ def heatmap_rgb_for_values(values):
|
||||
return np.clip(result, 0, 255).astype(np.uint8)
|
||||
|
||||
|
||||
def percentile_thresholds_from_unique(values, percent_steps):
|
||||
unique_values = sorted({value for value in values if value is not None}, reverse=True)
|
||||
if not unique_values:
|
||||
return []
|
||||
|
||||
thresholds = []
|
||||
for percent in percent_steps:
|
||||
index = max(0, math.ceil(len(unique_values) * percent) - 1)
|
||||
index = min(index, len(unique_values) - 1)
|
||||
thresholds.append(unique_values[index])
|
||||
return thresholds
|
||||
|
||||
|
||||
def color_for_excellent_value(value, thresholds):
|
||||
if len(thresholds) >= 1 and value > thresholds[0]:
|
||||
return (*EXCELLENT_COLORS[0], HEATMAP_ALPHA)
|
||||
if len(thresholds) >= 2 and value > thresholds[1]:
|
||||
return (*EXCELLENT_COLORS[1], HEATMAP_ALPHA)
|
||||
if len(thresholds) >= 3 and value > thresholds[2]:
|
||||
return (*EXCELLENT_COLORS[2], HEATMAP_ALPHA)
|
||||
return (*EXCELLENT_COLORS[3], HEATMAP_ALPHA)
|
||||
|
||||
|
||||
def gaussian_kernel(radius):
|
||||
if radius <= 0:
|
||||
return np.array([1.0], dtype=np.float32)
|
||||
@@ -417,6 +453,117 @@ def export_market_heatmap_tif(grid_conn, grid_layer, rtree, market, field, pixel
|
||||
}
|
||||
|
||||
|
||||
def export_market_excellent_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]
|
||||
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)
|
||||
candidates = 0
|
||||
skipped_no_value = 0
|
||||
matched_cells = []
|
||||
matched_values = []
|
||||
|
||||
for _fid, geom_blob, raw_value, raw_lon, raw_lat in grid_conn.execute(query, params):
|
||||
candidates += 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
|
||||
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
|
||||
|
||||
matched_cells.append((window, value))
|
||||
matched_values.append(value)
|
||||
|
||||
thresholds = percentile_thresholds_from_unique(matched_values, EXCELLENT_PERCENT_STEPS)
|
||||
for window, value in matched_cells:
|
||||
row_start, row_stop, col_start, col_stop = window
|
||||
image[row_start:row_stop, col_start:col_stop] = color_for_excellent_value(value, thresholds)
|
||||
|
||||
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": len(matched_cells),
|
||||
"data_pixels": int(np.count_nonzero(image[..., 3] > 0)),
|
||||
"skipped_no_value": skipped_no_value,
|
||||
"unique_value_count": len(set(matched_values)),
|
||||
"thresholds": thresholds,
|
||||
"percent_steps": list(EXCELLENT_PERCENT_STEPS),
|
||||
"width": width,
|
||||
"height": height,
|
||||
}
|
||||
|
||||
|
||||
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:
|
||||
@@ -429,6 +576,19 @@ def write_heatmap_legend(output_dir, field):
|
||||
return legend_path
|
||||
|
||||
|
||||
def write_excellent_heatmap_legend(output_dir, field):
|
||||
legend_path = output_dir / "excellent_heatmap_legend.csv"
|
||||
with legend_path.open("w", newline="", encoding="utf-8-sig") as file:
|
||||
writer = csv.writer(file)
|
||||
writer.writerow(["field", "rule", "red", "green", "blue", "alpha", "meaning"])
|
||||
writer.writerow([field, "> threshold_20_percent", *EXCELLENT_COLORS[0], HEATMAP_ALPHA, "highest values"])
|
||||
writer.writerow([field, "> threshold_40_percent", *EXCELLENT_COLORS[1], HEATMAP_ALPHA, "high values"])
|
||||
writer.writerow([field, "> threshold_60_percent", *EXCELLENT_COLORS[2], HEATMAP_ALPHA, "middle values"])
|
||||
writer.writerow([field, "else", *EXCELLENT_COLORS[3], HEATMAP_ALPHA, "lower values"])
|
||||
writer.writerow([field, "nodata", 0, 0, 0, 0, "transparent no data"])
|
||||
return legend_path
|
||||
|
||||
|
||||
def main():
|
||||
if SCALE <= 0:
|
||||
raise ValueError("SCALE 必须大于 0")
|
||||
@@ -443,7 +603,7 @@ def main():
|
||||
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"])
|
||||
require_columns(grid_conn, grid_layer.table_name, [RSRP_FIELD, EXCELLENT_CELL_FIELD, "longitude", "latitude"])
|
||||
grid_rtree = rtree_name(grid_conn, grid_layer)
|
||||
pixel_width = PIXEL_WIDTH
|
||||
pixel_height = PIXEL_HEIGHT
|
||||
@@ -464,13 +624,17 @@ def main():
|
||||
markets = markets[:LIMIT]
|
||||
|
||||
heatmap_legend_path = write_heatmap_legend(OUTPUT_DIR, RSRP_FIELD)
|
||||
excellent_legend_path = write_excellent_heatmap_legend(OUTPUT_DIR, EXCELLENT_CELL_FIELD)
|
||||
heatmap_results = []
|
||||
excellent_heatmap_results = []
|
||||
print(f"市场网格数量:{len(markets)}")
|
||||
print(f"Grid 图层:{grid_layer.table_name}")
|
||||
print(f"RSRP 字段:{RSRP_FIELD}")
|
||||
print(f"采样点字段:{EXCELLENT_CELL_FIELD}")
|
||||
print(f"分辨率倍数:{SCALE}")
|
||||
print(f"像元大小:{pixel_width}, {pixel_height}")
|
||||
print(f"热力图图例:{heatmap_legend_path}")
|
||||
print(f"采样点热力图图例:{excellent_legend_path}")
|
||||
|
||||
for index, market in enumerate(markets, start=1):
|
||||
market_dir = market_output_dir(OUTPUT_DIR, market)
|
||||
@@ -508,16 +672,51 @@ def main():
|
||||
f"有效像素:{heatmap_result['data_pixels']}"
|
||||
)
|
||||
|
||||
excellent_path = market_dir / excellent_heatmap_raster_filename(EXCELLENT_CELL_FIELD)
|
||||
if excellent_path.exists() and not OVERWRITE:
|
||||
print(f" 跳过已存在采样点热力图:{excellent_path.name}")
|
||||
excellent_heatmap_results.append(
|
||||
{
|
||||
"market_code": market.code,
|
||||
"market_name": market.name,
|
||||
"market_dir": str(market_dir),
|
||||
"output": str(excellent_path),
|
||||
"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']}"
|
||||
)
|
||||
|
||||
summary_path = OUTPUT_DIR / "summary.json"
|
||||
summary = {
|
||||
"market_gpkg": str(MARKET_GPKG),
|
||||
"grid_gpkg": str(GRID_GPKG),
|
||||
"field": RSRP_FIELD,
|
||||
"rsrp_field": RSRP_FIELD,
|
||||
"excellent_cell_field": EXCELLENT_CELL_FIELD,
|
||||
"clip_mode": CLIP_MODE,
|
||||
"scale": SCALE,
|
||||
"pixel_width": pixel_width,
|
||||
"pixel_height": pixel_height,
|
||||
"heatmap_results": heatmap_results,
|
||||
"excellent_heatmap_results": excellent_heatmap_results,
|
||||
}
|
||||
summary_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
print(f"汇总:{summary_path}")
|
||||
|
||||
Reference in New Issue
Block a user