512 lines
21 KiB
Python
512 lines
21 KiB
Python
"""竞对信号筛选和精确栅格化。"""
|
|
from shapely import Point
|
|
import csv
|
|
import numpy as np
|
|
import shapely
|
|
from . import config
|
|
from .metrics import grid_metrics_headers
|
|
from .gpkg import iter_geometry_batches
|
|
from .raster_math import market_raster_layout
|
|
from .metrics import metric_row
|
|
from .raster_math import pixel_center_mask_for_bounds
|
|
from .raster_math import rectangle_center_window
|
|
from .raster_math import pixel_center_mask_for_geometry
|
|
from .raster_math import pixel_window_for_bounds
|
|
from .raster_math import pixel_window_from_point
|
|
from .gpkg import quote_identifier
|
|
from .gpkg import require_columns
|
|
from .raster_math import to_float
|
|
from .raster_math import write_rgba_geotiff
|
|
|
|
|
|
def competitor_signal_filter_reason(mobile_weak, mobile_total, competitor_weak, competitor_total):
|
|
if mobile_weak is None or mobile_total is None or competitor_total is None:
|
|
return "invalid_fields"
|
|
if mobile_total <= 0 or mobile_weak < 0 or competitor_total < 0:
|
|
return "invalid_fields"
|
|
mobile_weak_ratio = mobile_weak / mobile_total * 100.0
|
|
if mobile_weak_ratio >= config.COMPETITOR_SIGNAL_MOBILE_WEAK_RATIO_MAX:
|
|
return "mobile_weak_ratio"
|
|
if competitor_total == 0:
|
|
return None
|
|
if competitor_weak is None or competitor_weak < 0:
|
|
return "invalid_fields"
|
|
competitor_weak_ratio = competitor_weak / competitor_total * 100.0
|
|
if competitor_weak_ratio <= config.COMPETITOR_SIGNAL_WEAK_RATIO_MIN:
|
|
return "competitor_weak_ratio"
|
|
return None
|
|
|
|
|
|
def _numeric_column(batch_rows, offset):
|
|
values = np.empty(len(batch_rows), dtype=np.float64)
|
|
for index, row in enumerate(batch_rows):
|
|
value = row[offset]
|
|
if value is None or value == "":
|
|
values[index] = np.nan
|
|
else:
|
|
try:
|
|
values[index] = float(value)
|
|
except (TypeError, ValueError):
|
|
values[index] = np.nan
|
|
return values
|
|
|
|
|
|
def _paint_rectangles(
|
|
batch_rows, fields, raster_fields, selected, bounds,
|
|
minx, maxy, pixel_width, pixel_height, width, height,
|
|
value_sum, value_weight, zero_total_mask, exclusion_counts,
|
|
):
|
|
"""相交的轴对齐格子按整窗填色,避免逐格做点在面内判断。"""
|
|
if not np.any(selected):
|
|
return 0, 0, 0
|
|
offset = {name: 2 + fields.index(name) for name in raster_fields}
|
|
mobile_weak = _numeric_column(batch_rows, offset[config.MOBILE_WEAK_COVER_FIELD])
|
|
mobile_total = _numeric_column(batch_rows, offset[config.MOBILE_TOTAL_FIELD])
|
|
competitor_weak = _numeric_column(batch_rows, offset[config.WEAK_COVER_FIELD])
|
|
competitor_total = _numeric_column(batch_rows, offset[config.EXCELLENT_CELL_FIELD])
|
|
competitor_rsrp = _numeric_column(batch_rows, offset[config.RSRP_FIELD])
|
|
|
|
missing = ~np.isfinite(mobile_weak) | ~np.isfinite(mobile_total) | ~np.isfinite(competitor_total)
|
|
invalid = selected & (missing | (mobile_total <= 0) | (mobile_weak < 0) | (competitor_total < 0))
|
|
exclusion_counts["invalid_fields"] += int(np.count_nonzero(invalid))
|
|
remaining = selected & ~invalid
|
|
mobile_ratio = np.zeros(len(batch_rows), dtype=np.float64)
|
|
np.divide(mobile_weak, mobile_total, out=mobile_ratio, where=remaining)
|
|
mobile_bad = remaining & (mobile_ratio * 100.0 >= config.COMPETITOR_SIGNAL_MOBILE_WEAK_RATIO_MAX)
|
|
exclusion_counts["mobile_weak_ratio"] += int(np.count_nonzero(mobile_bad))
|
|
remaining = remaining & ~mobile_bad
|
|
nonzero = remaining & (competitor_total != 0)
|
|
weak_missing = nonzero & (~np.isfinite(competitor_weak) | (competitor_weak < 0))
|
|
exclusion_counts["invalid_fields"] += int(np.count_nonzero(weak_missing))
|
|
nonzero = nonzero & ~weak_missing
|
|
weak_ratio = np.zeros(len(batch_rows), dtype=np.float64)
|
|
np.divide(competitor_weak, competitor_total, out=weak_ratio, where=nonzero)
|
|
weak_bad = nonzero & (weak_ratio * 100.0 <= config.COMPETITOR_SIGNAL_WEAK_RATIO_MIN)
|
|
exclusion_counts["competitor_weak_ratio"] += int(np.count_nonzero(weak_bad))
|
|
nonzero = nonzero & ~weak_bad
|
|
bad_rsrp = nonzero & (~np.isfinite(competitor_rsrp) | (competitor_rsrp > 0))
|
|
exclusion_counts["invalid_rsrp"] += int(np.count_nonzero(bad_rsrp))
|
|
valued = nonzero & ~bad_rsrp
|
|
zero = remaining & (competitor_total == 0)
|
|
|
|
painted = 0
|
|
zero_cells = 0
|
|
pixels = 0
|
|
for index in np.flatnonzero(zero | valued):
|
|
window = rectangle_center_window(
|
|
bounds[index], minx, maxy, pixel_width, pixel_height, width, height,
|
|
)
|
|
if window is None:
|
|
exclusion_counts["no_center_pixels"] += 1
|
|
continue
|
|
row_start, row_stop, col_start, col_stop = window
|
|
if competitor_total[index] == 0:
|
|
zero_total_mask[row_start:row_stop, col_start:col_stop] = True
|
|
zero_cells += 1
|
|
else:
|
|
value_sum[row_start:row_stop, col_start:col_stop] += competitor_rsrp[index]
|
|
value_weight[row_start:row_stop, col_start:col_stop] += 1
|
|
painted += 1
|
|
pixels += (row_stop - row_start) * (col_stop - col_start)
|
|
return painted, zero_cells, pixels
|
|
|
|
|
|
def competitor_signal_is_eligible(mobile_weak, mobile_total, competitor_weak, competitor_total):
|
|
return competitor_signal_filter_reason(mobile_weak, mobile_total, competitor_weak, competitor_total) is None
|
|
|
|
|
|
def competitor_signal_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(config.COMPETITOR_SIGNAL_RSRP_BREAKS, dtype=np.float32),
|
|
values[valid_mask],
|
|
side="right",
|
|
)
|
|
colors[valid_mask] = np.asarray(config.COMPETITOR_SIGNAL_RSRP_COLORS, dtype=np.uint8)[color_indices]
|
|
return colors, valid_mask
|
|
|
|
|
|
def render_competitor_signal_raster(
|
|
state,
|
|
market,
|
|
output_path,
|
|
minx,
|
|
maxy,
|
|
pixel_width,
|
|
pixel_height,
|
|
width,
|
|
height,
|
|
candidates,
|
|
):
|
|
image = np.full((height, width, 4), config.TRANSPARENT_PIXEL, dtype=np.uint8)
|
|
value_sum = state["value_sum"]
|
|
value_weight = state["value_weight"]
|
|
rsrp_mask = value_weight > 0
|
|
zero_total_mask = state["zero_total_mask"]
|
|
data_mask = rsrp_mask | zero_total_mask
|
|
class_pixel_counts = [0] * len(config.COMPETITOR_SIGNAL_RSRP_COLORS)
|
|
if np.any(rsrp_mask):
|
|
value_raster = np.zeros_like(value_sum)
|
|
np.divide(value_sum, value_weight, out=value_raster, where=rsrp_mask)
|
|
colors, valid_rsrp_mask = competitor_signal_rsrp_rgb_for_values(value_raster)
|
|
render_mask = rsrp_mask & valid_rsrp_mask
|
|
image[render_mask, :3] = colors[render_mask]
|
|
image[zero_total_mask, :3] = config.COMPETITOR_SIGNAL_RSRP_COLORS[0]
|
|
image[data_mask, 3] = config.HEATMAP_ALPHA
|
|
for index, color in enumerate(config.COMPETITOR_SIGNAL_RSRP_COLORS):
|
|
color_mask = data_mask & np.all(image[..., :3] == color, axis=-1)
|
|
class_pixel_counts[index] = int(np.count_nonzero(color_mask))
|
|
|
|
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_competitor_signal",
|
|
"rsrp_breaks": list(config.COMPETITOR_SIGNAL_RSRP_BREAKS),
|
|
"colors": [list(color) for color in config.COMPETITOR_SIGNAL_RSRP_COLORS],
|
|
"class_pixel_counts": class_pixel_counts,
|
|
"zero_total_pixels": int(np.count_nonzero(zero_total_mask)),
|
|
"smooth_radius": 0,
|
|
"width": width,
|
|
"height": height,
|
|
"skipped": False,
|
|
}
|
|
|
|
|
|
def export_market_grid_outputs(
|
|
grid_5g_conn,
|
|
grid_5g_layer,
|
|
grid_5g_rtree,
|
|
market,
|
|
pixel_width,
|
|
pixel_height,
|
|
# user_count_path,
|
|
competitor_signal_path,
|
|
csv_path,
|
|
# grid_4g_source=None,
|
|
max_raster_pixels=None,
|
|
):
|
|
minx, miny, maxx, maxy, pixel_width, pixel_height, width, height, scale_factor = market_raster_layout(
|
|
market.geometry.bounds,
|
|
pixel_width,
|
|
pixel_height,
|
|
max_raster_pixels,
|
|
)
|
|
raster_fields = (
|
|
config.EXCELLENT_CELL_FIELD,
|
|
config.RSRP_FIELD,
|
|
config.WEAK_COVER_FIELD,
|
|
config.MOBILE_TOTAL_FIELD,
|
|
config.MOBILE_WEAK_COVER_FIELD,
|
|
)
|
|
# user_count_records = {}
|
|
competitor_signal_value_sum = np.zeros((height, width), dtype=np.float32)
|
|
competitor_signal_value_weight = np.zeros((height, width), dtype=np.uint16)
|
|
zero_total_mask = np.zeros((height, width), dtype=bool)
|
|
competitor_signal_cells = 0
|
|
zero_total_cells = 0
|
|
exact_geometry_pixels = 0
|
|
exclusion_counts = {
|
|
"invalid_fields": 0,
|
|
"mobile_weak_ratio": 0,
|
|
"competitor_weak_ratio": 0,
|
|
"invalid_rsrp": 0,
|
|
"no_center_pixels": 0,
|
|
}
|
|
|
|
# fields = list(
|
|
# dict.fromkeys(
|
|
# (*CSV_SOURCE_FIELDS, *raster_fields, GRID_ID_FIELD)
|
|
# if csv_path is not None
|
|
# else (*raster_fields, GRID_ID_FIELD)
|
|
# )
|
|
# )
|
|
fields = list(dict.fromkeys((*config.CSV_SOURCE_FIELDS, *raster_fields) if csv_path is not None else raster_fields))
|
|
if csv_path is None and config.CLIP_MODE == "center":
|
|
fields.extend(field for field in ("longitude", "latitude") if field not in fields)
|
|
require_columns(grid_5g_conn, grid_5g_layer.table_name, fields)
|
|
table = quote_identifier(grid_5g_layer.table_name)
|
|
pk = quote_identifier(grid_5g_layer.pk_col)
|
|
geom = quote_identifier(grid_5g_layer.geom_col)
|
|
rtree_table = quote_identifier(grid_5g_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" >= ?
|
|
"""
|
|
params = (maxx, minx, maxy, miny)
|
|
candidates = 0
|
|
# user_count_5g_clipped_rows = 0
|
|
# user_count_5g_invalid_grid_ids = 0
|
|
csv_rows = 0
|
|
csv_skipped = csv_path is None or (csv_path.exists() and not config.OVERWRITE)
|
|
csv_file = None
|
|
csv_writer = None
|
|
if not csv_skipped:
|
|
csv_file = csv_path.open("w", newline="", encoding=config.CSV_ENCODING, errors="replace")
|
|
csv_writer = csv.writer(csv_file)
|
|
csv_writer.writerow(grid_metrics_headers())
|
|
|
|
try:
|
|
shapely.prepare(market.geometry)
|
|
cursor = grid_5g_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)
|
|
widths = geometry_bounds[:, 2] - geometry_bounds[:, 0]
|
|
heights = geometry_bounds[:, 3] - geometry_bounds[:, 1]
|
|
bbox_area = widths * heights
|
|
rectangular = (
|
|
valid_mask
|
|
& (shapely.get_num_coordinates(geometries) == 5)
|
|
& (np.abs(shapely.area(geometries) - bbox_area) <= np.maximum(bbox_area * 1e-6, 1e-18))
|
|
)
|
|
if config.CLIP_MODE == "intersects" and csv_writer is None:
|
|
painted, zero_cells, pixels = _paint_rectangles(
|
|
batch_rows, fields, raster_fields, intersects_mask & rectangular, geometry_bounds,
|
|
minx, maxy, pixel_width, pixel_height, width, height,
|
|
competitor_signal_value_sum, competitor_signal_value_weight, zero_total_mask,
|
|
exclusion_counts,
|
|
)
|
|
competitor_signal_cells += painted
|
|
zero_total_cells += zero_cells
|
|
exact_geometry_pixels += pixels
|
|
slow_indexes = np.flatnonzero(intersects_mask & ~rectangular)
|
|
else:
|
|
slow_indexes = range(len(batch_rows))
|
|
for index in slow_indexes:
|
|
row = batch_rows[index]
|
|
values = dict(zip(fields, row[2:]))
|
|
numeric_values = {field: to_float(values.get(field)) for field in raster_fields}
|
|
|
|
if not valid_mask[index]:
|
|
continue
|
|
intersects_market = bool(intersects_mask[index])
|
|
if intersects_market and csv_writer is not None:
|
|
csv_writer.writerow([market.code, *metric_row(values)])
|
|
csv_rows += 1
|
|
elif intersects_market and csv_path is not None:
|
|
csv_rows += 1
|
|
|
|
if config.CLIP_MODE == "intersects":
|
|
if not intersects_market:
|
|
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
|
|
|
|
# if user_count_path is not None:
|
|
# user_count_5g_clipped_rows += 1
|
|
# if not merge_user_count_record(
|
|
# user_count_records,
|
|
# values.get(GRID_ID_FIELD),
|
|
# window,
|
|
# numeric_values[EXCELLENT_CELL_FIELD],
|
|
# "5G",
|
|
# prefer_geometry=True,
|
|
# ):
|
|
# user_count_5g_invalid_grid_ids += 1
|
|
|
|
competitor_total = numeric_values[config.EXCELLENT_CELL_FIELD]
|
|
competitor_rsrp = numeric_values[config.RSRP_FIELD]
|
|
competitor_weak = numeric_values[config.WEAK_COVER_FIELD]
|
|
mobile_total = numeric_values[config.MOBILE_TOTAL_FIELD]
|
|
mobile_weak = numeric_values[config.MOBILE_WEAK_COVER_FIELD]
|
|
exclusion_reason = competitor_signal_filter_reason(
|
|
mobile_weak,
|
|
mobile_total,
|
|
competitor_weak,
|
|
competitor_total,
|
|
)
|
|
if exclusion_reason is not None:
|
|
exclusion_counts[exclusion_reason] += 1
|
|
continue
|
|
if competitor_total != 0 and (competitor_rsrp is None or competitor_rsrp > 0):
|
|
exclusion_counts["invalid_rsrp"] += 1
|
|
continue
|
|
|
|
signal_window = window if config.CLIP_MODE == "intersects" else pixel_window_for_bounds(
|
|
geometry_bounds[index],
|
|
minx,
|
|
maxy,
|
|
pixel_width,
|
|
pixel_height,
|
|
width,
|
|
height,
|
|
)
|
|
if signal_window is None:
|
|
exclusion_counts["no_center_pixels"] += 1
|
|
continue
|
|
mask_args = (signal_window, minx, maxy, pixel_width, pixel_height)
|
|
if rectangular[index]:
|
|
geometry_mask = pixel_center_mask_for_bounds(geometry_bounds[index], *mask_args)
|
|
else:
|
|
geometry_mask = pixel_center_mask_for_geometry(geometries[index], *mask_args)
|
|
geometry_pixel_count = int(np.count_nonzero(geometry_mask))
|
|
if geometry_pixel_count == 0:
|
|
exclusion_counts["no_center_pixels"] += 1
|
|
continue
|
|
|
|
row_start, row_stop, col_start, col_stop = signal_window
|
|
if competitor_total == 0:
|
|
zero_total_view = zero_total_mask[row_start:row_stop, col_start:col_stop]
|
|
zero_total_view |= geometry_mask
|
|
zero_total_cells += 1
|
|
else:
|
|
value_sum_view = competitor_signal_value_sum[row_start:row_stop, col_start:col_stop]
|
|
value_weight_view = competitor_signal_value_weight[row_start:row_stop, col_start:col_stop]
|
|
value_sum_view[geometry_mask] += competitor_rsrp
|
|
value_weight_view[geometry_mask] += 1
|
|
competitor_signal_cells += 1
|
|
exact_geometry_pixels += geometry_pixel_count
|
|
finally:
|
|
if csv_file is not None:
|
|
csv_file.close()
|
|
shapely.destroy_prepared(market.geometry)
|
|
|
|
# user_count_result = None
|
|
# if user_count_path is not None:
|
|
# if grid_4g_source is None:
|
|
# raise ValueError("生成竞对用户量图层时必须提供 Grid_4G 数据源")
|
|
# grid_4g_conn, grid_4g_layer, grid_4g_rtree = grid_4g_source
|
|
# source_stats = {
|
|
# "5G": {
|
|
# "candidates": candidates,
|
|
# "clipped_rows": user_count_5g_clipped_rows,
|
|
# "invalid_grid_ids": user_count_5g_invalid_grid_ids,
|
|
# }
|
|
# }
|
|
# source_stats["4G"] = collect_user_count_source(
|
|
# user_count_records,
|
|
# grid_4g_conn,
|
|
# grid_4g_layer,
|
|
# grid_4g_rtree,
|
|
# market,
|
|
# minx,
|
|
# maxy,
|
|
# pixel_width,
|
|
# pixel_height,
|
|
# width,
|
|
# height,
|
|
# "4G",
|
|
# )
|
|
# user_count_state = build_merged_user_count_state(user_count_records, height, width)
|
|
# user_count_result = render_ranked_raster(
|
|
# user_count_state,
|
|
# market,
|
|
# user_count_path,
|
|
# minx,
|
|
# maxy,
|
|
# pixel_width,
|
|
# pixel_height,
|
|
# width,
|
|
# height,
|
|
# sum(stats["candidates"] for stats in source_stats.values()),
|
|
# EXCELLENT_COLORS,
|
|
# EXCELLENT_PERCENT_STEPS,
|
|
# )
|
|
# user_count_result.update(merged_user_count_metadata(user_count_records, source_stats))
|
|
# del user_count_state
|
|
|
|
competitor_signal_state = {
|
|
"value_sum": competitor_signal_value_sum,
|
|
"value_weight": competitor_signal_value_weight,
|
|
"zero_total_mask": zero_total_mask,
|
|
"painted_cells": competitor_signal_cells,
|
|
"skipped_no_value": sum(exclusion_counts.values()),
|
|
}
|
|
competitor_signal_result = render_competitor_signal_raster(
|
|
competitor_signal_state,
|
|
market,
|
|
competitor_signal_path,
|
|
minx,
|
|
maxy,
|
|
pixel_width,
|
|
pixel_height,
|
|
width,
|
|
height,
|
|
candidates,
|
|
)
|
|
competitor_signal_result.update({
|
|
"data_source": str(config.GRID_5G_GPKG),
|
|
"uses_merged_user_count": False,
|
|
"geometry_rasterization": "pixel_center_inside_polygon",
|
|
"exact_geometry_pixels": exact_geometry_pixels,
|
|
"mobile_weak_ratio_formula": f"{config.MOBILE_WEAK_COVER_FIELD} / {config.MOBILE_TOTAL_FIELD} * 100",
|
|
"mobile_weak_ratio_operator": "<",
|
|
"mobile_weak_ratio_threshold": config.COMPETITOR_SIGNAL_MOBILE_WEAK_RATIO_MAX,
|
|
"competitor_total_field": config.EXCELLENT_CELL_FIELD,
|
|
"competitor_weak_ratio_formula": f"{config.WEAK_COVER_FIELD} / {config.EXCELLENT_CELL_FIELD} * 100",
|
|
"competitor_weak_ratio_operator": ">",
|
|
"competitor_weak_ratio_threshold": config.COMPETITOR_SIGNAL_WEAK_RATIO_MIN,
|
|
"zero_competitor_total_is_included": True,
|
|
"zero_competitor_total_color": list(config.COMPETITOR_SIGNAL_RSRP_COLORS[0]),
|
|
"zero_competitor_total_cells": zero_total_cells,
|
|
"rsrp_field": config.RSRP_FIELD,
|
|
"eligible_cells": competitor_signal_cells,
|
|
"exclusion_counts": exclusion_counts,
|
|
})
|
|
del (
|
|
competitor_signal_state,
|
|
competitor_signal_value_sum,
|
|
competitor_signal_value_weight,
|
|
zero_total_mask,
|
|
)
|
|
|
|
# for result in (user_count_result, competitor_signal_result):
|
|
for result in (competitor_signal_result,):
|
|
if result is None:
|
|
continue
|
|
result["raster_extent"] = [
|
|
minx,
|
|
maxy - height * pixel_height,
|
|
minx + width * pixel_width,
|
|
maxy,
|
|
]
|
|
result["pixel_width"] = pixel_width
|
|
result["pixel_height"] = pixel_height
|
|
result["resolution_scale_factor"] = scale_factor
|
|
csv_result = None
|
|
if csv_path is not None:
|
|
csv_result = {
|
|
"market_code": market.code,
|
|
"market_name": market.name,
|
|
"output": str(csv_path),
|
|
"candidates": candidates,
|
|
"row_count": csv_rows,
|
|
"skipped": csv_skipped,
|
|
}
|
|
return (
|
|
# user_count_result,
|
|
competitor_signal_result,
|
|
csv_result,
|
|
)
|