300 lines
14 KiB
Python
300 lines
14 KiB
Python
"""完整出图流程与并行调度。"""
|
||
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
|
||
from .output_layers import active_plan, enabled
|
||
|
||
|
||
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")
|
||
plan = active_plan()
|
||
need_5g = enabled(plan, "competitor") or enabled(plan, "sample")
|
||
need_info = enabled(plan, "buildinfo") or enabled(plan, "building")
|
||
if enabled(plan, "aoi") and config.AOI_CSV:
|
||
from .aoi_match import build_matched_aoi
|
||
print("正在按最大接触面积匹配 AOI……")
|
||
aoi_match = build_matched_aoi(config.AOI_CSV, config.MARKET_GPKG, config.AOI_GPKG)
|
||
print(
|
||
f"AOI 匹配完成:{aoi_match['matched']} 条已归属,"
|
||
f"{aoi_match['unassigned']} 条未纳入,输出 {aoi_match['output']}"
|
||
)
|
||
required_files = [config.MARKET_GPKG, config.GIS_PROJECT_SOURCE]
|
||
if need_5g:
|
||
required_files.append(config.GRID_5G_GPKG)
|
||
if enabled(plan, "sample"):
|
||
required_files.append(config.GRID_4G_GPKG)
|
||
if need_info:
|
||
required_files.append(config.BUILDING_INFO_GPKG)
|
||
if enabled(plan, "building"):
|
||
required_files.append(config.NR_BUILDINGS_DATA_GPKG)
|
||
if enabled(plan, "aoi"):
|
||
required_files.append(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:
|
||
market_layer = resolve_feature_layer(market_conn, config.MARKET_LAYER)
|
||
if market_layer.srs_id != 4326:
|
||
raise ValueError("当前脚本只处理 EPSG:4326 的输入图层")
|
||
pixel_width = config.PIXEL_WIDTH
|
||
pixel_height = config.PIXEL_HEIGHT
|
||
layer_names = {}
|
||
if need_5g:
|
||
with open_read_connection(config.GRID_5G_GPKG) as grid_5g_conn:
|
||
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)
|
||
if grid_5g_layer.srs_id != 4326:
|
||
raise ValueError("当前脚本只处理 EPSG:4326 的输入图层")
|
||
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)
|
||
rtree_name(grid_5g_conn, grid_5g_layer)
|
||
# rtree_name(grid_4g_conn, grid_4g_layer)
|
||
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
|
||
layer_names["grid_5g"] = grid_5g_layer.table_name
|
||
if need_info:
|
||
with open_read_connection(config.BUILDING_INFO_GPKG) as building_info_conn:
|
||
building_info_layer = resolve_feature_layer(building_info_conn, config.BUILDING_INFO_LAYER)
|
||
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(building_info_conn, building_info_layer.table_name, ["name"])
|
||
rtree_name(building_info_conn, building_info_layer)
|
||
layer_names["building_info"] = building_info_layer.table_name
|
||
if not need_5g:
|
||
pixel_width = pixel_width or 0.0001
|
||
pixel_height = pixel_height or 0.0001
|
||
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]
|
||
# excellent_legend_path = write_excellent_heatmap_legend(OUTPUT_DIR, EXCELLENT_CELL_FIELD)
|
||
competitor_signal_legend_path = None
|
||
if enabled(plan, "competitor"):
|
||
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}")
|
||
if "grid_5g" in layer_names:
|
||
print(f"5G Grid 图层:{layer_names['grid_5g']}")
|
||
# print(f"4G Grid 图层:{layer_names['grid_4g']}")
|
||
if "building_info" in layer_names:
|
||
print(f"BuildingInfo 图层:{layer_names['building_info']}")
|
||
print(f"像元大小:{pixel_width}, {pixel_height}")
|
||
# print(f"用户量图例:{excellent_legend_path}")
|
||
if competitor_signal_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["building_theme_results"] = [
|
||
item for outcome in outcomes for item in outcome.get("building_theme_results", [])
|
||
]
|
||
|
||
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
|