feat: 评估按拆除日的前一周和当周取 4G 周表,MR 和 5G 仍用模拟数据
This commit is contained in:
+227
-26
@@ -2,8 +2,9 @@
|
||||
|
||||
工参:本系统的工参快照(CellData_4G/5G),拆除前后按 pick_before / pick_after 选日期,库里没有的日期
|
||||
用提交人的大数据平台凭证经 OpenCode 补取;本系统账号没有凭证时借号池里的账号。
|
||||
指标:流量、质量、扇区等还没接即席查询,先用模拟数据,同一小区同一时间段每次结果相同。
|
||||
环境变量 DECOM_EVAL_SOURCE=mock 时工参也用模拟数据,便于本地演示。
|
||||
指标按周(周一到周日)取。4G 小区的流量、质量、扇区和频段取即席查询「[管理视图]重要场景-小区周粒度」;
|
||||
MR 覆盖、竞对和 5G 小区还没接,先用模拟数据,同一小区同一时间段每次结果相同。
|
||||
环境变量 DECOM_EVAL_SOURCE=mock 时工参和指标都用模拟数据,便于本地演示。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -14,7 +15,7 @@ import math
|
||||
import os
|
||||
from collections.abc import Callable, Iterator
|
||||
from contextlib import contextmanager
|
||||
from datetime import date, timedelta
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from typing import Protocol
|
||||
|
||||
from sqlalchemy import select
|
||||
@@ -23,11 +24,23 @@ 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 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")
|
||||
METRICS_MOCKED = True
|
||||
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):
|
||||
@@ -40,22 +53,29 @@ class GongcanSource(Protocol):
|
||||
|
||||
class MetricSource(Protocol):
|
||||
def window(self, cells: list[dict], start: date, end: date) -> dict[str, dict]:
|
||||
"""每个小区在 [start, end] 的日均指标,键见 METRIC_KEYS。"""
|
||||
"""每个小区在 [start, end] 这一周的指标,键见 METRIC_KEYS;没有数据的小区不出现。"""
|
||||
|
||||
def profile(self, cells: list[dict], day: date) -> dict[str, dict]:
|
||||
"""每个小区截至 day 的最近一个月的属性:扇区、频点、带宽、月均流量、MR 采样、竞对覆盖和各类是否标志。"""
|
||||
def profile(self, cells: list[dict], start: date, end: date) -> dict[str, dict]:
|
||||
"""每个小区在这一周的属性:扇区、频点、带宽、等效载波、流量、RRC、利用率、各类是否标志,以及 MR 采样和竞对覆盖。"""
|
||||
|
||||
def sector_members(self, sectors: set[str], day: date, pool: list[dict]) -> dict[str, list[dict]]:
|
||||
"""每个共站同覆盖区域(扇区)里的全部小区。"""
|
||||
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 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()
|
||||
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
|
||||
@@ -70,7 +90,7 @@ def platform_cookies(owner_kind: str, owner_id: str) -> Iterator[tuple[list, Cal
|
||||
return
|
||||
borrowed = borrow_account()
|
||||
if borrowed is None:
|
||||
raise GongcanError("号池里没有可用的大数据平台账号,补取不了工参")
|
||||
raise GongcanError("号池里没有可用的大数据平台账号,取不了平台数据")
|
||||
account_id, cookies = borrowed
|
||||
marks = {"invalid": False}
|
||||
|
||||
@@ -192,6 +212,187 @@ def _mock_cell(cgi: str, name: str, site: str, lat: float, lon: float, tech: str
|
||||
}
|
||||
|
||||
|
||||
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:
|
||||
"""模拟指标。数值范围按现网常见水平,拆除后周边小区流量略有上升。"""
|
||||
|
||||
@@ -213,38 +414,38 @@ class MockMetrics:
|
||||
}
|
||||
return result
|
||||
|
||||
def profile(self, cells: list[dict], day: date) -> dict[str, dict]:
|
||||
month = day.replace(day=1)
|
||||
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, month, "mr"))
|
||||
cover = round(_between(91.5, 99.8, cgi, month, "cover"), 2)
|
||||
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, 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 "否",
|
||||
"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, month, "unicom"), 2),
|
||||
"telecom_cov": round(_between(93, 99.6, cgi, month, "telecom"), 2),
|
||||
"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], day: date, pool: list[dict]) -> dict[str, list[dict]]:
|
||||
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)
|
||||
|
||||
Reference in New Issue
Block a user