refactor: 深度优化空间数据处理性能
This commit is contained in:
@@ -13,10 +13,10 @@ from pathlib import Path
|
||||
from time import perf_counter
|
||||
|
||||
import numpy as np
|
||||
import shapely
|
||||
import tifffile
|
||||
from shapely import Point, STRtree, from_wkb
|
||||
from shapely.errors import GEOSException
|
||||
from shapely.prepared import prep
|
||||
|
||||
|
||||
DEFAULT_SOURCE_DIR = Path("source") # 源数据目录,存放 MarketMap.gpkg、grid.gpkg 等输入文件。
|
||||
@@ -70,7 +70,8 @@ PIXEL_HEIGHT = None # 输出像元高度;None 表示自动按 Grid 单元高
|
||||
SCALE = 5.0 # 分辨率倍数;2.0 表示像元宽高减半,放大查看更清晰。
|
||||
SAMPLE_SIZE = 10000 # 自动估算像元大小时抽样读取的 Grid 要素数量。
|
||||
LIMIT = None # 限制处理前 N 个市场网格;None 表示处理全部市场网格。
|
||||
MAX_WORKERS = 2 # 市场网格并行处理进程数;1 表示串行,建议根据内存和磁盘性能设置为 2~4。
|
||||
MAX_WORKERS = 4 # 市场网格并行处理进程数;当前 4 核/32GB 环境实测 4 进程吞吐最佳,内存较小时可降为 2。
|
||||
GEOMETRY_BATCH_SIZE = 10000 # Shapely 批量解析和空间判断的每批要素数;增大可减少循环,过大会增加瞬时内存。
|
||||
MAX_RASTER_PIXELS = 25_000_000 # 单张 TIF 最大像元数;超限时自动降低该市场分辨率,避免内存溢出。
|
||||
CLIP_MODE = "intersects" # 裁切方式:intersects 按几何相交裁切,center 按 Grid 中心点落入裁切。
|
||||
BUILDING_ALLOWED_SRS_IDS = (4326, 100000) # Building 允许的经纬度坐标系 ID;100000 是 CRS84。
|
||||
@@ -232,6 +233,21 @@ def gpkg_blob_to_wkb(blob):
|
||||
return data[8 + envelope_sizes.get(envelope_code, 0):]
|
||||
|
||||
|
||||
def iter_geometry_batches(cursor, geom_index):
|
||||
while True:
|
||||
rows = cursor.fetchmany(GEOMETRY_BATCH_SIZE)
|
||||
if not rows:
|
||||
return
|
||||
|
||||
wkbs = np.empty(len(rows), dtype=object)
|
||||
for index, row in enumerate(rows):
|
||||
geom_blob = row[geom_index]
|
||||
wkbs[index] = gpkg_blob_to_wkb(geom_blob) if geom_blob is not None else None
|
||||
geometries = from_wkb(wkbs, on_invalid="ignore")
|
||||
valid_mask = ~shapely.is_missing(geometries) & ~shapely.is_empty(geometries)
|
||||
yield rows, geometries, valid_mask
|
||||
|
||||
|
||||
def gpkg_primary_key(conn, table_name):
|
||||
for row in conn.execute(f"pragma table_info({quote_identifier(table_name)})"):
|
||||
if row[5]:
|
||||
@@ -404,34 +420,31 @@ def collect_intersecting_features(source_conn, layer, rtree, market):
|
||||
|
||||
geom_index = columns.index(layer.geom_col)
|
||||
pk_index = columns.index(layer.pk_col)
|
||||
prepared_market = prep(market.geometry)
|
||||
rows = []
|
||||
rtree_rows = []
|
||||
extent = None
|
||||
candidates = 0
|
||||
|
||||
for row in source_conn.execute(query, (max_market_x, min_market_x, max_market_y, min_market_y)):
|
||||
candidates += 1
|
||||
geom_blob = row[geom_index]
|
||||
if geom_blob is None:
|
||||
cursor = source_conn.execute(query, (max_market_x, min_market_x, max_market_y, min_market_y))
|
||||
for batch_rows, geometries, valid_mask in iter_geometry_batches(cursor, geom_index):
|
||||
candidates += len(batch_rows)
|
||||
intersects_mask = valid_mask & shapely.intersects(market.geometry, geometries)
|
||||
matched_indexes = np.flatnonzero(intersects_mask)
|
||||
if matched_indexes.size == 0:
|
||||
continue
|
||||
try:
|
||||
geometry = from_wkb(gpkg_blob_to_wkb(geom_blob))
|
||||
except (GEOSException, ValueError):
|
||||
continue
|
||||
if geometry.is_empty or not prepared_market.intersects(geometry):
|
||||
continue
|
||||
|
||||
minx, miny, maxx, maxy = geometry.bounds
|
||||
rows.append(row)
|
||||
rtree_rows.append((row[pk_index], minx, maxx, miny, maxy))
|
||||
if extent is None:
|
||||
extent = [minx, miny, maxx, maxy]
|
||||
else:
|
||||
extent[0] = min(extent[0], minx)
|
||||
extent[1] = min(extent[1], miny)
|
||||
extent[2] = max(extent[2], maxx)
|
||||
extent[3] = max(extent[3], maxy)
|
||||
matched_bounds = shapely.bounds(geometries[matched_indexes])
|
||||
for index, bounds in zip(matched_indexes, matched_bounds):
|
||||
row = batch_rows[int(index)]
|
||||
minx, miny, maxx, maxy = bounds.tolist()
|
||||
rows.append(row)
|
||||
rtree_rows.append((row[pk_index], minx, maxx, miny, maxy))
|
||||
if extent is None:
|
||||
extent = [minx, miny, maxx, maxy]
|
||||
else:
|
||||
extent[0] = min(extent[0], minx)
|
||||
extent[1] = min(extent[1], miny)
|
||||
extent[2] = max(extent[2], maxx)
|
||||
extent[3] = max(extent[3], maxy)
|
||||
|
||||
return columns, rows, rtree_rows, tuple(extent) if extent else None, candidates
|
||||
|
||||
@@ -510,21 +523,15 @@ def collect_intersecting_metric_features(source_conn, layer, rtree, market, fiel
|
||||
and r."maxy" >= ?
|
||||
"""
|
||||
|
||||
prepared_market = prep(market.geometry)
|
||||
rows = []
|
||||
candidates = 0
|
||||
for row in source_conn.execute(query, (max_market_x, min_market_x, max_market_y, min_market_y)):
|
||||
candidates += 1
|
||||
geom_blob = row[1]
|
||||
if geom_blob is None:
|
||||
continue
|
||||
try:
|
||||
geometry = from_wkb(gpkg_blob_to_wkb(geom_blob))
|
||||
except (GEOSException, ValueError):
|
||||
continue
|
||||
if geometry.is_empty or not prepared_market.intersects(geometry):
|
||||
continue
|
||||
rows.append((dict(zip(fields, row[2:])), geometry))
|
||||
cursor = source_conn.execute(query, (max_market_x, min_market_x, max_market_y, min_market_y))
|
||||
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)
|
||||
for index in np.flatnonzero(intersects_mask):
|
||||
row = batch_rows[int(index)]
|
||||
rows.append((dict(zip(fields, row[2:])), geometries[index]))
|
||||
|
||||
return rows, candidates
|
||||
|
||||
@@ -549,18 +556,14 @@ def load_building_name_index(building_info_conn, layer, rtree, bounds):
|
||||
and r."maxy" >= ?
|
||||
order by b.{pk}
|
||||
"""
|
||||
for raw_name, geom_blob in building_info_conn.execute(query, (maxx, minx, maxy, miny)):
|
||||
name = csv_text(raw_name)
|
||||
if not name or geom_blob is None:
|
||||
continue
|
||||
try:
|
||||
geometry = from_wkb(gpkg_blob_to_wkb(geom_blob))
|
||||
except (GEOSException, ValueError):
|
||||
continue
|
||||
if geometry.is_empty:
|
||||
continue
|
||||
geometries.append(geometry)
|
||||
names.append(name)
|
||||
cursor = building_info_conn.execute(query, (maxx, minx, maxy, miny))
|
||||
for batch_rows, batch_geometries, valid_mask in iter_geometry_batches(cursor, 1):
|
||||
for index in np.flatnonzero(valid_mask):
|
||||
name = csv_text(batch_rows[int(index)][0])
|
||||
if not name:
|
||||
continue
|
||||
geometries.append(batch_geometries[index])
|
||||
names.append(name)
|
||||
if not geometries:
|
||||
return None
|
||||
return STRtree(geometries), geometries, names
|
||||
@@ -586,6 +589,46 @@ def match_building_info_name(name_index, geometry):
|
||||
return best_name
|
||||
|
||||
|
||||
def match_building_info_names(name_index, building_geometries):
|
||||
if name_index is None or not building_geometries:
|
||||
return [""] * len(building_geometries)
|
||||
|
||||
tree, info_geometries, names = name_index
|
||||
building_array = np.asarray(building_geometries, dtype=object)
|
||||
info_array = np.asarray(info_geometries, dtype=object)
|
||||
pairs = tree.query(building_array, predicate="intersects")
|
||||
if pairs.shape[1] == 0:
|
||||
return [""] * len(building_geometries)
|
||||
|
||||
result = np.full(len(building_geometries), "", dtype=object)
|
||||
names_array = np.asarray(names, dtype=object)
|
||||
match_counts = np.bincount(pairs[0], minlength=len(building_geometries))
|
||||
single_pair_mask = match_counts[pairs[0]] == 1
|
||||
single_pairs = pairs[:, single_pair_mask]
|
||||
result[single_pairs[0]] = names_array[single_pairs[1]]
|
||||
|
||||
multiple_pairs = pairs[:, ~single_pair_mask]
|
||||
if multiple_pairs.shape[1]:
|
||||
try:
|
||||
areas = shapely.area(
|
||||
shapely.intersection(
|
||||
building_array[multiple_pairs[0]],
|
||||
info_array[multiple_pairs[1]],
|
||||
)
|
||||
)
|
||||
except GEOSException:
|
||||
return [match_building_info_name(name_index, geometry) for geometry in building_geometries]
|
||||
|
||||
pair_positions = np.arange(multiple_pairs.shape[1])
|
||||
order = np.lexsort((pair_positions, -areas, multiple_pairs[0]))
|
||||
ordered_sources = multiple_pairs[0][order]
|
||||
_, first_positions = np.unique(ordered_sources, return_index=True)
|
||||
best_pair_positions = order[first_positions]
|
||||
result[multiple_pairs[0, best_pair_positions]] = names_array[multiple_pairs[1, best_pair_positions]]
|
||||
|
||||
return result.tolist()
|
||||
|
||||
|
||||
def write_metric_csv(output_path, headers, rows):
|
||||
if output_path.exists() and not OVERWRITE:
|
||||
return True
|
||||
@@ -627,16 +670,8 @@ def export_market_building_metrics_csv(
|
||||
market,
|
||||
CSV_SOURCE_FIELDS,
|
||||
)
|
||||
building_bounds = None
|
||||
for _values, geometry in rows:
|
||||
minx, miny, maxx, maxy = geometry.bounds
|
||||
if building_bounds is None:
|
||||
building_bounds = [minx, miny, maxx, maxy]
|
||||
else:
|
||||
building_bounds[0] = min(building_bounds[0], minx)
|
||||
building_bounds[1] = min(building_bounds[1], miny)
|
||||
building_bounds[2] = max(building_bounds[2], maxx)
|
||||
building_bounds[3] = max(building_bounds[3], maxy)
|
||||
building_geometries = [geometry for _values, geometry in rows]
|
||||
building_bounds = shapely.total_bounds(building_geometries) if building_geometries else None
|
||||
building_name_index = load_building_name_index(
|
||||
building_info_conn,
|
||||
building_info_layer,
|
||||
@@ -658,8 +693,8 @@ def export_market_building_metrics_csv(
|
||||
]
|
||||
csv_rows = []
|
||||
matched_names = 0
|
||||
for values, geometry in rows:
|
||||
building_name = match_building_info_name(building_name_index, geometry)
|
||||
building_names = match_building_info_names(building_name_index, building_geometries)
|
||||
for (values, _geometry), building_name in zip(rows, building_names):
|
||||
if building_name:
|
||||
matched_names += 1
|
||||
common_row = metric_row(values)
|
||||
@@ -805,12 +840,8 @@ def convolve_axis(array, kernel, axis):
|
||||
pad_width = [(0, 0)] * array.ndim
|
||||
pad_width[axis] = (radius, radius)
|
||||
padded = np.pad(array, pad_width, mode="edge")
|
||||
moved = np.moveaxis(padded, axis, 0)
|
||||
output = np.empty_like(np.moveaxis(array, axis, 0), dtype=np.float32)
|
||||
for index in range(output.shape[0]):
|
||||
window = moved[index:index + kernel.size]
|
||||
output[index] = np.tensordot(kernel, window, axes=(0, 0))
|
||||
return np.moveaxis(output, 0, axis)
|
||||
windows = np.lib.stride_tricks.sliding_window_view(padded, kernel.size, axis=axis)
|
||||
return (windows @ kernel).astype(np.float32, copy=False)
|
||||
|
||||
|
||||
def gaussian_blur(array, radius):
|
||||
@@ -822,6 +853,9 @@ def gaussian_blur(array, radius):
|
||||
def to_float(value):
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, (int, float)):
|
||||
number = float(value)
|
||||
return number if math.isfinite(number) else None
|
||||
try:
|
||||
text = str(value).strip()
|
||||
if not text:
|
||||
@@ -1036,7 +1070,6 @@ def export_market_grid_outputs(
|
||||
and r."maxy" >= ?
|
||||
"""
|
||||
params = (maxx, minx, maxy, miny)
|
||||
prepared_market = prep(market.geometry)
|
||||
candidates = 0
|
||||
csv_rows = 0
|
||||
csv_skipped = csv_path.exists() and not OVERWRITE
|
||||
@@ -1048,67 +1081,63 @@ def export_market_grid_outputs(
|
||||
csv_writer.writerow(grid_metrics_headers())
|
||||
|
||||
try:
|
||||
for row in grid_conn.execute(query, params):
|
||||
candidates += 1
|
||||
geom_blob = row[1]
|
||||
values = dict(zip(fields, row[2:]))
|
||||
numeric_values = {field: to_float(values.get(field)) for field in raster_fields}
|
||||
for field, value in numeric_values.items():
|
||||
if value is None:
|
||||
skipped_no_value[field] += 1
|
||||
cursor = grid_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):
|
||||
values = dict(zip(fields, row[2:]))
|
||||
numeric_values = {field: to_float(values.get(field)) for field in raster_fields}
|
||||
for field, value in numeric_values.items():
|
||||
if value is None:
|
||||
skipped_no_value[field] += 1
|
||||
|
||||
if geom_blob is None:
|
||||
continue
|
||||
try:
|
||||
grid_geometry = from_wkb(gpkg_blob_to_wkb(geom_blob))
|
||||
except (GEOSException, ValueError):
|
||||
continue
|
||||
if grid_geometry.is_empty:
|
||||
continue
|
||||
|
||||
intersects_market = prepared_market.intersects(grid_geometry)
|
||||
if intersects_market and csv_writer is not None:
|
||||
csv_writer.writerow([market.code, *metric_row(values)])
|
||||
csv_rows += 1
|
||||
elif intersects_market:
|
||||
csv_rows += 1
|
||||
|
||||
if CLIP_MODE == "intersects":
|
||||
if not intersects_market:
|
||||
if not valid_mask[index]:
|
||||
continue
|
||||
window = pixel_window_for_bounds(
|
||||
grid_geometry.bounds,
|
||||
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 prepared_market.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
|
||||
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:
|
||||
csv_rows += 1
|
||||
|
||||
row_start, row_stop, col_start, col_stop = window
|
||||
for field, value in numeric_values.items():
|
||||
if value is not None:
|
||||
painted_cells[field] += 1
|
||||
raster_cells.append(
|
||||
(
|
||||
row_start,
|
||||
row_stop,
|
||||
col_start,
|
||||
col_stop,
|
||||
numeric_values[RSRP_FIELD],
|
||||
numeric_values[EXCELLENT_CELL_FIELD],
|
||||
numeric_values[WEAK_COVER_FIELD],
|
||||
if 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
|
||||
|
||||
row_start, row_stop, col_start, col_stop = window
|
||||
for field, value in numeric_values.items():
|
||||
if value is not None:
|
||||
painted_cells[field] += 1
|
||||
raster_cells.append(
|
||||
(
|
||||
row_start,
|
||||
row_stop,
|
||||
col_start,
|
||||
col_stop,
|
||||
numeric_values[RSRP_FIELD],
|
||||
numeric_values[EXCELLENT_CELL_FIELD],
|
||||
numeric_values[WEAK_COVER_FIELD],
|
||||
)
|
||||
)
|
||||
)
|
||||
finally:
|
||||
if csv_file is not None:
|
||||
csv_file.close()
|
||||
@@ -1336,6 +1365,8 @@ def main():
|
||||
raise ValueError("SCALE 必须大于 0")
|
||||
if MAX_WORKERS <= 0:
|
||||
raise ValueError("MAX_WORKERS 必须大于 0")
|
||||
if GEOMETRY_BATCH_SIZE <= 0:
|
||||
raise ValueError("GEOMETRY_BATCH_SIZE 必须大于 0")
|
||||
if MAX_RASTER_PIXELS is not None and MAX_RASTER_PIXELS <= 0:
|
||||
raise ValueError("MAX_RASTER_PIXELS 必须大于 0 或设置为 None")
|
||||
if CLIP_MODE not in {"intersects", "center"}:
|
||||
|
||||
Reference in New Issue
Block a user