fix: 加快竞对信号和采样点生成
This commit is contained in:
@@ -8,6 +8,7 @@ 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 pixel_center_mask_for_geometry
|
||||
from .raster_math import pixel_window_for_bounds
|
||||
from .raster_math import pixel_window_from_point
|
||||
@@ -191,6 +192,14 @@ def export_market_grid_outputs(
|
||||
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))
|
||||
)
|
||||
for index, row in enumerate(batch_rows):
|
||||
values = dict(zip(fields, row[2:]))
|
||||
numeric_values = {field: to_float(values.get(field)) for field in raster_fields}
|
||||
@@ -255,7 +264,7 @@ def export_market_grid_outputs(
|
||||
exclusion_counts["invalid_rsrp"] += 1
|
||||
continue
|
||||
|
||||
signal_window = pixel_window_for_bounds(
|
||||
signal_window = window if config.CLIP_MODE == "intersects" else pixel_window_for_bounds(
|
||||
geometry_bounds[index],
|
||||
minx,
|
||||
maxy,
|
||||
@@ -267,14 +276,11 @@ def export_market_grid_outputs(
|
||||
if signal_window is None:
|
||||
exclusion_counts["no_center_pixels"] += 1
|
||||
continue
|
||||
geometry_mask = pixel_center_mask_for_geometry(
|
||||
geometries[index],
|
||||
signal_window,
|
||||
minx,
|
||||
maxy,
|
||||
pixel_width,
|
||||
pixel_height,
|
||||
)
|
||||
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
|
||||
|
||||
+12
-1
@@ -31,7 +31,12 @@ from .files import safe_filename
|
||||
from .files import write_market_zip
|
||||
|
||||
|
||||
def process_market(market, pixel_width, pixel_height, output_dir):
|
||||
def process_market(market, pixel_width, pixel_height, output_dir, report=None):
|
||||
def note(message):
|
||||
print(message, flush=True)
|
||||
if report:
|
||||
report(message)
|
||||
|
||||
config.check_cancelled()
|
||||
started_at = perf_counter()
|
||||
output_dir = Path(output_dir)
|
||||
@@ -85,6 +90,7 @@ def process_market(market, pixel_width, pixel_height, output_dir):
|
||||
grid_started_at = perf_counter()
|
||||
competitor_signal_result = None
|
||||
if enabled(plan, "competitor"):
|
||||
note(f"正在生成竞对信号:{market.name}")
|
||||
(
|
||||
# user_count_result,
|
||||
competitor_signal_result,
|
||||
@@ -101,6 +107,8 @@ def process_market(market, pixel_width, pixel_height, output_dir):
|
||||
None,
|
||||
# (grid_4g_conn, grid_4g_layer, grid_4g_rtree),
|
||||
)
|
||||
if enabled(plan, "sample"):
|
||||
note(f"正在合并采样点:{market.name}")
|
||||
sample_result = export_sample_grid(
|
||||
grid_5g_conn, grid_5g_layer, grid_5g_rtree,
|
||||
grid_4g_conn, grid_4g_layer, grid_4g_rtree,
|
||||
@@ -109,6 +117,8 @@ def process_market(market, pixel_width, pixel_height, output_dir):
|
||||
grid_elapsed = perf_counter() - grid_started_at
|
||||
|
||||
building_started_at = perf_counter()
|
||||
if enabled(plan, "buildinfo"):
|
||||
note(f"正在导出建筑信息:{market.name}")
|
||||
building_info_result = export_market_building_info_gpkg(
|
||||
building_info_conn,
|
||||
building_info_layer,
|
||||
@@ -140,6 +150,7 @@ def process_market(market, pixel_width, pixel_height, output_dir):
|
||||
boundary_result = export_market_boundary_gpkg(
|
||||
market, market_dir / boundary_filename(market),
|
||||
) if enabled(plan, "boundary") else None
|
||||
note(f"正在写入工程:{market.name}")
|
||||
gis_project_result = copy_gis_project_to_market(
|
||||
config.GIS_PROJECT_SOURCE,
|
||||
gis_project_path,
|
||||
|
||||
@@ -161,7 +161,11 @@ def main(settings=None, progress=None):
|
||||
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)
|
||||
def report(message, completed=index - 1):
|
||||
if progress:
|
||||
progress(completed, total_steps, message)
|
||||
|
||||
outcome = process_market(market, pixel_width, pixel_height, config.OUTPUT_DIR, report)
|
||||
outcomes.append(outcome)
|
||||
if progress:
|
||||
progress(index, total_steps, f"已完成 {market.name}")
|
||||
|
||||
@@ -176,6 +176,15 @@ def pixel_center_mask_for_geometry(geometry, window, minx, maxy, pixel_width, pi
|
||||
return np.asarray(shapely.contains_xy(geometry, x_grid, y_grid), dtype=bool)
|
||||
|
||||
|
||||
def pixel_center_mask_for_bounds(bounds, window, minx, maxy, pixel_width, pixel_height):
|
||||
"""轴对齐矩形的像元中心判断。边界上的中心点不算在内,和多边形 contains 一致。"""
|
||||
row_start, row_stop, col_start, col_stop = window
|
||||
geom_minx, geom_miny, geom_maxx, geom_maxy = bounds
|
||||
cols = minx + (np.arange(col_start, col_stop, dtype=np.float64) + 0.5) * pixel_width
|
||||
rows = maxy - (np.arange(row_start, row_stop, dtype=np.float64) + 0.5) * pixel_height
|
||||
return ((rows > geom_miny) & (rows < geom_maxy))[:, None] & ((cols > geom_minx) & (cols < geom_maxx))[None, :]
|
||||
|
||||
|
||||
def pixel_window_from_point(x, y, minx, maxy, pixel_width, pixel_height, width, height):
|
||||
col = int((x - minx) / pixel_width)
|
||||
row = int((maxy - y) / pixel_height)
|
||||
|
||||
+11
-19
@@ -5,7 +5,7 @@ from pathlib import Path
|
||||
import math
|
||||
import sqlite3
|
||||
|
||||
from shapely import Point, centroid, to_wkb
|
||||
from shapely import Point
|
||||
import shapely
|
||||
|
||||
from . import config
|
||||
@@ -87,11 +87,6 @@ def merge_sample_records(five, four, latitude, meters):
|
||||
return merged
|
||||
|
||||
|
||||
def _meters(lon1, lat1, lon2, lat2):
|
||||
scale_x = 111_320 * math.cos(math.radians((lat1 + lat2) / 2))
|
||||
return math.hypot((lon1 - lon2) * scale_x, (lat1 - lat2) * 110_540)
|
||||
|
||||
|
||||
def _bin(x, y, meters):
|
||||
return math.floor(x / meters), math.floor(y / meters)
|
||||
|
||||
@@ -104,8 +99,10 @@ def _collect(conn, layer, rtree, market):
|
||||
pk = quote_identifier(layer.pk_col)
|
||||
geom = quote_identifier(layer.geom_col)
|
||||
selected = [geom, *(quote_identifier(name) for name in columns)]
|
||||
# 栅格是轴对齐矩形,空间索引的外接框就是图形范围,不必把每个图形拆成 Shapely 再写回。
|
||||
query = f"""
|
||||
select b.{pk}, {", ".join(f"b.{name}" for name in selected)}
|
||||
select b.{pk}, {", ".join(f"b.{name}" for name in selected)},
|
||||
r."minx", r."maxx", r."miny", r."maxy"
|
||||
from {quote_identifier(rtree)} r
|
||||
join {table} b on b.{pk} = r."id"
|
||||
where r."minx" <= ? and r."maxx" >= ? and r."miny" <= ? and r."maxy" >= ?
|
||||
@@ -117,32 +114,27 @@ def _collect(conn, layer, rtree, market):
|
||||
cursor = conn.execute(query, (maxx, minx, maxy, miny))
|
||||
for batch, geometries, valid in iter_geometry_batches(cursor, 1):
|
||||
hits = valid & shapely.intersects(market.geometry, geometries)
|
||||
centers = centroid(geometries)
|
||||
for index, row in enumerate(batch):
|
||||
if not valid[index] or not hits[index]:
|
||||
if not hits[index] or row[1] is None:
|
||||
continue
|
||||
center_lon, center_lat = float(centers[index].x), float(centers[index].y)
|
||||
bounds = (row[7], row[9], row[8], row[10])
|
||||
lon, lat = to_float(row[2]), to_float(row[3])
|
||||
# 属性里的中心点若明显不在该栅格上,改用图形中心,避免空值或 0 把不相邻的栅格拼到一起。
|
||||
if lon is None or lat is None or _meters(lon, lat, center_lon, center_lat) > 20:
|
||||
lon, lat = center_lon, center_lat
|
||||
# 属性里的中心点若落在格子外面,改用外接框中心,避免空值或 0 把不相邻的栅格拼到一起。
|
||||
if lon is None or lat is None or not (bounds[0] <= lon <= bounds[2] and bounds[1] <= lat <= bounds[3]):
|
||||
lon = (bounds[0] + bounds[2]) / 2
|
||||
lat = (bounds[1] + bounds[3]) / 2
|
||||
if config.CLIP_MODE == "center" and not market.geometry.covers(Point(lon, lat)):
|
||||
continue
|
||||
values = [to_float(row[offset]) or 0.0 for offset in range(4, 7)]
|
||||
bounds = geometries[index].bounds
|
||||
rows.append({
|
||||
"lon": lon, "lat": lat, "dl": values[0], "gd": values[1], "yd": values[2],
|
||||
"blob": _gp_blob(geometries[index]), "bounds": bounds,
|
||||
"blob": row[1], "bounds": bounds,
|
||||
})
|
||||
finally:
|
||||
shapely.destroy_prepared(market.geometry)
|
||||
return rows
|
||||
|
||||
|
||||
def _gp_blob(geometry):
|
||||
return b"GP" + bytes((0, 1)) + int(SRS_ID).to_bytes(4, "little", signed=True) + to_wkb(geometry)
|
||||
|
||||
|
||||
def _extent(records, fallback):
|
||||
if not records:
|
||||
return fallback
|
||||
|
||||
Reference in New Issue
Block a user