"""评估用的 4G/5G 小区工参:按地市、日期整份保存,任务先查库,没有再去大数据平台取。 一份快照 = 即席查询当天的工参(经纬度是脱敏的)+ OpenCode 导出的当天 CGI 与经纬度,按 CGI 合并, OpenCode 里没有坐标的小区经纬度留空。即席查询取不到,或者它给的 CGI 和 OpenCode 那份对不上时, 改由 OpenCode 把属性列一起导出。OpenCode 那份按 eff_from_date/eff_to_date 取当天有效的记录,是日期口径的基准。 """ from __future__ import annotations import asyncio import hashlib import logging import math from collections.abc import Awaitable, Callable from dataclasses import dataclass from datetime import date, datetime, timedelta, timezone from sqlalchemy import delete, exists, insert, select, update from sqlalchemy.engine import Engine from sqlalchemy.exc import IntegrityError from app.models import GongcanCell, GongcanSnapshot, utcnow from app.nqi import adhoc from app.nqi.client import NqiClient, NqiError from app.nqi.opencode import EFFECTIVE, ExportFile, OpenCode, snapshot_where, task_session logger = logging.getLogger("decom") TECHS = ("4G", "5G") ADHOC_TABLES = {"4G": "appdbv3.v_a_common_cfg_lte_cellant_d", "5G": "appdbv3.a_common_cfg_nr_cellant_d"} PLATFORM_TABLES = {"4G": "appdbv3.a_common_cfg_lte_cellant_d", "5G": "appdbv3.a_common_cfg_nr_cellant_d"} KEYS = {"4G": ("cgi",), "5G": ("ncgi", "cgi")} NAMED_FIELDS = { "4G": {"cell_name": "cell_name", "site_name": "station_name", "node_id": "enodeb_id", "node_name": "enodeb_name"}, "5G": {"cell_name": "nrcell_name", "site_name": "station_name", "node_id": "gnodeb_id", "node_name": "gnodeb_name"}, } SHARED_FIELDS = ("network_type", "area", "town", "state", "cover_type", "frequency_band", "vendor", "azimuth") COORDS = ("longitude", "latitude") MATCH_RATIO = 0.98 FAILED_COOLDOWN = timedelta(minutes=10) STALE_LOADING = timedelta(minutes=40) class GongcanError(Exception): pass class GongcanMissing(GongcanError): pass @dataclass(frozen=True) class Target: """一个评估任务的对象:一个或几个 CGI,或者一个站点名。""" cgis: tuple[str, ...] = () site: str = "" def __post_init__(self) -> None: if bool(self.cgis) == bool(self.site): raise ValueError("目标要么给 CGI,要么给站点名称") @property def label(self) -> str: return f"站点 {self.site}" if self.site else f"小区 {'、'.join(self.cgis)}" def attribute_columns(tech: str) -> tuple[str, ...]: return tuple(NAMED_FIELDS[tech].values()) + SHARED_FIELDS def adhoc_fields(tech: str) -> tuple[str, ...]: return KEYS[tech] + attribute_columns(tech) def snapshot_task_name(city: str, day: date) -> str: """OpenCode 目录名不带日期样式的数字,平台的脱敏会把它当日期改掉。""" return "gc_" + hashlib.sha1(f"{city}|{day.isoformat()}".encode("utf-8")).hexdigest()[:12] def platform_files(task: str, city: str, day: date, *, attributes: bool) -> list[ExportFile]: """全市当天有效的工参。只要坐标时三四列;要属性时文字列把英文逗号换成中文逗号,避免 CSV 错列。""" files = [] for tech, name in (("4G", "lte"), ("5G", "nr")): columns = KEYS[tech] + COORDS + EFFECTIVE select_list = list(columns) if attributes: columns += attribute_columns(tech) select_list += [f"replace({column}::text, ',', ',') as {column}" for column in attribute_columns(tech)] sql = f"select {', '.join(select_list)} from {PLATFORM_TABLES[tech]} where {snapshot_where(city, day)}" files.append(ExportFile(task, "attr" if attributes else "xy", f"{name}.csv", sql, day, columns)) return files def key_of(row: dict, tech: str) -> str: for name in KEYS[tech]: value = str(row.get(name) or "").strip() if value: return value return "" def valid_coordinate(lon: object, lat: object) -> tuple[float | None, float | None]: try: lon_value, lat_value = float(lon), float(lat) except (TypeError, ValueError): return None, None if 70 <= lon_value <= 140 and 15 <= lat_value <= 55: return lon_value, lat_value return None, None def coordinates(rows: list[dict], tech: str) -> dict[str, tuple[float, float]]: """4G 表一行一个天线,同一 CGI 会有多行,取第一条有效坐标。""" found: dict[str, tuple[float, float]] = {} for row in rows: key = key_of(row, tech) if not key or key in found: continue lon, lat = valid_coordinate(row.get("longitude"), row.get("latitude")) if lon is not None: found[key] = (lat, lon) return found def build_cells(attr_rows: list[dict], coord_rows: list[dict], tech: str) -> list[dict]: coords = coordinates(coord_rows, tech) mapping = {**NAMED_FIELDS[tech], **{name: name for name in SHARED_FIELDS}} cells: dict[str, dict] = {} for row in attr_rows: key = key_of(row, tech) if not key or key in cells: continue lat, lon = coords.get(key, (None, None)) cell = {"tech": tech, "cgi": key, "latitude": lat, "longitude": lon} for target, source in mapping.items(): cell[target] = str(row.get(source) or "").strip() cells[key] = cell return list(cells.values()) def key_overlap(attr_rows: list[dict], coord_rows: list[dict], tech: str) -> float: left = {key_of(row, tech) for row in attr_rows} - {""} right = {key_of(row, tech) for row in coord_rows} - {""} if not left or not right: return 0.0 return len(left & right) / len(left | right) async def fetch_snapshot(nqi: NqiClient, oc: OpenCode, city: str, day: date, *, use_adhoc: bool = True) -> tuple[list[dict], str]: """从大数据平台取一份快照,返回小区列表和属性来源(adhoc / opencode)。""" attrs: dict[str, list[dict]] | None = None if use_adhoc: try: attrs = {tech: await adhoc.export_day(nqi, ADHOC_TABLES[tech], day, city, adhoc_fields(tech)) for tech in TECHS} except NqiError as exc: logger.info("即席查询取 %s %s 工参未成功,改由 OpenCode 导出属性: %s", city, day, exc) attrs = None task = snapshot_task_name(city, day) async with task_session(oc, task) as session_id: files = platform_files(task, city, day, attributes=attrs is None) tables = await oc.export(session_id, files) rows = {tech: tables[item.key].rows for tech, item in zip(TECHS, files)} if attrs is not None: ratios = {tech: key_overlap(attrs[tech], rows[tech], tech) for tech in TECHS} if min(ratios.values()) < MATCH_RATIO: logger.info("即席查询的 CGI 与 OpenCode 当天快照重合 %s,改用 OpenCode 的属性", ratios) attrs = None files = platform_files(task, city, day, attributes=True) tables = await oc.export(session_id, files) rows = {tech: tables[item.key].rows for tech, item in zip(TECHS, files)} source = "adhoc" if attrs is not None else "opencode" attrs = attrs if attrs is not None else rows cells = [cell for tech in TECHS for cell in build_cells(attrs[tech], rows[tech], tech)] if not any(cell["tech"] == "4G" for cell in cells) or not any(cell["tech"] == "5G" for cell in cells): raise GongcanError(f"{city} {day} 的工参是空的") return cells, source _SNAPSHOT = GongcanSnapshot.__table__ _CELL = GongcanCell.__table__ def _aware(value: datetime) -> datetime: return value if value.tzinfo else value.replace(tzinfo=timezone.utc) def claim_snapshot(engine: Engine, city: str, day: date, now: datetime) -> int | None: """抢到取数权返回快照 id;已就绪、别人正在取、或刚失败还在冷却时返回 None。""" try: with engine.begin() as connection: result = connection.execute( insert(_SNAPSHOT).values(city=city, snapshot_date=day, status="loading", error="", created_at=now, updated_at=now) ) return int(result.inserted_primary_key[0]) except IntegrityError: pass with engine.begin() as connection: row = connection.execute( select(_SNAPSHOT.c.id, _SNAPSHOT.c.status, _SNAPSHOT.c.updated_at).where(_SNAPSHOT.c.city == city, _SNAPSHOT.c.snapshot_date == day) ).first() if row is None or row.status == "ready": return None wait = FAILED_COOLDOWN if row.status == "failed" else STALE_LOADING if _aware(row.updated_at) > now - wait: return None taken = connection.execute( update(_SNAPSHOT) .where(_SNAPSHOT.c.id == row.id, _SNAPSHOT.c.status == row.status, _SNAPSHOT.c.updated_at <= now - wait) .values(status="loading", error="", updated_at=now) ) return int(row.id) if taken.rowcount == 1 else None def save_snapshot(engine: Engine, snapshot_id: int, cells: list[dict], source: str, now: datetime) -> None: with engine.begin() as connection: connection.execute(delete(_CELL).where(_CELL.c.snapshot_id == snapshot_id)) for start in range(0, len(cells), 2000): connection.execute(insert(_CELL), [{**cell, "snapshot_id": snapshot_id} for cell in cells[start:start + 2000]]) connection.execute( update(_SNAPSHOT) .where(_SNAPSHOT.c.id == snapshot_id) .values( status="ready", attr_source=source, lte_cells=sum(1 for cell in cells if cell["tech"] == "4G"), nr_cells=sum(1 for cell in cells if cell["tech"] == "5G"), located_cells=sum(1 for cell in cells if cell["latitude"] is not None), error="", updated_at=now, ) ) def fail_snapshot(engine: Engine, snapshot_id: int, error: str, now: datetime) -> None: with engine.begin() as connection: connection.execute(update(_SNAPSHOT).where(_SNAPSHOT.c.id == snapshot_id).values(status="failed", error=error[:500], updated_at=now)) def _has_target(target: Target): condition = _CELL.c.site_name == target.site if target.site else _CELL.c.cgi.in_(target.cgis) return exists(select(_CELL.c.id).where(_CELL.c.snapshot_id == _SNAPSHOT.c.id, condition)) def _ready(city: str, start: date, end: date): return (_SNAPSHOT.c.city == city, _SNAPSHOT.c.status == "ready", _SNAPSHOT.c.snapshot_date >= start, _SNAPSHOT.c.snapshot_date < end) class GongcanStore: """快照的读写和按需取数。loader 负责从平台取一份快照,测试里可以换成假的。""" def __init__( self, engine: Engine, loader: Callable[[str, date], Awaitable[tuple[list[dict], str]]], *, poll_seconds: float = 10.0, wait_timeout: timedelta = timedelta(minutes=45), clock: Callable[[], datetime] = utcnow, ): self.engine = engine self.loader = loader self.poll_seconds = poll_seconds self.wait_timeout = wait_timeout self.clock = clock def ready_dates(self, city: str, start: date, end: date) -> list[date]: """start <= 日期 < end 的已就绪快照。""" with self.engine.connect() as connection: return sorted(connection.execute(select(_SNAPSHOT.c.snapshot_date).where(*_ready(city, start, end))).scalars()) def dates_with_target(self, city: str, target: Target, start: date, end: date) -> list[date]: with self.engine.connect() as connection: query = select(_SNAPSHOT.c.snapshot_date).where(*_ready(city, start, end), _has_target(target)) return sorted(connection.execute(query).scalars()) def has_target(self, city: str, day: date, target: Target) -> bool: return bool(self.dates_with_target(city, target, day, day + timedelta(days=1))) def cells(self, city: str, day: date) -> list[dict]: columns = [column for column in _CELL.c if column.name not in ("id", "snapshot_id")] with self.engine.connect() as connection: query = select(*columns).join(_SNAPSHOT, _SNAPSHOT.c.id == _CELL.c.snapshot_id).where(*_ready(city, day, day + timedelta(days=1))) return [dict(row._mapping) for row in connection.execute(query)] def _state(self, city: str, day: date): with self.engine.connect() as connection: return connection.execute( select(_SNAPSHOT.c.status, _SNAPSHOT.c.error).where(_SNAPSHOT.c.city == city, _SNAPSHOT.c.snapshot_date == day) ).first() async def ensure(self, city: str, day: date) -> None: """库里没有这一天就去平台取。别的任务正在取同一天时等它,不重复取。""" deadline = self.clock() + self.wait_timeout while True: state = self._state(city, day) if state is not None and state.status == "ready": return snapshot_id = claim_snapshot(self.engine, city, day, self.clock()) if snapshot_id is not None: await self._load(snapshot_id, city, day) return state = self._state(city, day) if state is not None and state.status == "failed": raise GongcanError(f"{city} {day} 的工参刚取失败,稍后再试:{state.error}") if self.clock() > deadline: raise GongcanError(f"等待 {city} {day} 的工参超时") await asyncio.sleep(self.poll_seconds) async def _load(self, snapshot_id: int, city: str, day: date) -> None: try: cells, source = await self.loader(city, day) save_snapshot(self.engine, snapshot_id, cells, source, self.clock()) except BaseException as exc: fail_snapshot(self.engine, snapshot_id, f"{type(exc).__name__}: {exc}", self.clock()) raise logger.info("工参快照 %s %s 已入库:%s 个小区,属性来自 %s", city, day, len(cells), source) def platform_loader(nqi: NqiClient, *, use_adhoc: bool = True) -> Callable[[str, date], Awaitable[tuple[list[dict], str]]]: oc = OpenCode(nqi) async def load(city: str, day: date) -> tuple[list[dict], str]: return await fetch_snapshot(nqi, oc, city, day, use_adhoc=use_adhoc) return load def china_today() -> date: return (datetime.now(timezone.utc) + timedelta(hours=8)).date() def month_start(day: date, offset: int = 0) -> date: index = day.year * 12 + day.month - 1 + offset return date(index // 12, index % 12 + 1, 1) @dataclass(frozen=True) class AfterPick: day: date target_present: bool async def pick_before(store: GongcanStore, city: str, target: Target, removal: date, months: int = 3) -> date: """拆除前用的工参日期。 库里拆除日前、近 months 个月(从 months 个月前的 1 号算起)有目标的快照,取最晚的一份; 没有就从拆除日上个月 1 号起逐月往前,库里没有的那天才去平台取,取到有目标的为止。 """ earliest = month_start(removal, -months) found = store.dates_with_target(city, target, earliest, removal) if found: return found[-1] stored = set(store.ready_dates(city, earliest, removal)) for back in range(1, months + 1): day = month_start(removal, -back) if day in stored: continue await store.ensure(city, day) if store.has_target(city, day, target): return day raise GongcanMissing(f"拆除前 {months} 个月的工参里都没有{target.label}") async def pick_after(store: GongcanStore, city: str, target: Target, removal: date, today: date) -> AfterPick | None: """拆除后用的工参日期,越接近今天越好。 库里拆除日之后、目标已经不在的快照取最晚的一份;都还在时,最晚那份是昨天就直接用, 不是就去平台取昨天的。目标仍在只做标记,不算失败。拆除日还没过去时返回 None。 """ yesterday = today - timedelta(days=1) if yesterday <= removal: return None start = removal + timedelta(days=1) stored = store.ready_dates(city, start, today) present = set(store.dates_with_target(city, target, start, today)) absent = [day for day in stored if day not in present] if absent: return AfterPick(absent[-1], False) if stored and stored[-1] == yesterday: return AfterPick(yesterday, True) await store.ensure(city, yesterday) return AfterPick(yesterday, store.has_target(city, yesterday, target)) def is_indoor(cell: dict) -> bool: return "W-" in (cell.get("cell_name") or "") def evaluable(cell: dict) -> bool: """与模板工具入库规则一致:去室分(小区名含 W-)和 4G 的 NB-IoT。""" return not is_indoor(cell) and not (cell.get("tech") == "4G" and (cell.get("network_type") or "").upper() == "NB-IOT") def haversine(lat1: float, lon1: float, lat2: float, lon2: float) -> float: p1, p2 = math.radians(lat1), math.radians(lat2) a = math.sin((p2 - p1) / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(math.radians(lon2 - lon1) / 2) ** 2 return 2 * 6371000.0 * math.asin(math.sqrt(a)) def target_center(cells: list[dict]) -> tuple[float, float] | None: """目标坐标取室外小区的平均;全是室分时用全部有坐标的小区。""" located = [cell for cell in cells if cell.get("latitude") is not None] chosen = [cell for cell in located if evaluable(cell)] or located if not chosen: return None return sum(cell["latitude"] for cell in chosen) / len(chosen), sum(cell["longitude"] for cell in chosen) / len(chosen) def nearest_sites( cells: list[dict], lat: float, lon: float, *, exclude: set[str], k: int = 3, exclude_keywords: tuple[str, ...] = ("微小",), ) -> list[tuple[str, float]]: """站点坐标取其可评估小区坐标的平均,按到目标的距离取最近 k 个,1 米内的视为同址不算。""" sums: dict[str, list[float]] = {} for cell in cells: site = cell.get("site_name") or "" if cell.get("latitude") is None or not site or site in exclude or not evaluable(cell): continue if any(word in (cell.get("cell_name") or "") for word in exclude_keywords): continue acc = sums.setdefault(site, [0.0, 0.0, 0.0]) acc[0] += cell["latitude"] acc[1] += cell["longitude"] acc[2] += 1 found = [] for site, (lat_sum, lon_sum, count) in sums.items(): dist = haversine(lat, lon, lat_sum / count, lon_sum / count) if dist >= 1.0: found.append((site, round(dist, 1))) found.sort(key=lambda item: item[1]) return found[:k]