import tempfile import sqlite3 import struct import unittest import xml.etree.ElementTree as ET import zipfile from pathlib import Path from contextlib import closing import numpy as np import tifffile from shapely import STRtree from shapely.geometry import Polygon, box from marketgrid import competitor, config, files, gpkg, legacy_user_count, metrics, models, qgis, raster_math class SignalRulesTest(unittest.TestCase): def test_signal_level_boundaries(self): self.assertEqual(metrics.signal_level(None), "无采集信息") self.assertEqual(metrics.signal_level(-105), "较差") self.assertEqual(metrics.signal_level(-95), "一般") self.assertEqual(metrics.signal_level(-94.9), "正常") class RankedHeatmapTest(unittest.TestCase): def test_equal_values_are_not_split_between_colors(self): values = np.array([[10.0, 0.0, 0.0], [0.0, 0.0, 0.0]], dtype=np.float32) mask = np.ones(values.shape, dtype=bool) result, thresholds, counts = raster_math.ranked_pixel_rgb_for_values( values, mask, config.EXCELLENT_COLORS, config.EXCELLENT_PERCENT_STEPS, ) self.assertEqual(thresholds, [0.0, 0.0, 0.0]) self.assertEqual(counts, [1, 0, 0, 5]) self.assertTrue(np.all(result[values == 0] == config.EXCELLENT_COLORS[-1])) self.assertTrue(np.all(result[values == 10] == config.EXCELLENT_COLORS[0])) def test_invalid_color_threshold_configuration_fails(self): values = np.array([[1.0]], dtype=np.float32) mask = np.ones(values.shape, dtype=bool) with self.assertRaises(ValueError): raster_math.ranked_pixel_rgb_for_values(values, mask, ((255, 0, 0),), (0.5,)) def test_ranked_colors_can_reuse_existing_thresholds(self): values = np.array([[20.0, 10.0, 5.0, 1.0]], dtype=np.float32) mask = np.ones(values.shape, dtype=bool) result, counts = raster_math.ranked_pixel_rgb_for_values_with_thresholds( values, mask, config.EXCELLENT_COLORS, [15.0, 7.5, 2.5], ) self.assertEqual(counts, [1, 1, 1, 1]) self.assertEqual(result[0, 0].tolist(), list(config.EXCELLENT_COLORS[0])) self.assertEqual(result[0, 1].tolist(), list(config.EXCELLENT_COLORS[1])) self.assertEqual(result[0, 2].tolist(), list(config.EXCELLENT_COLORS[2])) self.assertEqual(result[0, 3].tolist(), list(config.EXCELLENT_COLORS[3])) class UserCountMergeTest(unittest.TestCase): def test_4g_and_5g_counts_are_summed_by_grid20_id_without_duplicates(self): records = {} self.assertTrue(legacy_user_count.merge_user_count_record(records, "shared", (0, 1, 0, 1), 10.0, "5G", True)) self.assertTrue(legacy_user_count.merge_user_count_record(records, "shared", (0, 1, 1, 2), 5.0, "4G")) self.assertTrue(legacy_user_count.merge_user_count_record(records, "4g-only", (0, 1, 1, 2), 7.0, "4G")) self.assertTrue(legacy_user_count.merge_user_count_record(records, "5g-only", (0, 1, 2, 3), 3.0, "5G", True)) self.assertFalse(legacy_user_count.merge_user_count_record(records, " ", (0, 1, 0, 1), 99.0, "4G")) state = legacy_user_count.build_merged_user_count_state(records, 1, 3) metadata = legacy_user_count.merged_user_count_metadata(records, {"5G": {}, "4G": {}}) self.assertEqual(state["value_sum"].tolist(), [[15.0, 7.0, 3.0]]) self.assertEqual(state["value_weight"].tolist(), [[1, 1, 1]]) self.assertEqual(state["painted_cells"], 3) self.assertEqual(metadata["merged_grid_count"], 3) self.assertEqual(metadata["shared_grid_count"], 1) self.assertEqual(metadata["four_g_only_grid_count"], 1) self.assertEqual(metadata["five_g_only_grid_count"], 1) def test_local_summary_render_matches_full_canvas_colors(self): records = {} legacy_user_count.merge_user_count_record(records, "a", (24, 27, 24, 27), 20.0, "5G", True) legacy_user_count.merge_user_count_record(records, "b", (28, 31, 28, 31), 10.0, "5G", True) legacy_user_count.merge_user_count_record(records, "c", (32, 35, 32, 35), 5.0, "4G") thresholds = [15.0, 7.5, 2.5] full_state = legacy_user_count.build_merged_user_count_state(records, 64, 64) full_mask = full_state["value_weight"] > 0 full_values = np.zeros((64, 64), dtype=np.float32) np.divide( full_state["value_sum"], full_state["value_weight"], out=full_values, where=full_mask, ) full_ranked, _ = raster_math.ranked_pixel_rgb_for_values_with_thresholds( full_values, full_mask, config.EXCELLENT_COLORS, thresholds, ) expected = raster_math.smooth_rgb_inside_mask(full_ranked, full_mask, config.HEATMAP_SMOOTH_RADIUS) local = legacy_user_count.render_merged_user_count_records(records, 64, 64, thresholds) actual = np.zeros_like(expected) row_start, row_stop, col_start, col_stop = local["window"] actual[row_start:row_stop, col_start:col_stop] = local["rgb"] np.testing.assert_array_equal(actual, expected) self.assertLess(local["data_mask"].size, full_mask.size) class CompetitorSignalTest(unittest.TestCase): def test_grid_export_needs_no_4g_or_user_count_grid_id(self): with closing(sqlite3.connect(":memory:")) as conn, tempfile.TemporaryDirectory() as temp_dir: conn.execute( "create table grid (fid integer primary key, geom blob, mro_total_dl real, " "ssb_rsrp_dl real, rsrp_lt_neg105_dl real, mro_total_yd real, rsrp_lt_neg105_yd real)" ) conn.execute("create virtual table grid_rtree using rtree(id, minx, maxx, miny, maxy)") for index, (total, rsrp, weak) in enumerate(((100, -95, 40), (0, None, None), (100, -95, 0))): conn.execute("insert into grid values (?, ?, ?, ?, ?, 100, 10)", (index + 1, box(index, 0, index + 1, 1).wkb, total, rsrp, weak)) conn.execute("insert into grid_rtree values (?, ?, ?, 0, 1)", (index + 1, index, index + 1)) output = Path(temp_dir) / config.COMPETITOR_SIGNAL_OUTPUT_FILENAME result, csv_result = competitor.export_market_grid_outputs( conn, models.LayerInfo("grid", "geom", "fid", 4326), "grid_rtree", models.MarketFeature(1, "1-test", "test", box(0, 0, 3, 1)), 1, 1, output, None, ) pixels = tifffile.imread(output) self.assertEqual(pixels[0, :, 3].tolist(), [config.HEATMAP_ALPHA, config.HEATMAP_ALPHA, 0]) self.assertEqual(pixels[0, 1, :3].tolist(), list(config.COMPETITOR_SIGNAL_RSRP_COLORS[0])) self.assertEqual(result["raster_extent"], [0, 0, 3, 1]) self.assertIsNone(csv_result) self.assertEqual([item.name for item in Path(temp_dir).iterdir()], [config.COMPETITOR_SIGNAL_OUTPUT_FILENAME]) def test_filter_accepts_weak_coverage_or_zero_competitor_samples(self): self.assertTrue(competitor.competitor_signal_is_eligible(199.0, 1000.0, 1.0, 1.0)) self.assertTrue(competitor.competitor_signal_is_eligible(199.0, 1000.0, None, 0.0)) self.assertFalse(competitor.competitor_signal_is_eligible(200.0, 1000.0, 1.0, 1.0)) self.assertFalse(competitor.competitor_signal_is_eligible(199.0, 1000.0, 20.0, 100.0)) def test_filter_rejects_invalid_ratio_fields(self): invalid_cases = ( (None, 1000.0, 201.0, 1001.0), (1.0, 0.0, 201.0, 1001.0), (-1.0, 1000.0, 201.0, 1001.0), (199.0, 1000.0, None, 1001.0), (199.0, 1000.0, -1.0, 1001.0), (199.0, 1000.0, 1.0, -1.0), ) for values in invalid_cases: with self.subTest(values=values): self.assertEqual(competitor.competitor_signal_filter_reason(*values), "invalid_fields") def test_competitor_signal_uses_eight_discrete_color_classes(self): values = np.array( [[-200.0, -110.1, -110.0, -104.0, -98.0, -92.0, -86.0, -80.0, -74.0, 0.0, 0.1, np.nan]], dtype=np.float32, ) colors, valid_mask = competitor.competitor_signal_rsrp_rgb_for_values(values) expected_colors = [ config.COMPETITOR_SIGNAL_RSRP_COLORS[0], config.COMPETITOR_SIGNAL_RSRP_COLORS[0], config.COMPETITOR_SIGNAL_RSRP_COLORS[1], config.COMPETITOR_SIGNAL_RSRP_COLORS[2], config.COMPETITOR_SIGNAL_RSRP_COLORS[3], config.COMPETITOR_SIGNAL_RSRP_COLORS[4], config.COMPETITOR_SIGNAL_RSRP_COLORS[5], config.COMPETITOR_SIGNAL_RSRP_COLORS[6], config.COMPETITOR_SIGNAL_RSRP_COLORS[7], config.COMPETITOR_SIGNAL_RSRP_COLORS[7], ] self.assertEqual(colors[0, :10].tolist(), [list(color) for color in expected_colors]) self.assertEqual(valid_mask.tolist(), [[True] * 10 + [False, False]]) self.assertEqual(colors[0, 10:].tolist(), [[0, 0, 0], [0, 0, 0]]) def test_adjacent_grid_geometries_do_not_share_pixels(self): canvas = { "minx": -0.1, "maxy": 1.0, "pixel_width": 0.25, "pixel_height": 0.25, "width": 9, "height": 4, } left_geometry = box(0, 0, 1, 1) right_geometry = box(1, 0, 2, 1) left_window = raster_math.pixel_window_for_bounds(left_geometry.bounds, **canvas) right_window = raster_math.pixel_window_for_bounds(right_geometry.bounds, **canvas) left_mask = raster_math.pixel_center_mask_for_geometry( left_geometry, left_window, canvas["minx"], canvas["maxy"], canvas["pixel_width"], canvas["pixel_height"], ) right_mask = raster_math.pixel_center_mask_for_geometry( right_geometry, right_window, canvas["minx"], canvas["maxy"], canvas["pixel_width"], canvas["pixel_height"], ) left_pixels = np.zeros((canvas["height"], canvas["width"]), dtype=bool) right_pixels = np.zeros_like(left_pixels) lr0, lr1, lc0, lc1 = left_window rr0, rr1, rc0, rc1 = right_window left_pixels[lr0:lr1, lc0:lc1] = left_mask right_pixels[rr0:rr1, rc0:rc1] = right_mask self.assertFalse(np.any(left_pixels & right_pixels)) self.assertFalse(left_pixels[:, 4].any()) self.assertTrue(right_pixels[:, 4].all()) def test_zero_competitor_samples_render_red_without_rsrp(self): state = { "value_sum": np.array([[-90.0, 0.0]], dtype=np.float32), "value_weight": np.array([[1, 0]], dtype=np.uint16), "zero_total_mask": np.array([[False, True]], dtype=bool), "painted_cells": 2, "skipped_no_value": 0, } market = models.MarketFeature(1, "1-test", "test", box(0, 0, 2, 1)) with tempfile.TemporaryDirectory() as temp_dir: output_path = Path(temp_dir) / config.COMPETITOR_SIGNAL_OUTPUT_FILENAME result = competitor.render_competitor_signal_raster( state, market, output_path, 0, 1, 1, 1, 2, 1, 2, ) image = tifffile.imread(output_path) self.assertEqual(image[0, 1, :3].tolist(), list(config.COMPETITOR_SIGNAL_RSRP_COLORS[0])) self.assertEqual(image[0, 1, 3], config.HEATMAP_ALPHA) self.assertEqual(result["zero_total_pixels"], 1) def test_smoothing_radius_must_be_a_nonnegative_integer(self): raster_math.validate_smoothing_radius("radius", 0) raster_math.validate_smoothing_radius("radius", 10) for value in (-1, 1.5, True): with self.subTest(value=value): with self.assertRaises(ValueError): raster_math.validate_smoothing_radius("radius", value) class SpatialNameIndexTest(unittest.TestCase): def test_largest_intersection_wins(self): geometries = [box(0, 0, 1, 1), box(0, 0, 2, 2)] index = (STRtree(geometries), geometries, ["小建筑", "大建筑"]) self.assertEqual(metrics.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 = [metrics.match_building_info_name(index, geometry) for geometry in buildings] self.assertEqual(metrics.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 = raster_math.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 = raster_math.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 = raster_math.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_summary_market_unions_all_market_geometries(self): markets = [ models.MarketFeature(1, "1-a", "a", box(0, 0, 1, 1)), models.MarketFeature(2, "2-b", "b", box(2, 0, 3, 1)), ] summary_market = gpkg.build_summary_market(markets) self.assertEqual(summary_market.code, config.SUMMARY_MARKET_CODE) self.assertEqual(summary_market.geometry.bounds, (0.0, 0.0, 3.0, 1.0)) self.assertEqual(summary_market.geometry.area, 2.0) def test_summary_market_requires_input(self): with self.assertRaises(ValueError): gpkg.build_summary_market([]) def test_summary_market_repairs_invalid_geometry(self): invalid_geometry = Polygon([(0, 0), (1, 1), (1, 0), (0, 1), (0, 0)]) self.assertFalse(invalid_geometry.is_valid) summary_market = gpkg.build_summary_market( [models.MarketFeature(1, "1-a", "a", invalid_geometry)] ) self.assertTrue(summary_market.geometry.is_valid) self.assertFalse(summary_market.geometry.is_empty) def test_raster_layout_respects_pixel_limit(self): original_limit = config.MAX_RASTER_PIXELS config.MAX_RASTER_PIXELS = 100 try: layout = raster_math.market_raster_layout((0, 0, 10, 10), 0.1, 0.1) finally: config.MAX_RASTER_PIXELS = original_limit self.assertLessEqual(layout[6] * layout[7], 100) self.assertGreater(layout[8], 1.0) def test_summary_raster_layout_uses_independent_pixel_limit(self): layout = raster_math.market_raster_layout((0, 0, 10, 10), 0.1, 0.1, 400) self.assertLessEqual(layout[6] * layout[7], 400) self.assertEqual((layout[6], layout[7]), (20, 20)) def test_zip_output_is_complete(self): with tempfile.TemporaryDirectory() as temp_dir: root = Path(temp_dir) workspace = root / "workspace" workspace.mkdir() (workspace / "a.txt").write_text("a", encoding="utf-8") (workspace / "b.txt").write_text("b", encoding="utf-8") zip_path = root / "market.zip" market = models.MarketFeature(1, "1-test", "test", box(0, 0, 1, 1)) result = files.write_market_zip(workspace, zip_path, market) with zipfile.ZipFile(zip_path) as archive: self.assertEqual(sorted(archive.namelist()), ["a.txt", "b.txt"]) self.assertEqual(result["entries"], ["a.txt", "b.txt"]) self.assertFalse((root / ".market.zip.tmp").exists()) def test_full_source_file_is_copied_without_filtering(self): with tempfile.TemporaryDirectory() as temp_dir: root = Path(temp_dir) source = root / "CellData.gpkg" output = root / "result" / "CellData.gpkg" output.parent.mkdir() source.write_bytes(b"cell-data") market = models.MarketFeature(1, "1-test", "test", box(0, 0, 1, 1)) result = files.copy_full_source_file(source, output, market) self.assertEqual(output.read_bytes(), b"cell-data") self.assertTrue(result["copied_full_source"]) self.assertEqual(result["bytes"], len(b"cell-data")) class AoiLayerTest(unittest.TestCase): def setUp(self): self.conn = sqlite3.connect(":memory:") self.addCleanup(self.conn.close) self.temp = tempfile.TemporaryDirectory() self.addCleanup(self.temp.cleanup) self.conn.executescript(''' create table gpkg_spatial_ref_sys (srs_id integer primary key, definition text); create table gpkg_contents (table_name text primary key, data_type text, min_x real, min_y real, max_x real, max_y real, srs_id integer); create table gpkg_geometry_columns (table_name text, column_name text, geometry_type_name text, srs_id integer, z integer, m integer); create table gpkg_ogr_contents (table_name text primary key, feature_count integer); create table aoi (fid integer primary key, geom blob, "所属市场网格" text, "AOI唯一标签" text, "AOI名称" text, metric real); create virtual table rtree_aoi_geom using rtree(id, minx, maxx, miny, maxy); insert into gpkg_contents values ('aoi', 'features', 0, 0, 11, 1, 4326); insert into gpkg_geometry_columns values ('aoi', 'geom', 'POLYGON', 4326, 0, 0); insert into gpkg_ogr_contents values ('aoi', 4); ''') self.conn.execute("insert into gpkg_spatial_ref_sys values (4326, ?)", ('GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],' 'PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433],AUTHORITY["EPSG","4326"]]',)) for fid, owner, start in ((1, "A", 0), (2, "B", 0.5), (3, "A", 10), (4, None, 0)): geometry = b"GP\x00\x01" + struct.pack(" 0011 100100200200 cell-idCellData./CellData.gpkg|layername=_20260701 BuildingInfo./BuildingInfo.gpkg|layername=BuildingInfo0011 用户量./用户量.tif100100200200100100200200 竞对信号./竞对信号.tif100100200200100100200200 ''' with tempfile.TemporaryDirectory() as temp_dir: root_dir = Path(temp_dir) source_path = root_dir / "source.qgz" output_path = root_dir / "GIS.qgz" with zipfile.ZipFile(source_path, "w", compression=zipfile.ZIP_DEFLATED) as archive: archive.writestr("GIS.qgs", project_xml) archive.writestr("styles.db", b"style-data") market = models.MarketFeature(1, "1-test", "test", box(0, 0, 1, 1)) result = qgis.copy_gis_project_to_market( source_path, output_path, market, (10, 20, 30, 40), (0, -1, 2, 1), include_cell_data=False, ) with zipfile.ZipFile(output_path) as archive: updated_xml = archive.read("GIS.qgs") self.assertTrue(updated_xml.startswith(b"\xef\xbb\xbf