464 lines
20 KiB
Python
464 lines
20 KiB
Python
"""评估取数。
|
|
|
|
工参:本系统的工参快照(CellData_4G/5G),拆除前后按 pick_before / pick_after 选日期,库里没有的日期
|
|
用提交人的大数据平台凭证经 OpenCode 补取;本系统账号没有凭证时借号池里的账号。
|
|
指标按周(周一到周日)取。4G 小区的流量、质量、扇区和频段取即席查询「[管理视图]重要场景-小区周粒度」;
|
|
MR 覆盖、竞对和 5G 小区还没接,先用模拟数据,同一小区同一时间段每次结果相同。
|
|
环境变量 DECOM_EVAL_SOURCE=mock 时工参和指标都用模拟数据,便于本地演示。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import hashlib
|
|
import math
|
|
import os
|
|
from collections.abc import Callable, Iterator
|
|
from contextlib import contextmanager
|
|
from datetime import date, datetime, time, timedelta
|
|
from typing import Protocol
|
|
|
|
from sqlalchemy import select
|
|
|
|
from app.collect.accounts import borrow_account, release_account
|
|
from app.collect.gongcan import AfterPick, GongcanError, GongcanStore, Target, fetch_snapshot, month_start, pick_after, pick_before
|
|
from app.db import engine, session_scope
|
|
from app.models import NqiAccount
|
|
from app.nqi import adhoc
|
|
from app.nqi.client import NqiAuthError, NqiClient, NqiError
|
|
from app.nqi.opencode import OpenCode
|
|
|
|
METRIC_KEYS = ("traffic_gb", "rrc_max", "high_load", "mr_weak_pct", "access_rate", "drop_rate", "util_peak")
|
|
MR_PROFILE_KEYS = ("mr_total", "mr_good_cnt", "mr_cover_pct", "unicom_cov", "telecom_cov", "weak_cell", "worse_unicom", "worse_telecom")
|
|
WEEK_TABLE = "appdbv3.a_overview_ispm_lte_cell_w"
|
|
WEEK_FIELDS = (
|
|
"starttime", "cgi", "cell_name", "station_name", "state", "freq_name", "freq", "bandwidth", "equivalent_20m_carrier",
|
|
"coverlayer", "sectors_name", "upoctudl_avg", "bh_effectiveconnmax", "bh_connmax", "bh_peak_use_rate",
|
|
"radio_succ_rate", "radio_drop_rate_cell", "is_highflow", "is_highload", "is_highflow_perceive",
|
|
)
|
|
MOCK_PREFIX = "模拟数据:"
|
|
|
|
|
|
class MetricError(Exception):
|
|
pass
|
|
|
|
|
|
class GongcanSource(Protocol):
|
|
def before_day(self, city: str, target: Target, removal: date) -> date: ...
|
|
|
|
def after_pick(self, city: str, target: Target, removal: date, today: date) -> AfterPick | None: ...
|
|
|
|
def cells(self, city: str, day: date) -> list[dict]: ...
|
|
|
|
|
|
class MetricSource(Protocol):
|
|
def window(self, cells: list[dict], start: date, end: date) -> dict[str, dict]:
|
|
"""每个小区在 [start, end] 这一周的指标,键见 METRIC_KEYS;没有数据的小区不出现。"""
|
|
|
|
def profile(self, cells: list[dict], start: date, end: date) -> dict[str, dict]:
|
|
"""每个小区在这一周的属性:扇区、频点、带宽、等效载波、流量、RRC、利用率、各类是否标志,以及 MR 采样和竞对覆盖。"""
|
|
|
|
def sector_members(self, sectors: set[str], start: date, end: date, pool: list[dict]) -> dict[str, list[dict]]:
|
|
"""这一周每个共站同覆盖区域(扇区)里的全部小区。"""
|
|
|
|
|
|
def eval_mode() -> str:
|
|
return "mock" if os.environ.get("DECOM_EVAL_SOURCE", "").strip().lower() == "mock" else "live"
|
|
|
|
|
|
def mock_notice() -> str:
|
|
if eval_mode() == "mock":
|
|
return f"{MOCK_PREFIX}演示模式,工参和指标都是模拟的,站点、距离和数值都不是现网的"
|
|
return f"{MOCK_PREFIX}MR 弱覆盖、覆盖率、竞对占比和 5G 小区的指标暂为模拟值;4G 小区的流量、质量和扇区取自即席查询周表"
|
|
|
|
|
|
def build_sources(owner_kind: str, owner_id: str, city: str) -> tuple[GongcanSource, MetricSource]:
|
|
if eval_mode() == "mock":
|
|
return MockGongcan(), MockMetrics()
|
|
return StoreGongcan(owner_kind, owner_id), PlatformMetrics(WeeklyLte(owner_kind, owner_id, city), MockMetrics())
|
|
|
|
|
|
@contextmanager
|
|
def platform_cookies(owner_kind: str, owner_id: str) -> Iterator[tuple[list, Callable[..., None]]]:
|
|
"""优先用提交人自己的大数据平台凭证;本系统账号或凭证失效时借号池里的账号。"""
|
|
if owner_kind == "nqi":
|
|
with session_scope() as session:
|
|
account = session.scalar(select(NqiAccount).where(NqiAccount.login_id == owner_id))
|
|
own = list(account.cookies or []) if account is not None and account.credential_valid else []
|
|
if own:
|
|
yield own, lambda invalid=False: None
|
|
return
|
|
borrowed = borrow_account()
|
|
if borrowed is None:
|
|
raise GongcanError("号池里没有可用的大数据平台账号,取不了平台数据")
|
|
account_id, cookies = borrowed
|
|
marks = {"invalid": False}
|
|
|
|
def mark(invalid: bool = False) -> None:
|
|
marks["invalid"] = marks["invalid"] or invalid
|
|
|
|
try:
|
|
yield cookies, mark
|
|
finally:
|
|
release_account(account_id, invalid=marks["invalid"])
|
|
|
|
|
|
class StoreGongcan:
|
|
"""工参快照库;缺的日期由 OpenCode 补取后入库,别的任务取同一天时会等它。"""
|
|
|
|
def __init__(self, owner_kind: str, owner_id: str):
|
|
self.owner_kind = owner_kind
|
|
self.owner_id = owner_id
|
|
self.store = GongcanStore(engine(), self._load)
|
|
|
|
async def _load(self, city: str, day: date) -> dict[str, list[dict]]:
|
|
with platform_cookies(self.owner_kind, self.owner_id) as (cookies, mark):
|
|
client = NqiClient()
|
|
client.import_cookies(cookies)
|
|
try:
|
|
return await fetch_snapshot(OpenCode(client), city, day)
|
|
except NqiAuthError as exc:
|
|
mark(True)
|
|
raise GongcanError("大数据平台登录已失效,请重新登录后再提交") from exc
|
|
finally:
|
|
await client.aclose()
|
|
|
|
def before_day(self, city: str, target: Target, removal: date) -> date:
|
|
return asyncio.run(pick_before(self.store, city, target, removal))
|
|
|
|
def after_pick(self, city: str, target: Target, removal: date, today: date) -> AfterPick | None:
|
|
return asyncio.run(pick_after(self.store, city, target, removal, today))
|
|
|
|
def cells(self, city: str, day: date) -> list[dict]:
|
|
return self.store.cells(city, day)
|
|
|
|
|
|
def _unit(*parts: object) -> float:
|
|
digest = hashlib.sha256("|".join(str(part) for part in parts).encode("utf-8")).digest()
|
|
return int.from_bytes(digest[:8], "big") / 2**64
|
|
|
|
|
|
def _between(low: float, high: float, *parts: object) -> float:
|
|
return low + (high - low) * _unit(*parts)
|
|
|
|
|
|
class MockGongcan:
|
|
"""演示用工参:待拆小区放在一处,周围散布模拟站点,拆除前取上个月 1 号、拆除后取昨天。"""
|
|
|
|
SITES = 24
|
|
|
|
def __init__(self):
|
|
self.targets: dict[str, str] = {}
|
|
|
|
def before_day(self, city: str, target: Target, removal: date) -> date:
|
|
for cgi in target.cgis:
|
|
self.targets.setdefault(cgi, target.site)
|
|
if target.site:
|
|
self.targets.setdefault(f"site:{target.site}", target.site)
|
|
return month_start(removal, -1)
|
|
|
|
def after_pick(self, city: str, target: Target, removal: date, today: date) -> AfterPick | None:
|
|
yesterday = today - timedelta(days=1)
|
|
return None if yesterday <= removal else AfterPick(yesterday, False)
|
|
|
|
def cells(self, city: str, day: date) -> list[dict]:
|
|
seed = sorted(self.targets)[0] if self.targets else city
|
|
base_lat = 22.2 + _between(0, 0.4, seed, "lat")
|
|
base_lon = 112.6 + _between(0, 0.5, seed, "lon")
|
|
cells: list[dict] = []
|
|
target_site = next((site for site in self.targets.values() if site), "") or "模拟待拆站点"
|
|
cgis = [key for key in self.targets if not key.startswith("site:")] or ["460-00-990000-1", "460-00-990000-2"]
|
|
for index, cgi in enumerate(cgis, start=1):
|
|
cells.append(_mock_cell(cgi, f"{target_site}-{index}", target_site, base_lat, base_lon, "4G"))
|
|
node = cgis[0].rsplit("-", 1)[0]
|
|
taken = set(cgis)
|
|
for sector in range(4, 10):
|
|
cgi = f"{node}-{sector}"
|
|
if cgi not in taken:
|
|
cells.append(_mock_cell(cgi, f"{target_site}-共站{sector}", target_site, base_lat, base_lon, "4G"))
|
|
for number in range(1, self.SITES + 1):
|
|
angle = _between(0, 2 * math.pi, seed, number, "angle")
|
|
meters = _between(180, 3500, seed, number, "dist")
|
|
lat = base_lat + meters * math.cos(angle) / 111_000
|
|
lon = base_lon + meters * math.sin(angle) / (111_000 * math.cos(math.radians(base_lat)))
|
|
site = f"模拟站点{number:02d}F-ZLH"
|
|
node = 900000 + number
|
|
for sector in range(1, 4):
|
|
cells.append(_mock_cell(f"460-00-{node}-{sector}", f"{site}-{sector}", site, lat, lon, "4G"))
|
|
if number % 2 == 0:
|
|
for sector in range(1, 3):
|
|
cells.append(_mock_cell(f"460-00-{12000000 + number * 10}-{sector}", f"{site}-NR-{sector}", site, lat, lon, "5G"))
|
|
return cells
|
|
|
|
|
|
def _mock_cell(cgi: str, name: str, site: str, lat: float, lon: float, tech: str) -> dict:
|
|
return {
|
|
"tech": tech,
|
|
"cgi": cgi,
|
|
"cell_name": name,
|
|
"site_name": site,
|
|
"node_id": cgi.rsplit("-", 1)[0],
|
|
"node_name": site,
|
|
"latitude": round(lat, 6),
|
|
"longitude": round(lon, 6),
|
|
"network_type": "NR" if tech == "5G" else "TDD",
|
|
"area": "",
|
|
"town": "",
|
|
"state": "现网有业务",
|
|
"cover_type": "室外",
|
|
"frequency_band": "",
|
|
"vendor": "",
|
|
"azimuth": "",
|
|
}
|
|
|
|
|
|
def _number(value: object) -> float | None:
|
|
if value is None or (isinstance(value, str) and not value.strip()):
|
|
return None
|
|
try:
|
|
return float(value)
|
|
except (TypeError, ValueError):
|
|
return None
|
|
|
|
|
|
def _yes(value: object) -> str:
|
|
text = value.strip().lower() if isinstance(value, str) else value
|
|
return "是" if text in (True, 1, "true", "1", "是", "yes") else "否"
|
|
|
|
|
|
def _week_monday(value: object) -> date | None:
|
|
text = str(value or "").strip()
|
|
if len(text) < 10:
|
|
return None
|
|
try:
|
|
return date.fromisoformat(text[:10])
|
|
except ValueError:
|
|
return None
|
|
|
|
|
|
def window_from_week(row: dict) -> dict:
|
|
"""周表一行对应周边站表用的一周指标。MR 弱覆盖不在这张表里。"""
|
|
return {
|
|
"traffic_gb": _number(row.get("upoctudl_avg")),
|
|
"rrc_max": _number(row.get("bh_effectiveconnmax")),
|
|
"high_load": 1 if _yes(row.get("is_highload")) == "是" else 0,
|
|
"access_rate": _number(row.get("radio_succ_rate")),
|
|
"drop_rate": _number(row.get("radio_drop_rate_cell")),
|
|
"util_peak": _number(row.get("bh_peak_use_rate")),
|
|
}
|
|
|
|
|
|
def profile_from_week(row: dict) -> dict:
|
|
"""周表一行对应低效拆除第 1 节的流量、质量和扇区。MR 采样仍由调用方补。"""
|
|
return {
|
|
"sector_name": str(row.get("sectors_name") or "").strip(),
|
|
"freq": str(row.get("freq_name") or "").strip(),
|
|
"freq_band": str(row.get("freq") or "").strip(),
|
|
"bandwidth": _number(row.get("bandwidth")),
|
|
"equiv": _number(row.get("equivalent_20m_carrier")),
|
|
"traffic_gb": _number(row.get("upoctudl_avg")),
|
|
"rrc_max": _number(row.get("bh_effectiveconnmax")),
|
|
"rrc_max_abs": _number(row.get("bh_connmax")),
|
|
"util_peak": _number(row.get("bh_peak_use_rate")),
|
|
"high_traffic_warn": _yes(row.get("is_highflow")),
|
|
"high_load_expand": _yes(row.get("is_highload")),
|
|
"high_perception": _yes(row.get("is_highflow_perceive")),
|
|
}
|
|
|
|
|
|
class WeeklyLte:
|
|
"""即席查询「[管理视图]重要场景-小区周粒度」,一行是一个 4G 小区的一整周。"""
|
|
|
|
def __init__(self, owner_kind: str, owner_id: str, city: str):
|
|
self.owner_kind = owner_kind
|
|
self.owner_id = owner_id
|
|
self.city = city
|
|
self._cgi_rows: dict[tuple[date, date], dict[str, dict | None]] = {}
|
|
self._sector_rows: dict[tuple[date, date], dict[str, list[dict]]] = {}
|
|
|
|
def by_cgi(self, cgis: list[str], start: date, end: date) -> dict[str, dict]:
|
|
names = [value for value in dict.fromkeys(str(item).strip() for item in cgis) if value]
|
|
cached = self._cgi_rows.setdefault((start, end), {})
|
|
missing = [name for name in names if name not in cached]
|
|
if missing:
|
|
for row in self._query("cgi", missing, start, end):
|
|
cgi = str(row.get("cgi") or "").strip()
|
|
monday = _week_monday(row.get("starttime"))
|
|
if not cgi or cgi in cached or monday is None or not (start <= monday <= end):
|
|
continue
|
|
cached[cgi] = row
|
|
for name in missing:
|
|
cached.setdefault(name, None)
|
|
return {name: row for name in names if (row := cached.get(name))}
|
|
|
|
def by_sector(self, sectors: set[str], start: date, end: date) -> dict[str, list[dict]]:
|
|
names = [value for value in dict.fromkeys(str(item).strip() for item in sectors) if value and "," not in value]
|
|
cached = self._sector_rows.setdefault((start, end), {})
|
|
missing = [name for name in names if name not in cached]
|
|
if missing:
|
|
grouped: dict[str, list[dict]] = {name: [] for name in missing}
|
|
seen = {name: set() for name in missing}
|
|
for row in self._query("sectors_name", missing, start, end):
|
|
sector = str(row.get("sectors_name") or "").strip()
|
|
cgi = str(row.get("cgi") or "").strip()
|
|
if sector not in grouped or not cgi or cgi in seen[sector]:
|
|
continue
|
|
seen[sector].add(cgi)
|
|
grouped[sector].append(
|
|
{
|
|
"cgi": cgi,
|
|
"cell_name": str(row.get("cell_name") or ""),
|
|
"site_name": str(row.get("station_name") or ""),
|
|
"tech": "4G",
|
|
}
|
|
)
|
|
cached.update(grouped)
|
|
return {name: list(cached.get(name, [])) for name in names}
|
|
|
|
def _query(self, field: str, values: list[str], start: date, end: date) -> list[dict]:
|
|
if not values:
|
|
return []
|
|
|
|
async def run() -> list[dict]:
|
|
with platform_cookies(self.owner_kind, self.owner_id) as (cookies, mark):
|
|
client = NqiClient()
|
|
client.import_cookies(cookies)
|
|
try:
|
|
return await adhoc.select_rows(
|
|
client,
|
|
WEEK_TABLE,
|
|
datetime.combine(start, time.min),
|
|
datetime.combine(end, time(23, 59, 59)),
|
|
self.city,
|
|
field,
|
|
values,
|
|
WEEK_FIELDS,
|
|
)
|
|
except NqiAuthError as exc:
|
|
mark(True)
|
|
raise MetricError("大数据平台登录已失效,请重新登录后再提交") from exc
|
|
except NqiError as exc:
|
|
raise MetricError(f"即席查询周数据失败:{exc}") from exc
|
|
finally:
|
|
await client.aclose()
|
|
|
|
return asyncio.run(run())
|
|
|
|
|
|
class PlatformMetrics:
|
|
"""4G 小区用周表的真实值;周表没有的 MR、竞对,以及全部 5G 小区,仍用模拟数据。"""
|
|
|
|
def __init__(self, weekly: WeeklyLte, fallback: MockMetrics):
|
|
self.weekly = weekly
|
|
self.fallback = fallback
|
|
|
|
def window(self, cells: list[dict], start: date, end: date) -> dict[str, dict]:
|
|
lte = [cell for cell in cells if cell.get("tech") != "5G"]
|
|
nr = [cell for cell in cells if cell.get("tech") == "5G"]
|
|
real = self.weekly.by_cgi([cell["cgi"] for cell in lte], start, end) if lte else {}
|
|
mocked = self.fallback.window(lte, start, end) if lte else {}
|
|
result: dict[str, dict] = {}
|
|
for cell in lte:
|
|
row = real.get(cell["cgi"])
|
|
if row is None:
|
|
continue
|
|
metrics = window_from_week(row)
|
|
metrics["mr_weak_pct"] = (mocked.get(cell["cgi"]) or {}).get("mr_weak_pct")
|
|
result[cell["cgi"]] = metrics
|
|
if nr:
|
|
result.update(self.fallback.window(nr, start, end))
|
|
return result
|
|
|
|
def profile(self, cells: list[dict], start: date, end: date) -> dict[str, dict]:
|
|
lte = [cell for cell in cells if cell.get("tech") != "5G"]
|
|
nr = [cell for cell in cells if cell.get("tech") == "5G"]
|
|
real = self.weekly.by_cgi([cell["cgi"] for cell in lte], start, end) if lte else {}
|
|
mocked = self.fallback.profile(cells, start, end)
|
|
result: dict[str, dict] = {}
|
|
for cell in lte:
|
|
base = mocked.get(cell["cgi"], {})
|
|
row = real.get(cell["cgi"])
|
|
if row is None:
|
|
result[cell["cgi"]] = {key: base.get(key) for key in MR_PROFILE_KEYS}
|
|
continue
|
|
mapped = profile_from_week(row)
|
|
for key in MR_PROFILE_KEYS:
|
|
mapped[key] = base.get(key)
|
|
result[cell["cgi"]] = mapped
|
|
for cell in nr:
|
|
result[cell["cgi"]] = mocked.get(cell["cgi"], {})
|
|
return result
|
|
|
|
def sector_members(self, sectors: set[str], start: date, end: date, pool: list[dict]) -> dict[str, list[dict]]:
|
|
return self.weekly.by_sector(sectors, start, end)
|
|
|
|
|
|
class MockMetrics:
|
|
"""模拟指标。数值范围按现网常见水平,拆除后周边小区流量略有上升。"""
|
|
|
|
FREQS_4G = ("D1", "D2", "E1", "F1", "FDD1800", "FDD900", "A")
|
|
|
|
def window(self, cells: list[dict], start: date, end: date) -> dict[str, dict]:
|
|
result: dict[str, dict] = {}
|
|
for cell in cells:
|
|
cgi = cell["cgi"]
|
|
base_traffic = _between(1.5, 55.0, cgi, "traffic")
|
|
result[cgi] = {
|
|
"traffic_gb": round(base_traffic * (1 + _between(-0.15, 0.25, cgi, start, "t")), 2),
|
|
"rrc_max": int(_between(8, 160, cgi, start, "rrc")),
|
|
"high_load": 1 if _unit(cgi, start, "load") < 0.04 else 0,
|
|
"mr_weak_pct": round(_between(0.3, 8.5, cgi, start, "weak"), 2),
|
|
"access_rate": round(_between(99.2, 99.99, cgi, start, "access"), 2),
|
|
"drop_rate": round(_between(0.01, 0.26, cgi, start, "drop"), 3),
|
|
"util_peak": round(_between(5, 68, cgi, start, "util"), 2),
|
|
}
|
|
return result
|
|
|
|
def profile(self, cells: list[dict], start: date, end: date) -> dict[str, dict]:
|
|
result: dict[str, dict] = {}
|
|
for cell in cells:
|
|
cgi = cell["cgi"]
|
|
nr = cell.get("tech") == "5G"
|
|
freq = "N41" if nr else self.FREQS_4G[int(_unit(cgi, "freq") * len(self.FREQS_4G))]
|
|
mr_total = int(_between(300_000, 1_800_000, cgi, start, "mr"))
|
|
cover = round(_between(91.5, 99.8, cgi, start, "cover"), 2)
|
|
result[cgi] = {
|
|
"sector_name": mock_sector(cell),
|
|
"freq": freq,
|
|
"freq_band": "2.6G" if nr else ("3D-MIMO" if _unit(cgi, "mimo") < 0.08 else ""),
|
|
"bandwidth": 100 if nr else (15 if freq.startswith("FDD") and _unit(cgi, "bw") < 0.5 else 20),
|
|
"traffic_gb": round(_between(1.5, 55.0, cgi, "traffic"), 2),
|
|
"rrc_max": int(_between(8, 160, cgi, start, "rrc")),
|
|
"rrc_max_abs": int(_between(12, 220, cgi, start, "rrcabs")),
|
|
"util_peak": round(_between(5, 68, cgi, start, "util"), 2),
|
|
"high_traffic_warn": "是" if _unit(cgi, start, "warn") < 0.05 else "否",
|
|
"high_load_expand": "是" if _unit(cgi, start, "expand") < 0.04 else "否",
|
|
"high_perception": "否",
|
|
"mr_total": mr_total,
|
|
"mr_good_cnt": int(mr_total * cover / 100),
|
|
"mr_cover_pct": cover,
|
|
"unicom_cov": round(_between(93, 99.6, cgi, start, "unicom"), 2),
|
|
"telecom_cov": round(_between(93, 99.6, cgi, start, "telecom"), 2),
|
|
"weak_cell": "是" if cover < 93 else "否",
|
|
"worse_unicom": "否",
|
|
"worse_telecom": "否",
|
|
}
|
|
return result
|
|
|
|
def sector_members(self, sectors: set[str], start: date, end: date, pool: list[dict]) -> dict[str, list[dict]]:
|
|
members: dict[str, list[dict]] = {sector: [] for sector in sectors}
|
|
for cell in pool:
|
|
sector = mock_sector(cell)
|
|
if sector in members:
|
|
members[sector].append(cell)
|
|
return members
|
|
|
|
|
|
def mock_sector(cell: dict) -> str:
|
|
"""模拟的共站同覆盖区域名:同站同扇区号(CGI 末段除以 3 取余)的小区归一个扇区。"""
|
|
try:
|
|
number = int(str(cell["cgi"]).rsplit("-", 1)[1])
|
|
except (IndexError, ValueError):
|
|
number = 0
|
|
return f"{cell.get('site_name') or ''}-扇区{number % 3 + 1}"
|