"""评估用的 4G/5G 小区工参:按地市、日期整份保存,任务先查库,没有再去大数据平台取。 一份快照由 OpenCode 在一条提示词里导出:全市当天有效(eff_from_date <= 当天 < eff_to_date)的 4G、5G 工参, CGI、经纬度和属性在同一条 SQL 里,没有有效坐标的小区经纬度留空。 即席查询的工参表没有日期列,4G 只有当前记录,取不到历史日,所以工参不走即席查询。 """ 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, or_, select, update from sqlalchemy.engine import Engine from sqlalchemy.exc import IntegrityError from app.models import CellData4G, CellData5G, GongcanSnapshot, utcnow from app.nqi.client import NqiClient from app.nqi.opencode import EFFECTIVE, ExportFile, OpenCode, snapshot_where, task_session logger = logging.getLogger("decom") TECHS = ("4G", "5G") PLATFORM_TABLES = {"4G": "appdbv3.a_common_cfg_lte_cellant_d", "5G": "appdbv3.a_common_cfg_nr_cellant_d"} KEYS = {"4G": ("cgi",), "5G": ("ncgi", "cgi")} KEY_COLUMN = {"4G": "cgi", "5G": "ncgi"} SHARED_FIELDS = ("network_type", "area", "town", "state", "cover_type", "frequency_band", "vendor", "azimuth") ATTRIBUTES = { "4G": ("cell_name", "station_name", "enodeb_id", "enodeb_name") + SHARED_FIELDS, "5G": ("nrcell_name", "station_name", "gnodeb_id", "gnodeb_name") + SHARED_FIELDS, } CELL_TABLES = {"4G": CellData4G.__table__, "5G": CellData5G.__table__} COORDS = ("longitude", "latitude") 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 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) -> list[ExportFile]: """全市当天有效的工参。文字列把英文逗号换成中文逗号,避免 CSV 错列。""" files = [] for tech, name in (("4G", "lte"), ("5G", "nr")): plain = KEYS[tech] + COORDS + EFFECTIVE select_list = list(plain) + [f"replace({column}::text, ',', ',') as {column}" for column in ATTRIBUTES[tech]] sql = f"select {', '.join(select_list)} from {PLATFORM_TABLES[tech]} where {snapshot_where(city, day)}" files.append(ExportFile(task, "gc", f"{name}.csv", sql, day, plain + ATTRIBUTES[tech])) 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(rows: list[dict], tech: str) -> list[dict]: """按 CellData_4G / CellData_5G 的列名组成一行一个小区,属性取该 CGI 的第一行。""" coords = coordinates(rows, tech) cells: dict[str, dict] = {} for row in rows: key = key_of(row, tech) if not key or key in cells: continue lat, lon = coords.get(key, (None, None)) cell = {KEY_COLUMN[tech]: key, "latitude": lat, "longitude": lon} for column in ATTRIBUTES[tech]: cell[column] = str(row.get(column) or "").strip() cells[key] = cell return list(cells.values()) def unified(row, tech: str) -> dict: """两张表的行换成同一套字段,邻站等计算不用分制式。""" name, site, node_id, node_name = ATTRIBUTES[tech][:4] item = { "tech": tech, "cgi": row[KEY_COLUMN[tech]], "cell_name": row[name], "site_name": row[site], "node_id": row[node_id], "node_name": row[node_name], "latitude": row["latitude"], "longitude": row["longitude"], } item.update({column: row[column] for column in SHARED_FIELDS}) return item async def fetch_snapshot(oc: OpenCode, city: str, day: date) -> dict[str, list[dict]]: """从大数据平台取一份快照,返回按制式分开的小区行。""" task = snapshot_task_name(city, day) async with task_session(oc, task) as session_id: files = platform_files(task, city, day) tables = await oc.export(session_id, files) cells = {tech: build_cells(tables[item.key].rows, tech) for tech, item in zip(TECHS, files)} if not all(cells.values()): raise GongcanError(f"{city} {day} 的工参是空的") return cells _SNAPSHOT = GongcanSnapshot.__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: dict[str, list[dict]], now: datetime) -> None: with engine.begin() as connection: for tech, table in CELL_TABLES.items(): rows = cells.get(tech) or [] connection.execute(delete(table).where(table.c.snapshot_id == snapshot_id)) for start in range(0, len(rows), 2000): connection.execute(insert(table), [{**row, "snapshot_id": snapshot_id} for row in rows[start:start + 2000]]) connection.execute( update(_SNAPSHOT) .where(_SNAPSHOT.c.id == snapshot_id) .values( status="ready", attr_source="opencode", lte_cells=len(cells.get("4G") or []), nr_cells=len(cells.get("5G") or []), located_cells=sum(1 for rows in cells.values() for row in rows if row["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): found = [] for tech, table in CELL_TABLES.items(): condition = table.c.station_name == target.site if target.site else table.c[KEY_COLUMN[tech]].in_(target.cgis) found.append(exists(select(table.c.id).where(table.c.snapshot_id == _SNAPSHOT.c.id, condition))) return or_(*found) 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[dict[str, list[dict]]]], *, 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]: """当天快照里 4G、5G 的全部小区,字段见 unified。""" with self.engine.connect() as connection: snapshot_id = connection.execute(select(_SNAPSHOT.c.id).where(*_ready(city, day, day + timedelta(days=1)))).scalar() if snapshot_id is None: return [] return [ unified(row, tech) for tech, table in CELL_TABLES.items() for row in connection.execute(select(table).where(table.c.snapshot_id == snapshot_id)).mappings() ] 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 = await self.loader(city, day) save_snapshot(self.engine, snapshot_id, cells, self.clock()) except BaseException as exc: fail_snapshot(self.engine, snapshot_id, f"{type(exc).__name__}: {exc}", self.clock()) raise logger.info("工参快照 %s %s 已入库:4G %s 个、5G %s 个小区", city, day, len(cells.get("4G") or []), len(cells.get("5G") or [])) def platform_loader(nqi: NqiClient) -> Callable[[str, date], Awaitable[dict[str, list[dict]]]]: oc = OpenCode(nqi) async def load(city: str, day: date) -> dict[str, list[dict]]: return await fetch_snapshot(oc, city, day) 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]