feat: 增加连续RSRP热力图输出
This commit is contained in:
@@ -23,3 +23,7 @@
|
|||||||
- 每个市场目录新增 `build.gpkg`,保留原 Build 图层名、字段、原始几何和属性,同时写入 GeoPackage 元数据、feature_count 和 RTree。
|
- 每个市场目录新增 `build.gpkg`,保留原 Build 图层名、字段、原始几何和属性,同时写入 GeoPackage 元数据、feature_count 和 RTree。
|
||||||
- `python main.py` 会一次性完成 RSRP tif 导出和 Build GPKG 拆分;全量结果已生成 106 个 `build.gpkg`,合计约 375MB。
|
- `python main.py` 会一次性完成 RSRP tif 导出和 Build GPKG 拆分;全量结果已生成 106 个 `build.gpkg`,合计约 375MB。
|
||||||
- `summary.json` 已拆分记录 `tif_results` 和 `build_results`,便于分别查看栅格和 Build 拆分统计。
|
- `summary.json` 已拆分记录 `tif_results` 和 `build_results`,便于分别查看栅格和 Build 拆分统计。
|
||||||
|
- 新增连续渐变热力图输出,文件名为 `ssb_rsrp_dx_heatmap.tif`,与分级 tif 和 `build.gpkg` 放在同一个 `output/JMXXXX/` 市场目录中。
|
||||||
|
- 热力图使用红-黄-绿连续渐变:`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 结果。
|
||||||
|
|||||||
@@ -25,11 +25,17 @@ BUILD_LAYER = None # Build 图层名;None 表示自动使用 GPKG 中第一
|
|||||||
MARKET_CODE_FIELD = "micro_grid" # 市场网格编码字段,用于输出文件夹名,例如 JM010404。
|
MARKET_CODE_FIELD = "micro_grid" # 市场网格编码字段,用于输出文件夹名,例如 JM010404。
|
||||||
MARKET_NAME_FIELD = "micro_gr_1" # 市场网格名称字段,用于日志和汇总信息。
|
MARKET_NAME_FIELD = "micro_gr_1" # 市场网格名称字段,用于日志和汇总信息。
|
||||||
BUILD_OUTPUT_FILENAME = "build.gpkg" # 每个市场网格目录内输出的 Build 拆分文件名。
|
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 小于等于该值视为信号差。
|
||||||
|
HEATMAP_SMOOTH_RADIUS = 4 # 热力图平滑半径,数值越大边界感越弱但细节越柔。
|
||||||
PIXEL_WIDTH = None # 输出像元宽度;None 表示自动按 Grid 单元宽度估算。
|
PIXEL_WIDTH = None # 输出像元宽度;None 表示自动按 Grid 单元宽度估算。
|
||||||
PIXEL_HEIGHT = None # 输出像元高度;None 表示自动按 Grid 单元高度估算。
|
PIXEL_HEIGHT = None # 输出像元高度;None 表示自动按 Grid 单元高度估算。
|
||||||
SCALE = 2.0 # 分辨率倍数;2.0 表示像元宽高减半,放大查看更清晰。
|
SCALE = 2.0 # 分辨率倍数;2.0 表示像元宽高减半,放大查看更清晰。
|
||||||
SAMPLE_SIZE = 5000 # 自动估算像元大小时抽样读取的 Grid 要素数量。
|
SAMPLE_SIZE = 5000 # 自动估算像元大小时抽样读取的 Grid 要素数量。
|
||||||
LIMIT = None # 限制处理前 N 个市场网格;None 表示处理全部市场网格。
|
LIMIT = 1 # 限制处理前 N 个市场网格;None 表示处理全部市场网格。
|
||||||
CLIP_MODE = "intersects" # 裁切方式:intersects 按几何相交裁切,center 按 Grid 中心点落入裁切。
|
CLIP_MODE = "intersects" # 裁切方式:intersects 按几何相交裁切,center 按 Grid 中心点落入裁切。
|
||||||
OVERWRITE = True # 输出文件已存在时是否覆盖。
|
OVERWRITE = True # 输出文件已存在时是否覆盖。
|
||||||
TRANSPARENT_PIXEL = (0, 0, 0, 0) # 无数据/背景像元颜色,RGBA 中 alpha=0 表示透明。
|
TRANSPARENT_PIXEL = (0, 0, 0, 0) # 无数据/背景像元颜色,RGBA 中 alpha=0 表示透明。
|
||||||
@@ -79,6 +85,10 @@ def raster_filename(field):
|
|||||||
return f"{safe_filename(field)}.tif"
|
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):
|
def build_output_path(output_dir, market):
|
||||||
return market_output_dir(output_dir, market) / BUILD_OUTPUT_FILENAME
|
return market_output_dir(output_dir, market) / BUILD_OUTPUT_FILENAME
|
||||||
|
|
||||||
@@ -205,6 +215,60 @@ def color_for_value(value):
|
|||||||
return (*COLOR_BREAKS[-1][1], 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)
|
||||||
|
end = np.array(end_color, dtype=np.float32)
|
||||||
|
return start + (end - start) * ratio
|
||||||
|
|
||||||
|
|
||||||
|
def heatmap_rgb_for_values(values):
|
||||||
|
red = (215, 48, 39)
|
||||||
|
yellow = (255, 255, 191)
|
||||||
|
green = (26, 152, 80)
|
||||||
|
result = np.zeros((*values.shape, 3), dtype=np.float32)
|
||||||
|
|
||||||
|
lower = values < HEATMAP_MID_RSRP
|
||||||
|
upper = ~lower
|
||||||
|
if np.any(lower):
|
||||||
|
ratio = (values[lower] - HEATMAP_BAD_RSRP) / (HEATMAP_MID_RSRP - HEATMAP_BAD_RSRP)
|
||||||
|
result[lower] = interpolate_color(red, yellow, ratio)
|
||||||
|
if np.any(upper):
|
||||||
|
ratio = (values[upper] - HEATMAP_MID_RSRP) / (HEATMAP_GOOD_RSRP - HEATMAP_MID_RSRP)
|
||||||
|
result[upper] = interpolate_color(yellow, green, ratio)
|
||||||
|
return np.clip(result, 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 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")
|
||||||
|
moved = np.moveaxis(padded, axis, 0)
|
||||||
|
output = np.empty_like(np.moveaxis(array, axis, 0), dtype=np.float32)
|
||||||
|
for index in range(output.shape[0]):
|
||||||
|
window = moved[index:index + kernel.size]
|
||||||
|
output[index] = np.tensordot(kernel, window, axes=(0, 0))
|
||||||
|
return np.moveaxis(output, 0, axis)
|
||||||
|
|
||||||
|
|
||||||
|
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):
|
def to_float(value):
|
||||||
if value is None:
|
if value is None:
|
||||||
return None
|
return None
|
||||||
@@ -367,6 +431,114 @@ def export_market_tif(grid_conn, grid_layer, rtree, market, field, pixel_width,
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def export_market_heatmap_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]
|
||||||
|
value_sum = np.zeros((height, width), dtype=np.float32)
|
||||||
|
value_weight = np.zeros((height, width), dtype=np.float32)
|
||||||
|
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
|
||||||
|
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
|
||||||
|
value_sum[row_start:row_stop, col_start:col_stop] += value
|
||||||
|
value_weight[row_start:row_stop, col_start:col_stop] += 1.0
|
||||||
|
painted += 1
|
||||||
|
|
||||||
|
data_mask = value_weight > 0
|
||||||
|
if np.any(data_mask):
|
||||||
|
smoothed_sum = gaussian_blur(value_sum, HEATMAP_SMOOTH_RADIUS)
|
||||||
|
smoothed_weight = gaussian_blur(value_weight, HEATMAP_SMOOTH_RADIUS)
|
||||||
|
smoothed_value = np.zeros_like(value_sum)
|
||||||
|
np.divide(smoothed_sum, smoothed_weight, out=smoothed_value, where=smoothed_weight > 0)
|
||||||
|
smoothed_value = np.clip(smoothed_value, HEATMAP_BAD_RSRP, HEATMAP_GOOD_RSRP)
|
||||||
|
image[data_mask, :3] = heatmap_rgb_for_values(smoothed_value)[data_mask]
|
||||||
|
image[data_mask, 3] = 255
|
||||||
|
|
||||||
|
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,
|
||||||
|
"data_pixels": int(np.count_nonzero(data_mask)),
|
||||||
|
"skipped_no_value": skipped_no_value,
|
||||||
|
"smooth_radius": HEATMAP_SMOOTH_RADIUS,
|
||||||
|
"width": width,
|
||||||
|
"height": height,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def sqlite_create_sql(conn, name):
|
def sqlite_create_sql(conn, name):
|
||||||
row = conn.execute(
|
row = conn.execute(
|
||||||
"select sql from sqlite_master where type = 'table' and name = ?",
|
"select sql from sqlite_master where type = 'table' and name = ?",
|
||||||
@@ -588,6 +760,18 @@ def write_legend(output_dir, field):
|
|||||||
return legend_path
|
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:
|
||||||
|
writer = csv.writer(file)
|
||||||
|
writer.writerow(["field", "rsrp", "red", "green", "blue", "alpha", "meaning"])
|
||||||
|
writer.writerow([field, HEATMAP_GOOD_RSRP, 26, 152, 80, 255, "good signal"])
|
||||||
|
writer.writerow([field, HEATMAP_MID_RSRP, 255, 255, 191, 255, "middle signal"])
|
||||||
|
writer.writerow([field, HEATMAP_BAD_RSRP, 215, 48, 39, 255, "bad signal"])
|
||||||
|
writer.writerow([field, "nodata", 0, 0, 0, 0, "transparent no data"])
|
||||||
|
return legend_path
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
if SCALE <= 0:
|
if SCALE <= 0:
|
||||||
raise ValueError("SCALE 必须大于 0")
|
raise ValueError("SCALE 必须大于 0")
|
||||||
@@ -629,7 +813,9 @@ def main():
|
|||||||
markets = markets[:LIMIT]
|
markets = markets[:LIMIT]
|
||||||
|
|
||||||
legend_path = write_legend(OUTPUT_DIR, RSRP_FIELD)
|
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 = []
|
tif_results = []
|
||||||
|
heatmap_results = []
|
||||||
build_results = []
|
build_results = []
|
||||||
print(f"市场网格数量:{len(markets)}")
|
print(f"市场网格数量:{len(markets)}")
|
||||||
print(f"Grid 图层:{grid_layer.table_name}")
|
print(f"Grid 图层:{grid_layer.table_name}")
|
||||||
@@ -638,6 +824,8 @@ def main():
|
|||||||
print(f"分辨率倍数:{SCALE}")
|
print(f"分辨率倍数:{SCALE}")
|
||||||
print(f"像元大小:{pixel_width}, {pixel_height}")
|
print(f"像元大小:{pixel_width}, {pixel_height}")
|
||||||
print(f"图例:{legend_path}")
|
print(f"图例:{legend_path}")
|
||||||
|
if heatmap_legend_path:
|
||||||
|
print(f"热力图图例:{heatmap_legend_path}")
|
||||||
|
|
||||||
for index, market in enumerate(markets, start=1):
|
for index, market in enumerate(markets, start=1):
|
||||||
market_dir = market_output_dir(OUTPUT_DIR, market)
|
market_dir = market_output_dir(OUTPUT_DIR, market)
|
||||||
@@ -672,6 +860,40 @@ def main():
|
|||||||
tif_results.append(result)
|
tif_results.append(result)
|
||||||
print(f" 像素:{result['width']}x{result['height']},已着色:{result['painted_pixels']}")
|
print(f" 像素:{result['width']}x{result['height']},已着色:{result['painted_pixels']}")
|
||||||
|
|
||||||
|
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)
|
build_path = build_output_path(OUTPUT_DIR, market)
|
||||||
print(f" 拆分 Build:{build_path.name}")
|
print(f" 拆分 Build:{build_path.name}")
|
||||||
build_result = export_market_build_gpkg(
|
build_result = export_market_build_gpkg(
|
||||||
@@ -696,6 +918,7 @@ def main():
|
|||||||
"pixel_width": pixel_width,
|
"pixel_width": pixel_width,
|
||||||
"pixel_height": pixel_height,
|
"pixel_height": pixel_height,
|
||||||
"tif_results": tif_results,
|
"tif_results": tif_results,
|
||||||
|
"heatmap_results": heatmap_results,
|
||||||
"build_results": build_results,
|
"build_results": build_results,
|
||||||
}
|
}
|
||||||
summary_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
|
summary_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||||
|
|||||||
Reference in New Issue
Block a user