241 lines
11 KiB
Python
241 lines
11 KiB
Python
import tempfile
|
|
import unittest
|
|
import xml.etree.ElementTree as ET
|
|
import zipfile
|
|
from pathlib import Path
|
|
|
|
import numpy as np
|
|
from shapely import STRtree
|
|
from shapely.geometry import Polygon, box
|
|
|
|
import main
|
|
|
|
|
|
class SignalRulesTest(unittest.TestCase):
|
|
def test_signal_level_boundaries(self):
|
|
self.assertEqual(main.signal_level(None), "无采集信息")
|
|
self.assertEqual(main.signal_level(-105), "较差")
|
|
self.assertEqual(main.signal_level(-95), "一般")
|
|
self.assertEqual(main.signal_level(-94.9), "正常")
|
|
|
|
def test_signal_raster_colors(self):
|
|
values = np.array([[-110.0, -105.0, -100.0, -95.0, -87.5, -80.0, -70.0]], dtype=np.float32)
|
|
colors = main.heatmap_rgb_for_values(values)
|
|
self.assertEqual(
|
|
colors.tolist(),
|
|
[[
|
|
[255, 0, 0],
|
|
[255, 0, 0],
|
|
[255, 128, 0],
|
|
[255, 255, 0],
|
|
[128, 216, 40],
|
|
[0, 176, 80],
|
|
[0, 176, 80],
|
|
]],
|
|
)
|
|
|
|
|
|
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 = main.ranked_pixel_rgb_for_values(
|
|
values,
|
|
mask,
|
|
main.EXCELLENT_COLORS,
|
|
main.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] == main.EXCELLENT_COLORS[-1]))
|
|
self.assertTrue(np.all(result[values == 10] == main.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):
|
|
main.ranked_pixel_rgb_for_values(values, mask, ((255, 0, 0),), (0.5,))
|
|
|
|
|
|
class ContinuousHeatmapTest(unittest.TestCase):
|
|
def test_percentile_heatmap_is_continuous_and_preserves_ties(self):
|
|
values = np.array([[0.0, 0.0, 5.0, 10.0, 20.0]], dtype=np.float32)
|
|
mask = np.ones(values.shape, dtype=bool)
|
|
anchor_scores = (0.0, main.WEAK_COVER_YELLOW_PERCENTILE, 1.0)
|
|
scores, anchors = main.percentile_scores_for_values(values, mask, anchor_scores)
|
|
colors = main.continuous_heatmap_rgb_for_scores(scores, main.WEAK_COVER_YELLOW_PERCENTILE)
|
|
|
|
self.assertEqual(anchors, [0.0, 10.0, 20.0])
|
|
self.assertEqual(colors[0, 0].tolist(), list(main.CONTINUOUS_HEATMAP_GREEN))
|
|
self.assertEqual(colors[0, 0].tolist(), colors[0, 1].tolist())
|
|
self.assertNotIn(colors[0, 2].tolist(), [
|
|
list(main.CONTINUOUS_HEATMAP_GREEN),
|
|
list(main.CONTINUOUS_HEATMAP_YELLOW),
|
|
list(main.CONTINUOUS_HEATMAP_RED),
|
|
])
|
|
self.assertEqual(colors[0, 4].tolist(), list(main.CONTINUOUS_HEATMAP_RED))
|
|
|
|
|
|
class WeakCoverRatioTest(unittest.TestCase):
|
|
def test_continuous_percentage_color_anchors(self):
|
|
values = np.array([[0.0, 2.5, 5.0, 7.5, 10.0, 15.0, 20.0, 100.0]], dtype=np.float32)
|
|
colors = main.weak_cover_ratio_rgb_for_values(values)
|
|
self.assertEqual(colors[0, 0].tolist(), list(main.WEAK_COVER_RATIO_GREEN))
|
|
self.assertEqual(colors[0, 2].tolist(), list(main.WEAK_COVER_RATIO_BLUE))
|
|
self.assertEqual(colors[0, 4].tolist(), list(main.WEAK_COVER_RATIO_YELLOW))
|
|
self.assertEqual(colors[0, 6].tolist(), list(main.WEAK_COVER_RATIO_RED))
|
|
self.assertEqual(colors[0, 7].tolist(), list(main.WEAK_COVER_RATIO_RED))
|
|
for index in (1, 3, 5):
|
|
self.assertNotIn(colors[0, index].tolist(), [
|
|
list(main.WEAK_COVER_RATIO_GREEN),
|
|
list(main.WEAK_COVER_RATIO_BLUE),
|
|
list(main.WEAK_COVER_RATIO_YELLOW),
|
|
list(main.WEAK_COVER_RATIO_RED),
|
|
])
|
|
|
|
|
|
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(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_summary_market_unions_all_market_geometries(self):
|
|
markets = [
|
|
main.MarketFeature(1, "1-a", "a", box(0, 0, 1, 1)),
|
|
main.MarketFeature(2, "2-b", "b", box(2, 0, 3, 1)),
|
|
]
|
|
summary_market = main.build_summary_market(markets)
|
|
self.assertEqual(summary_market.code, main.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):
|
|
main.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 = main.build_summary_market(
|
|
[main.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 = main.MAX_RASTER_PIXELS
|
|
main.MAX_RASTER_PIXELS = 100
|
|
try:
|
|
layout = main.market_raster_layout((0, 0, 10, 10), 0.1, 0.1)
|
|
finally:
|
|
main.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 = main.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 = main.MarketFeature(1, "1-test", "test", box(0, 0, 1, 1))
|
|
result = main.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())
|
|
|
|
|
|
class QgisProjectTest(unittest.TestCase):
|
|
def test_project_extent_tracks_building_info(self):
|
|
project_xml = b'''\xef\xbb\xbf<!DOCTYPE qgis PUBLIC 'http://mrcc.com/qgis.dtd' 'SYSTEM'>
|
|
<qgis>
|
|
<mapcanvas name="theMapCanvas"><extent><xmin>0</xmin><ymin>0</ymin><xmax>1</xmax><ymax>1</ymax></extent></mapcanvas>
|
|
<mapcanvas name="mAreaCanvas"><extent><xmin>100</xmin><ymin>100</ymin><xmax>200</xmax><ymax>200</ymax></extent></mapcanvas>
|
|
<projectlayers>
|
|
<maplayer><layername>BuildingInfo</layername><datasource>./BuildingInfo.gpkg|layername=BuildingInfo</datasource><extent><xmin>0</xmin><ymin>0</ymin><xmax>1</xmax><ymax>1</ymax></extent></maplayer>
|
|
<maplayer><layername>弱覆盖占比</layername><datasource>./弱覆盖占比.tif</datasource><extent><xmin>100</xmin><ymin>100</ymin><xmax>200</xmax><ymax>200</ymax></extent><wgs84extent><xmin>100</xmin><ymin>100</ymin><xmax>200</xmax><ymax>200</ymax></wgs84extent></maplayer>
|
|
</projectlayers>
|
|
</qgis>'''
|
|
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 = main.MarketFeature(1, "1-test", "test", box(0, 0, 1, 1))
|
|
result = main.copy_gis_project_to_market(source_path, output_path, market, (10, 20, 30, 40))
|
|
|
|
with zipfile.ZipFile(output_path) as archive:
|
|
updated_xml = archive.read("GIS.qgs")
|
|
self.assertTrue(updated_xml.startswith(b"\xef\xbb\xbf<!DOCTYPE qgis "))
|
|
self.assertEqual(archive.read("styles.db"), b"style-data")
|
|
project = ET.fromstring(updated_xml)
|
|
|
|
def read_extent(element):
|
|
return tuple(float(element.findtext(tag)) for tag in ("xmin", "ymin", "xmax", "ymax"))
|
|
|
|
canvas = project.find(".//mapcanvas[@name='theMapCanvas']/extent")
|
|
overview = project.find(".//mapcanvas[@name='mAreaCanvas']/extent")
|
|
building_layer = project.find(".//projectlayers/maplayer/extent")
|
|
ratio_layer = next(
|
|
layer
|
|
for layer in project.findall(".//projectlayers/maplayer")
|
|
if layer.findtext("datasource") == "./弱覆盖占比.tif"
|
|
)
|
|
self.assertEqual(read_extent(canvas), (9, 19, 31, 41))
|
|
self.assertEqual(read_extent(overview), (100, 100, 200, 200))
|
|
self.assertEqual(read_extent(building_layer), (10, 20, 30, 40))
|
|
self.assertEqual(read_extent(ratio_layer.find("extent")), (0, 0, 1, 1))
|
|
self.assertEqual(read_extent(ratio_layer.find("wgs84extent")), (0, 0, 1, 1))
|
|
self.assertEqual(result["extent_source"], "building_info")
|
|
self.assertEqual(result["canvas_extent"], [9.0, 19.0, 31.0, 41.0])
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|