From 270dd92c9bb9dddd2ddb094114cc5f33782214d1 Mon Sep 17 00:00:00 2001 From: RBP15P Date: Sat, 18 Jul 2026 14:58:29 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E6=B7=B1=E5=BA=A6=E4=BC=98?= =?UTF-8?q?=E5=8C=96=E7=A9=BA=E9=97=B4=E6=95=B0=E6=8D=AE=E5=A4=84=E7=90=86?= =?UTF-8?q?=E6=80=A7=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 13 +- aidocs/project_context.md | 12 +- main.py | 281 +++++++++++++++++++++----------------- tests/test_main.py | 31 +++++ 4 files changed, 204 insertions(+), 133 deletions(-) diff --git a/README.md b/README.md index b7a6445..5f36875 100644 --- a/README.md +++ b/README.md @@ -180,7 +180,8 @@ CSV 中的 `移动信号` 和 `竟对信号` 使用同一套文字等级: | --- | --- | --- | | `OUTPUT_DIR` | `output` | 输出目录 | | `LIMIT` | `None` | `None` 表示处理全部市场网格 | -| `MAX_WORKERS` | `2` | 市场网格并行处理进程数;内存和磁盘充足时可尝试 `3` 或 `4` | +| `MAX_WORKERS` | `4` | 市场网格并行处理进程数;当前 4 核、32GB、NVMe 环境实测 4 进程吞吐最佳 | +| `GEOMETRY_BATCH_SIZE` | `10000` | Shapely 批量解析和空间判断的每批要素数,通常无需修改 | | `MAX_RASTER_PIXELS` | `25000000` | 单张 TIF 最大像元数;超限市场自动降低分辨率,防止内存溢出 | | `SCALE` | `5.0` | 分辨率倍数,越大输出越清晰,文件也越大 | | `CLIP_MODE` | `intersects` | Grid 热力图裁切模式 | @@ -193,7 +194,9 @@ CSV 中的 `移动信号` 和 `竟对信号` 使用同一套文字等级: 当前处理流程已做以下加速: - 同一市场的 Grid 数据只执行一次 RTree 查询和几何相交判断,同时缓存像元窗口并写出 `栅格指标.csv`;三张 TIF 顺序复用栅格矩阵内存。 -- 楼宇名称匹配使用市场内 STRtree 内存空间索引,避免逐栋楼宇重复查询 BuildingInfo 数据库。 +- Grid、Building 和 BuildingInfo 使用 Shapely 批量解析 WKB、判断几何相交并提取边界,减少大量 Python 逐要素调用。 +- 热力图平滑使用 NumPy 滑动窗口矩阵乘法,一次处理完整像元矩阵,不再逐行执行卷积。 +- 楼宇名称匹配使用市场内 STRtree 批量空间查询,仅对存在多个候选的建筑计算相交面积,避免逐栋楼重复查询数据库和无效面积计算。 - 不同市场网格使用独立进程并行处理,每个进程自行打开只读 GeoPackage 连接并写入独立 zip。 - 单市场范围过大时按 `MAX_RASTER_PIXELS` 自动调整像元大小,结果中记录实际像元尺寸和分辨率调整系数。 - zip 和 `summary.json` 使用临时文件完成后原子替换,处理中断时不会先删除已有成果。 @@ -201,6 +204,8 @@ CSV 中的 `移动信号` 和 `竟对信号` 使用同一套文字等级: 并发建议: -- 普通办公电脑建议 `MAX_WORKERS = 2`。 -- 内存充足且数据位于 SSD 时可尝试 `3` 或 `4`。 +- 当前 4 核 8 线程、32GB、NVMe 环境建议保持 `MAX_WORKERS = 4`。 +- 内存小于 16GB 或机械硬盘环境建议降为 `2`。 - 如果出现内存占用过高或磁盘持续满负载,应降低并发数。 + +当前环境基准:`1-城区蓬江` 单市场由 23.56 秒降至 11.66 秒;前 4 个市场使用 4 进程由 55.6 秒降至 21.4 秒;约 2495 万像元的 `16-台山海宴` 由约 69 秒降至 25.2 秒。 diff --git a/aidocs/project_context.md b/aidocs/project_context.md index e42c9eb..5a1cf3e 100644 --- a/aidocs/project_context.md +++ b/aidocs/project_context.md @@ -72,11 +72,15 @@ ## 2026-07-18 - Grid 处理已改为单次 RTree 查询和单次几何相交判断,同时生成 `信号.tif`、`用户量.tif`、`信号差用户量.tif` 和 `栅格指标.csv`,删除旧的重复扫描路径。 - 楼宇名称匹配已改为按市场 Building 联合范围一次加载 BuildingInfo 候选并构建 Shapely STRtree,避免逐栋楼宇查询 SQLite;边界外但与楼宇相交的 BuildingInfo 仍会纳入候选,保证结果与旧逻辑一致。 -- 新增 `MAX_WORKERS = 2` 市场级多进程配置;每个 worker 独立打开只读 GeoPackage 连接并生成独立 zip,主进程负责进度和 summary 汇总。 +- 市场级多进程默认值已由 `MAX_WORKERS = 2` 调整为 `4`;当前 4 核 8 线程、32GB、NVMe 环境对前 4 个市场实测由 2 进程 77.7 秒降至 4 进程 55.6 秒,结果包成员逐一校验一致。每个 worker 独立打开只读 GeoPackage 连接并生成独立 zip,主进程负责进度和 summary 汇总。 - `summary.json` 新增 `max_workers`、`total_elapsed_seconds` 和 `market_timings`,记录总耗时及 Grid/Building 分阶段耗时。 -- 性能基准:新版市场 `1-城区蓬江` 完整生成由约 70 秒降至 33 秒;两个市场使用 2 个进程总耗时约 36 秒,相比串行估算约 60 秒以上进一步缩短。 +- 首轮性能基准:新版市场 `1-城区蓬江` 完整生成由约 70 秒降至 33 秒;后续在无 profiler 的同机热缓存基准中,优化前为 23.56 秒,批量计算优化后为 11.66 秒,进一步提速约 50.5%。 - 排名热力图修复重复值分层伪影:相同值像元不再为强制凑比例而按栅格位置拆色,统一进入同一颜色档;弱覆盖阈值 `[6.5, 0]` 的测试市场不再出现由大量 `0` 值稳定排序造成的空间大块分层。 - Grid 单次查询后改为缓存紧凑像元窗口,三张 TIF 顺序复用矩阵内存;新增 `MAX_RASTER_PIXELS = 25000000`,超限市场自动降低分辨率并在结果中记录调整系数。 -- 最大范围市场 `16-台山海宴` 从原规划约 3.99 亿像元自动调整为约 2495 万像元,分辨率调整系数约 4.0,69 秒完成全部 7 个包内文件;BuildingInfo 要素数和 RTree 均为 12490,完整性检查为 `ok`。 +- 最大范围市场 `16-台山海宴` 从原规划约 3.99 亿像元自动调整为约 2495 万像元,分辨率调整系数约 4.0;批量计算优化后 25.2 秒完成全部 7 个包内文件,原基准约 69 秒。BuildingInfo 要素数和 RTree 均为 12490,完整性检查为 `ok`。 - zip 和 `summary.json` 改为临时文件写完后原子替换,避免异常中断时先删除已有成果;worker 会自行创建输出目录,所有输入文件会在启动前显式校验。 -- 优化前后 `信号.tif`、两个 CSV 和 BuildingInfo 结果保持一致;`用户量.tif`、`信号差用户量.tif` 因同值同色修复按预期发生变化。新增 7 个标准库单元测试覆盖信号边界、同值分类、STRtree、像元上限和 zip 完整性。 +- Grid、Building、BuildingInfo 的 WKB 解析、有效性判断、空间相交和边界计算已改为每批 10000 个要素的 Shapely 2 向量化计算;Grid 18.8 万候选的几何热路径实测由约 1.68 秒降至 0.31 秒。 +- 热力图二维高斯卷积改用 NumPy 滑动窗口矩阵乘法,避免逐行调用 `tensordot`;楼宇名称匹配改为 STRtree 批量查询,仅对具有多个候选的建筑计算相交面积,仍按最大相交面积选名。 +- 批量优化后 4 市场/4 进程总耗时由 55.6 秒降至 21.4 秒,提速约 61.5%;单进程与多进程生成的 7 个 zip 成员完全一致。 +- 新旧版本的 BuildingInfo、GIS 和两个 CSV 字节一致,TIF 的范围、透明通道、阈值和空间位置一致;因浮点累加顺序变化,连续平滑颜色可能有极少像元出现 1 个色阶舍入差异。现有 9 个标准库单元测试覆盖信号边界、同值分类、批量卷积、批量 STRtree 匹配、像元上限和 zip 完整性。 +- 最终 profile 中主要剩余耗时为 SQLite `fetchmany`、三张栅格的必要像元填充,以及多候选楼宇的真实相交面积计算;这些路径均直接对应输出需求,继续优化需要明显增加内存或引入额外依赖,当前版本不再为小幅收益增加复杂度。 diff --git a/main.py b/main.py index ffc5fde..fb7f15d 100644 --- a/main.py +++ b/main.py @@ -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"}: diff --git a/tests/test_main.py b/tests/test_main.py index f25e8fe..9b1527a 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -52,6 +52,37 @@ class SpatialNameIndexTest(unittest.TestCase): index = (STRtree(geometries), geometries, ["小建筑", "大建筑"]) self.assertEqual(main.match_building_info_name(index, box(0, 0, 1.5, 1.5)), "大建筑") + def test_batch_matching_matches_scalar_results(self): + info_geometries = [box(0, 0, 1, 1), box(0, 0, 2, 2), box(5, 5, 6, 6)] + index = (STRtree(info_geometries), info_geometries, ["小建筑", "大建筑", "远端建筑"]) + buildings = [box(0, 0, 1.5, 1.5), box(5.2, 5.2, 5.8, 5.8), box(10, 10, 11, 11)] + expected = [main.match_building_info_name(index, geometry) for geometry in buildings] + self.assertEqual(main.match_building_info_names(index, buildings), expected) + + +class GaussianBlurTest(unittest.TestCase): + def test_batch_convolution_matches_scalar_reference(self): + array = np.arange(30, dtype=np.float32).reshape(5, 6) + kernel = main.gaussian_kernel(2) + radius = kernel.size // 2 + padded = np.pad(array, ((radius, radius), (0, 0)), mode="edge") + moved = np.moveaxis(padded, 0, 0) + expected = np.empty_like(array) + for index in range(expected.shape[0]): + expected[index] = np.tensordot(kernel, moved[index:index + kernel.size], axes=(0, 0)) + + actual = main.convolve_axis(array, kernel, axis=0) + np.testing.assert_allclose(actual, expected, rtol=1e-6, atol=1e-6) + + padded = np.pad(array, ((0, 0), (radius, radius)), mode="edge") + moved = np.moveaxis(padded, 1, 0) + expected = np.empty_like(np.moveaxis(array, 1, 0)) + for index in range(expected.shape[0]): + expected[index] = np.tensordot(kernel, moved[index:index + kernel.size], axes=(0, 0)) + + actual = main.convolve_axis(array, kernel, axis=1) + np.testing.assert_allclose(actual, np.moveaxis(expected, 0, 1), rtol=1e-6, atol=1e-6) + class OutputSafetyTest(unittest.TestCase): def test_raster_layout_respects_pixel_limit(self):