Files
2026-11-05 15:07:45 +08:00

132 lines
5.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""地理计算:站点坐标索引 + 最近站点查询。
性能要点
--------
* 站点级去重:5765 个 4G 站 + 4568 个 5G 站,先按 ``site_name`` 聚合出站点中心点;
* 局部等距投影:把经纬度投影到以测区平均纬度为基准的平面(米),把球面距离
换成平面欧氏距离,误差在几十公里尺度内 < 0.1%;
* 空间索引:优先用 ``scipy.spatial.cKDTree``,没有 scipy 时退化为 numpy 的
``argpartition``(O(n) 选出前 k 个),200 个逻辑站 × 1 万站点仍然毫秒级。
"""
from __future__ import annotations
import math
import numpy as np
import polars as pl
EARTH_R = 6371000.0
class SiteIndex:
"""站点索引。
``exclude_keywords`` 可选:小区名称含这些词的记录不进入索引。
用于"邻站候选池"——微小站/皮站的小区名普遍带「(微小M)」等标记,
按名称排除即可,无需依赖工参的「站点类型」列。
需要给清单 CGI 定位时应传入空元组,保证待拆站本身能查到。
"""
def __init__(
self, gongcan: pl.DataFrame, exclude_keywords: tuple[str, ...] = ()
) -> None:
df = gongcan.filter(
pl.col("lat").is_not_null()
& pl.col("lon").is_not_null()
& pl.col("site_name").is_not_null()
& (pl.col("site_name") != "")
)
keywords = tuple(k for k in (exclude_keywords or ()) if k)
if keywords:
hit = pl.col("cell_name").fill_null("").str.contains(keywords[0], literal=True)
for k in keywords[1:]:
hit = hit | pl.col("cell_name").fill_null("").str.contains(k, literal=True)
df = df.filter(~hit)
if df.height == 0:
raise ValueError("工参表为空或缺少经纬度,无法做周边站计算")
self.cells: dict[str, list[dict]] = {}
for row in df.iter_rows(named=True):
self.cells.setdefault(row["site_name"], []).append(row)
self.site_of_cgi: dict[str, str] = {r["cgi"]: r["site_name"] for r in df.iter_rows(named=True)}
agg = (
df.group_by("site_name")
.agg(
pl.col("lat").mean().alias("lat"),
pl.col("lon").mean().alias("lon"),
pl.len().alias("n"),
)
.sort("site_name")
)
self.names: list[str] = agg["site_name"].to_list()
self.lat = agg["lat"].to_numpy().astype(float)
self.lon = agg["lon"].to_numpy().astype(float)
self._ref_lat = math.radians(float(np.mean(self.lat)))
self.x = np.radians(self.lon) * EARTH_R * math.cos(self._ref_lat)
self.y = np.radians(self.lat) * EARTH_R
self._pts = np.column_stack([self.x, self.y])
self._tree = None
try: # 有 scipy 就用 KD 树
from scipy.spatial import cKDTree
self._tree = cKDTree(self._pts)
except Exception: # noqa: BLE001 - 没有 scipy 时走 numpy 兜底
self._tree = None
# ------------------------------------------------------------------ 查询
def _project(self, lat: float, lon: float) -> tuple[float, float]:
x = math.radians(lon) * EARTH_R * math.cos(self._ref_lat)
y = math.radians(lat) * EARTH_R
return x, y
def nearest(
self, lat: float, lon: float, k: int = 3, exclude: set[str] | None = None
) -> list[tuple[str, float]]:
"""返回最近 k 个站点 [(站点名, 距离米)],已排除 ``exclude`` 中的站点。"""
exclude = exclude or set()
need = k + len(exclude) + 8
need = min(need, len(self.names))
x, y = self._project(lat, lon)
q = np.array([x, y])
if self._tree is not None:
dist, idx = self._tree.query(q, k=need)
else: # pragma: no cover - 兜底分支
d = np.hypot(self._pts[:, 0] - x, self._pts[:, 1] - y)
idx = np.argpartition(d, need - 1)[:need]
idx = idx[np.argsort(d[idx])]
dist = d[idx]
dist = np.atleast_1d(dist)
idx = np.atleast_1d(idx)
out: list[tuple[str, float]] = []
for i, dd in zip(idx.tolist(), dist.tolist()):
name = self.names[i]
if name in exclude:
continue
if dd < 1.0: # 同一坐标(同站不同名)也排除
continue
out.append((name, float(dd)))
if len(out) >= k:
break
return out
def site_center(self, site_name: str) -> tuple[float, float] | None:
rows = self.cells.get(site_name)
if not rows:
return None
lat = sum(r["lat"] for r in rows) / len(rows)
lon = sum(r["lon"] for r in rows) / len(rows)
return lat, lon
def haversine(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
p1, p2 = math.radians(lat1), math.radians(lat2)
dp = p2 - p1
dl = math.radians(lon2 - lon1)
a = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2
return 2 * EARTH_R * math.asin(math.sqrt(a))