import csv import sqlite3 import tempfile import unittest from contextlib import closing from pathlib import Path from shapely.geometry import box from marketgrid import config from marketgrid.aoi_match import assign_market, build_matched_aoi from marketgrid.gpkg import open_read_connection, resolve_feature_layer from marketgrid.models import MarketFeature from tests.test_toolbox import create_gpkg class AoiAssignTest(unittest.TestCase): def setUp(self): self.markets = [ MarketFeature(1, "1-甲", "甲", box(0, 0, 2, 1)), MarketFeature(2, "2-乙", "乙", box(2, 0, 4, 1)), ] from shapely import STRtree self.tree = STRtree([market.geometry for market in self.markets]) def test_largest_contact_area_wins_and_touch_without_area_is_unassigned(self): self.assertEqual(assign_market(box(1.5, 0, 3.5, 1), self.markets, self.tree), "乙") self.assertIsNone(assign_market(box(-1, 0, 0, 1), self.markets, self.tree)) self.assertIsNone(assign_market(box(4, 0, 5, 1), self.markets, self.tree)) def test_equal_area_keeps_smaller_fid(self): self.assertEqual(assign_market(box(1, 0, 3, 1), self.markets, self.tree), "甲") class AoiBuildTest(unittest.TestCase): def test_csv_is_written_with_market_field_and_spatial_index(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) create_gpkg(root / "markets.gpkg", "MarketMap", '"Name" text', [ (1, box(0, 0, 2, 1), ["甲"]), (2, box(2, 0, 4, 1), ["乙"]), ]) csv_path = root / "aoi.csv" with csv_path.open("w", encoding="utf-8-sig", newline="") as output: writer = csv.writer(output) writer.writerow(["地市名称", "AOI唯一标签", "AOI名称", "空间信息(几何)", "移动C端采样点占比", "联通C端采样点占比", "电信C端采样点占比", "广电C端采样点占比", "电联C端采样点占比"]) writer.writerow(["江门", "a", "甲AOI", box(0.2, 0.2, 0.8, 0.8).wkt, 10, 20, 30, 5, 50]) writer.writerow(["江门", "edge", "贴边", box(-1, 0, 0, 1).wkt, "", "", "", "", ""]) output_path = root / "matched.gpkg" stats = build_matched_aoi(csv_path, root / "markets.gpkg", output_path) self.assertEqual(stats["matched"], 1) self.assertEqual(stats["unassigned"], 1) with closing(sqlite3.connect(output_path)) as conn: rows = conn.execute(f'select "AOI唯一标签", "所属市场网格" from "{config.AOI_LAYER}" order by fid').fetchall() self.assertEqual(rows, [("a", "甲"), ("edge", None)]) self.assertEqual(conn.execute(f'select count(*) from "rtree_{config.AOI_LAYER}_geom"').fetchone()[0], 2) with open_read_connection(output_path) as source: layer = resolve_feature_layer(source, config.AOI_LAYER) self.assertEqual(layer.srs_id, 4326)