Refactor tests and update QGIS project layers
- Removed obsolete tests related to signal raster colors and continuous heatmap. - Introduced new tests for target grid eligibility and RSRP color classes. - Updated QGIS project layer names and data sources to reflect changes in output filenames. - Ensured that the repository template contains only the relevant thematic rasters.
This commit is contained in:
@@ -31,7 +31,8 @@ GIS_PROJECT_SOURCE = MAP_PARK_DIR / "GIS.qgz" # 每个市场网格结果包要
|
||||
RSRP_FIELD = "ssb_rsrp_dl" # 用于生成热力图的电信 RSRP 字段名。
|
||||
EXCELLENT_CELL_FIELD = "mro_total_dl" # 用于生成用户量热力图的字段名,值越大越红。
|
||||
WEAK_COVER_FIELD = "rsrp_lt_neg105_dl" # 用于生成信号差用户量热力图的字段名,值越大越红。
|
||||
MOBILE_RSRP_FIELD = "ssb_rsrp_yd" # 移动 RSRP 字段名,用于筛选移动信号达到正常水平的 Grid。
|
||||
MOBILE_TOTAL_FIELD = "mro_total_yd" # 移动采样点总数字段,用作移动弱覆盖比例分母。
|
||||
MOBILE_WEAK_COVER_FIELD = "rsrp_lt_neg105_yd" # 移动弱覆盖采样点字段,用作目标 Grid 筛选。
|
||||
MARKET_LAYER = None # 市场网格图层名;None 表示自动使用 GPKG 中第一个 feature 图层。
|
||||
GRID_LAYER = None # Grid 指标图层名;None 表示自动使用 GPKG 中第一个 feature 图层。
|
||||
BUILDING_LAYER = None # Building 建筑指标图层名;None 表示自动使用 GPKG 中第一个 feature 图层。
|
||||
@@ -39,7 +40,6 @@ BUILDING_INFO_LAYER = None # BuildingInfo 建筑信息图层名;None 表示
|
||||
MARKET_CODE_FIELD = "fid" # 市场网格唯一 ID 前缀字段,新版 MarketMap 使用 fid。
|
||||
MARKET_NAME_FIELD = "Name" # 市场网格名称字段,新版 MarketMap 使用 Name。
|
||||
MARKET_ID_SEPARATOR = "-" # 市场网格唯一 ID 拼接符,输出为 fid-name,例如 1-城区蓬江。
|
||||
SIGNAL_OUTPUT_FILENAME = "信号.tif" # RSRP 连续红黄绿热力图输出文件名。
|
||||
BUILDING_INFO_OUTPUT_FILENAME = "BuildingInfo.gpkg" # 每个市场网格结果包内输出的建筑信息拆分文件名。
|
||||
BUILDING_METRICS_CSV_FILENAME = "楼宇指标.csv" # 每个市场网格结果包内输出的楼宇指标 CSV 文件名。
|
||||
GRID_METRICS_CSV_FILENAME = "栅格指标.csv" # 每个市场网格结果包内输出的栅格指标 CSV 文件名。
|
||||
@@ -48,43 +48,36 @@ CSV_SOURCE_FIELDS = ("area_type", "area_name", "longitude", "latitude", "mro_tot
|
||||
SIGNAL_BAD_THRESHOLD = -105.0 # 信号等级“较差”的阈值,小于等于该值输出较差。
|
||||
SIGNAL_NORMAL_THRESHOLD = -95.0 # 信号等级“一般/正常”的分界,大于该值输出正常。
|
||||
GIS_PROJECT_OUTPUT_FILENAME = "GIS.qgz" # 每个市场网格结果包内输出的 QGIS 项目文件名,画布范围按 BuildingInfo 自动更新。
|
||||
HEATMAP_MID_RSRP = -95.0 # 热力图黄色中间阈值。
|
||||
HEATMAP_BAD_RSRP = -105.0 # 热力图红色端阈值;RSRP 小于等于该值视为信号差。
|
||||
HEATMAP_GOOD_RSRP = -80.0 # 热力图绿色端阈值;RSRP 大于等于该值使用纯绿色。
|
||||
HEATMAP_SMOOTH_RADIUS = 10 # 热力图平滑半径,数值越大边界感越弱但细节越柔。
|
||||
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 输出文件名。
|
||||
MOBILE_ADVANTAGE_OUTPUT_FILENAME = "移动优竟对弱用户分布图.tif" # 移动信号好区域内的竟对潜在用户机会分布图文件名。
|
||||
MOBILE_ADVANTAGE_GOOD_RSRP_THRESHOLD = -95.0 # 移动信号门槛;仅 ssb_rsrp_yd 严格大于该值的 Grid 参与目标热力图。
|
||||
MOBILE_ADVANTAGE_YELLOW_PERCENTILE = 0.75 # 目标热力图黄色锚点百分位;高于该位置的热点逐步由黄色趋向红色。
|
||||
MOBILE_ADVANTAGE_SMOOTH_RADIUS = 5 # 目标热力图平滑半径;默认 5 以保留定位精度,可改为 10 或其他非负整数。
|
||||
MOBILE_ADVANTAGE_SCORE_FORMULA = f"{EXCELLENT_CELL_FIELD} + max({WEAK_COVER_FIELD}, 0)" # 机会分值:竟对总采样量计一次,弱覆盖采样量额外加一次。
|
||||
WEAK_COVER_RATIO_GREEN_ANCHOR = 0.0 # 弱覆盖占比连续色带绿色端点,单位为百分比。
|
||||
WEAK_COVER_RATIO_BLUE_ANCHOR = 5.0 # 弱覆盖占比连续色带蓝色锚点,单位为百分比。
|
||||
WEAK_COVER_RATIO_YELLOW_ANCHOR = 10.0 # 弱覆盖占比连续色带黄色锚点,单位为百分比。
|
||||
WEAK_COVER_RATIO_RED_ANCHOR = 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) # 弱覆盖占比高值档颜色。
|
||||
TARGET_RSRP_OUTPUT_FILENAME = "目标栅格竟对RSRP.tif" # 满足移动非弱覆盖、竟对高价值弱覆盖条件的 Grid 八档 RSRP 图。
|
||||
TARGET_MOBILE_WEAK_RATIO_MAX = 20.0 # 移动弱覆盖比例必须严格小于该百分比。
|
||||
TARGET_COMPETITOR_TOTAL_MIN = 200.0 # 竟对采样点总数必须严格大于该值。
|
||||
TARGET_COMPETITOR_WEAK_RATIO_MIN = 20.0 # 竟对弱覆盖比例必须严格大于该百分比。
|
||||
TARGET_RSRP_BREAKS = (-110.0, -104.0, -98.0, -92.0, -86.0, -80.0, -74.0) # 八档颜色的七个分界点。
|
||||
TARGET_RSRP_COLORS = (
|
||||
(253, 0, 5), # < -110,红色。
|
||||
(255, 138, 0), # [-110, -104),橙色。
|
||||
(254, 253, 2), # [-104, -98),黄色。
|
||||
(214, 251, 199), # [-98, -92),浅绿色。
|
||||
(42, 231, 41), # [-92, -86),亮绿色。
|
||||
(34, 174, 51), # [-86, -80),深绿色。
|
||||
(0, 149, 231), # [-80, -74),蓝色。
|
||||
(58, 14, 247), # [-74, 0],紫色。
|
||||
)
|
||||
SUMMARY_OUTPUT_ENABLED = True # 是否额外生成全部市场网格汇总 TIF 结果包。
|
||||
SUMMARY_OUTPUT_FILENAME = "所有网格汇总.zip" # 汇总结果包文件名,包含五张 TIF、GIS.qgz 和完整 BuildingInfo.gpkg。
|
||||
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% 位置作为结果记录阈值。
|
||||
EXCELLENT_PERCENT_STEPS = (0.1, 0.4, 0.7) # 按最终有效像元降序四等分,取 25%、50%、75% 位置作为结果记录阈值。
|
||||
EXCELLENT_COLORS = (
|
||||
(255, 0, 0), # 高值端,红色。
|
||||
(255, 255, 0), # 偏高值,黄色。
|
||||
(0, 112, 255), # 偏低值,蓝色。
|
||||
(0, 176, 80), # 低值端,绿色。
|
||||
)
|
||||
CONTINUOUS_HEATMAP_RED = (255, 0, 0) # 连续热力图高风险端颜色。
|
||||
CONTINUOUS_HEATMAP_YELLOW = (255, 255, 0) # 连续热力图中间颜色。
|
||||
CONTINUOUS_HEATMAP_GREEN = (0, 176, 80) # 连续热力图低风险端颜色。
|
||||
WEAK_COVER_YELLOW_PERCENTILE = 0.75 # 信号差用户量黄色锚点百分位;0.75 使红色集中在最高值约 25% 区域。
|
||||
PIXEL_WIDTH = None # 输出像元宽度;None 表示自动按 Grid 单元宽度估算。
|
||||
PIXEL_HEIGHT = None # 输出像元高度;None 表示自动按 Grid 单元高度估算。
|
||||
SCALE = 5.0 # 分辨率倍数;2.0 表示像元宽高减半,放大查看更清晰。
|
||||
@@ -145,24 +138,12 @@ def build_summary_market(markets):
|
||||
return MarketFeature(0, SUMMARY_MARKET_CODE, SUMMARY_MARKET_CODE, geometry)
|
||||
|
||||
|
||||
def heatmap_raster_filename(_field):
|
||||
return SIGNAL_OUTPUT_FILENAME
|
||||
|
||||
|
||||
def excellent_heatmap_raster_filename(_field):
|
||||
return USER_COUNT_OUTPUT_FILENAME
|
||||
|
||||
|
||||
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 mobile_advantage_raster_filename():
|
||||
return MOBILE_ADVANTAGE_OUTPUT_FILENAME
|
||||
def target_rsrp_raster_filename():
|
||||
return TARGET_RSRP_OUTPUT_FILENAME
|
||||
|
||||
|
||||
def set_xml_extent(extent_element, extent):
|
||||
@@ -245,11 +226,8 @@ def copy_gis_project_to_market(source_path, output_path, market, building_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,
|
||||
MOBILE_ADVANTAGE_OUTPUT_FILENAME,
|
||||
TARGET_RSRP_OUTPUT_FILENAME,
|
||||
}
|
||||
for layer in root.findall(".//projectlayers/maplayer"):
|
||||
datasource = (layer.findtext("datasource") or "").replace("\\", "/")
|
||||
@@ -899,85 +877,6 @@ def estimate_pixel_size(conn, layer, sample_size):
|
||||
return float(np.median(widths)), float(np.median(heights))
|
||||
|
||||
|
||||
def continuous_heatmap_rgb_for_scores(scores, yellow_score=0.5):
|
||||
if not 0 < yellow_score < 1:
|
||||
raise ValueError("yellow_score 必须大于 0 且小于 1")
|
||||
normalized = np.clip(np.asarray(scores, dtype=np.float32), 0.0, 1.0)
|
||||
result = np.empty((*normalized.shape, 3), dtype=np.float32)
|
||||
green = np.asarray(CONTINUOUS_HEATMAP_GREEN, dtype=np.float32)
|
||||
yellow = np.asarray(CONTINUOUS_HEATMAP_YELLOW, dtype=np.float32)
|
||||
red = np.asarray(CONTINUOUS_HEATMAP_RED, dtype=np.float32)
|
||||
|
||||
lower_mask = normalized <= yellow_score
|
||||
lower_weight = (normalized[lower_mask] / yellow_score)[..., None]
|
||||
result[lower_mask] = green + (yellow - green) * lower_weight
|
||||
|
||||
upper_mask = ~lower_mask
|
||||
upper_weight = ((normalized[upper_mask] - yellow_score) / (1.0 - yellow_score))[..., None]
|
||||
result[upper_mask] = yellow + (red - yellow) * upper_weight
|
||||
return np.rint(np.clip(result, 0, 255)).astype(np.uint8)
|
||||
|
||||
|
||||
def heatmap_rgb_for_values(values):
|
||||
values = np.asarray(values, dtype=np.float32)
|
||||
scores = np.empty(values.shape, dtype=np.float32)
|
||||
scores[values <= HEATMAP_BAD_RSRP] = 1.0
|
||||
|
||||
middle_mask = (values > HEATMAP_BAD_RSRP) & (values <= HEATMAP_MID_RSRP)
|
||||
scores[middle_mask] = 1.0 - 0.5 * (
|
||||
(values[middle_mask] - HEATMAP_BAD_RSRP) / (HEATMAP_MID_RSRP - HEATMAP_BAD_RSRP)
|
||||
)
|
||||
|
||||
good_mask = (values > HEATMAP_MID_RSRP) & (values < HEATMAP_GOOD_RSRP)
|
||||
scores[good_mask] = 0.5 * (
|
||||
(HEATMAP_GOOD_RSRP - values[good_mask]) / (HEATMAP_GOOD_RSRP - HEATMAP_MID_RSRP)
|
||||
)
|
||||
scores[values >= HEATMAP_GOOD_RSRP] = 0.0
|
||||
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.float32)
|
||||
anchors = (
|
||||
(WEAK_COVER_RATIO_GREEN_ANCHOR, WEAK_COVER_RATIO_GREEN),
|
||||
(WEAK_COVER_RATIO_BLUE_ANCHOR, WEAK_COVER_RATIO_BLUE),
|
||||
(WEAK_COVER_RATIO_YELLOW_ANCHOR, WEAK_COVER_RATIO_YELLOW),
|
||||
(WEAK_COVER_RATIO_RED_ANCHOR, WEAK_COVER_RATIO_RED),
|
||||
)
|
||||
colors[:] = anchors[0][1]
|
||||
for (lower_value, lower_color), (upper_value, upper_color) in zip(anchors, anchors[1:]):
|
||||
mask = (values > lower_value) & (values < upper_value)
|
||||
weight = ((values[mask] - lower_value) / (upper_value - lower_value))[..., None]
|
||||
lower_rgb = np.asarray(lower_color, dtype=np.float32)
|
||||
upper_rgb = np.asarray(upper_color, dtype=np.float32)
|
||||
colors[mask] = lower_rgb + (upper_rgb - lower_rgb) * weight
|
||||
colors[values == upper_value] = upper_rgb
|
||||
colors[values >= WEAK_COVER_RATIO_RED_ANCHOR] = WEAK_COVER_RATIO_RED
|
||||
return np.rint(np.clip(colors, 0, 255)).astype(np.uint8)
|
||||
|
||||
|
||||
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]
|
||||
if valid_values.size == 0:
|
||||
return scores, []
|
||||
|
||||
unique_values, inverse, counts = np.unique(valid_values, return_inverse=True, return_counts=True)
|
||||
if unique_values.size == 1:
|
||||
scores[data_mask] = anchor_scores[len(anchor_scores) // 2]
|
||||
return scores, [float(unique_values[0])] * len(anchor_scores)
|
||||
|
||||
cumulative_before = np.cumsum(counts, dtype=np.int64) - counts
|
||||
rank_scores = cumulative_before.astype(np.float32) / float(cumulative_before[-1])
|
||||
scores[data_mask] = rank_scores[inverse]
|
||||
anchor_values = []
|
||||
for anchor_score in anchor_scores:
|
||||
index = min(int(np.searchsorted(rank_scores, anchor_score, side="left")), unique_values.size - 1)
|
||||
anchor_values.append(float(unique_values[index]))
|
||||
return scores, anchor_values
|
||||
|
||||
|
||||
def percentile_thresholds_from_values(values, percent_steps):
|
||||
sorted_values = np.sort(np.asarray(values, dtype=np.float32))[::-1]
|
||||
sorted_values = sorted_values[np.isfinite(sorted_values)]
|
||||
@@ -1079,13 +978,39 @@ def to_float(value):
|
||||
return None
|
||||
|
||||
|
||||
def mobile_advantage_opportunity_score(mobile_rsrp, total_users, weak_cover_users):
|
||||
if mobile_rsrp is None or total_users is None:
|
||||
return None
|
||||
if mobile_rsrp <= MOBILE_ADVANTAGE_GOOD_RSRP_THRESHOLD or total_users <= 0:
|
||||
return None
|
||||
weak_cover_bonus = weak_cover_users if weak_cover_users is not None and weak_cover_users > 0 else 0.0
|
||||
return total_users + weak_cover_bonus
|
||||
def target_grid_filter_reason(mobile_weak, mobile_total, competitor_weak, competitor_total):
|
||||
values = (mobile_weak, mobile_total, competitor_weak, competitor_total)
|
||||
if any(value is None for value in values):
|
||||
return "invalid_fields"
|
||||
if mobile_total <= 0 or mobile_weak < 0 or competitor_total <= 0 or competitor_weak < 0:
|
||||
return "invalid_fields"
|
||||
mobile_weak_ratio = mobile_weak / mobile_total * 100.0
|
||||
if mobile_weak_ratio >= TARGET_MOBILE_WEAK_RATIO_MAX:
|
||||
return "mobile_weak_ratio"
|
||||
if competitor_total <= TARGET_COMPETITOR_TOTAL_MIN:
|
||||
return "competitor_total"
|
||||
competitor_weak_ratio = competitor_weak / competitor_total * 100.0
|
||||
if competitor_weak_ratio <= TARGET_COMPETITOR_WEAK_RATIO_MIN:
|
||||
return "competitor_weak_ratio"
|
||||
return None
|
||||
|
||||
|
||||
def target_grid_is_eligible(mobile_weak, mobile_total, competitor_weak, competitor_total):
|
||||
return target_grid_filter_reason(mobile_weak, mobile_total, competitor_weak, competitor_total) is None
|
||||
|
||||
|
||||
def target_rsrp_rgb_for_values(values):
|
||||
values = np.asarray(values, dtype=np.float32)
|
||||
colors = np.zeros((*values.shape, 3), dtype=np.uint8)
|
||||
valid_mask = np.isfinite(values) & (values <= 0)
|
||||
if np.any(valid_mask):
|
||||
color_indices = np.searchsorted(
|
||||
np.asarray(TARGET_RSRP_BREAKS, dtype=np.float32),
|
||||
values[valid_mask],
|
||||
side="right",
|
||||
)
|
||||
colors[valid_mask] = np.asarray(TARGET_RSRP_COLORS, dtype=np.uint8)[color_indices]
|
||||
return colors, valid_mask
|
||||
|
||||
|
||||
def geotiff_extratags(minx, maxy, pixel_width, pixel_height):
|
||||
@@ -1171,49 +1096,6 @@ def market_raster_layout(bounds, pixel_width, pixel_height, max_raster_pixels=No
|
||||
return minx, miny, maxx, maxy, pixel_width, pixel_height, width, height, scale_factor
|
||||
|
||||
|
||||
def smooth_weighted_values(value_sum, value_weight, radius):
|
||||
data_mask = value_weight > 0
|
||||
smoothed_value = np.zeros_like(value_sum)
|
||||
if np.any(data_mask):
|
||||
smoothed_sum = gaussian_blur(value_sum, radius)
|
||||
smoothed_weight = gaussian_blur(value_weight, radius)
|
||||
np.divide(smoothed_sum, smoothed_weight, out=smoothed_value, where=smoothed_weight > 0)
|
||||
return smoothed_value, data_mask
|
||||
|
||||
|
||||
def render_signal_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"],
|
||||
HEATMAP_SMOOTH_RADIUS,
|
||||
)
|
||||
if np.any(data_mask):
|
||||
image[data_mask, :3] = heatmap_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_pixels": state["painted_cells"],
|
||||
"data_pixels": int(np.count_nonzero(data_mask)),
|
||||
"skipped_no_value": state["skipped_no_value"],
|
||||
"color_mode": "continuous_fixed_rsrp",
|
||||
"color_anchors": {
|
||||
"red": HEATMAP_BAD_RSRP,
|
||||
"yellow": HEATMAP_MID_RSRP,
|
||||
"green": HEATMAP_GOOD_RSRP,
|
||||
},
|
||||
"smooth_radius": HEATMAP_SMOOTH_RADIUS,
|
||||
"width": width,
|
||||
"height": height,
|
||||
"skipped": False,
|
||||
}
|
||||
|
||||
|
||||
def replace_file_with_retry(source_path, target_path, attempts=20, delay_seconds=0.5):
|
||||
for attempt in range(attempts):
|
||||
try:
|
||||
@@ -1225,104 +1107,6 @@ def replace_file_with_retry(source_path, target_path, attempts=20, delay_seconds
|
||||
sleep(delay_seconds)
|
||||
|
||||
|
||||
def render_percentile_heatmap_raster(
|
||||
state,
|
||||
market,
|
||||
output_path,
|
||||
minx,
|
||||
maxy,
|
||||
pixel_width,
|
||||
pixel_height,
|
||||
width,
|
||||
height,
|
||||
candidates,
|
||||
yellow_percentile,
|
||||
smooth_radius,
|
||||
):
|
||||
image = np.full((height, width, 4), TRANSPARENT_PIXEL, dtype=np.uint8)
|
||||
smoothed_value, data_mask = smooth_weighted_values(
|
||||
state["value_sum"],
|
||||
state["value_weight"],
|
||||
smooth_radius,
|
||||
)
|
||||
anchor_values = []
|
||||
if np.any(data_mask):
|
||||
anchor_scores = (0.0, yellow_percentile, 1.0)
|
||||
scores, anchor_values = percentile_scores_for_values(smoothed_value, data_mask, anchor_scores)
|
||||
image[data_mask, :3] = continuous_heatmap_rgb_for_scores(
|
||||
scores,
|
||||
yellow_score=yellow_percentile,
|
||||
)[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": "continuous_percentile",
|
||||
"yellow_percentile": yellow_percentile,
|
||||
"color_anchor_values": {
|
||||
"green": anchor_values[0],
|
||||
"yellow": anchor_values[1],
|
||||
"red": anchor_values[2],
|
||||
} if anchor_values else None,
|
||||
"smooth_radius": smooth_radius,
|
||||
"width": width,
|
||||
"height": height,
|
||||
"skipped": False,
|
||||
}
|
||||
|
||||
|
||||
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"],
|
||||
HEATMAP_SMOOTH_RADIUS,
|
||||
)
|
||||
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": "continuous_fixed_weak_cover_ratio",
|
||||
"percentage_anchors": {
|
||||
"green": WEAK_COVER_RATIO_GREEN_ANCHOR,
|
||||
"blue": WEAK_COVER_RATIO_BLUE_ANCHOR,
|
||||
"yellow": WEAK_COVER_RATIO_YELLOW_ANCHOR,
|
||||
"red": WEAK_COVER_RATIO_RED_ANCHOR,
|
||||
},
|
||||
"smooth_radius": HEATMAP_SMOOTH_RADIUS,
|
||||
"width": width,
|
||||
"height": height,
|
||||
"skipped": False,
|
||||
}
|
||||
|
||||
|
||||
def render_ranked_raster(
|
||||
state,
|
||||
market,
|
||||
@@ -1375,6 +1159,60 @@ def render_ranked_raster(
|
||||
}
|
||||
|
||||
|
||||
def render_target_rsrp_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)
|
||||
value_sum = state["value_sum"]
|
||||
value_weight = state["value_weight"]
|
||||
data_mask = value_weight > 0
|
||||
class_pixel_counts = [0] * len(TARGET_RSRP_COLORS)
|
||||
if np.any(data_mask):
|
||||
value_raster = np.zeros_like(value_sum)
|
||||
np.divide(value_sum, value_weight, out=value_raster, where=data_mask)
|
||||
colors, valid_rsrp_mask = target_rsrp_rgb_for_values(value_raster)
|
||||
render_mask = data_mask & valid_rsrp_mask
|
||||
image[render_mask, :3] = colors[render_mask]
|
||||
image[render_mask, 3] = HEATMAP_ALPHA
|
||||
class_indices = np.searchsorted(
|
||||
np.asarray(TARGET_RSRP_BREAKS, dtype=np.float32),
|
||||
value_raster[render_mask],
|
||||
side="right",
|
||||
)
|
||||
class_pixel_counts = np.bincount(
|
||||
class_indices,
|
||||
minlength=len(TARGET_RSRP_COLORS),
|
||||
).astype(int).tolist()
|
||||
|
||||
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(image[..., 3])),
|
||||
"skipped_no_value": state["skipped_no_value"],
|
||||
"color_mode": "discrete_target_rsrp",
|
||||
"rsrp_breaks": list(TARGET_RSRP_BREAKS),
|
||||
"colors": [list(color) for color in TARGET_RSRP_COLORS],
|
||||
"class_pixel_counts": class_pixel_counts,
|
||||
"smooth_radius": 0,
|
||||
"width": width,
|
||||
"height": height,
|
||||
"skipped": False,
|
||||
}
|
||||
|
||||
|
||||
def export_market_grid_outputs(
|
||||
grid_conn,
|
||||
grid_layer,
|
||||
@@ -1382,11 +1220,8 @@ def export_market_grid_outputs(
|
||||
market,
|
||||
pixel_width,
|
||||
pixel_height,
|
||||
signal_path,
|
||||
user_count_path,
|
||||
weak_cover_path,
|
||||
weak_cover_ratio_path,
|
||||
mobile_advantage_path,
|
||||
target_rsrp_path,
|
||||
csv_path,
|
||||
max_raster_pixels=None,
|
||||
):
|
||||
@@ -1396,12 +1231,18 @@ def export_market_grid_outputs(
|
||||
pixel_height,
|
||||
max_raster_pixels,
|
||||
)
|
||||
raster_fields = (RSRP_FIELD, EXCELLENT_CELL_FIELD, WEAK_COVER_FIELD, MOBILE_RSRP_FIELD)
|
||||
raster_fields = (
|
||||
EXCELLENT_CELL_FIELD,
|
||||
RSRP_FIELD,
|
||||
WEAK_COVER_FIELD,
|
||||
MOBILE_TOTAL_FIELD,
|
||||
MOBILE_WEAK_COVER_FIELD,
|
||||
)
|
||||
skipped_no_value = {field: 0 for field in raster_fields}
|
||||
painted_cells = {field: 0 for field in raster_fields}
|
||||
raster_cells = []
|
||||
|
||||
fields = list(dict.fromkeys(CSV_SOURCE_FIELDS if csv_path is not None else raster_fields))
|
||||
fields = list(dict.fromkeys((*CSV_SOURCE_FIELDS, *raster_fields) if csv_path is not None else raster_fields))
|
||||
if csv_path is None and CLIP_MODE == "center":
|
||||
fields.extend(field for field in ("longitude", "latitude") if field not in fields)
|
||||
require_columns(grid_conn, grid_layer.table_name, fields)
|
||||
@@ -1484,10 +1325,11 @@ def export_market_grid_outputs(
|
||||
row_stop,
|
||||
col_start,
|
||||
col_stop,
|
||||
numeric_values[RSRP_FIELD],
|
||||
numeric_values[EXCELLENT_CELL_FIELD],
|
||||
numeric_values[RSRP_FIELD],
|
||||
numeric_values[WEAK_COVER_FIELD],
|
||||
numeric_values[MOBILE_RSRP_FIELD],
|
||||
numeric_values[MOBILE_TOTAL_FIELD],
|
||||
numeric_values[MOBILE_WEAK_COVER_FIELD],
|
||||
)
|
||||
)
|
||||
finally:
|
||||
@@ -1511,12 +1353,7 @@ def export_market_grid_outputs(
|
||||
"skipped_no_value": skipped_no_value[field],
|
||||
}
|
||||
|
||||
signal_state = build_state(RSRP_FIELD, 0)
|
||||
signal_result = render_signal_raster(
|
||||
signal_state, market, signal_path, minx, maxy, pixel_width, pixel_height, width, height, candidates
|
||||
)
|
||||
del signal_state
|
||||
user_count_state = build_state(EXCELLENT_CELL_FIELD, 1)
|
||||
user_count_state = build_state(EXCELLENT_CELL_FIELD, 0)
|
||||
user_count_result = render_ranked_raster(
|
||||
user_count_state,
|
||||
market,
|
||||
@@ -1532,48 +1369,49 @@ def export_market_grid_outputs(
|
||||
EXCELLENT_PERCENT_STEPS,
|
||||
)
|
||||
del user_count_state
|
||||
weak_cover_state = build_state(WEAK_COVER_FIELD, 2)
|
||||
weak_cover_result = render_percentile_heatmap_raster(
|
||||
weak_cover_state,
|
||||
market,
|
||||
weak_cover_path,
|
||||
minx,
|
||||
maxy,
|
||||
pixel_width,
|
||||
pixel_height,
|
||||
width,
|
||||
height,
|
||||
candidates,
|
||||
WEAK_COVER_YELLOW_PERCENTILE,
|
||||
HEATMAP_SMOOTH_RADIUS,
|
||||
)
|
||||
del weak_cover_state
|
||||
|
||||
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,
|
||||
target_value_sum = np.zeros((height, width), dtype=np.float32)
|
||||
target_value_weight = np.zeros((height, width), dtype=np.uint16)
|
||||
target_cells = 0
|
||||
exclusion_counts = {
|
||||
"invalid_fields": 0,
|
||||
"mobile_weak_ratio": 0,
|
||||
"competitor_total": 0,
|
||||
"competitor_weak_ratio": 0,
|
||||
"invalid_rsrp": 0,
|
||||
}
|
||||
weak_cover_ratio_result = render_weak_cover_ratio_raster(
|
||||
ratio_state,
|
||||
for cell in raster_cells:
|
||||
competitor_total = cell[4]
|
||||
competitor_rsrp = cell[5]
|
||||
competitor_weak = cell[6]
|
||||
mobile_total = cell[7]
|
||||
mobile_weak = cell[8]
|
||||
exclusion_reason = target_grid_filter_reason(
|
||||
mobile_weak,
|
||||
mobile_total,
|
||||
competitor_weak,
|
||||
competitor_total,
|
||||
)
|
||||
if exclusion_reason is not None:
|
||||
exclusion_counts[exclusion_reason] += 1
|
||||
continue
|
||||
if competitor_rsrp is None or competitor_rsrp > 0:
|
||||
exclusion_counts["invalid_rsrp"] += 1
|
||||
continue
|
||||
row_start, row_stop, col_start, col_stop = cell[:4]
|
||||
target_value_sum[row_start:row_stop, col_start:col_stop] += competitor_rsrp
|
||||
target_value_weight[row_start:row_stop, col_start:col_stop] += 1
|
||||
target_cells += 1
|
||||
target_state = {
|
||||
"value_sum": target_value_sum,
|
||||
"value_weight": target_value_weight,
|
||||
"painted_cells": target_cells,
|
||||
"skipped_no_value": sum(exclusion_counts.values()),
|
||||
}
|
||||
target_rsrp_result = render_target_rsrp_raster(
|
||||
target_state,
|
||||
market,
|
||||
weak_cover_ratio_path,
|
||||
target_rsrp_path,
|
||||
minx,
|
||||
maxy,
|
||||
pixel_width,
|
||||
@@ -1582,81 +1420,23 @@ def export_market_grid_outputs(
|
||||
height,
|
||||
candidates,
|
||||
)
|
||||
del ratio_state, ratio_value_sum, ratio_value_weight
|
||||
|
||||
mobile_advantage_value_sum = np.zeros((height, width), dtype=np.float32)
|
||||
mobile_advantage_value_weight = np.zeros((height, width), dtype=np.uint16)
|
||||
mobile_advantage_cells = 0
|
||||
excluded_by_mobile_gate = 0
|
||||
excluded_without_total_users = 0
|
||||
included_without_weak_cover = 0
|
||||
included_with_weak_cover_bonus = 0
|
||||
missing_weak_cover_bonus = 0
|
||||
for cell in raster_cells:
|
||||
mobile_rsrp = cell[7]
|
||||
total_users = cell[5]
|
||||
weak_cover_users = cell[6]
|
||||
target_value = mobile_advantage_opportunity_score(mobile_rsrp, total_users, weak_cover_users)
|
||||
if target_value is None:
|
||||
if mobile_rsrp is None or mobile_rsrp <= MOBILE_ADVANTAGE_GOOD_RSRP_THRESHOLD:
|
||||
excluded_by_mobile_gate += 1
|
||||
else:
|
||||
excluded_without_total_users += 1
|
||||
continue
|
||||
if weak_cover_users is None:
|
||||
missing_weak_cover_bonus += 1
|
||||
included_without_weak_cover += 1
|
||||
elif weak_cover_users > 0:
|
||||
included_with_weak_cover_bonus += 1
|
||||
else:
|
||||
included_without_weak_cover += 1
|
||||
row_start, row_stop, col_start, col_stop = cell[:4]
|
||||
mobile_advantage_value_sum[row_start:row_stop, col_start:col_stop] += target_value
|
||||
mobile_advantage_value_weight[row_start:row_stop, col_start:col_stop] += 1
|
||||
mobile_advantage_cells += 1
|
||||
mobile_advantage_state = {
|
||||
"value_sum": mobile_advantage_value_sum,
|
||||
"value_weight": mobile_advantage_value_weight,
|
||||
"painted_cells": mobile_advantage_cells,
|
||||
"skipped_no_value": excluded_by_mobile_gate + excluded_without_total_users,
|
||||
}
|
||||
mobile_advantage_result = render_percentile_heatmap_raster(
|
||||
mobile_advantage_state,
|
||||
market,
|
||||
mobile_advantage_path,
|
||||
minx,
|
||||
maxy,
|
||||
pixel_width,
|
||||
pixel_height,
|
||||
width,
|
||||
height,
|
||||
candidates,
|
||||
MOBILE_ADVANTAGE_YELLOW_PERCENTILE,
|
||||
MOBILE_ADVANTAGE_SMOOTH_RADIUS,
|
||||
)
|
||||
mobile_advantage_result.update({
|
||||
"gate_field": MOBILE_RSRP_FIELD,
|
||||
"gate_operator": ">",
|
||||
"gate_threshold": MOBILE_ADVANTAGE_GOOD_RSRP_THRESHOLD,
|
||||
"score_formula": MOBILE_ADVANTAGE_SCORE_FORMULA,
|
||||
"value_fields": [EXCELLENT_CELL_FIELD, WEAK_COVER_FIELD],
|
||||
"zero_weak_cover_is_included": True,
|
||||
"eligible_cells": mobile_advantage_cells,
|
||||
"excluded_by_mobile_gate": excluded_by_mobile_gate,
|
||||
"excluded_without_total_users": excluded_without_total_users,
|
||||
"included_without_weak_cover": included_without_weak_cover,
|
||||
"included_with_weak_cover_bonus": included_with_weak_cover_bonus,
|
||||
"missing_weak_cover_bonus": missing_weak_cover_bonus,
|
||||
target_rsrp_result.update({
|
||||
"mobile_weak_ratio_formula": f"{MOBILE_WEAK_COVER_FIELD} / {MOBILE_TOTAL_FIELD} * 100",
|
||||
"mobile_weak_ratio_operator": "<",
|
||||
"mobile_weak_ratio_threshold": TARGET_MOBILE_WEAK_RATIO_MAX,
|
||||
"competitor_total_field": EXCELLENT_CELL_FIELD,
|
||||
"competitor_total_operator": ">",
|
||||
"competitor_total_threshold": TARGET_COMPETITOR_TOTAL_MIN,
|
||||
"competitor_weak_ratio_formula": f"{WEAK_COVER_FIELD} / {EXCELLENT_CELL_FIELD} * 100",
|
||||
"competitor_weak_ratio_operator": ">",
|
||||
"competitor_weak_ratio_threshold": TARGET_COMPETITOR_WEAK_RATIO_MIN,
|
||||
"rsrp_field": RSRP_FIELD,
|
||||
"eligible_cells": target_cells,
|
||||
"exclusion_counts": exclusion_counts,
|
||||
})
|
||||
del mobile_advantage_state, mobile_advantage_value_sum, mobile_advantage_value_weight
|
||||
del target_state, target_value_sum, target_value_weight
|
||||
|
||||
for result in (
|
||||
signal_result,
|
||||
user_count_result,
|
||||
weak_cover_result,
|
||||
weak_cover_ratio_result,
|
||||
mobile_advantage_result,
|
||||
):
|
||||
for result in (user_count_result, target_rsrp_result):
|
||||
result["raster_extent"] = [
|
||||
minx,
|
||||
maxy - height * pixel_height,
|
||||
@@ -1677,27 +1457,12 @@ def export_market_grid_outputs(
|
||||
"skipped": csv_skipped,
|
||||
}
|
||||
return (
|
||||
signal_result,
|
||||
user_count_result,
|
||||
weak_cover_result,
|
||||
weak_cover_ratio_result,
|
||||
mobile_advantage_result,
|
||||
target_rsrp_result,
|
||||
csv_result,
|
||||
)
|
||||
|
||||
|
||||
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_anchor", "red", "green", "blue", "alpha", "meaning"])
|
||||
writer.writerow([field, f"<= {HEATMAP_BAD_RSRP}", *CONTINUOUS_HEATMAP_RED, HEATMAP_ALPHA, "bad signal red endpoint"])
|
||||
writer.writerow([field, HEATMAP_MID_RSRP, *CONTINUOUS_HEATMAP_YELLOW, HEATMAP_ALPHA, "continuous yellow anchor"])
|
||||
writer.writerow([field, f">= {HEATMAP_GOOD_RSRP}", *CONTINUOUS_HEATMAP_GREEN, HEATMAP_ALPHA, "good signal green endpoint"])
|
||||
writer.writerow([field, "nodata", 0, 0, 0, 0, "transparent no data"])
|
||||
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:
|
||||
@@ -1710,42 +1475,29 @@ def write_excellent_heatmap_legend(output_dir, field):
|
||||
return legend_path
|
||||
|
||||
|
||||
def write_weak_cover_heatmap_legend(output_dir, field):
|
||||
legend_path = output_dir / "weak_cover_heatmap_legend.csv"
|
||||
def write_target_rsrp_legend(output_dir):
|
||||
legend_path = output_dir / "target_rsrp_legend.csv"
|
||||
with legend_path.open("w", newline="", encoding="utf-8-sig") as file:
|
||||
writer = csv.writer(file)
|
||||
writer.writerow(["field", "percentile_anchor", "red", "green", "blue", "alpha", "meaning"])
|
||||
writer.writerow([field, "highest_value", *CONTINUOUS_HEATMAP_RED, HEATMAP_ALPHA, "most weak-cover users"])
|
||||
writer.writerow([field, f"percentile_{WEAK_COVER_YELLOW_PERCENTILE}", *CONTINUOUS_HEATMAP_YELLOW, HEATMAP_ALPHA, "continuous yellow anchor"])
|
||||
writer.writerow([field, "lowest_value", *CONTINUOUS_HEATMAP_GREEN, HEATMAP_ALPHA, "fewest weak-cover users"])
|
||||
writer.writerow([field, "nodata", 0, 0, 0, 0, "transparent no data"])
|
||||
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_GREEN_ANCHOR}%", *WEAK_COVER_RATIO_GREEN, HEATMAP_ALPHA, "green endpoint"])
|
||||
writer.writerow([formula, f"{WEAK_COVER_RATIO_BLUE_ANCHOR}%", *WEAK_COVER_RATIO_BLUE, HEATMAP_ALPHA, "blue anchor"])
|
||||
writer.writerow([formula, f"{WEAK_COVER_RATIO_YELLOW_ANCHOR}%", *WEAK_COVER_RATIO_YELLOW, HEATMAP_ALPHA, "yellow anchor"])
|
||||
writer.writerow([formula, f">= {WEAK_COVER_RATIO_RED_ANCHOR}%", *WEAK_COVER_RATIO_RED, HEATMAP_ALPHA, "red endpoint"])
|
||||
writer.writerow([formula, "no valid total", 0, 0, 0, 0, "transparent no data"])
|
||||
return legend_path
|
||||
|
||||
|
||||
def write_mobile_advantage_legend(output_dir):
|
||||
legend_path = output_dir / "mobile_advantage_legend.csv"
|
||||
with legend_path.open("w", newline="", encoding="utf-8-sig") as file:
|
||||
writer = csv.writer(file)
|
||||
writer.writerow(["gate", "score_formula", "percentile_anchor", "red", "green", "blue", "alpha", "meaning"])
|
||||
gate = f"{MOBILE_RSRP_FIELD} > {MOBILE_ADVANTAGE_GOOD_RSRP_THRESHOLD}"
|
||||
writer.writerow([gate, MOBILE_ADVANTAGE_SCORE_FORMULA, "highest_value", *CONTINUOUS_HEATMAP_RED, HEATMAP_ALPHA, "highest opportunity score"])
|
||||
writer.writerow([gate, MOBILE_ADVANTAGE_SCORE_FORMULA, f"percentile_{MOBILE_ADVANTAGE_YELLOW_PERCENTILE}", *CONTINUOUS_HEATMAP_YELLOW, HEATMAP_ALPHA, "continuous yellow anchor"])
|
||||
writer.writerow([gate, MOBILE_ADVANTAGE_SCORE_FORMULA, "lowest_positive_value", *CONTINUOUS_HEATMAP_GREEN, HEATMAP_ALPHA, "lowest positive opportunity score"])
|
||||
writer.writerow([gate, MOBILE_ADVANTAGE_SCORE_FORMULA, "gate_failed_or_no_users", 0, 0, 0, 0, "transparent non-target area"])
|
||||
writer.writerow(["field", "rsrp_range", "red", "green", "blue", "alpha", "target_filter"])
|
||||
target_filter = (
|
||||
f"{MOBILE_WEAK_COVER_FIELD}/{MOBILE_TOTAL_FIELD} < {TARGET_MOBILE_WEAK_RATIO_MAX}%"
|
||||
f" and {EXCELLENT_CELL_FIELD} > {TARGET_COMPETITOR_TOTAL_MIN}"
|
||||
f" and {WEAK_COVER_FIELD}/{EXCELLENT_CELL_FIELD} > {TARGET_COMPETITOR_WEAK_RATIO_MIN}%"
|
||||
)
|
||||
ranges = (
|
||||
"< -110",
|
||||
"[-110, -104)",
|
||||
"[-104, -98)",
|
||||
"[-98, -92)",
|
||||
"[-92, -86)",
|
||||
"[-86, -80)",
|
||||
"[-80, -74)",
|
||||
"[-74, 0]",
|
||||
)
|
||||
for value_range, color in zip(ranges, TARGET_RSRP_COLORS):
|
||||
writer.writerow([RSRP_FIELD, value_range, *color, HEATMAP_ALPHA, target_filter])
|
||||
writer.writerow([RSRP_FIELD, "not_target_or_invalid", 0, 0, 0, 0, target_filter])
|
||||
return legend_path
|
||||
|
||||
|
||||
@@ -1809,19 +1561,13 @@ def process_market(market, pixel_width, pixel_height, output_dir):
|
||||
market_dir = Path(temp_dir)
|
||||
gis_project_path = market_dir / GIS_PROJECT_OUTPUT_FILENAME
|
||||
|
||||
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()
|
||||
mobile_advantage_path = market_dir / mobile_advantage_raster_filename()
|
||||
target_rsrp_path = market_dir / target_rsrp_raster_filename()
|
||||
grid_metrics_path = market_dir / GRID_METRICS_CSV_FILENAME
|
||||
grid_started_at = perf_counter()
|
||||
(
|
||||
signal_result,
|
||||
user_count_result,
|
||||
weak_cover_result,
|
||||
weak_cover_ratio_result,
|
||||
mobile_advantage_result,
|
||||
target_rsrp_result,
|
||||
grid_metrics_result,
|
||||
) = export_market_grid_outputs(
|
||||
grid_conn,
|
||||
@@ -1830,11 +1576,8 @@ def process_market(market, pixel_width, pixel_height, output_dir):
|
||||
market,
|
||||
pixel_width,
|
||||
pixel_height,
|
||||
signal_path,
|
||||
user_count_path,
|
||||
weak_cover_path,
|
||||
weak_cover_ratio_path,
|
||||
mobile_advantage_path,
|
||||
target_rsrp_path,
|
||||
grid_metrics_path,
|
||||
)
|
||||
grid_elapsed = perf_counter() - grid_started_at
|
||||
@@ -1853,7 +1596,7 @@ def process_market(market, pixel_width, pixel_height, output_dir):
|
||||
gis_project_path,
|
||||
market,
|
||||
building_info_result["extent"],
|
||||
signal_result["raster_extent"],
|
||||
target_rsrp_result["raster_extent"],
|
||||
)
|
||||
building_metrics_path = market_dir / BUILDING_METRICS_CSV_FILENAME
|
||||
building_metrics_result = export_market_building_metrics_csv(
|
||||
@@ -1877,11 +1620,8 @@ def process_market(market, pixel_width, pixel_height, output_dir):
|
||||
"market_fid": market.fid,
|
||||
"market_code": market.code,
|
||||
"market_name": market.name,
|
||||
"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),
|
||||
"mobile_advantage_result": rewrite_result_for_zip(mobile_advantage_result, zip_path, market_dir),
|
||||
"target_rsrp_result": rewrite_result_for_zip(target_rsrp_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),
|
||||
@@ -1919,17 +1659,11 @@ def process_summary_grid_outputs(markets, pixel_width, pixel_height, output_dir)
|
||||
grid_rtree = rtree_name(grid_conn, grid_layer)
|
||||
with tempfile.TemporaryDirectory(prefix="market_grid_summary_") as temp_dir:
|
||||
summary_dir = Path(temp_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)
|
||||
weak_cover_ratio_path = summary_dir / weak_cover_ratio_raster_filename()
|
||||
mobile_advantage_path = summary_dir / mobile_advantage_raster_filename()
|
||||
target_rsrp_path = summary_dir / target_rsrp_raster_filename()
|
||||
(
|
||||
signal_result,
|
||||
user_count_result,
|
||||
weak_cover_result,
|
||||
weak_cover_ratio_result,
|
||||
mobile_advantage_result,
|
||||
target_rsrp_result,
|
||||
_,
|
||||
) = export_market_grid_outputs(
|
||||
grid_conn,
|
||||
@@ -1938,11 +1672,8 @@ def process_summary_grid_outputs(markets, pixel_width, pixel_height, output_dir)
|
||||
summary_market,
|
||||
pixel_width,
|
||||
pixel_height,
|
||||
signal_path,
|
||||
user_count_path,
|
||||
weak_cover_path,
|
||||
weak_cover_ratio_path,
|
||||
mobile_advantage_path,
|
||||
target_rsrp_path,
|
||||
None,
|
||||
SUMMARY_MAX_RASTER_PIXELS,
|
||||
)
|
||||
@@ -1967,16 +1698,13 @@ def process_summary_grid_outputs(markets, pixel_width, pixel_height, output_dir)
|
||||
gis_project_path,
|
||||
summary_market,
|
||||
building_info_extent,
|
||||
signal_result["raster_extent"],
|
||||
target_rsrp_result["raster_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),
|
||||
"mobile_advantage_result": rewrite_result_for_zip(mobile_advantage_result, zip_path, summary_dir),
|
||||
"target_rsrp_result": rewrite_result_for_zip(target_rsrp_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,
|
||||
@@ -1993,18 +1721,17 @@ def main():
|
||||
raise ValueError("GEOMETRY_BATCH_SIZE 必须大于 0")
|
||||
if PROJECT_EXTENT_PADDING_RATIO < 0:
|
||||
raise ValueError("PROJECT_EXTENT_PADDING_RATIO 不能小于 0")
|
||||
if not HEATMAP_BAD_RSRP < HEATMAP_MID_RSRP < HEATMAP_GOOD_RSRP:
|
||||
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")
|
||||
validate_smoothing_radius("HEATMAP_SMOOTH_RADIUS", HEATMAP_SMOOTH_RADIUS)
|
||||
if not math.isfinite(MOBILE_ADVANTAGE_GOOD_RSRP_THRESHOLD):
|
||||
raise ValueError("MOBILE_ADVANTAGE_GOOD_RSRP_THRESHOLD 必须是有限数值")
|
||||
if not 0 < MOBILE_ADVANTAGE_YELLOW_PERCENTILE < 1:
|
||||
raise ValueError("MOBILE_ADVANTAGE_YELLOW_PERCENTILE 必须大于 0 且小于 1")
|
||||
validate_smoothing_radius("MOBILE_ADVANTAGE_SMOOTH_RADIUS", MOBILE_ADVANTAGE_SMOOTH_RADIUS)
|
||||
if not 0 <= WEAK_COVER_RATIO_GREEN_ANCHOR < WEAK_COVER_RATIO_BLUE_ANCHOR < WEAK_COVER_RATIO_YELLOW_ANCHOR < WEAK_COVER_RATIO_RED_ANCHOR:
|
||||
raise ValueError("弱覆盖占比锚点必须满足 0 <= GREEN < BLUE < YELLOW < RED")
|
||||
if not 0 <= TARGET_MOBILE_WEAK_RATIO_MAX <= 100:
|
||||
raise ValueError("TARGET_MOBILE_WEAK_RATIO_MAX 必须在 0 到 100 之间")
|
||||
if TARGET_COMPETITOR_TOTAL_MIN < 0 or not math.isfinite(TARGET_COMPETITOR_TOTAL_MIN):
|
||||
raise ValueError("TARGET_COMPETITOR_TOTAL_MIN 必须是非负有限数值")
|
||||
if not 0 <= TARGET_COMPETITOR_WEAK_RATIO_MIN <= 100:
|
||||
raise ValueError("TARGET_COMPETITOR_WEAK_RATIO_MIN 必须在 0 到 100 之间")
|
||||
if len(TARGET_RSRP_COLORS) != len(TARGET_RSRP_BREAKS) + 1:
|
||||
raise ValueError("目标 RSRP 颜色数量必须比分界点数量多 1")
|
||||
if any(left >= right for left, right in zip(TARGET_RSRP_BREAKS, TARGET_RSRP_BREAKS[1:])):
|
||||
raise ValueError("TARGET_RSRP_BREAKS 必须严格递增")
|
||||
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:
|
||||
@@ -2037,7 +1764,7 @@ def main():
|
||||
require_columns(
|
||||
grid_conn,
|
||||
grid_layer.table_name,
|
||||
CSV_SOURCE_FIELDS,
|
||||
(*CSV_SOURCE_FIELDS, MOBILE_TOTAL_FIELD, MOBILE_WEAK_COVER_FIELD),
|
||||
)
|
||||
require_columns(building_info_conn, building_info_layer.table_name, ["name"])
|
||||
rtree_name(grid_conn, grid_layer)
|
||||
@@ -2066,11 +1793,8 @@ def main():
|
||||
"building_info": building_info_layer.table_name,
|
||||
}
|
||||
|
||||
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)
|
||||
mobile_advantage_legend_path = write_mobile_advantage_legend(OUTPUT_DIR)
|
||||
target_rsrp_legend_path = write_target_rsrp_legend(OUTPUT_DIR)
|
||||
worker_count = max(1, min(MAX_WORKERS, len(markets))) if markets else 1
|
||||
print(f"市场网格数量:{len(markets)}")
|
||||
print(f"并行进程数:{worker_count}")
|
||||
@@ -2078,11 +1802,8 @@ def main():
|
||||
print(f"Building 图层:{layer_names['building']}")
|
||||
print(f"BuildingInfo 图层:{layer_names['building_info']}")
|
||||
print(f"像元大小:{pixel_width}, {pixel_height}")
|
||||
print(f"热力图图例:{heatmap_legend_path}")
|
||||
print(f"用户量图例:{excellent_legend_path}")
|
||||
print(f"信号差用户量图例:{weak_cover_legend_path}")
|
||||
print(f"弱覆盖占比图例:{weak_cover_ratio_legend_path}")
|
||||
print(f"移动优竟对弱用户分布图图例:{mobile_advantage_legend_path}")
|
||||
print(f"目标栅格竟对 RSRP 图例:{target_rsrp_legend_path}")
|
||||
|
||||
started_at = perf_counter()
|
||||
outcomes = []
|
||||
@@ -2090,7 +1811,7 @@ def main():
|
||||
for index, market in enumerate(markets, start=1):
|
||||
outcome = process_market(market, pixel_width, pixel_height, OUTPUT_DIR)
|
||||
outcomes.append(outcome)
|
||||
scale_factor = outcome.get("heatmap_result", {}).get("resolution_scale_factor", 1.0)
|
||||
scale_factor = outcome.get("target_rsrp_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},"
|
||||
@@ -2111,7 +1832,7 @@ def main():
|
||||
raise RuntimeError(f"市场网格处理失败:{market.code}") from error
|
||||
outcomes.append(outcome)
|
||||
completed += 1
|
||||
scale_factor = outcome.get("heatmap_result", {}).get("resolution_scale_factor", 1.0)
|
||||
scale_factor = outcome.get("target_rsrp_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},"
|
||||
@@ -2128,11 +1849,8 @@ def main():
|
||||
f"耗时 {summary_grid_result['elapsed_seconds']:.1f} 秒"
|
||||
)
|
||||
result_mappings = {
|
||||
"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",
|
||||
"mobile_advantage_results": "mobile_advantage_result",
|
||||
"target_rsrp_results": "target_rsrp_result",
|
||||
"building_info_results": "building_info_result",
|
||||
"building_metrics_csv_results": "building_metrics_csv_result",
|
||||
"grid_metrics_csv_results": "grid_metrics_csv_result",
|
||||
@@ -2148,11 +1866,13 @@ def main():
|
||||
"rsrp_field": RSRP_FIELD,
|
||||
"excellent_cell_field": EXCELLENT_CELL_FIELD,
|
||||
"weak_cover_field": WEAK_COVER_FIELD,
|
||||
"mobile_rsrp_field": MOBILE_RSRP_FIELD,
|
||||
"mobile_advantage_gate": f"{MOBILE_RSRP_FIELD} > {MOBILE_ADVANTAGE_GOOD_RSRP_THRESHOLD}",
|
||||
"mobile_advantage_score_formula": MOBILE_ADVANTAGE_SCORE_FORMULA,
|
||||
"mobile_advantage_smooth_radius": MOBILE_ADVANTAGE_SMOOTH_RADIUS,
|
||||
"weak_cover_ratio_formula": f"{WEAK_COVER_FIELD} / {EXCELLENT_CELL_FIELD} * 100",
|
||||
"mobile_total_field": MOBILE_TOTAL_FIELD,
|
||||
"mobile_weak_cover_field": MOBILE_WEAK_COVER_FIELD,
|
||||
"target_mobile_weak_ratio_formula": f"{MOBILE_WEAK_COVER_FIELD} / {MOBILE_TOTAL_FIELD} * 100",
|
||||
"target_mobile_weak_ratio_rule": f"< {TARGET_MOBILE_WEAK_RATIO_MAX}",
|
||||
"target_competitor_total_rule": f"{EXCELLENT_CELL_FIELD} > {TARGET_COMPETITOR_TOTAL_MIN}",
|
||||
"target_competitor_weak_ratio_formula": f"{WEAK_COVER_FIELD} / {EXCELLENT_CELL_FIELD} * 100",
|
||||
"target_competitor_weak_ratio_rule": f"> {TARGET_COMPETITOR_WEAK_RATIO_MIN}",
|
||||
"clip_mode": CLIP_MODE,
|
||||
"scale": SCALE,
|
||||
"pixel_width": pixel_width,
|
||||
|
||||
Reference in New Issue
Block a user