Files
MarketGrid/marketgrid/pipeline.py
T

282 lines
13 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""完整出图流程与并行调度。"""
from concurrent.futures import ProcessPoolExecutor, as_completed
from time import perf_counter
import json
from . import config
from .gpkg import estimate_pixel_size
from .gpkg import load_market_features
from .gpkg import open_read_connection
from .gpkg import require_columns
from .gpkg import resolve_feature_layer
from .gpkg import rtree_name
from .legends import write_competitor_signal_legend
from .jobs import process_market, process_summary_grid_outputs
def main(settings=None, progress=None):
if settings:
config.apply_settings(settings)
config.check_cancelled()
if config.SCALE <= 0:
raise ValueError("SCALE 必须大于 0")
if config.MAX_WORKERS <= 0:
raise ValueError("MAX_WORKERS 必须大于 0")
if config.GEOMETRY_BATCH_SIZE <= 0:
raise ValueError("GEOMETRY_BATCH_SIZE 必须大于 0")
if config.PROJECT_EXTENT_PADDING_RATIO < 0:
raise ValueError("PROJECT_EXTENT_PADDING_RATIO 不能小于 0")
# validate_smoothing_radius("HEATMAP_SMOOTH_RADIUS", HEATMAP_SMOOTH_RADIUS)
if not 0 <= config.COMPETITOR_SIGNAL_MOBILE_WEAK_RATIO_MAX <= 100:
raise ValueError("COMPETITOR_SIGNAL_MOBILE_WEAK_RATIO_MAX 必须在 0 到 100 之间")
if not 0 <= config.COMPETITOR_SIGNAL_WEAK_RATIO_MIN <= 100:
raise ValueError("COMPETITOR_SIGNAL_WEAK_RATIO_MIN 必须在 0 到 100 之间")
if len(config.COMPETITOR_SIGNAL_RSRP_COLORS) != len(config.COMPETITOR_SIGNAL_RSRP_BREAKS) + 1:
raise ValueError("竟对信号 RSRP 颜色数量必须比分界点数量多 1")
if any(
left >= right
for left, right in zip(
config.COMPETITOR_SIGNAL_RSRP_BREAKS,
config.COMPETITOR_SIGNAL_RSRP_BREAKS[1:],
)
):
raise ValueError("COMPETITOR_SIGNAL_RSRP_BREAKS 必须严格递增")
if config.MAX_RASTER_PIXELS is not None and config.MAX_RASTER_PIXELS <= 0:
raise ValueError("MAX_RASTER_PIXELS 必须大于 0 或设置为 None")
if config.SUMMARY_MAX_RASTER_PIXELS is None or config.SUMMARY_MAX_RASTER_PIXELS <= 0:
raise ValueError("SUMMARY_MAX_RASTER_PIXELS 必须大于 0")
if config.CLIP_MODE not in {"intersects", "center"}:
raise ValueError("CLIP_MODE 必须是 intersects 或 center")
required_files = (
config.MARKET_GPKG,
config.GRID_5G_GPKG,
# GRID_4G_GPKG,
config.BUILDING_INFO_GPKG,
config.NR_BUILDINGS_DATA_GPKG,
config.GIS_PROJECT_SOURCE,
config.AOI_GPKG,
)
missing_files = [str(path) for path in required_files if not path.is_file()]
if missing_files:
raise FileNotFoundError(f"缺少输入文件:{', '.join(missing_files)}")
config.OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
with (
open_read_connection(config.MARKET_GPKG) as market_conn,
open_read_connection(config.GRID_5G_GPKG) as grid_5g_conn,
# open_read_connection(GRID_4G_GPKG) as grid_4g_conn,
open_read_connection(config.BUILDING_INFO_GPKG) as building_info_conn,
):
market_layer = resolve_feature_layer(market_conn, config.MARKET_LAYER)
grid_5g_layer = resolve_feature_layer(grid_5g_conn, config.GRID_5G_LAYER)
# grid_4g_layer = resolve_feature_layer(grid_4g_conn, GRID_4G_LAYER)
building_info_layer = resolve_feature_layer(building_info_conn, config.BUILDING_INFO_LAYER)
if (
market_layer.srs_id != 4326
or grid_5g_layer.srs_id != 4326
# or grid_4g_layer.srs_id != 4326
):
raise ValueError("当前脚本只处理 EPSG:4326 的输入图层")
if building_info_layer.srs_id not in config.BUILDING_INFO_ALLOWED_SRS_IDS:
raise ValueError(f"BuildingInfo 图层坐标系不在允许范围内:{building_info_layer.srs_id}")
require_columns(
grid_5g_conn,
grid_5g_layer.table_name,
# (*CSV_SOURCE_FIELDS, MOBILE_TOTAL_FIELD, MOBILE_WEAK_COVER_FIELD, GRID_ID_FIELD),
(*config.CSV_SOURCE_FIELDS, config.MOBILE_TOTAL_FIELD, config.MOBILE_WEAK_COVER_FIELD),
)
# grid_4g_required_fields = [GRID_ID_FIELD, EXCELLENT_CELL_FIELD]
# if CLIP_MODE == "center":
# grid_4g_required_fields.extend(("longitude", "latitude"))
# require_columns(grid_4g_conn, grid_4g_layer.table_name, grid_4g_required_fields)
require_columns(building_info_conn, building_info_layer.table_name, ["name"])
rtree_name(grid_5g_conn, grid_5g_layer)
# rtree_name(grid_4g_conn, grid_4g_layer)
rtree_name(building_info_conn, building_info_layer)
pixel_width = config.PIXEL_WIDTH
pixel_height = config.PIXEL_HEIGHT
if pixel_width is None or pixel_height is None:
estimated_width, estimated_height = estimate_pixel_size(
grid_5g_conn,
grid_5g_layer,
config.SAMPLE_SIZE,
)
pixel_width = pixel_width or estimated_width
pixel_height = pixel_height or estimated_height
pixel_width = pixel_width / config.SCALE
pixel_height = pixel_height / config.SCALE
markets = load_market_features(
market_conn,
market_layer,
config.MARKET_CODE_FIELD,
config.MARKET_NAME_FIELD,
)
if config.SELECTED_MARKET_IDS is not None:
selected = set(config.SELECTED_MARKET_IDS)
markets = [market for market in markets if market.fid in selected]
if not markets:
raise ValueError("没有可处理的市场网格,请检查市场选择和输入几何。")
if config.LIMIT:
markets = markets[:config.LIMIT]
layer_names = {
"grid_5g": grid_5g_layer.table_name,
# "grid_4g": grid_4g_layer.table_name,
"building_info": building_info_layer.table_name,
}
# excellent_legend_path = write_excellent_heatmap_legend(OUTPUT_DIR, EXCELLENT_CELL_FIELD)
competitor_signal_legend_path = write_competitor_signal_legend(config.OUTPUT_DIR)
worker_count = max(1, min(config.MAX_WORKERS, len(markets))) if markets else 1
print(f"市场网格数量:{len(markets)}")
print(f"并行进程数:{worker_count}")
print(f"5G Grid 图层:{layer_names['grid_5g']}")
# print(f"4G Grid 图层:{layer_names['grid_4g']}")
print(f"BuildingInfo 图层:{layer_names['building_info']}")
print(f"像元大小:{pixel_width}, {pixel_height}")
# print(f"用户量图例:{excellent_legend_path}")
print(f"竟对信号图例:{competitor_signal_legend_path}")
started_at = perf_counter()
outcomes = []
total_steps = len(markets) + int(config.SUMMARY_OUTPUT_ENABLED)
if progress:
progress(0, total_steps, "开始处理市场网格")
if worker_count == 1:
for index, market in enumerate(markets, start=1):
outcome = process_market(market, pixel_width, pixel_height, config.OUTPUT_DIR)
outcomes.append(outcome)
if progress:
progress(index, total_steps, f"已完成 {market.name}")
config.check_cancelled()
scale_factor = outcome.get("competitor_signal_result", {}).get("resolution_scale_factor", 1.0)
resolution_note = f",分辨率自动调整 x{scale_factor:.2f}" if scale_factor > 1.001 else ""
print(
f"[{index}/{len(markets)}] 完成 {market.code},"
f"耗时 {outcome['elapsed_seconds']:.1f} 秒{resolution_note}"
)
else:
with ProcessPoolExecutor(max_workers=worker_count, initializer=config.apply_settings,
initargs=(config.snapshot(),)) as executor:
future_markets = {
executor.submit(process_market, market, pixel_width, pixel_height, config.OUTPUT_DIR): market
for market in markets
}
completed = 0
for future in as_completed(future_markets):
market = future_markets[future]
try:
outcome = future.result()
except config.TaskCancelled:
for pending in future_markets:
pending.cancel()
raise
except Exception as error:
raise RuntimeError(f"市场网格处理失败:{market.code}") from error
outcomes.append(outcome)
completed += 1
if progress:
progress(completed, total_steps, f"已完成 {market.name}")
config.check_cancelled()
scale_factor = outcome.get("competitor_signal_result", {}).get("resolution_scale_factor", 1.0)
resolution_note = f",分辨率自动调整 x{scale_factor:.2f}" if scale_factor > 1.001 else ""
print(
f"[{completed}/{len(markets)}] 完成 {market.code},"
f"耗时 {outcome['elapsed_seconds']:.1f} 秒{resolution_note}"
)
outcomes.sort(key=lambda item: item["market_fid"])
summary_grid_result = None
if config.SUMMARY_OUTPUT_ENABLED and markets:
config.check_cancelled()
if progress:
progress(len(markets), total_steps, "正在生成全量汇总包")
print("开始生成全部市场网格汇总 TIF……")
# market_user_thresholds = {
# outcome["market_code"]: outcome["excellent_heatmap_result"].get("thresholds")
# for outcome in outcomes
# if outcome.get("excellent_heatmap_result")
# }
summary_grid_result = process_summary_grid_outputs(
markets,
pixel_width,
pixel_height,
config.OUTPUT_DIR,
# market_user_thresholds,
)
print(
f"汇总 TIF 完成:{summary_grid_result['zip_result']['output']},"
f"耗时 {summary_grid_result['elapsed_seconds']:.1f} 秒"
)
result_mappings = {
# "excellent_heatmap_results": "excellent_heatmap_result",
"competitor_signal_results": "competitor_signal_result",
"building_info_results": "building_info_result",
"aoi_results": "aoi_result",
"gis_project_results": "gis_project_result",
"zip_results": "zip_result",
}
summary = {
"market_gpkg": str(config.MARKET_GPKG),
"grid_5g_gpkg": str(config.GRID_5G_GPKG),
# "grid_4g_gpkg": str(GRID_4G_GPKG),
# "user_count_grid_id_field": GRID_ID_FIELD,
# "user_count_merge_rule": "Grid_5G + Grid_4G union by grid20_id and sum mro_total_dl",
"building_info_gpkg": str(config.BUILDING_INFO_GPKG),
"aoi_gpkg": str(config.AOI_GPKG),
"aoi_match_field": config.AOI_MARKET_FIELD,
"gis_project_source": str(config.GIS_PROJECT_SOURCE),
"rsrp_field": config.RSRP_FIELD,
"excellent_cell_field": config.EXCELLENT_CELL_FIELD,
"weak_cover_field": config.WEAK_COVER_FIELD,
"mobile_total_field": config.MOBILE_TOTAL_FIELD,
"mobile_weak_cover_field": config.MOBILE_WEAK_COVER_FIELD,
"competitor_signal_mobile_weak_ratio_formula": (
f"{config.MOBILE_WEAK_COVER_FIELD} / {config.MOBILE_TOTAL_FIELD} * 100"
),
"competitor_signal_mobile_weak_ratio_rule": (
f"< {config.COMPETITOR_SIGNAL_MOBILE_WEAK_RATIO_MAX}"
),
"competitor_signal_eligibility_rule": (
f"{config.EXCELLENT_CELL_FIELD} = 0 or "
f"{config.WEAK_COVER_FIELD} / {config.EXCELLENT_CELL_FIELD} * 100 "
f"> {config.COMPETITOR_SIGNAL_WEAK_RATIO_MIN}"
),
"competitor_signal_zero_total_color": list(config.COMPETITOR_SIGNAL_RSRP_COLORS[0]),
"clip_mode": config.CLIP_MODE,
"scale": config.SCALE,
"pixel_width": pixel_width,
"pixel_height": pixel_height,
"max_workers": worker_count,
"summary_output_enabled": config.SUMMARY_OUTPUT_ENABLED,
"total_elapsed_seconds": perf_counter() - started_at,
"market_timings": [
{
"market_code": outcome["market_code"],
"elapsed_seconds": outcome["elapsed_seconds"],
**outcome.get("timings", {}),
}
for outcome in outcomes
],
}
for summary_key, outcome_key in result_mappings.items():
summary[summary_key] = [outcome[outcome_key] for outcome in outcomes if outcome_key in outcome]
summary["summary_grid_result"] = summary_grid_result
summary_path = config.OUTPUT_DIR / "summary.json"
temp_summary_path = summary_path.with_name(f".{summary_path.name}.tmp")
try:
temp_summary_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
temp_summary_path.replace(summary_path)
except Exception:
if temp_summary_path.exists():
temp_summary_path.unlink()
raise
print(f"总耗时:{summary['total_elapsed_seconds']:.1f} 秒")
print(f"汇总:{summary_path}")
if progress:
progress(total_steps, total_steps, "成果生成完成")
return summary