fix: 按像元四等分生成用户量热力图
This commit is contained in:
@@ -41,7 +41,7 @@ HEATMAP_SMOOTH_RADIUS = 10 # 热力图平滑半径,数值越大边界感越
|
||||
HEATMAP_ALPHA = 191 # 热力图有效像元透明度;191 约等于 75% 不透明度。
|
||||
USER_COUNT_OUTPUT_FILENAME = "用户量.tif" # 采样点数量热力图输出文件名。
|
||||
WEAK_COVER_OUTPUT_FILENAME = "信号差用户量.tif" # 信号差用户量热力图输出文件名。
|
||||
EXCELLENT_PERCENT_STEPS = (0.2, 0.4, 0.6, 0.8) # 不去重,按所有匹配值降序取前 20%、40%、60%、80% 作为连续渐变控制点。
|
||||
EXCELLENT_PERCENT_STEPS = (0.25, 0.5, 0.75) # 按最终有效像元降序四等分,取 25%、50%、75% 位置作为结果记录阈值。
|
||||
EXCELLENT_COLORS = (
|
||||
(255, 0, 0), # 高值端,红色。
|
||||
(255, 255, 0), # 偏高值,黄色。
|
||||
@@ -519,59 +519,52 @@ def heatmap_rgb_for_values(values):
|
||||
|
||||
|
||||
def percentile_thresholds_from_values(values, percent_steps):
|
||||
sorted_values = sorted((value for value in values if value is not None), reverse=True)
|
||||
if not sorted_values:
|
||||
sorted_values = np.sort(np.asarray(values, dtype=np.float32))[::-1]
|
||||
sorted_values = sorted_values[np.isfinite(sorted_values)]
|
||||
if sorted_values.size == 0:
|
||||
return []
|
||||
|
||||
thresholds = []
|
||||
for percent in percent_steps:
|
||||
index = max(0, math.ceil(len(sorted_values) * percent) - 1)
|
||||
index = min(index, len(sorted_values) - 1)
|
||||
thresholds.append(sorted_values[index])
|
||||
index = max(0, math.ceil(sorted_values.size * percent) - 1)
|
||||
index = min(index, sorted_values.size - 1)
|
||||
thresholds.append(float(sorted_values[index]))
|
||||
return thresholds
|
||||
|
||||
|
||||
def palette_colors_for_steps(step_count):
|
||||
if step_count <= 0:
|
||||
return []
|
||||
if step_count == 1:
|
||||
return [EXCELLENT_COLORS[0]]
|
||||
def ranked_pixel_rgb_for_values(values, data_mask):
|
||||
result = np.zeros((*values.shape, 3), dtype=np.uint8)
|
||||
valid_positions = np.flatnonzero(data_mask.ravel())
|
||||
if valid_positions.size == 0:
|
||||
return result, [], []
|
||||
|
||||
colors = []
|
||||
palette_max = len(EXCELLENT_COLORS) - 1
|
||||
for index in range(step_count):
|
||||
position = index / (step_count - 1)
|
||||
scaled = position * palette_max
|
||||
start_index = int(math.floor(scaled))
|
||||
end_index = min(start_index + 1, palette_max)
|
||||
ratio = scaled - start_index
|
||||
color = interpolate_color(EXCELLENT_COLORS[start_index], EXCELLENT_COLORS[end_index], ratio)
|
||||
colors.append(tuple(int(round(channel)) for channel in color))
|
||||
return colors
|
||||
valid_values = values.ravel()[valid_positions]
|
||||
order = np.argsort(-valid_values, kind="mergesort")
|
||||
sorted_positions = valid_positions[order]
|
||||
rank_groups = np.array_split(sorted_positions, len(EXCELLENT_COLORS))
|
||||
flat_result = result.reshape(-1, 3)
|
||||
rank_counts = []
|
||||
for color, group in zip(EXCELLENT_COLORS, rank_groups):
|
||||
if group.size:
|
||||
flat_result[group] = color
|
||||
rank_counts.append(int(group.size))
|
||||
|
||||
thresholds = percentile_thresholds_from_values(valid_values, EXCELLENT_PERCENT_STEPS)
|
||||
return result, thresholds, rank_counts
|
||||
|
||||
|
||||
def excellent_rgb_for_values(values, thresholds):
|
||||
result = np.zeros((*values.shape, 3), dtype=np.float32)
|
||||
if not thresholds:
|
||||
result[:] = EXCELLENT_COLORS[-1]
|
||||
return result.astype(np.uint8)
|
||||
def smooth_rgb_inside_mask(rgb, data_mask, radius):
|
||||
if radius <= 0:
|
||||
return rgb
|
||||
|
||||
control_colors = palette_colors_for_steps(len(thresholds))
|
||||
result[:] = control_colors[-1]
|
||||
|
||||
high = values >= thresholds[0]
|
||||
if np.any(high):
|
||||
result[high] = control_colors[0]
|
||||
|
||||
for index in range(1, len(thresholds)):
|
||||
upper_threshold = thresholds[index - 1]
|
||||
lower_threshold = thresholds[index]
|
||||
between = (values < upper_threshold) & (values >= lower_threshold)
|
||||
if np.any(between):
|
||||
ratio = (values[between] - lower_threshold) / max(upper_threshold - lower_threshold, 1e-9)
|
||||
result[between] = interpolate_color(control_colors[index], control_colors[index - 1], ratio)
|
||||
|
||||
return np.clip(result, 0, 255).astype(np.uint8)
|
||||
weight = data_mask.astype(np.float32)
|
||||
blurred_weight = gaussian_blur(weight, radius)
|
||||
smoothed = np.zeros_like(rgb, dtype=np.float32)
|
||||
for channel in range(3):
|
||||
blurred_channel = gaussian_blur(rgb[..., channel].astype(np.float32) * weight, radius)
|
||||
np.divide(blurred_channel, blurred_weight, out=smoothed[..., channel], where=blurred_weight > 0)
|
||||
smoothed[~data_mask] = 0
|
||||
return np.clip(smoothed, 0, 255).astype(np.uint8)
|
||||
|
||||
|
||||
def gaussian_kernel(radius):
|
||||
@@ -611,7 +604,10 @@ def to_float(value):
|
||||
text = str(value).strip()
|
||||
if not text:
|
||||
return None
|
||||
return float(text)
|
||||
number = float(text)
|
||||
if not math.isfinite(number):
|
||||
return None
|
||||
return number
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
@@ -814,8 +810,8 @@ def export_market_excellent_heatmap_tif(
|
||||
"""
|
||||
params = (max_market_x, min_market_x, max_market_y, min_market_y)
|
||||
candidates = 0
|
||||
matched_cells = 0
|
||||
skipped_no_value = 0
|
||||
matched_values = []
|
||||
|
||||
for _fid, geom_blob, raw_value, raw_lon, raw_lat in grid_conn.execute(query, params):
|
||||
candidates += 1
|
||||
@@ -869,16 +865,17 @@ def export_market_excellent_heatmap_tif(
|
||||
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
|
||||
matched_values.append(value)
|
||||
matched_cells += 1
|
||||
|
||||
thresholds = percentile_thresholds_from_values(matched_values, EXCELLENT_PERCENT_STEPS)
|
||||
data_mask = value_weight > 0
|
||||
thresholds = []
|
||||
rank_pixel_counts = []
|
||||
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)
|
||||
image[data_mask, :3] = excellent_rgb_for_values(smoothed_value, thresholds)[data_mask]
|
||||
value_raster = np.zeros_like(value_sum)
|
||||
np.divide(value_sum, value_weight, out=value_raster, where=data_mask)
|
||||
ranked_rgb, thresholds, rank_pixel_counts = ranked_pixel_rgb_for_values(value_raster, data_mask)
|
||||
smoothed_rgb = smooth_rgb_inside_mask(ranked_rgb, data_mask, HEATMAP_SMOOTH_RADIUS)
|
||||
image[data_mask, :3] = smoothed_rgb[data_mask]
|
||||
image[data_mask, 3] = HEATMAP_ALPHA
|
||||
|
||||
write_rgba_geotiff(output_path, image, minx, maxy, pixel_width, pixel_height)
|
||||
@@ -887,11 +884,12 @@ def export_market_excellent_heatmap_tif(
|
||||
"market_name": market.name,
|
||||
"output": str(output_path),
|
||||
"candidates": candidates,
|
||||
"painted_cells": len(matched_values),
|
||||
"painted_cells": matched_cells,
|
||||
"data_pixels": int(np.count_nonzero(image[..., 3] > 0)),
|
||||
"skipped_no_value": skipped_no_value,
|
||||
"threshold_value_count": len(matched_values),
|
||||
"threshold_value_count": int(np.count_nonzero(data_mask)),
|
||||
"thresholds": thresholds,
|
||||
"rank_pixel_counts": rank_pixel_counts,
|
||||
"percent_steps": list(EXCELLENT_PERCENT_STEPS),
|
||||
"width": width,
|
||||
"height": height,
|
||||
@@ -914,11 +912,10 @@ 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:
|
||||
writer = csv.writer(file)
|
||||
writer.writerow(["field", "control_point", "red", "green", "blue", "alpha", "meaning"])
|
||||
for percent, color in zip(EXCELLENT_PERCENT_STEPS, palette_colors_for_steps(len(EXCELLENT_PERCENT_STEPS))):
|
||||
writer.writerow(
|
||||
[field, f"threshold_{int(round(percent * 100))}_percent", *color, HEATMAP_ALPHA, "sorted-value control"]
|
||||
)
|
||||
writer.writerow(["field", "rank_range", "red", "green", "blue", "alpha", "meaning"])
|
||||
rank_ranges = ("top_25_percent", "25_to_50_percent", "50_to_75_percent", "bottom_25_percent")
|
||||
for rank_range, color in zip(rank_ranges, EXCELLENT_COLORS):
|
||||
writer.writerow([field, rank_range, *color, HEATMAP_ALPHA, "ranked-pixel quartile"])
|
||||
writer.writerow([field, "nodata", 0, 0, 0, 0, "transparent no data"])
|
||||
return legend_path
|
||||
|
||||
@@ -927,11 +924,10 @@ def write_weak_cover_heatmap_legend(output_dir, field):
|
||||
legend_path = output_dir / "weak_cover_heatmap_legend.csv"
|
||||
with legend_path.open("w", newline="", encoding="utf-8-sig") as file:
|
||||
writer = csv.writer(file)
|
||||
writer.writerow(["field", "control_point", "red", "green", "blue", "alpha", "meaning"])
|
||||
for percent, color in zip(EXCELLENT_PERCENT_STEPS, palette_colors_for_steps(len(EXCELLENT_PERCENT_STEPS))):
|
||||
writer.writerow(
|
||||
[field, f"threshold_{int(round(percent * 100))}_percent", *color, HEATMAP_ALPHA, "sorted-value control"]
|
||||
)
|
||||
writer.writerow(["field", "rank_range", "red", "green", "blue", "alpha", "meaning"])
|
||||
rank_ranges = ("top_25_percent", "25_to_50_percent", "50_to_75_percent", "bottom_25_percent")
|
||||
for rank_range, color in zip(rank_ranges, EXCELLENT_COLORS):
|
||||
writer.writerow([field, rank_range, *color, HEATMAP_ALPHA, "ranked-pixel quartile"])
|
||||
writer.writerow([field, "nodata", 0, 0, 0, 0, "transparent no data"])
|
||||
return legend_path
|
||||
|
||||
|
||||
Reference in New Issue
Block a user