每个逻辑站点一个排队任务,与采集共用并行数量;工参按拆除前后规则取本系统快照,指标暂用模拟数据;全部站点结束后写频段清退、低效拆除两份结果表。去掉原来的通用导出任务。
263 lines
12 KiB
Python
263 lines
12 KiB
Python
"""评估取数。
|
|
|
|
工参:本系统的工参快照(CellData_4G/5G),拆除前后按 pick_before / pick_after 选日期,库里没有的日期
|
|
用提交人的大数据平台凭证经 OpenCode 补取;本系统账号没有凭证时借号池里的账号。
|
|
指标:流量、质量、扇区等还没接即席查询,先用模拟数据,同一小区同一时间段每次结果相同。
|
|
环境变量 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, 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.client import NqiAuthError, NqiClient
|
|
from app.nqi.opencode import OpenCode
|
|
|
|
METRIC_KEYS = ("traffic_gb", "rrc_max", "high_load", "mr_weak_pct", "access_rate", "drop_rate", "util_peak")
|
|
METRICS_MOCKED = True
|
|
|
|
|
|
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], day: date) -> dict[str, dict]:
|
|
"""每个小区截至 day 的最近一个月的属性:扇区、频点、带宽、月均流量、MR 采样、竞对覆盖和各类是否标志。"""
|
|
|
|
def sector_members(self, sectors: set[str], day: 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 build_sources(owner_kind: str, owner_id: str) -> tuple[GongcanSource, MetricSource]:
|
|
gongcan: GongcanSource = MockGongcan() if eval_mode() == "mock" else StoreGongcan(owner_kind, owner_id)
|
|
return gongcan, 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": "",
|
|
}
|
|
|
|
|
|
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], day: date) -> dict[str, dict]:
|
|
month = day.replace(day=1)
|
|
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, month, "mr"))
|
|
cover = round(_between(91.5, 99.8, cgi, month, "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, month, "rrc")),
|
|
"rrc_max_abs": int(_between(12, 220, cgi, month, "rrcabs")),
|
|
"util_peak": round(_between(5, 68, cgi, month, "util"), 2),
|
|
"high_traffic_warn": "是" if _unit(cgi, month, "warn") < 0.05 else "否",
|
|
"high_load_expand": "是" if _unit(cgi, month, "expand") < 0.04 else "否",
|
|
"mr_total": mr_total,
|
|
"mr_good_cnt": int(mr_total * cover / 100),
|
|
"mr_cover_pct": cover,
|
|
"unicom_cov": round(_between(93, 99.6, cgi, month, "unicom"), 2),
|
|
"telecom_cov": round(_between(93, 99.6, cgi, month, "telecom"), 2),
|
|
"weak_cell": "是" if cover < 93 else "否",
|
|
"worse_unicom": "否",
|
|
"worse_telecom": "否",
|
|
}
|
|
return result
|
|
|
|
def sector_members(self, sectors: set[str], day: 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}"
|