Files
DecomEval/backend/app/collect/gongcan.py
T
nixevol 9225d7e45b fix: 拆除后工参改用拆除日下一周的周一
停闭后一周的指标周三就有、下一周周一的工参周四才取,中间这一天周边站先按拆除前工参算,并在结果说明里写明。
2026-11-12 14:57:19 +08:00

501 lines
20 KiB
Python
Raw 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.
"""评估用的 4G/5G 小区工参:按地市、日期整份保存,任务先查库,没有再去大数据平台取。
一份快照由 OpenCode 在一条提示词里导出:全市当天有效(eff_from_date <= 当天 < eff_to_date)的 4G、5G 工参,
CGI、经纬度和属性在同一条 SQL 里,没有有效坐标的小区经纬度留空。
即席查询的工参表没有日期列,4G 只有当前记录,取不到历史日,所以工参不走即席查询。
快照只取每周一的:从 HISTORY_START 起每周一一份,提前缓存进库(见 gongcan_sync),评估按周一取用。
平台数据约三天同步好,所以最新能取的是三天前所在那一周的周一。
"""
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)
SYNC_LAG_DAYS = 3
HISTORY_START = date(2024, 1, 1)
BEFORE_LOOKBACK_WEEKS = 4
class GongcanError(Exception):
pass
def short_city(name: object) -> str:
"""平台账号里的地市带「市」「分公司」,工参和即席查询用不带后缀的名字。"""
text = str(name or "").strip()
for suffix in ("分公司", "市"):
if text.endswith(suffix) and len(text) > len(suffix):
text = text[: -len(suffix)]
return text
def monday_of(day: date) -> date:
return day - timedelta(days=day.weekday())
def latest_monday(today: date) -> date:
"""现在能取的最新一个周一。周一的工参要到周四才取。"""
return monday_of(today - timedelta(days=SYNC_LAG_DAYS))
def expected_mondays(today: date) -> list[date]:
"""库里应该有的全部周一,从早到晚。"""
last = latest_monday(today)
days = []
day = HISTORY_START
while day <= last:
days.append(day)
day += timedelta(days=7)
return days
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 release_loading(engine: Engine) -> int:
"""排队进程启动时调用:上一个进程没取完的快照行删掉,后面的任务可以马上重新取,不用等它过期。"""
with engine.begin() as connection:
return connection.execute(delete(_SNAPSHOT).where(_SNAPSHOT.c.status == "loading")).rowcount
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 missing_dates(self, city: str, days: list[date]) -> list[date]:
"""days 里库中还没有就绪快照的日期,顺序不变。"""
if not days:
return []
ready = set(self.ready_dates(city, min(days), max(days) + timedelta(days=1)))
return [day for day in days if day not in ready]
def next_to_fill(self, city: str, days: list[date]) -> date | None:
"""days 里下一份该补的日期,按 days 的顺序挑,取失败过的排到最后。
这个地市有快照正在取、或刚取失败还在冷却时返回 None:一个地市一次只取一份,平台出错时不连着打。
"""
missing = self.missing_dates(city, days)
if not missing:
return None
now = self.clock()
failed: set[date] = set()
with self.engine.connect() as connection:
rows = connection.execute(
select(_SNAPSHOT.c.snapshot_date, _SNAPSHOT.c.status, _SNAPSHOT.c.updated_at).where(_SNAPSHOT.c.city == city, _SNAPSHOT.c.status != "ready")
).all()
for row in rows:
age = now - _aware(row.updated_at)
if row.status == "loading" and age < STALE_LOADING:
return None
if row.status == "failed":
if age < FAILED_COOLDOWN:
return None
failed.add(row.snapshot_date)
return next((day for day in missing if day not in failed), missing[0])
async def fill(self, city: str, day: date) -> bool:
"""取回这一天入库。别人抢先在取时返回 False。"""
snapshot_id = claim_snapshot(self.engine, city, day, self.clock())
if snapshot_id is None:
return False
await self._load(snapshot_id, city, day)
return True
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()
@dataclass(frozen=True)
class AfterPick:
day: date
target_present: bool
def before_monday(removal: date, today: date) -> date:
"""拆除前工参:拆除日上一周的周一。那一天还取不到时用现在能取的最新一个周一。"""
return min(monday_of(removal) - timedelta(days=7), latest_monday(today))
def after_monday(removal: date, today: date) -> date | None:
"""拆除后工参:拆除日下一周的周一。那一天还取不到时没有拆除后工参。"""
day = monday_of(removal) + timedelta(days=7)
return day if day <= latest_monday(today) else None
async def pick_before(store: GongcanStore, city: str, target: Target, removal: date, today: date) -> date:
"""拆除前用的工参日期:拆除日上一周的周一;那份里没有目标就再往前一周,最多往前 BEFORE_LOOKBACK_WEEKS 周。
库里没有的周一才去平台取。
"""
first = before_monday(removal, today)
if first < HISTORY_START:
raise GongcanMissing(f"拆除日期 {removal} 太早,工参只从 {HISTORY_START} 起缓存")
for back in range(BEFORE_LOOKBACK_WEEKS + 1):
day = first - timedelta(days=7 * back)
if day < HISTORY_START:
break
await store.ensure(city, day)
if store.has_target(city, day, target):
return day
raise GongcanMissing(f"{first} 及之前 {BEFORE_LOOKBACK_WEEKS} 周的工参里都没有{target.label}")
async def pick_after(store: GongcanStore, city: str, target: Target, removal: date, today: date) -> AfterPick | None:
"""拆除后用的工参日期:拆除日下一周的周一。
拆掉的小区有时还留在工参里,这是正常的,只做标记。还取不到这一天时返回 None。
"""
day = after_monday(removal, today)
if day is None:
return None
await store.ensure(city, day)
return AfterPick(day, store.has_target(city, day, 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]