feat: 新增弱覆盖占比专题图

This commit is contained in:
RBP15P
2026-07-19 13:26:49 +08:00
parent 1e0b655f04
commit 7233021b16
4 changed files with 255 additions and 11 deletions
+197 -7
View File
@@ -11,7 +11,7 @@ from concurrent.futures import ProcessPoolExecutor, as_completed
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
from time import perf_counter
from time import perf_counter, sleep
import numpy as np
import shapely
@@ -55,8 +55,16 @@ HEATMAP_ALPHA = 191 # 热力图有效像元透明度;191 约等于 75% 不透
PROJECT_EXTENT_PADDING_RATIO = 0.05 # QGIS 打开后的画布留白比例;0.05 表示在 BuildingInfo 范围四周各增加 5%。
USER_COUNT_OUTPUT_FILENAME = "用户量.tif" # 采样点数量热力图输出文件名。
WEAK_COVER_OUTPUT_FILENAME = "信号差用户量.tif" # 信号差用户量热力图输出文件名。
WEAK_COVER_RATIO_OUTPUT_FILENAME = "弱覆盖占比.tif" # 弱覆盖采样点占总采样点比例的分级 TIF 输出文件名。
WEAK_COVER_RATIO_GREEN_MAX = 5.0 # 弱覆盖占比小于等于该百分比时使用绿色。
WEAK_COVER_RATIO_YELLOW_MIN = 10.0 # 弱覆盖占比大于等于该百分比时由蓝色进入黄色。
WEAK_COVER_RATIO_RED_MIN = 20.0 # 弱覆盖占比大于等于该百分比时使用红色。
WEAK_COVER_RATIO_GREEN = (0, 176, 80) # 弱覆盖占比低值档颜色。
WEAK_COVER_RATIO_BLUE = (0, 112, 255) # 弱覆盖占比偏低档颜色。
WEAK_COVER_RATIO_YELLOW = (255, 255, 0) # 弱覆盖占比偏高档颜色。
WEAK_COVER_RATIO_RED = (255, 0, 0) # 弱覆盖占比高值档颜色。
SUMMARY_OUTPUT_ENABLED = True # 是否额外生成全部市场网格汇总 TIF 结果包。
SUMMARY_OUTPUT_FILENAME = "所有网格汇总.zip" # 汇总结果包文件名,包内只包含三张 TIF。
SUMMARY_OUTPUT_FILENAME = "所有网格汇总.zip" # 汇总结果包文件名,包含四张 TIF、GIS.qgz 和完整 BuildingInfo.gpkg。
SUMMARY_MARKET_CODE = "所有网格汇总" # 汇总任务在日志和 summary.json 中使用的标识。
SUMMARY_MAX_RASTER_PIXELS = 100_000_000 # 汇总 TIF 最大像元数;提高该值可增强清晰度,但会增加内存、耗时和文件体积。
EXCELLENT_PERCENT_STEPS = (0.25, 0.5, 0.75) # 按最终有效像元降序四等分,取 25%、50%、75% 位置作为结果记录阈值。
@@ -142,6 +150,10 @@ def weak_cover_heatmap_raster_filename(_field):
return WEAK_COVER_OUTPUT_FILENAME
def weak_cover_ratio_raster_filename():
return WEAK_COVER_RATIO_OUTPUT_FILENAME
def set_xml_extent(extent_element, extent):
for tag, value in zip(("xmin", "ymin", "xmax", "ymax"), extent):
child = extent_element.find(tag)
@@ -219,6 +231,22 @@ def copy_gis_project_to_market(source_path, output_path, market, building_extent
if layer_extent_element is None:
layer_extent_element = ET.SubElement(building_layer, "extent")
set_xml_extent(layer_extent_element, layer_extent)
raster_filenames = {
SIGNAL_OUTPUT_FILENAME,
USER_COUNT_OUTPUT_FILENAME,
WEAK_COVER_OUTPUT_FILENAME,
WEAK_COVER_RATIO_OUTPUT_FILENAME,
}
for layer in root.findall(".//projectlayers/maplayer"):
datasource = (layer.findtext("datasource") or "").replace("\\", "/")
if Path(datasource).name not in raster_filenames:
continue
for extent_tag in ("extent", "wgs84extent"):
raster_extent = layer.find(extent_tag)
if raster_extent is None:
raster_extent = ET.SubElement(layer, extent_tag)
set_xml_extent(raster_extent, market.geometry.bounds)
data = serialize_qgis_project(root, data)
target_zip.writestr(info, data)
temp_output_path.replace(output_path)
@@ -280,7 +308,7 @@ def write_market_zip(workspace_dir, zip_path, market):
with zipfile.ZipFile(temp_zip_path, "w", compression=zipfile.ZIP_DEFLATED) as zip_file:
for path in entries:
zip_file.write(path, path.relative_to(workspace_dir).as_posix())
temp_zip_path.replace(zip_path)
replace_file_with_retry(temp_zip_path, zip_path)
except Exception:
if temp_zip_path.exists():
temp_zip_path.unlink()
@@ -894,6 +922,16 @@ def heatmap_rgb_for_values(values):
return continuous_heatmap_rgb_for_scores(scores)
def weak_cover_ratio_rgb_for_values(values):
values = np.asarray(values, dtype=np.float32)
colors = np.empty((*values.shape, 3), dtype=np.uint8)
colors[:] = WEAK_COVER_RATIO_GREEN
colors[(values > WEAK_COVER_RATIO_GREEN_MAX) & (values < WEAK_COVER_RATIO_YELLOW_MIN)] = WEAK_COVER_RATIO_BLUE
colors[(values >= WEAK_COVER_RATIO_YELLOW_MIN) & (values < WEAK_COVER_RATIO_RED_MIN)] = WEAK_COVER_RATIO_YELLOW
colors[values >= WEAK_COVER_RATIO_RED_MIN] = WEAK_COVER_RATIO_RED
return colors
def percentile_scores_for_values(values, data_mask, anchor_scores=(0.0, 0.5, 1.0)):
scores = np.zeros(values.shape, dtype=np.float32)
valid_values = values[data_mask]
@@ -1132,6 +1170,17 @@ def render_signal_raster(state, market, output_path, minx, maxy, pixel_width, pi
}
def replace_file_with_retry(source_path, target_path, attempts=20, delay_seconds=0.5):
for attempt in range(attempts):
try:
source_path.replace(target_path)
return
except PermissionError:
if attempt == attempts - 1:
raise
sleep(delay_seconds)
def render_percentile_heatmap_raster(
state,
market,
@@ -1179,6 +1228,46 @@ def render_percentile_heatmap_raster(
}
def render_weak_cover_ratio_raster(
state,
market,
output_path,
minx,
maxy,
pixel_width,
pixel_height,
width,
height,
candidates,
):
image = np.full((height, width, 4), TRANSPARENT_PIXEL, dtype=np.uint8)
smoothed_value, data_mask = smooth_weighted_values(state["value_sum"], state["value_weight"])
if np.any(data_mask):
image[data_mask, :3] = weak_cover_ratio_rgb_for_values(smoothed_value)[data_mask]
image[data_mask, 3] = HEATMAP_ALPHA
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": state["painted_cells"],
"data_pixels": int(np.count_nonzero(data_mask)),
"skipped_no_value": state["skipped_no_value"],
"color_mode": "fixed_weak_cover_ratio_classes",
"percentage_thresholds": {
"green_max": WEAK_COVER_RATIO_GREEN_MAX,
"yellow_min": WEAK_COVER_RATIO_YELLOW_MIN,
"red_min": WEAK_COVER_RATIO_RED_MIN,
},
"smooth_radius": HEATMAP_SMOOTH_RADIUS,
"width": width,
"height": height,
"skipped": False,
}
def render_ranked_raster(
state,
market,
@@ -1241,6 +1330,7 @@ def export_market_grid_outputs(
signal_path,
user_count_path,
weak_cover_path,
weak_cover_ratio_path,
csv_path,
max_raster_pixels=None,
):
@@ -1399,7 +1489,43 @@ def export_market_grid_outputs(
candidates,
)
del weak_cover_state
for result in (signal_result, user_count_result, weak_cover_result):
ratio_value_sum = np.zeros((height, width), dtype=np.float32)
ratio_value_weight = np.zeros((height, width), dtype=np.uint16)
ratio_painted_cells = 0
ratio_skipped_no_value = 0
for cell in raster_cells:
row_start, row_stop, col_start, col_stop = cell[:4]
total = cell[5]
weak_cover = cell[6]
if total is None or total <= 0 or weak_cover is None or weak_cover < 0:
ratio_skipped_no_value += 1
continue
ratio = weak_cover / total * 100.0
ratio_value_sum[row_start:row_stop, col_start:col_stop] += ratio
ratio_value_weight[row_start:row_stop, col_start:col_stop] += 1
ratio_painted_cells += 1
ratio_state = {
"value_sum": ratio_value_sum,
"value_weight": ratio_value_weight,
"painted_cells": ratio_painted_cells,
"skipped_no_value": ratio_skipped_no_value,
}
weak_cover_ratio_result = render_weak_cover_ratio_raster(
ratio_state,
market,
weak_cover_ratio_path,
minx,
maxy,
pixel_width,
pixel_height,
width,
height,
candidates,
)
del ratio_state, ratio_value_sum, ratio_value_weight
for result in (signal_result, user_count_result, weak_cover_result, weak_cover_ratio_result):
result["pixel_width"] = pixel_width
result["pixel_height"] = pixel_height
result["resolution_scale_factor"] = scale_factor
@@ -1413,7 +1539,7 @@ def export_market_grid_outputs(
"row_count": csv_rows,
"skipped": csv_skipped,
}
return signal_result, user_count_result, weak_cover_result, csv_result
return signal_result, user_count_result, weak_cover_result, weak_cover_ratio_result, csv_result
def write_heatmap_legend(output_dir, field):
@@ -1452,6 +1578,20 @@ def write_weak_cover_heatmap_legend(output_dir, field):
return legend_path
def write_weak_cover_ratio_legend(output_dir):
legend_path = output_dir / "weak_cover_ratio_legend.csv"
with legend_path.open("w", newline="", encoding="utf-8-sig") as file:
writer = csv.writer(file)
writer.writerow(["formula", "percentage_range", "red", "green", "blue", "alpha", "meaning"])
formula = f"{WEAK_COVER_FIELD} / {EXCELLENT_CELL_FIELD} * 100"
writer.writerow([formula, f">= {WEAK_COVER_RATIO_RED_MIN}%", *WEAK_COVER_RATIO_RED, HEATMAP_ALPHA, "high weak-cover ratio"])
writer.writerow([formula, f">= {WEAK_COVER_RATIO_YELLOW_MIN}% and < {WEAK_COVER_RATIO_RED_MIN}%", *WEAK_COVER_RATIO_YELLOW, HEATMAP_ALPHA, "medium-high weak-cover ratio"])
writer.writerow([formula, f"> {WEAK_COVER_RATIO_GREEN_MAX}% and < {WEAK_COVER_RATIO_YELLOW_MIN}%", *WEAK_COVER_RATIO_BLUE, HEATMAP_ALPHA, "medium-low weak-cover ratio"])
writer.writerow([formula, f"<= {WEAK_COVER_RATIO_GREEN_MAX}%", *WEAK_COVER_RATIO_GREEN, HEATMAP_ALPHA, "low weak-cover ratio"])
writer.writerow([formula, "no valid total", 0, 0, 0, 0, "transparent no data"])
return legend_path
@contextmanager
def open_read_connection(path):
conn = sqlite3.connect(path)
@@ -1463,6 +1603,20 @@ def open_read_connection(path):
conn.close()
def gpkg_layer_extent(conn, layer):
row = conn.execute(
"select min_x, min_y, max_x, max_y from gpkg_contents where table_name = ?",
(layer.table_name,),
).fetchone()
if row and all(value is not None for value in row):
return tuple(float(value) for value in row)
rtree = rtree_name(conn, layer)
row = conn.execute(
f"select min(minx), min(miny), max(maxx), max(maxy) from {quote_identifier(rtree)}"
).fetchone()
return tuple(float(value) for value in row) if row and all(value is not None for value in row) else None
def process_market(market, pixel_width, pixel_height, output_dir):
started_at = perf_counter()
output_dir = Path(output_dir)
@@ -1501,9 +1655,10 @@ def process_market(market, pixel_width, pixel_height, output_dir):
signal_path = market_dir / heatmap_raster_filename(RSRP_FIELD)
user_count_path = market_dir / excellent_heatmap_raster_filename(EXCELLENT_CELL_FIELD)
weak_cover_path = market_dir / weak_cover_heatmap_raster_filename(WEAK_COVER_FIELD)
weak_cover_ratio_path = market_dir / weak_cover_ratio_raster_filename()
grid_metrics_path = market_dir / GRID_METRICS_CSV_FILENAME
grid_started_at = perf_counter()
signal_result, user_count_result, weak_cover_result, grid_metrics_result = export_market_grid_outputs(
signal_result, user_count_result, weak_cover_result, weak_cover_ratio_result, grid_metrics_result = export_market_grid_outputs(
grid_conn,
grid_layer,
grid_rtree,
@@ -1513,6 +1668,7 @@ def process_market(market, pixel_width, pixel_height, output_dir):
signal_path,
user_count_path,
weak_cover_path,
weak_cover_ratio_path,
grid_metrics_path,
)
grid_elapsed = perf_counter() - grid_started_at
@@ -1557,6 +1713,7 @@ def process_market(market, pixel_width, pixel_height, output_dir):
"heatmap_result": rewrite_result_for_zip(signal_result, zip_path, market_dir),
"excellent_heatmap_result": rewrite_result_for_zip(user_count_result, zip_path, market_dir),
"weak_cover_heatmap_result": rewrite_result_for_zip(weak_cover_result, zip_path, market_dir),
"weak_cover_ratio_result": rewrite_result_for_zip(weak_cover_ratio_result, zip_path, market_dir),
"building_info_result": rewrite_result_for_zip(building_info_result, zip_path, market_dir),
"building_metrics_csv_result": rewrite_result_for_zip(building_metrics_result, zip_path, market_dir),
"grid_metrics_csv_result": rewrite_result_for_zip(grid_metrics_result, zip_path, market_dir),
@@ -1597,7 +1754,8 @@ def process_summary_grid_outputs(markets, pixel_width, pixel_height, output_dir)
signal_path = summary_dir / heatmap_raster_filename(RSRP_FIELD)
user_count_path = summary_dir / excellent_heatmap_raster_filename(EXCELLENT_CELL_FIELD)
weak_cover_path = summary_dir / weak_cover_heatmap_raster_filename(WEAK_COVER_FIELD)
signal_result, user_count_result, weak_cover_result, _ = export_market_grid_outputs(
weak_cover_ratio_path = summary_dir / weak_cover_ratio_raster_filename()
signal_result, user_count_result, weak_cover_result, weak_cover_ratio_result, _ = export_market_grid_outputs(
grid_conn,
grid_layer,
grid_rtree,
@@ -1607,15 +1765,41 @@ def process_summary_grid_outputs(markets, pixel_width, pixel_height, output_dir)
signal_path,
user_count_path,
weak_cover_path,
weak_cover_ratio_path,
None,
SUMMARY_MAX_RASTER_PIXELS,
)
building_info_path = summary_dir / BUILDING_INFO_OUTPUT_FILENAME
shutil.copy2(BUILDING_INFO_GPKG, building_info_path)
with open_read_connection(BUILDING_INFO_GPKG) as building_info_conn:
building_info_layer = resolve_feature_layer(building_info_conn, BUILDING_INFO_LAYER)
building_info_extent = gpkg_layer_extent(building_info_conn, building_info_layer)
building_info_result = {
"market_code": summary_market.code,
"market_name": summary_market.name,
"source": str(BUILDING_INFO_GPKG),
"output": str(building_info_path),
"extent": list(building_info_extent) if building_info_extent else None,
"bytes": building_info_path.stat().st_size,
"copied_full_source": True,
"skipped": False,
}
gis_project_path = summary_dir / GIS_PROJECT_OUTPUT_FILENAME
gis_project_result = copy_gis_project_to_market(
GIS_PROJECT_SOURCE,
gis_project_path,
summary_market,
building_info_extent,
)
zip_result = write_market_zip(summary_dir, zip_path, summary_market)
return {
"market_code": summary_market.code,
"heatmap_result": rewrite_result_for_zip(signal_result, zip_path, summary_dir),
"excellent_heatmap_result": rewrite_result_for_zip(user_count_result, zip_path, summary_dir),
"weak_cover_heatmap_result": rewrite_result_for_zip(weak_cover_result, zip_path, summary_dir),
"weak_cover_ratio_result": rewrite_result_for_zip(weak_cover_ratio_result, zip_path, summary_dir),
"building_info_result": rewrite_result_for_zip(building_info_result, zip_path, summary_dir),
"gis_project_result": rewrite_result_for_zip(gis_project_result, zip_path, summary_dir),
"zip_result": zip_result,
"elapsed_seconds": perf_counter() - started_at,
}
@@ -1634,6 +1818,8 @@ def main():
raise ValueError("RSRP 热力图阈值必须满足 HEATMAP_BAD_RSRP < HEATMAP_MID_RSRP < HEATMAP_GOOD_RSRP")
if not 0 < WEAK_COVER_YELLOW_PERCENTILE < 1:
raise ValueError("WEAK_COVER_YELLOW_PERCENTILE 必须大于 0 且小于 1")
if not 0 <= WEAK_COVER_RATIO_GREEN_MAX < WEAK_COVER_RATIO_YELLOW_MIN < WEAK_COVER_RATIO_RED_MIN:
raise ValueError("弱覆盖占比阈值必须满足 0 <= GREEN_MAX < YELLOW_MIN < RED_MIN")
if MAX_RASTER_PIXELS is not None and MAX_RASTER_PIXELS <= 0:
raise ValueError("MAX_RASTER_PIXELS 必须大于 0 或设置为 None")
if SUMMARY_MAX_RASTER_PIXELS is None or SUMMARY_MAX_RASTER_PIXELS <= 0:
@@ -1698,6 +1884,7 @@ def main():
heatmap_legend_path = write_heatmap_legend(OUTPUT_DIR, RSRP_FIELD)
excellent_legend_path = write_excellent_heatmap_legend(OUTPUT_DIR, EXCELLENT_CELL_FIELD)
weak_cover_legend_path = write_weak_cover_heatmap_legend(OUTPUT_DIR, WEAK_COVER_FIELD)
weak_cover_ratio_legend_path = write_weak_cover_ratio_legend(OUTPUT_DIR)
worker_count = max(1, min(MAX_WORKERS, len(markets))) if markets else 1
print(f"市场网格数量:{len(markets)}")
print(f"并行进程数:{worker_count}")
@@ -1708,6 +1895,7 @@ def main():
print(f"热力图图例:{heatmap_legend_path}")
print(f"用户量图例:{excellent_legend_path}")
print(f"信号差用户量图例:{weak_cover_legend_path}")
print(f"弱覆盖占比图例:{weak_cover_ratio_legend_path}")
started_at = perf_counter()
outcomes = []
@@ -1756,6 +1944,7 @@ def main():
"heatmap_results": "heatmap_result",
"excellent_heatmap_results": "excellent_heatmap_result",
"weak_cover_heatmap_results": "weak_cover_heatmap_result",
"weak_cover_ratio_results": "weak_cover_ratio_result",
"building_info_results": "building_info_result",
"building_metrics_csv_results": "building_metrics_csv_result",
"grid_metrics_csv_results": "grid_metrics_csv_result",
@@ -1771,6 +1960,7 @@ def main():
"rsrp_field": RSRP_FIELD,
"excellent_cell_field": EXCELLENT_CELL_FIELD,
"weak_cover_field": WEAK_COVER_FIELD,
"weak_cover_ratio_formula": f"{WEAK_COVER_FIELD} / {EXCELLENT_CELL_FIELD} * 100",
"clip_mode": CLIP_MODE,
"scale": SCALE,
"pixel_width": pixel_width,