feat: 新增模块化Streamlit本地工具箱
This commit is contained in:
@@ -0,0 +1,426 @@
|
||||
"""已停用用户量算法,保留恢复依据。"""
|
||||
from shapely import Point
|
||||
import numpy as np
|
||||
import shapely
|
||||
from . import config
|
||||
from .gpkg import build_summary_market
|
||||
from .gpkg import iter_geometry_batches
|
||||
from .raster_math import market_raster_layout
|
||||
from .raster_math import pixel_window_for_bounds
|
||||
from .raster_math import pixel_window_from_point
|
||||
from .gpkg import quote_identifier
|
||||
from .raster_math import ranked_pixel_rgb_for_values
|
||||
from .raster_math import ranked_pixel_rgb_for_values_with_thresholds
|
||||
from .gpkg import require_columns
|
||||
from .raster_math import smooth_rgb_inside_mask
|
||||
from .raster_math import to_float
|
||||
from .raster_math import write_rgba_geotiff
|
||||
|
||||
|
||||
def excellent_heatmap_raster_filename(_field):
|
||||
return config.USER_COUNT_OUTPUT_FILENAME
|
||||
|
||||
|
||||
def render_ranked_raster(
|
||||
state,
|
||||
market,
|
||||
output_path,
|
||||
minx,
|
||||
maxy,
|
||||
pixel_width,
|
||||
pixel_height,
|
||||
width,
|
||||
height,
|
||||
candidates,
|
||||
colors,
|
||||
percent_steps,
|
||||
):
|
||||
image = np.full((height, width, 4), config.TRANSPARENT_PIXEL, dtype=np.uint8)
|
||||
value_sum = state["value_sum"]
|
||||
value_weight = state["value_weight"]
|
||||
data_mask = value_weight > 0
|
||||
thresholds = []
|
||||
rank_pixel_counts = []
|
||||
if np.any(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,
|
||||
colors,
|
||||
percent_steps,
|
||||
)
|
||||
smoothed_rgb = smooth_rgb_inside_mask(ranked_rgb, data_mask, config.HEATMAP_SMOOTH_RADIUS)
|
||||
image[data_mask, :3] = smoothed_rgb[data_mask]
|
||||
image[data_mask, 3] = config.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"],
|
||||
"threshold_value_count": int(np.count_nonzero(data_mask)),
|
||||
"thresholds": thresholds,
|
||||
"rank_pixel_counts": rank_pixel_counts,
|
||||
"percent_steps": list(percent_steps),
|
||||
"width": width,
|
||||
"height": height,
|
||||
"skipped": False,
|
||||
}
|
||||
|
||||
|
||||
def normalized_grid_id(value):
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, bytes):
|
||||
value = value.decode("utf-8", errors="replace")
|
||||
normalized = str(value).strip()
|
||||
return normalized or None
|
||||
|
||||
|
||||
def merge_user_count_record(records, grid_id, window, value, source_name, prefer_geometry=False):
|
||||
grid_id = normalized_grid_id(grid_id)
|
||||
if grid_id is None:
|
||||
return False
|
||||
record = records.get(grid_id)
|
||||
if record is None:
|
||||
record = {
|
||||
"window": window,
|
||||
"value_sum": 0.0,
|
||||
"has_value": False,
|
||||
"sources": set(),
|
||||
}
|
||||
records[grid_id] = record
|
||||
elif prefer_geometry:
|
||||
record["window"] = window
|
||||
record["sources"].add(source_name)
|
||||
if value is not None:
|
||||
record["value_sum"] += value
|
||||
record["has_value"] = True
|
||||
return True
|
||||
|
||||
|
||||
def collect_user_count_source(
|
||||
records,
|
||||
conn,
|
||||
layer,
|
||||
rtree,
|
||||
market,
|
||||
minx,
|
||||
maxy,
|
||||
pixel_width,
|
||||
pixel_height,
|
||||
width,
|
||||
height,
|
||||
source_name,
|
||||
prefer_geometry=False,
|
||||
):
|
||||
fields = [config.GRID_ID_FIELD, config.EXCELLENT_CELL_FIELD]
|
||||
if config.CLIP_MODE == "center":
|
||||
fields.extend(("longitude", "latitude"))
|
||||
require_columns(conn, layer.table_name, fields)
|
||||
table = quote_identifier(layer.table_name)
|
||||
pk = quote_identifier(layer.pk_col)
|
||||
geom = quote_identifier(layer.geom_col)
|
||||
rtree_table = quote_identifier(rtree)
|
||||
field_sql = ", ".join(f"b.{quote_identifier(field)}" for field in fields)
|
||||
query = f"""
|
||||
select b.{pk}, b.{geom}, {field_sql}
|
||||
from {rtree_table} r
|
||||
join {table} b on b.{pk} = r."id"
|
||||
where r."minx" <= ?
|
||||
and r."maxx" >= ?
|
||||
and r."miny" <= ?
|
||||
and r."maxy" >= ?
|
||||
"""
|
||||
market_minx, market_miny, market_maxx, market_maxy = market.geometry.bounds
|
||||
params = (market_maxx, market_minx, market_maxy, market_miny)
|
||||
candidates = 0
|
||||
clipped_rows = 0
|
||||
invalid_grid_ids = 0
|
||||
try:
|
||||
shapely.prepare(market.geometry)
|
||||
cursor = conn.execute(query, params)
|
||||
for batch_rows, geometries, valid_mask in iter_geometry_batches(cursor, 1):
|
||||
candidates += len(batch_rows)
|
||||
intersects_mask = valid_mask & shapely.intersects(market.geometry, geometries)
|
||||
geometry_bounds = shapely.bounds(geometries)
|
||||
for index, row in enumerate(batch_rows):
|
||||
if not valid_mask[index]:
|
||||
continue
|
||||
values = dict(zip(fields, row[2:]))
|
||||
if config.CLIP_MODE == "intersects":
|
||||
if not bool(intersects_mask[index]):
|
||||
continue
|
||||
window = pixel_window_for_bounds(
|
||||
geometry_bounds[index],
|
||||
minx,
|
||||
maxy,
|
||||
pixel_width,
|
||||
pixel_height,
|
||||
width,
|
||||
height,
|
||||
)
|
||||
else:
|
||||
lon = to_float(values.get("longitude"))
|
||||
lat = to_float(values.get("latitude"))
|
||||
if lon is None or lat is None or not market.geometry.covers(Point(lon, lat)):
|
||||
continue
|
||||
window = pixel_window_from_point(
|
||||
lon,
|
||||
lat,
|
||||
minx,
|
||||
maxy,
|
||||
pixel_width,
|
||||
pixel_height,
|
||||
width,
|
||||
height,
|
||||
)
|
||||
if window is None:
|
||||
continue
|
||||
clipped_rows += 1
|
||||
if not merge_user_count_record(
|
||||
records,
|
||||
values.get(config.GRID_ID_FIELD),
|
||||
window,
|
||||
to_float(values.get(config.EXCELLENT_CELL_FIELD)),
|
||||
source_name,
|
||||
prefer_geometry,
|
||||
):
|
||||
invalid_grid_ids += 1
|
||||
finally:
|
||||
shapely.destroy_prepared(market.geometry)
|
||||
return {
|
||||
"candidates": candidates,
|
||||
"clipped_rows": clipped_rows,
|
||||
"invalid_grid_ids": invalid_grid_ids,
|
||||
}
|
||||
|
||||
|
||||
def build_merged_user_count_state(records, height, width, row_offset=0, col_offset=0):
|
||||
value_sum = np.zeros((height, width), dtype=np.float32)
|
||||
value_weight = np.zeros((height, width), dtype=np.uint16)
|
||||
painted_cells = 0
|
||||
skipped_no_value = 0
|
||||
for record in records.values():
|
||||
if not record["has_value"]:
|
||||
skipped_no_value += 1
|
||||
continue
|
||||
row_start, row_stop, col_start, col_stop = record["window"]
|
||||
row_start -= row_offset
|
||||
row_stop -= row_offset
|
||||
col_start -= col_offset
|
||||
col_stop -= col_offset
|
||||
value_sum[row_start:row_stop, col_start:col_stop] += record["value_sum"]
|
||||
value_weight[row_start:row_stop, col_start:col_stop] += 1
|
||||
painted_cells += 1
|
||||
return {
|
||||
"value_sum": value_sum,
|
||||
"value_weight": value_weight,
|
||||
"painted_cells": painted_cells,
|
||||
"skipped_no_value": skipped_no_value,
|
||||
}
|
||||
|
||||
|
||||
def render_merged_user_count_records(records, canvas_height, canvas_width, thresholds=None):
|
||||
valid_records = [record for record in records.values() if record["has_value"]]
|
||||
if not valid_records:
|
||||
empty_mask = np.zeros((0, 0), dtype=bool)
|
||||
empty_rgb = np.zeros((0, 0, 3), dtype=np.uint8)
|
||||
return {
|
||||
"window": (0, 0, 0, 0),
|
||||
"data_mask": empty_mask,
|
||||
"rgb": empty_rgb,
|
||||
"thresholds": [],
|
||||
"rank_pixel_counts": [],
|
||||
"painted_cells": 0,
|
||||
"skipped_no_value": len(records),
|
||||
}
|
||||
|
||||
row_start = min(record["window"][0] for record in valid_records)
|
||||
row_stop = max(record["window"][1] for record in valid_records)
|
||||
col_start = min(record["window"][2] for record in valid_records)
|
||||
col_stop = max(record["window"][3] for record in valid_records)
|
||||
padding = config.HEATMAP_SMOOTH_RADIUS
|
||||
row_start = max(0, row_start - padding)
|
||||
row_stop = min(canvas_height, row_stop + padding)
|
||||
col_start = max(0, col_start - padding)
|
||||
col_stop = min(canvas_width, col_stop + padding)
|
||||
|
||||
state = build_merged_user_count_state(
|
||||
records,
|
||||
row_stop - row_start,
|
||||
col_stop - col_start,
|
||||
row_offset=row_start,
|
||||
col_offset=col_start,
|
||||
)
|
||||
value_sum = state["value_sum"]
|
||||
value_weight = state["value_weight"]
|
||||
data_mask = value_weight > 0
|
||||
value_raster = np.zeros_like(value_sum)
|
||||
np.divide(value_sum, value_weight, out=value_raster, where=data_mask)
|
||||
if thresholds:
|
||||
ranked_rgb, rank_pixel_counts = ranked_pixel_rgb_for_values_with_thresholds(
|
||||
value_raster,
|
||||
data_mask,
|
||||
config.EXCELLENT_COLORS,
|
||||
thresholds,
|
||||
)
|
||||
applied_thresholds = [float(value) for value in thresholds]
|
||||
else:
|
||||
ranked_rgb, applied_thresholds, rank_pixel_counts = ranked_pixel_rgb_for_values(
|
||||
value_raster,
|
||||
data_mask,
|
||||
config.EXCELLENT_COLORS,
|
||||
config.EXCELLENT_PERCENT_STEPS,
|
||||
)
|
||||
smoothed_rgb = smooth_rgb_inside_mask(ranked_rgb, data_mask, config.HEATMAP_SMOOTH_RADIUS)
|
||||
return {
|
||||
"window": (row_start, row_stop, col_start, col_stop),
|
||||
"data_mask": data_mask,
|
||||
"rgb": smoothed_rgb,
|
||||
"thresholds": applied_thresholds,
|
||||
"rank_pixel_counts": rank_pixel_counts,
|
||||
"painted_cells": state["painted_cells"],
|
||||
"skipped_no_value": state["skipped_no_value"],
|
||||
}
|
||||
|
||||
|
||||
def merged_user_count_metadata(records, source_stats):
|
||||
shared_grids = 0
|
||||
five_g_only_grids = 0
|
||||
four_g_only_grids = 0
|
||||
for record in records.values():
|
||||
sources = record["sources"]
|
||||
if sources == {"5G", "4G"}:
|
||||
shared_grids += 1
|
||||
elif "5G" in sources:
|
||||
five_g_only_grids += 1
|
||||
elif "4G" in sources:
|
||||
four_g_only_grids += 1
|
||||
return {
|
||||
"data_source_mode": "Grid_5G + Grid_4G sum by grid20_id",
|
||||
"grid_id_field": config.GRID_ID_FIELD,
|
||||
"value_field": config.EXCELLENT_CELL_FIELD,
|
||||
"merge_rule": "union grid20_id; sum mro_total_dl for duplicate ids",
|
||||
"merged_grid_count": len(records),
|
||||
"shared_grid_count": shared_grids,
|
||||
"five_g_only_grid_count": five_g_only_grids,
|
||||
"four_g_only_grid_count": four_g_only_grids,
|
||||
"source_stats": source_stats,
|
||||
}
|
||||
|
||||
|
||||
def render_summary_user_count_by_market(
|
||||
grid_sources,
|
||||
markets,
|
||||
pixel_width,
|
||||
pixel_height,
|
||||
output_path,
|
||||
max_raster_pixels,
|
||||
market_thresholds=None,
|
||||
):
|
||||
summary_market = build_summary_market(markets)
|
||||
minx, miny, maxx, maxy, pixel_width, pixel_height, width, height, scale_factor = market_raster_layout(
|
||||
summary_market.geometry.bounds,
|
||||
pixel_width,
|
||||
pixel_height,
|
||||
max_raster_pixels,
|
||||
)
|
||||
image = np.full((height, width, 4), config.TRANSPARENT_PIXEL, dtype=np.uint8)
|
||||
market_results = []
|
||||
total_candidates = 0
|
||||
total_painted_cells = 0
|
||||
total_skipped_no_value = 0
|
||||
for market in markets:
|
||||
records = {}
|
||||
source_stats = {}
|
||||
for source_name, conn, layer, rtree in grid_sources:
|
||||
source_stats[source_name] = collect_user_count_source(
|
||||
records,
|
||||
conn,
|
||||
layer,
|
||||
rtree,
|
||||
market,
|
||||
minx,
|
||||
maxy,
|
||||
pixel_width,
|
||||
pixel_height,
|
||||
width,
|
||||
height,
|
||||
source_name,
|
||||
prefer_geometry=source_name == "5G",
|
||||
)
|
||||
candidates = sum(stats["candidates"] for stats in source_stats.values())
|
||||
render_result = render_merged_user_count_records(
|
||||
records,
|
||||
height,
|
||||
width,
|
||||
(market_thresholds or {}).get(market.code),
|
||||
)
|
||||
painted_cells = render_result["painted_cells"]
|
||||
skipped_no_value = render_result["skipped_no_value"]
|
||||
data_mask = render_result["data_mask"]
|
||||
thresholds = render_result["thresholds"]
|
||||
rank_pixel_counts = render_result["rank_pixel_counts"]
|
||||
data_pixels = int(np.count_nonzero(data_mask))
|
||||
if data_pixels:
|
||||
row_start, row_stop, col_start, col_stop = render_result["window"]
|
||||
target = image[row_start:row_stop, col_start:col_stop]
|
||||
target[data_mask, :3] = render_result["rgb"][data_mask]
|
||||
target[data_mask, 3] = config.HEATMAP_ALPHA
|
||||
|
||||
total_candidates += candidates
|
||||
total_painted_cells += painted_cells
|
||||
total_skipped_no_value += skipped_no_value
|
||||
market_result = {
|
||||
"market_code": market.code,
|
||||
"market_name": market.name,
|
||||
"candidates": candidates,
|
||||
"painted_cells": painted_cells,
|
||||
"data_pixels": data_pixels,
|
||||
"skipped_no_value": skipped_no_value,
|
||||
"thresholds": thresholds,
|
||||
"threshold_source": "market_zip" if (market_thresholds or {}).get(market.code) else "summary_raster",
|
||||
"rank_pixel_counts": rank_pixel_counts,
|
||||
"render_window": list(render_result["window"]),
|
||||
"render_buffer_pixels": int(data_mask.size),
|
||||
}
|
||||
market_result.update(merged_user_count_metadata(records, source_stats))
|
||||
market_results.append(market_result)
|
||||
|
||||
write_rgba_geotiff(output_path, image, minx, maxy, pixel_width, pixel_height)
|
||||
return {
|
||||
"market_code": summary_market.code,
|
||||
"market_name": summary_market.name,
|
||||
"output": str(output_path),
|
||||
"candidates": total_candidates,
|
||||
"painted_cells": total_painted_cells,
|
||||
"data_pixels": int(np.count_nonzero(image[..., 3])),
|
||||
"skipped_no_value": total_skipped_no_value,
|
||||
"threshold_value_count": int(np.count_nonzero(image[..., 3])),
|
||||
"thresholds": None,
|
||||
"rank_pixel_counts": None,
|
||||
"percent_steps": list(config.EXCELLENT_PERCENT_STEPS),
|
||||
"color_scope": "per_market",
|
||||
"threshold_source": "market_zip",
|
||||
"render_scope": "market_local_window",
|
||||
"render_padding_pixels": config.HEATMAP_SMOOTH_RADIUS,
|
||||
"market_results": market_results,
|
||||
"width": width,
|
||||
"height": height,
|
||||
"raster_extent": [
|
||||
minx,
|
||||
maxy - height * pixel_height,
|
||||
minx + width * pixel_width,
|
||||
maxy,
|
||||
],
|
||||
"pixel_width": pixel_width,
|
||||
"pixel_height": pixel_height,
|
||||
"resolution_scale_factor": scale_factor,
|
||||
"skipped": False,
|
||||
}
|
||||
Reference in New Issue
Block a user