import io import zipfile from pathlib import Path import numpy as np import pytest import shapefile from election_data.geo import _SHP_STEM, area_km2, count_points_in, load_villages from election_data.impute import NeighborIndex, impute pytestmark = pytest.mark.unit # 三個 0.01 度見方的格子:A、B 相鄰(同鄉鎮),C 在遠處(另一個鄉鎮) SQUARES = { "68000010001": (121.00, 25.00, "68000010", "桃園區", "甲里"), "68000010002": (121.01, 25.00, "68000010", "桃園區", "乙里"), "68000020001": (121.20, 25.00, "68000020", "中壢區", "丙里"), } def make_zip(tmp_path: Path) -> Path: shp, shx, dbf = io.BytesIO(), io.BytesIO(), io.BytesIO() writer = shapefile.Writer(shp=shp, shx=shx, dbf=dbf, shapeType=shapefile.POLYGON, encoding="utf-8") for name in ("VILLCODE", "COUNTYNAME", "TOWNNAME", "VILLNAME", "COUNTYCODE", "TOWNCODE"): writer.field(name, "C", 40) for code, (x, y, town_code, town, name) in SQUARES.items(): writer.poly([[[x, y], [x, y + 0.01], [x + 0.01, y + 0.01], [x + 0.01, y], [x, y]]]) writer.record(code, "桃園市", town, name, "68000", town_code) writer.close() path = tmp_path / "v.zip" with zipfile.ZipFile(path, "w") as zf: zf.writestr(f"{_SHP_STEM}.shp", shp.getvalue()) zf.writestr(f"{_SHP_STEM}.shx", shx.getvalue()) zf.writestr(f"{_SHP_STEM}.dbf", dbf.getvalue()) return path def test_load_filter_area_and_points(tmp_path: Path) -> None: villages = load_villages(make_zip(tmp_path), "68000") assert [v.code for v in villages] == sorted(SQUARES) assert villages[0].town_name == "桃園區" # 0.01 度見方在北緯 25 度約 1.009 × 1.106 平方公里 assert area_km2(villages[0].geometry) == pytest.approx(1.116, rel=0.01) counts = count_points_in( villages, [(121.005, 25.005), (121.015, 25.005), (121.015, 25.006), (130.0, 25.0)] ) assert counts == {"68000010001": 1, "68000010002": 2, "68000020001": 0} assert load_villages(make_zip(tmp_path), "99999") == [] def test_impute_prefers_neighbors_then_town_then_county(tmp_path: Path) -> None: villages = load_villages(make_zip(tmp_path), None) index = NeighborIndex(villages) assert index.neighbors("68000010001") == ["68000010002"] weights = dict.fromkeys(SQUARES, 1.0) town = lambda code: [c for c in SQUARES if c[:8] == code[:8]] # noqa: E731 county = list(SQUARES) known = {"68000010002": np.array([0.4]), "68000020001": np.array([0.9])} found = impute("68000010001", known, weights, index, town, county) assert found is not None and found.source == "neighbors" and found.value[0] == pytest.approx(0.4) found = impute("68000020001", {"68000010001": np.array([0.2])}, weights, index, town, county) assert found is not None and found.source == "county" assert impute("68000010001", {}, weights, index, town, county) is None