feat: 评估按拆除日的前一周和当周取 4G 周表,MR 和 5G 仍用模拟数据
This commit is contained in:
+1
-1
@@ -20,7 +20,7 @@ Vue 3、TypeScript、Naive UI。Node.js 只用于安装依赖、本地开发和
|
|||||||
|
|
||||||
## Positioning
|
## Positioning
|
||||||
|
|
||||||
工参按地市、日期存成快照。评估先用库里的快照,缺的日期用提交人的大数据平台凭证实时补取。流量、质量等指标计划从即席查询实时获取,目前为模拟数据。
|
工参按地市、日期存成快照。评估先用库里的快照,缺的日期用提交人的大数据平台凭证实时补取。4G 小区的流量、质量和扇区按拆除前一周和拆除当周从即席查询周表取实际数据;MR、竞对和 5G 小区的指标仍为模拟数据。
|
||||||
|
|
||||||
## Operating Context
|
## Operating Context
|
||||||
|
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ from app.evaluate.demand import (
|
|||||||
template_workbook,
|
template_workbook,
|
||||||
)
|
)
|
||||||
from app.evaluate.runner import JOB_FINAL, create_job, dispatch, remove_files, result_path
|
from app.evaluate.runner import JOB_FINAL, create_job, dispatch, remove_files, result_path
|
||||||
from app.evaluate.sources import METRICS_MOCKED, eval_mode
|
from app.evaluate.sources import eval_mode, mock_notice
|
||||||
from app.models import EvalJob, EvalTask, GongcanSnapshot, NqiAccount
|
from app.models import EvalJob, EvalTask, GongcanSnapshot, NqiAccount
|
||||||
|
|
||||||
router = APIRouter(prefix="/api/eval")
|
router = APIRouter(prefix="/api/eval")
|
||||||
@@ -92,7 +92,8 @@ def options(actor: Actor = Depends(current_actor), session: Session = db_session
|
|||||||
"applicant": actor.name,
|
"applicant": actor.name,
|
||||||
"orderTypes": list(ORDER_TYPES),
|
"orderTypes": list(ORDER_TYPES),
|
||||||
"neighbors": NEIGHBOR_SITES,
|
"neighbors": NEIGHBOR_SITES,
|
||||||
"metricsMocked": METRICS_MOCKED,
|
"metricsMocked": True,
|
||||||
|
"metricsNote": mock_notice(),
|
||||||
"gongcanMocked": eval_mode() == "mock",
|
"gongcanMocked": eval_mode() == "mock",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -15,7 +15,6 @@ from app.evaluate.demand import DemandRow, SiteGroup
|
|||||||
from app.evaluate.sources import GongcanSource, MetricSource
|
from app.evaluate.sources import GongcanSource, MetricSource
|
||||||
|
|
||||||
NEIGHBOR_SITES = 3
|
NEIGHBOR_SITES = 3
|
||||||
WINDOW_DAYS = 30
|
|
||||||
EXCLUDE_KEYWORDS = ("微小",)
|
EXCLUDE_KEYWORDS = ("微小",)
|
||||||
|
|
||||||
|
|
||||||
@@ -23,14 +22,19 @@ class EvalFailure(Exception):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def week_of(day: date) -> tuple[date, date]:
|
||||||
|
"""拆除日所在的自然周,周一到周日。"""
|
||||||
|
monday = day - timedelta(days=day.weekday())
|
||||||
|
return monday, monday + timedelta(days=6)
|
||||||
|
|
||||||
|
|
||||||
def windows(removal: date, today: date) -> tuple[tuple[date, date], tuple[date, date] | None]:
|
def windows(removal: date, today: date) -> tuple[tuple[date, date], tuple[date, date] | None]:
|
||||||
"""停闭前取拆除日前 30 天;停闭后取拆除日后 30 天,截至昨天,拆除日还没过就没有停闭后。"""
|
"""停闭前是拆除日所在周的上一周,停闭后是拆除日所在的那一周。当周周日还没过就没有停闭后。"""
|
||||||
before = (removal - timedelta(days=WINDOW_DAYS), removal - timedelta(days=1))
|
after_start, after_end = week_of(removal)
|
||||||
start = removal + timedelta(days=1)
|
before = (after_start - timedelta(days=7), after_end - timedelta(days=7))
|
||||||
last = today - timedelta(days=1)
|
if today <= after_end:
|
||||||
if start > last:
|
|
||||||
return before, None
|
return before, None
|
||||||
return before, (start, min(removal + timedelta(days=WINDOW_DAYS), last))
|
return before, (after_start, after_end)
|
||||||
|
|
||||||
|
|
||||||
def norm_freq(value: object) -> str:
|
def norm_freq(value: object) -> str:
|
||||||
@@ -122,7 +126,7 @@ def evaluate_site(
|
|||||||
stage("查询停闭前后指标")
|
stage("查询停闭前后指标")
|
||||||
before_window, after_window = windows(group.removal, today)
|
before_window, after_window = windows(group.removal, today)
|
||||||
if after_window is None:
|
if after_window is None:
|
||||||
notes.append("拆除日期还没过,没有停闭后的指标")
|
notes.append("拆除当周还没结束,没有停闭后的指标")
|
||||||
by_site: dict[str, list[dict]] = {}
|
by_site: dict[str, list[dict]] = {}
|
||||||
for cell in pool:
|
for cell in pool:
|
||||||
name = cell.get("cell_name") or ""
|
name = cell.get("cell_name") or ""
|
||||||
@@ -199,8 +203,7 @@ def _dixiao_sections(
|
|||||||
after_window: tuple[date, date] | None,
|
after_window: tuple[date, date] | None,
|
||||||
) -> tuple[list[dict], list[dict], list[str]]:
|
) -> tuple[list[dict], list[dict], list[str]]:
|
||||||
notes: list[str] = []
|
notes: list[str] = []
|
||||||
profile_day = before_window[1]
|
own = metrics.profile(targets, *before_window)
|
||||||
own = metrics.profile(targets, profile_day)
|
|
||||||
section1 = []
|
section1 = []
|
||||||
for row in rows:
|
for row in rows:
|
||||||
item = own.get(row.cgi, {})
|
item = own.get(row.cgi, {})
|
||||||
@@ -217,7 +220,7 @@ def _dixiao_sections(
|
|||||||
"自忙时峰值利用率": item.get("util_peak"),
|
"自忙时峰值利用率": item.get("util_peak"),
|
||||||
"是否高流量预警小区": item.get("high_traffic_warn"),
|
"是否高流量预警小区": item.get("high_traffic_warn"),
|
||||||
"是否高负荷待扩容小区": item.get("high_load_expand"),
|
"是否高负荷待扩容小区": item.get("high_load_expand"),
|
||||||
"是否高流量感知问题小区": "否",
|
"是否高流量感知问题小区": item.get("high_perception") or "否",
|
||||||
"(移动)总采样点数": item.get("mr_total"),
|
"(移动)总采样点数": item.get("mr_total"),
|
||||||
"(移动)采样点数量(大于-110)": item.get("mr_good_cnt"),
|
"(移动)采样点数量(大于-110)": item.get("mr_good_cnt"),
|
||||||
"(移动)弱覆盖采样点大于-110占比": item.get("mr_cover_pct"),
|
"(移动)弱覆盖采样点大于-110占比": item.get("mr_cover_pct"),
|
||||||
@@ -245,7 +248,7 @@ def _dixiao_sections(
|
|||||||
by_sector.setdefault(sector, []).append(row)
|
by_sector.setdefault(sector, []).append(row)
|
||||||
else:
|
else:
|
||||||
notes.append(f"{row.cell_name or row.cgi} 没有共站同覆盖区域名,第 2 节未纳入")
|
notes.append(f"{row.cell_name or row.cgi} 没有共站同覆盖区域名,第 2 节未纳入")
|
||||||
members = metrics.sector_members(set(by_sector), profile_day, pool) if by_sector else {}
|
members = metrics.sector_members(set(by_sector), before_window[0], before_window[1], pool) if by_sector else {}
|
||||||
sectors: list[dict] = []
|
sectors: list[dict] = []
|
||||||
for sector, sector_rows in by_sector.items():
|
for sector, sector_rows in by_sector.items():
|
||||||
everyone = members.get(sector, [])
|
everyone = members.get(sector, [])
|
||||||
@@ -253,8 +256,8 @@ def _dixiao_sections(
|
|||||||
if not remain:
|
if not remain:
|
||||||
notes.append(f"扇区 {sector} 除待拆小区外没有其他小区,第 2 节未纳入")
|
notes.append(f"扇区 {sector} 除待拆小区外没有其他小区,第 2 节未纳入")
|
||||||
continue
|
continue
|
||||||
profile = metrics.profile(remain, profile_day)
|
profile = metrics.profile(remain, *before_window)
|
||||||
later = metrics.profile(remain, after_window[1]) if after_window else {}
|
later = metrics.profile(remain, *after_window) if after_window else {}
|
||||||
before = metrics.window(remain, *before_window)
|
before = metrics.window(remain, *before_window)
|
||||||
after = metrics.window(remain, *after_window) if after_window else {}
|
after = metrics.window(remain, *after_window) if after_window else {}
|
||||||
sectors.append(_sector_group(sector, sector_rows, len(everyone), remain, profile, later, before, after))
|
sectors.append(_sector_group(sector, sector_rows, len(everyone), remain, profile, later, before, after))
|
||||||
@@ -272,7 +275,7 @@ def _sector_group(sector, sector_rows, total, remain, profile, later, before, af
|
|||||||
"cell": cell.get("cell_name") or cgi,
|
"cell": cell.get("cell_name") or cgi,
|
||||||
"cgi": cgi,
|
"cgi": cgi,
|
||||||
"band": norm_freq(info.get("freq")) if not nr else (info.get("freq_band") or norm_freq(info.get("freq"))),
|
"band": norm_freq(info.get("freq")) if not nr else (info.get("freq_band") or norm_freq(info.get("freq"))),
|
||||||
"equiv": None if nr else equiv_carriers(info.get("freq"), info.get("freq_band"), info.get("bandwidth")),
|
"equiv": info.get("equiv") if info.get("equiv") is not None else (None if nr else equiv_carriers(info.get("freq"), info.get("freq_band"), info.get("bandwidth"))),
|
||||||
"traffic_b": (before.get(cgi) or {}).get("traffic_gb"),
|
"traffic_b": (before.get(cgi) or {}).get("traffic_gb"),
|
||||||
"traffic_a": (after.get(cgi) or {}).get("traffic_gb"),
|
"traffic_a": (after.get(cgi) or {}).get("traffic_gb"),
|
||||||
"util_b": (before.get(cgi) or {}).get("util_peak"),
|
"util_b": (before.get(cgi) or {}).get("util_peak"),
|
||||||
|
|||||||
@@ -17,13 +17,11 @@ from app.db import session_scope
|
|||||||
from app.evaluate.compute import EvalFailure, evaluate_site
|
from app.evaluate.compute import EvalFailure, evaluate_site
|
||||||
from app.evaluate.demand import KIND_LABELS, DemandRow, SiteGroup
|
from app.evaluate.demand import KIND_LABELS, DemandRow, SiteGroup
|
||||||
from app.evaluate.report import Item1, NeighborGroup, write_dixiao, write_pinduan
|
from app.evaluate.report import Item1, NeighborGroup, write_dixiao, write_pinduan
|
||||||
from app.evaluate.sources import METRICS_MOCKED, build_sources, eval_mode
|
from app.evaluate.sources import MetricError, build_sources, mock_notice
|
||||||
from app.models import EvalJob, EvalTask, utcnow
|
from app.models import EvalJob, EvalTask, utcnow
|
||||||
|
|
||||||
logger = logging.getLogger("decom")
|
logger = logging.getLogger("decom")
|
||||||
JOB_FINAL = ("done", "partial", "failed")
|
JOB_FINAL = ("done", "partial", "failed")
|
||||||
MOCK_NOTICE = "流量和质量指标暂为模拟数据,接入即席查询后替换"
|
|
||||||
GONGCAN_MOCK_NOTICE = "演示模式:工参也是模拟数据,站点、距离和日期都不是现网的"
|
|
||||||
MAX_WARNINGS = 300
|
MAX_WARNINGS = 300
|
||||||
|
|
||||||
|
|
||||||
@@ -122,10 +120,10 @@ def execute_task(task_id: int) -> None:
|
|||||||
try:
|
try:
|
||||||
if group.removal is None:
|
if group.removal is None:
|
||||||
raise EvalFailure("缺少拆除日期")
|
raise EvalFailure("缺少拆除日期")
|
||||||
gongcan, metrics = build_sources(owner_kind, owner_id)
|
gongcan, metrics = build_sources(owner_kind, owner_id, city)
|
||||||
payload = evaluate_site(group, city, china_today(), gongcan, metrics, stage=lambda label: _stage(task_id, label))
|
payload = evaluate_site(group, city, china_today(), gongcan, metrics, stage=lambda label: _stage(task_id, label))
|
||||||
_finish_task(task_id, "done", payload=payload)
|
_finish_task(task_id, "done", payload=payload)
|
||||||
except (EvalFailure, GongcanError) as exc:
|
except (EvalFailure, GongcanError, MetricError) as exc:
|
||||||
_finish_task(task_id, "failed", error=str(exc) or "评估失败")
|
_finish_task(task_id, "failed", error=str(exc) or "评估失败")
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.exception("评估站点 %s 出错", task_id)
|
logger.exception("评估站点 %s 出错", task_id)
|
||||||
@@ -207,9 +205,7 @@ def finalize_job(job_id: int) -> None:
|
|||||||
|
|
||||||
|
|
||||||
def _write_results(job_id: int, title: str, entries: list[dict]) -> tuple[list[dict], list[str]]:
|
def _write_results(job_id: int, title: str, entries: list[dict]) -> tuple[list[dict], list[str]]:
|
||||||
warnings: list[str] = [MOCK_NOTICE] if METRICS_MOCKED else []
|
warnings: list[str] = [mock_notice()]
|
||||||
if eval_mode() == "mock":
|
|
||||||
warnings.append(GONGCAN_MOCK_NOTICE)
|
|
||||||
for entry in entries:
|
for entry in entries:
|
||||||
site = entry["payload"].get("site") or entry["key"]
|
site = entry["payload"].get("site") or entry["key"]
|
||||||
if entry["status"] == "failed":
|
if entry["status"] == "failed":
|
||||||
|
|||||||
+227
-26
@@ -2,8 +2,9 @@
|
|||||||
|
|
||||||
工参:本系统的工参快照(CellData_4G/5G),拆除前后按 pick_before / pick_after 选日期,库里没有的日期
|
工参:本系统的工参快照(CellData_4G/5G),拆除前后按 pick_before / pick_after 选日期,库里没有的日期
|
||||||
用提交人的大数据平台凭证经 OpenCode 补取;本系统账号没有凭证时借号池里的账号。
|
用提交人的大数据平台凭证经 OpenCode 补取;本系统账号没有凭证时借号池里的账号。
|
||||||
指标:流量、质量、扇区等还没接即席查询,先用模拟数据,同一小区同一时间段每次结果相同。
|
指标按周(周一到周日)取。4G 小区的流量、质量、扇区和频段取即席查询「[管理视图]重要场景-小区周粒度」;
|
||||||
环境变量 DECOM_EVAL_SOURCE=mock 时工参也用模拟数据,便于本地演示。
|
MR 覆盖、竞对和 5G 小区还没接,先用模拟数据,同一小区同一时间段每次结果相同。
|
||||||
|
环境变量 DECOM_EVAL_SOURCE=mock 时工参和指标都用模拟数据,便于本地演示。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -14,7 +15,7 @@ import math
|
|||||||
import os
|
import os
|
||||||
from collections.abc import Callable, Iterator
|
from collections.abc import Callable, Iterator
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
from datetime import date, timedelta
|
from datetime import date, datetime, time, timedelta
|
||||||
from typing import Protocol
|
from typing import Protocol
|
||||||
|
|
||||||
from sqlalchemy import select
|
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.collect.gongcan import AfterPick, GongcanError, GongcanStore, Target, fetch_snapshot, month_start, pick_after, pick_before
|
||||||
from app.db import engine, session_scope
|
from app.db import engine, session_scope
|
||||||
from app.models import NqiAccount
|
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
|
from app.nqi.opencode import OpenCode
|
||||||
|
|
||||||
METRIC_KEYS = ("traffic_gb", "rrc_max", "high_load", "mr_weak_pct", "access_rate", "drop_rate", "util_peak")
|
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):
|
class GongcanSource(Protocol):
|
||||||
@@ -40,22 +53,29 @@ class GongcanSource(Protocol):
|
|||||||
|
|
||||||
class MetricSource(Protocol):
|
class MetricSource(Protocol):
|
||||||
def window(self, cells: list[dict], start: date, end: date) -> dict[str, dict]:
|
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]:
|
def profile(self, cells: list[dict], start: date, end: date) -> dict[str, dict]:
|
||||||
"""每个小区截至 day 的最近一个月的属性:扇区、频点、带宽、月均流量、MR 采样、竞对覆盖和各类是否标志。"""
|
"""每个小区在这一周的属性:扇区、频点、带宽、等效载波、流量、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:
|
def eval_mode() -> str:
|
||||||
return "mock" if os.environ.get("DECOM_EVAL_SOURCE", "").strip().lower() == "mock" else "live"
|
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]:
|
def mock_notice() -> str:
|
||||||
gongcan: GongcanSource = MockGongcan() if eval_mode() == "mock" else StoreGongcan(owner_kind, owner_id)
|
if eval_mode() == "mock":
|
||||||
return gongcan, MockMetrics()
|
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
|
@contextmanager
|
||||||
@@ -70,7 +90,7 @@ def platform_cookies(owner_kind: str, owner_id: str) -> Iterator[tuple[list, Cal
|
|||||||
return
|
return
|
||||||
borrowed = borrow_account()
|
borrowed = borrow_account()
|
||||||
if borrowed is None:
|
if borrowed is None:
|
||||||
raise GongcanError("号池里没有可用的大数据平台账号,补取不了工参")
|
raise GongcanError("号池里没有可用的大数据平台账号,取不了平台数据")
|
||||||
account_id, cookies = borrowed
|
account_id, cookies = borrowed
|
||||||
marks = {"invalid": False}
|
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:
|
class MockMetrics:
|
||||||
"""模拟指标。数值范围按现网常见水平,拆除后周边小区流量略有上升。"""
|
"""模拟指标。数值范围按现网常见水平,拆除后周边小区流量略有上升。"""
|
||||||
|
|
||||||
@@ -213,38 +414,38 @@ class MockMetrics:
|
|||||||
}
|
}
|
||||||
return result
|
return result
|
||||||
|
|
||||||
def profile(self, cells: list[dict], day: date) -> dict[str, dict]:
|
def profile(self, cells: list[dict], start: date, end: date) -> dict[str, dict]:
|
||||||
month = day.replace(day=1)
|
|
||||||
result: dict[str, dict] = {}
|
result: dict[str, dict] = {}
|
||||||
for cell in cells:
|
for cell in cells:
|
||||||
cgi = cell["cgi"]
|
cgi = cell["cgi"]
|
||||||
nr = cell.get("tech") == "5G"
|
nr = cell.get("tech") == "5G"
|
||||||
freq = "N41" if nr else self.FREQS_4G[int(_unit(cgi, "freq") * len(self.FREQS_4G))]
|
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"))
|
mr_total = int(_between(300_000, 1_800_000, cgi, start, "mr"))
|
||||||
cover = round(_between(91.5, 99.8, cgi, month, "cover"), 2)
|
cover = round(_between(91.5, 99.8, cgi, start, "cover"), 2)
|
||||||
result[cgi] = {
|
result[cgi] = {
|
||||||
"sector_name": mock_sector(cell),
|
"sector_name": mock_sector(cell),
|
||||||
"freq": freq,
|
"freq": freq,
|
||||||
"freq_band": "2.6G" if nr else ("3D-MIMO" if _unit(cgi, "mimo") < 0.08 else ""),
|
"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),
|
"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),
|
"traffic_gb": round(_between(1.5, 55.0, cgi, "traffic"), 2),
|
||||||
"rrc_max": int(_between(8, 160, cgi, month, "rrc")),
|
"rrc_max": int(_between(8, 160, cgi, start, "rrc")),
|
||||||
"rrc_max_abs": int(_between(12, 220, cgi, month, "rrcabs")),
|
"rrc_max_abs": int(_between(12, 220, cgi, start, "rrcabs")),
|
||||||
"util_peak": round(_between(5, 68, cgi, month, "util"), 2),
|
"util_peak": round(_between(5, 68, cgi, start, "util"), 2),
|
||||||
"high_traffic_warn": "是" if _unit(cgi, month, "warn") < 0.05 else "否",
|
"high_traffic_warn": "是" if _unit(cgi, start, "warn") < 0.05 else "否",
|
||||||
"high_load_expand": "是" if _unit(cgi, month, "expand") < 0.04 else "否",
|
"high_load_expand": "是" if _unit(cgi, start, "expand") < 0.04 else "否",
|
||||||
|
"high_perception": "否",
|
||||||
"mr_total": mr_total,
|
"mr_total": mr_total,
|
||||||
"mr_good_cnt": int(mr_total * cover / 100),
|
"mr_good_cnt": int(mr_total * cover / 100),
|
||||||
"mr_cover_pct": cover,
|
"mr_cover_pct": cover,
|
||||||
"unicom_cov": round(_between(93, 99.6, cgi, month, "unicom"), 2),
|
"unicom_cov": round(_between(93, 99.6, cgi, start, "unicom"), 2),
|
||||||
"telecom_cov": round(_between(93, 99.6, cgi, month, "telecom"), 2),
|
"telecom_cov": round(_between(93, 99.6, cgi, start, "telecom"), 2),
|
||||||
"weak_cell": "是" if cover < 93 else "否",
|
"weak_cell": "是" if cover < 93 else "否",
|
||||||
"worse_unicom": "否",
|
"worse_unicom": "否",
|
||||||
"worse_telecom": "否",
|
"worse_telecom": "否",
|
||||||
}
|
}
|
||||||
return result
|
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}
|
members: dict[str, list[dict]] = {sector: [] for sector in sectors}
|
||||||
for cell in pool:
|
for cell in pool:
|
||||||
sector = mock_sector(cell)
|
sector = mock_sector(cell)
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ PAGE = f"{ADHOC}/adhocquery"
|
|||||||
ENTRY = f"{ADHOC}/index"
|
ENTRY = f"{ADHOC}/index"
|
||||||
PAGE_SIZE = 200
|
PAGE_SIZE = 200
|
||||||
MAX_PAGES = 2000
|
MAX_PAGES = 2000
|
||||||
|
IN_BATCH = 500
|
||||||
TIME_MODES = {"prev_month", "prev_week", "prev_day", "prev_weeks", "prev_months", "prev_days"}
|
TIME_MODES = {"prev_month", "prev_week", "prev_day", "prev_weeks", "prev_months", "prev_days"}
|
||||||
|
|
||||||
|
|
||||||
@@ -144,15 +145,50 @@ async def export_table(
|
|||||||
raise NqiError("这张表没有可导出的字段")
|
raise NqiError("这张表没有可导出的字段")
|
||||||
title = str(columns[0].get("tablename_cn") or tablename)
|
title = str(columns[0].get("tablename_cn") or tablename)
|
||||||
where = _where(columns[0], start, end, city, timed=_has_time_column(columns))
|
where = _where(columns[0], start, end, city, timed=_has_time_column(columns))
|
||||||
|
return title, columns, await _fetch_all(client, columns[0], columns, where)
|
||||||
|
|
||||||
|
|
||||||
|
async def select_rows(
|
||||||
|
client: NqiClient,
|
||||||
|
tablename: str,
|
||||||
|
start: datetime,
|
||||||
|
end: datetime,
|
||||||
|
city: str,
|
||||||
|
field: str,
|
||||||
|
values: list[str],
|
||||||
|
wanted: tuple[str, ...] = (),
|
||||||
|
) -> list[dict]:
|
||||||
|
"""按 field 的取值清单查 [start, end] 的行,和页面一样把清单逗号拼进 in 条件,每批 IN_BATCH 个。wanted 给出时只取这些列。"""
|
||||||
|
await ensure_session(client)
|
||||||
|
columns = await _columns(client, tablename)
|
||||||
|
if not columns:
|
||||||
|
raise NqiError("这张表没有可查的字段")
|
||||||
|
head = columns[0]
|
||||||
|
chosen = [column for column in columns if column.get("columnname") in wanted] if wanted else columns
|
||||||
|
names = [value for value in dict.fromkeys(str(item).strip() for item in values) if value and "," not in value]
|
||||||
|
timed = _has_time_column(columns)
|
||||||
|
rows: list[dict] = []
|
||||||
|
for offset in range(0, len(names), IN_BATCH):
|
||||||
|
where = _where(head, start, end, city, timed=timed)
|
||||||
|
at = len(where) - (1 if city.strip() else 0)
|
||||||
|
where.insert(
|
||||||
|
at,
|
||||||
|
{"datatype": "character", "feild": field, "feildName": "", "symbol": "in", "val": ",".join(names[offset : offset + IN_BATCH]), "whereCon": "and", "query": True},
|
||||||
|
)
|
||||||
|
rows.extend(await _fetch_all(client, head, chosen, where))
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
async def _fetch_all(client: NqiClient, head: dict, columns: list[dict], where: list[dict]) -> list[dict]:
|
||||||
common = {
|
common = {
|
||||||
"geographicdimension": columns[0].get("geographicdimension") or "",
|
"geographicdimension": head.get("geographicdimension") or "",
|
||||||
"timedimension": columns[0].get("timedimension") or "",
|
"timedimension": head.get("timedimension") or "",
|
||||||
"enodebField": columns[0].get("enodeb_field") or "",
|
"enodebField": head.get("enodeb_field") or "",
|
||||||
"cgiField": columns[0].get("cgi_field") or "",
|
"cgiField": head.get("cgi_field") or "",
|
||||||
"timeField": columns[0].get("time_field") or "starttime",
|
"timeField": head.get("time_field") or "starttime",
|
||||||
"cellField": columns[0].get("cell_field") or "",
|
"cellField": head.get("cell_field") or "",
|
||||||
"cityField": columns[0].get("city_field") or "city",
|
"cityField": head.get("city_field") or "city",
|
||||||
"result": _result_json(columns[0], columns),
|
"result": _result_json(head, columns),
|
||||||
"where": json.dumps(where, ensure_ascii=False),
|
"where": json.dumps(where, ensure_ascii=False),
|
||||||
}
|
}
|
||||||
total, index_count = await _count(client, common)
|
total, index_count = await _count(client, common)
|
||||||
@@ -186,7 +222,7 @@ async def export_table(
|
|||||||
if len(batch) < PAGE_SIZE:
|
if len(batch) < PAGE_SIZE:
|
||||||
break
|
break
|
||||||
start_at += PAGE_SIZE
|
start_at += PAGE_SIZE
|
||||||
return title, columns, rows
|
return rows
|
||||||
|
|
||||||
|
|
||||||
async def _count(client: NqiClient, common: dict) -> tuple[int, str]:
|
async def _count(client: NqiClient, common: dict) -> tuple[int, str]:
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import json
|
import json
|
||||||
from datetime import date
|
from datetime import date, datetime
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
@@ -56,3 +56,42 @@ def test_count_sends_indexcount_and_rejects_error_payload(monkeypatch):
|
|||||||
for _ in range(2):
|
for _ in range(2):
|
||||||
with pytest.raises(NqiError):
|
with pytest.raises(NqiError):
|
||||||
asyncio.run(adhoc._count(None, {"where": "[]"}))
|
asyncio.run(adhoc._count(None, {"where": "[]"}))
|
||||||
|
|
||||||
|
|
||||||
|
def test_select_rows_inserts_the_list_before_city_and_batches(monkeypatch):
|
||||||
|
monkeypatch.setattr(adhoc, "IN_BATCH", 2)
|
||||||
|
table = "appdbv3.a_overview_ispm_lte_cell_w"
|
||||||
|
table_columns = [
|
||||||
|
{**HEAD, "tablename": table, "columnname": "starttime", "time_field": "starttime", "city_field": "city"},
|
||||||
|
{**HEAD, "tablename": table, "columnname": "cgi"},
|
||||||
|
{**HEAD, "tablename": table, "columnname": "upoctudl_avg"},
|
||||||
|
]
|
||||||
|
seen = []
|
||||||
|
|
||||||
|
async def fake_columns(client, name):
|
||||||
|
assert name == table
|
||||||
|
return table_columns
|
||||||
|
|
||||||
|
async def session(client):
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def fetch(client, head, chosen, where):
|
||||||
|
seen.append(([column["columnname"] for column in chosen], where))
|
||||||
|
return [{"cgi": "ok"}]
|
||||||
|
|
||||||
|
monkeypatch.setattr(adhoc, "_columns", fake_columns)
|
||||||
|
monkeypatch.setattr(adhoc, "ensure_session", session)
|
||||||
|
monkeypatch.setattr(adhoc, "_fetch_all", fetch)
|
||||||
|
start, end = datetime(2026, 10, 5), datetime(2026, 10, 11, 23, 59, 59)
|
||||||
|
rows = asyncio.run(adhoc.select_rows(None, table, start, end, "江门", "cgi", ["460-00-1-1", "460-00-1-1", "bad,cgi", "460-00-1-2", "460-00-1-3"], ("cgi", "upoctudl_avg")))
|
||||||
|
assert rows == [{"cgi": "ok"}, {"cgi": "ok"}]
|
||||||
|
assert [item[0] for item in seen] == [["cgi", "upoctudl_avg"], ["cgi", "upoctudl_avg"]]
|
||||||
|
assert [(item["feild"], item["symbol"], item["val"]) for item in seen[0][1]] == [
|
||||||
|
("starttime", ">=", "2026-10-05 00:00:00"),
|
||||||
|
("starttime", "<", "2026-10-11 23:59:59"),
|
||||||
|
("cgi", "in", "460-00-1-1,460-00-1-2"),
|
||||||
|
("city", "in", "江门"),
|
||||||
|
]
|
||||||
|
assert seen[1][1][-2]["val"] == "460-00-1-3"
|
||||||
|
assert asyncio.run(adhoc.select_rows(None, table, start, end, "江门", "cgi", [])) == []
|
||||||
|
assert len(seen) == 2
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ from app.collect.gongcan import GongcanMissing
|
|||||||
from app.evaluate.compute import EvalFailure, equiv_carriers, evaluate_site, norm_freq, windows
|
from app.evaluate.compute import EvalFailure, equiv_carriers, evaluate_site, norm_freq, windows
|
||||||
from app.evaluate.demand import DemandError, DemandRow, SiteGroup, group_rows, parse_demand, template_workbook
|
from app.evaluate.demand import DemandError, DemandRow, SiteGroup, group_rows, parse_demand, template_workbook
|
||||||
from app.evaluate.report import Item1, NeighborGroup, write_dixiao, write_pinduan
|
from app.evaluate.report import Item1, NeighborGroup, write_dixiao, write_pinduan
|
||||||
from app.evaluate.sources import MockGongcan, MockMetrics
|
from app.evaluate.sources import MockGongcan, MockMetrics, PlatformMetrics
|
||||||
|
|
||||||
TODAY = date(2026, 11, 11)
|
TODAY = date(2026, 11, 11)
|
||||||
|
|
||||||
@@ -88,11 +88,60 @@ def test_frequency_rules_and_windows():
|
|||||||
assert equiv_carriers("E1", "3D-MIMO", 20) == 2.5
|
assert equiv_carriers("E1", "3D-MIMO", 20) == 2.5
|
||||||
assert equiv_carriers("", "", 20) is None
|
assert equiv_carriers("", "", 20) is None
|
||||||
before, after = windows(date(2026, 10, 15), TODAY)
|
before, after = windows(date(2026, 10, 15), TODAY)
|
||||||
assert before == (date(2026, 9, 15), date(2026, 10, 14))
|
assert before == (date(2026, 10, 5), date(2026, 10, 11))
|
||||||
assert after == (date(2026, 10, 16), date(2026, 11, 10))
|
assert after == (date(2026, 10, 12), date(2026, 10, 18))
|
||||||
assert windows(date(2026, 11, 10), TODAY)[1] is None
|
assert windows(date(2026, 11, 10), TODAY)[1] is None
|
||||||
|
|
||||||
|
|
||||||
|
class _WeekStub:
|
||||||
|
def __init__(self, row: dict):
|
||||||
|
self.row = row
|
||||||
|
|
||||||
|
def by_cgi(self, cgis, start, end):
|
||||||
|
return {cgi: self.row for cgi in cgis if cgi == self.row["cgi"]}
|
||||||
|
|
||||||
|
def by_sector(self, sectors, start, end):
|
||||||
|
return {"礼睦-扇区0": [{"cgi": "460-00-1-9", "cell_name": "礼睦-9", "site_name": "礼睦", "tech": "4G"}]}
|
||||||
|
|
||||||
|
|
||||||
|
def test_platform_metrics_keeps_weekly_lte_and_mocks_mr_and_nr():
|
||||||
|
metrics = PlatformMetrics(
|
||||||
|
_WeekStub(
|
||||||
|
{
|
||||||
|
"cgi": "460-00-1-1",
|
||||||
|
"upoctudl_avg": "21.1019",
|
||||||
|
"bh_effectiveconnmax": "25.28571",
|
||||||
|
"bh_connmax": "49.71429",
|
||||||
|
"bh_peak_use_rate": "31.7206",
|
||||||
|
"radio_succ_rate": "99.92656",
|
||||||
|
"radio_drop_rate_cell": "0.02945",
|
||||||
|
"is_highflow": False,
|
||||||
|
"is_highload": "false",
|
||||||
|
"is_highflow_perceive": True,
|
||||||
|
"sectors_name": "礼睦-扇区0",
|
||||||
|
"freq_name": "F1",
|
||||||
|
"freq": "F频段",
|
||||||
|
"bandwidth": "20",
|
||||||
|
"equivalent_20m_carrier": "1.0",
|
||||||
|
}
|
||||||
|
),
|
||||||
|
MockMetrics(),
|
||||||
|
)
|
||||||
|
cells = [{"cgi": "460-00-1-1", "tech": "4G", "site_name": "礼睦"}, {"cgi": "460-00-9-1", "tech": "5G", "site_name": "礼睦"}]
|
||||||
|
week = (date(2026, 10, 5), date(2026, 10, 11))
|
||||||
|
window = metrics.window(cells, *week)
|
||||||
|
assert window["460-00-1-1"]["traffic_gb"] == pytest.approx(21.1019)
|
||||||
|
assert window["460-00-1-1"]["high_load"] == 0 and window["460-00-1-1"]["mr_weak_pct"] is not None
|
||||||
|
assert "460-00-2-2" not in metrics.window([{"cgi": "460-00-2-2", "tech": "4G"}], *week)
|
||||||
|
assert window["460-00-9-1"]["traffic_gb"] is not None
|
||||||
|
profile = metrics.profile(cells, *week)
|
||||||
|
assert profile["460-00-1-1"]["sector_name"] == "礼睦-扇区0"
|
||||||
|
assert profile["460-00-1-1"]["high_perception"] == "是" and profile["460-00-1-1"]["equiv"] == 1.0
|
||||||
|
assert profile["460-00-1-1"]["mr_cover_pct"] is not None
|
||||||
|
assert profile["460-00-9-1"]["freq"] == "N41"
|
||||||
|
assert metrics.sector_members({"礼睦-扇区0"}, *week, [])["礼睦-扇区0"][0]["cgi"] == "460-00-1-9"
|
||||||
|
|
||||||
|
|
||||||
def demand(cgi: str, name: str, order: str = "频段清退", when: date = date(2026, 10, 15)) -> DemandRow:
|
def demand(cgi: str, name: str, order: str = "频段清退", when: date = date(2026, 10, 15)) -> DemandRow:
|
||||||
return DemandRow(line=2, cgi=cgi, order_type=order, need_date=when, cell_name=name, county="台山市", applicant="张三", retire_reason="搬迁")
|
return DemandRow(line=2, cgi=cgi, order_type=order, need_date=when, cell_name=name, county="台山市", applicant="张三", retire_reason="搬迁")
|
||||||
|
|
||||||
@@ -113,7 +162,7 @@ def test_evaluate_site_finds_neighbors_and_sectors_with_mock_sources():
|
|||||||
|
|
||||||
low = SiteGroup(key="低效站", kind="dixiao", order_type="低效拆除", removal=date(2026, 12, 20), rows=[demand("460-00-6001-1", "低效站E-ZLW-1", "低效拆除", date(2026, 12, 20))])
|
low = SiteGroup(key="低效站", kind="dixiao", order_type="低效拆除", removal=date(2026, 12, 20), rows=[demand("460-00-6001-1", "低效站E-ZLW-1", "低效拆除", date(2026, 12, 20))])
|
||||||
result = evaluate_site(low, "江门", TODAY, MockGongcan(), MockMetrics())
|
result = evaluate_site(low, "江门", TODAY, MockGongcan(), MockMetrics())
|
||||||
assert result["afterDay"] is None and "拆除日期还没过,没有停闭后的指标" in result["notes"]
|
assert result["afterDay"] is None and "拆除当周还没结束,没有停闭后的指标" in result["notes"]
|
||||||
assert len(result["section1"]) == 1 and result["section1"][0]["站点类型"] == "室分"
|
assert len(result["section1"]) == 1 and result["section1"][0]["站点类型"] == "室分"
|
||||||
assert result["sectors"] and result["sectors"][0]["base"] >= 1
|
assert result["sectors"] and result["sectors"][0]["base"] >= 1
|
||||||
assert all(item["after"] == {} for item in result["item2"])
|
assert all(item["after"] == {} for item in result["item2"])
|
||||||
@@ -255,7 +304,7 @@ def test_eval_api_end_to_end(client: TestClient):
|
|||||||
detail = wait_job(client, user, created["id"])
|
detail = wait_job(client, user, created["id"])
|
||||||
assert detail["job"]["status"] == "done", detail
|
assert detail["job"]["status"] == "done", detail
|
||||||
assert [result["kind"] for result in detail["job"]["results"]] == ["pinduan", "dixiao"]
|
assert [result["kind"] for result in detail["job"]["results"]] == ["pinduan", "dixiao"]
|
||||||
assert detail["job"]["warnings"][0].startswith("流量和质量指标暂为模拟数据")
|
assert detail["job"]["warnings"][0].startswith("模拟数据:")
|
||||||
assert [task["status"] for task in detail["tasks"]] == ["done", "done"]
|
assert [task["status"] for task in detail["tasks"]] == ["done", "done"]
|
||||||
assert detail["tasks"][0]["beforeDate"] == "2026-09-01" and len(detail["tasks"][0]["neighbors"]) == 3
|
assert detail["tasks"][0]["beforeDate"] == "2026-09-01" and len(detail["tasks"][0]["neighbors"]) == 3
|
||||||
for result in detail["job"]["results"]:
|
for result in detail["job"]["results"]:
|
||||||
|
|||||||
+40
-37
@@ -47,8 +47,8 @@
|
|||||||
2. **定位**:在拆除前工参里找目标小区(按小区)或站点名(按站点)。清单没写小区名的从工参补上;部分 CGI 不在工参里只记说明。
|
2. **定位**:在拆除前工参里找目标小区(按小区)或站点名(按站点)。清单没写小区名的从工参补上;部分 CGI 不在工参里只记说明。
|
||||||
3. **周边站**:离待拆小区中心最近的 3 个物理站,用拆除后工参(没有就用拆除前的)。排除待拆站本身、室分(小区名含 `W-`)、NB-IoT、
|
3. **周边站**:离待拆小区中心最近的 3 个物理站,用拆除后工参(没有就用拆除前的)。排除待拆站本身、室分(小区名含 `W-`)、NB-IoT、
|
||||||
名称含「微小」的小区。站内 4G 在前、再按小区名排。待拆小区没有经纬度时算不了周边站,结果表第 1 部分标红。
|
名称含「微小」的小区。站内 4G 在前、再按小区名排。待拆小区没有经纬度时算不了周边站,结果表第 1 部分标红。
|
||||||
4. **时间段**:停闭前为拆除日前 30 天到前 1 天;停闭后为拆除日后 1 天到「拆除后 30 天」和「昨天」中较早的一天。拆除日没过就没有停闭后。
|
4. **时间段**:停闭前是拆除日所在周的上一周(周一到周日),停闭后是拆除日所在的那一周。拆除当周的周日还没过,就没有停闭后,结果表判断列显示「拆除后再评估」。
|
||||||
5. **低效拆除另算两节**:第 1 节是本站各小区截至停闭前最后一天的月粒度属性;第 2 节按共站同覆盖区域(扇区)汇总除待拆小区外的其余小区。
|
5. **低效拆除另算两节**:第 1 节用停闭前那一周的小区属性;第 2 节按共站同覆盖区域(扇区)汇总除待拆小区外的其余小区,停闭后覆盖率用拆除当周。
|
||||||
- 等效 20M 载波数:TDD 为带宽/20;FDD1800、FDD900 为带宽/20×1.5;使用频段含 3D-MIMO 固定 2.5;5G 不算(填「/」)。
|
- 等效 20M 载波数:TDD 为带宽/20;FDD1800、FDD900 为带宽/20×1.5;使用频段含 3D-MIMO 固定 2.5;5G 不算(填「/」)。
|
||||||
- 频点 E1 记作 E,F1、F2、FDD1800、FDD900、3D-MIMO 原样。
|
- 频点 E1 记作 E,F1、F2、FDD1800、FDD900、3D-MIMO 原样。
|
||||||
- 扇区汇总:流量求和;等效单载波流量 = 流量和 / 等效载波数和;等效利用率按等效载波数加权平均;覆盖率取平均。
|
- 扇区汇总:流量求和;等效单载波流量 = 流量和 / 等效载波数和;等效利用率按等效载波数加权平均;覆盖率取平均。
|
||||||
@@ -72,51 +72,54 @@
|
|||||||
| 数据 | 现在 |
|
| 数据 | 现在 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| 工参 | 实际数据:本系统的工参快照;库里没有的日期用提交人的大数据平台凭证经 OpenCode 补取,自有账号用户借号池里的账号 |
|
| 工参 | 实际数据:本系统的工参快照;库里没有的日期用提交人的大数据平台凭证经 OpenCode 补取,自有账号用户借号池里的账号 |
|
||||||
| 指标 | 模拟数据:按 CGI 和时间段固定生成,同一小区同一时间段每次一样。`sources.METRICS_MOCKED` 为真时结果说明里会提示 |
|
| 4G 周指标 | 即席查询「[管理视图]重要场景-小区周粒度」(`appdbv3.a_overview_ispm_lte_cell_w`)。按 CGI 或扇区名分批查询,一次覆盖拆除前一周或拆除当周 |
|
||||||
|
| MR、竞对、5G | 仍是模拟数据。结果说明以「模拟数据:」开头 |
|
||||||
|
|
||||||
本地演示时设环境变量 `DECOM_EVAL_SOURCE=mock`,工参也用模拟数据,页面和结果说明会标出演示模式。
|
本地演示时设环境变量 `DECOM_EVAL_SOURCE=mock`,工参和 4G 指标也用模拟数据,页面和结果说明会标出演示模式。
|
||||||
|
|
||||||
## 待抓包的指标
|
## 已接入和仍待接入的指标
|
||||||
|
|
||||||
接入即席查询要实现 `sources.MetricSource` 的三个方法。下面是要从即席查询拿到的数据,4G、5G 都要。
|
`MetricSource` 的三个方法已按周调用。4G 来自周表,下表里标「周表」的键已是真实值;标「模拟」的键仍按 CGI 和周固定生成。5G 小区整行仍是模拟值。同一小区同一周每次结果相同。
|
||||||
|
|
||||||
### 周边站日指标(`window`)
|
### 周边站一周指标(`window`)
|
||||||
|
|
||||||
按小区按天,程序取时间段内的日均值,填两份模板的(5G、LTE)周边站表,低效拆除第 2 节也用其中的流量和利用率。
|
每个小区取这一周的一行,填两份模板的(5G、LTE)周边站表,低效拆除第 2 节也用其中的流量和利用率。
|
||||||
|
|
||||||
| 键 | 模板列 |
|
| 键 | 模板列 | 来源 |
|
||||||
| --- | --- |
|
| --- | --- | --- |
|
||||||
| `traffic_gb` | 日均流量(GB) / 小区流量(GB) |
|
| `traffic_gb` | 日均流量(GB) / 小区流量(GB) | 周表 `upoctudl_avg` |
|
||||||
| `rrc_max` | 日均有效 RRC 连接最大数 |
|
| `rrc_max` | 日均有效 RRC 连接最大数 | 周表 `bh_effectiveconnmax` |
|
||||||
| `high_load` | 是否高负荷待扩容小区(是 1,否 0) |
|
| `high_load` | 是否高负荷待扩容小区(是 1,否 0) | 周表 `is_highload` |
|
||||||
| `mr_weak_pct` | MR 弱覆盖(<-110dBm 的采样比例) |
|
| `mr_weak_pct` | MR 弱覆盖(<-110dBm 的采样比例) | 模拟,周表没有 |
|
||||||
| `access_rate` | 无线接通率(%) |
|
| `access_rate` | 无线接通率(%) | 周表 `radio_succ_rate` |
|
||||||
| `drop_rate` | 无线掉线率(%) |
|
| `drop_rate` | 无线掉线率(%) | 周表 `radio_drop_rate_cell` |
|
||||||
| `util_peak` | 自忙时峰值利用率% |
|
| `util_peak` | 自忙时峰值利用率% | 周表 `bh_peak_use_rate` |
|
||||||
|
|
||||||
### 本站小区月粒度(`profile`,低效拆除第 1 节和第 2 节)
|
### 本站小区一周属性(`profile`,低效拆除第 1 节和第 2 节)
|
||||||
|
|
||||||
取截至指定日期最近一个月的值。第 1 节用停闭前最后一天;第 2 节停闭后的覆盖率用停闭后时间段的最后一天。
|
第 1 节和第 2 节停闭前用拆除日前一周;第 2 节停闭后的覆盖率用拆除当周。周表同一 CGI 有完全相同的重复行时留第一条;这一周没有行的小区,流量和质量留空。
|
||||||
|
|
||||||
| 键 | 模板列 |
|
| 键 | 模板列 | 来源 |
|
||||||
| --- | --- |
|
| --- | --- | --- |
|
||||||
| `sector_name` | 扇区名称(所属共站同覆盖区域名) |
|
| `sector_name` | 扇区名称(所属共站同覆盖区域名) | 周表 `sectors_name` |
|
||||||
| `freq`、`freq_band`、`bandwidth` | 频段;用来算等效 20M 载波数(使用频段判断 3D-MIMO) |
|
| `freq`、`freq_band`、`bandwidth`、`equiv` | 频段和等效 20M 载波数 | 周表 `freq_name`、`freq`、`bandwidth`、`equivalent_20m_carrier`;等效载波优先用周表的值 |
|
||||||
| `traffic_gb` | 日均4G流量(GB) |
|
| `traffic_gb` | 日均4G流量(GB) | 周表 `upoctudl_avg` |
|
||||||
| `rrc_max` | 自忙时有效RRC连接最大数 |
|
| `rrc_max` | 自忙时有效RRC连接最大数 | 周表 `bh_effectiveconnmax` |
|
||||||
| `rrc_max_abs` | 自忙时RRC连接最大数 |
|
| `rrc_max_abs` | 自忙时RRC连接最大数 | 周表 `bh_connmax` |
|
||||||
| `util_peak` | 自忙时峰值利用率 |
|
| `util_peak` | 自忙时峰值利用率 | 周表 `bh_peak_use_rate` |
|
||||||
| `high_traffic_warn` | 是否高流量预警小区 |
|
| `high_traffic_warn` | 是否高流量预警小区 | 周表 `is_highflow` |
|
||||||
| `high_load_expand` | 是否高负荷待扩容小区 |
|
| `high_load_expand` | 是否高负荷待扩容小区 | 周表 `is_highload` |
|
||||||
| `mr_total` | (移动)总采样点数 |
|
| `high_perception` | 是否高流量感知问题小区 | 周表 `is_highflow_perceive` |
|
||||||
| `mr_good_cnt` | (移动)采样点数量(大于-110) |
|
| `mr_total` | (移动)总采样点数 | 模拟 |
|
||||||
| `mr_cover_pct` | (移动)弱覆盖采样点大于-110占比;第 2 节的基础覆盖层覆盖率 |
|
| `mr_good_cnt` | (移动)采样点数量(大于-110) | 模拟 |
|
||||||
| `unicom_cov`、`telecom_cov` | 移动联通 / 移动电信竞对采样点大于-110占比 |
|
| `mr_cover_pct` | (移动)弱覆盖采样点大于-110占比;第 2 节的基础覆盖层覆盖率 | 模拟 |
|
||||||
| `weak_cell`、`worse_unicom`、`worse_telecom` | 是否弱覆盖小区、是否劣化于联通、是否劣化于电信 |
|
| `unicom_cov`、`telecom_cov` | 移动联通 / 移动电信竞对采样点大于-110占比 | 模拟 |
|
||||||
|
| `weak_cell`、`worse_unicom`、`worse_telecom` | 是否弱覆盖小区、是否劣化于联通、是否劣化于电信 | 模拟 |
|
||||||
|
|
||||||
第 1 节这些列现在固定填写,有数据源后再接:是否高流量感知问题小区、取数期间是否存在退服情况、前三月是否为热点投诉、
|
第 1 节这些列仍固定填写:取数期间是否存在退服情况、前三月是否为热点投诉、是否人有我无区域(否);方案库聚类问题点的四列(无);评估结果(通过)。关联投诉量填 0。
|
||||||
是否人有我无区域(否);方案库聚类问题点的四列(无);评估结果(通过)。
|
|
||||||
|
|
||||||
### 扇区成员(`sector_members`)
|
### 扇区成员(`sector_members`)
|
||||||
|
|
||||||
给出共站同覆盖区域名,返回区域里的全部小区(CGI、小区名、制式)。模拟数据按「同站、CGI 末段除以 3 的余数相同」归为一个扇区。
|
4G 按周表 `sectors_name` 查询这一周的全部小区(CGI、小区名、站点名)。5G 扇区成员还没接。模拟数据按「同站、CGI 末段除以 3 的余数相同」归为一个扇区。
|
||||||
|
|
||||||
|
还没接上的表:MR 月表、5G 容量周表(`a_adhoc_capacity_nr_nrcell_w`)、投诉。
|
||||||
|
|||||||
@@ -36,8 +36,11 @@ const filtered = computed(() => {
|
|||||||
return tasks.value.filter((task) => task.status === filter.value);
|
return tasks.value.filter((task) => task.status === filter.value);
|
||||||
});
|
});
|
||||||
const shown = computed(() => filtered.value.slice(0, limit.value));
|
const shown = computed(() => filtered.value.slice(0, limit.value));
|
||||||
const notices = computed(() => (job.value?.warnings || []).filter((text) => !text.startsWith("流量和质量指标暂为模拟数据")));
|
function mockNotice(text: string) {
|
||||||
const mocked = computed(() => (job.value?.warnings || []).some((text) => text.startsWith("流量和质量指标暂为模拟数据")));
|
return text.startsWith("模拟数据:") || text.startsWith("流量和质量指标暂为模拟数据") || text.startsWith("演示模式:");
|
||||||
|
}
|
||||||
|
const notices = computed(() => (job.value?.warnings || []).filter((text) => !mockNotice(text)));
|
||||||
|
const mocked = computed(() => (job.value?.warnings || []).filter(mockNotice).map((text) => text.replace(/^模拟数据:/, "")));
|
||||||
|
|
||||||
function stop() {
|
function stop() {
|
||||||
window.clearTimeout(timer);
|
window.clearTimeout(timer);
|
||||||
@@ -134,7 +137,7 @@ function windowText(task: EvalTask) {
|
|||||||
</n-button>
|
</n-button>
|
||||||
</div>
|
</div>
|
||||||
<n-alert v-if="job.error" type="error" :show-icon="false">{{ job.error }}</n-alert>
|
<n-alert v-if="job.error" type="error" :show-icon="false">{{ job.error }}</n-alert>
|
||||||
<n-alert v-if="mocked" type="warning" :show-icon="false">流量和质量指标暂为模拟数据,接入即席查询后替换。</n-alert>
|
<n-alert v-if="mocked.length" type="warning" :show-icon="false">{{ mocked.join(";") }}</n-alert>
|
||||||
<n-collapse v-if="notices.length">
|
<n-collapse v-if="notices.length">
|
||||||
<n-collapse-item :title="`说明(${notices.length})`" name="notes">
|
<n-collapse-item :title="`说明(${notices.length})`" name="notes">
|
||||||
<ul class="notes">
|
<ul class="notes">
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { onMounted, onUnmounted, ref } from "vue";
|
import { computed, onMounted, onUnmounted, ref } from "vue";
|
||||||
import { NAlert, NButton, NIcon, NProgress, NTooltip, useDialog } from "naive-ui";
|
import { NAlert, NButton, NIcon, NProgress, NTooltip, useDialog } from "naive-ui";
|
||||||
import { CloudUploadOutline, DownloadOutline, EyeOutline, TrashOutline } from "@vicons/ionicons5";
|
import { CloudUploadOutline, DownloadOutline, EyeOutline, TrashOutline } from "@vicons/ionicons5";
|
||||||
import Shell from "../../shell/Shell.vue";
|
import Shell from "../../shell/Shell.vue";
|
||||||
@@ -16,6 +16,7 @@ const dialog = useDialog();
|
|||||||
const jobs = ref<EvalJob[]>([]);
|
const jobs = ref<EvalJob[]>([]);
|
||||||
const loaded = ref(false);
|
const loaded = ref(false);
|
||||||
const options = ref<EvalOptions | null>(null);
|
const options = ref<EvalOptions | null>(null);
|
||||||
|
const metricsNote = computed(() => (options.value?.metricsNote || "").replace(/^模拟数据:/, ""));
|
||||||
const singleOpen = ref(false);
|
const singleOpen = ref(false);
|
||||||
const importOpen = ref(false);
|
const importOpen = ref(false);
|
||||||
const drawerOpen = ref(false);
|
const drawerOpen = ref(false);
|
||||||
@@ -133,10 +134,7 @@ onUnmounted(stopPoll);
|
|||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
<div class="admin-scroll">
|
<div class="admin-scroll">
|
||||||
<n-alert v-if="options?.metricsMocked" class="admin-alert" type="warning" :show-icon="false">
|
<n-alert v-if="metricsNote" class="admin-alert" type="warning" :show-icon="false">{{ metricsNote }}</n-alert>
|
||||||
<template v-if="options.gongcanMocked">演示模式:工参和指标都是模拟数据,结果表只用来看流程和格式。</template>
|
|
||||||
<template v-else>流量和质量指标还没接入即席查询,结果表里的指标暂为模拟数据;工参按拆除前后规则取实际数据。</template>
|
|
||||||
</n-alert>
|
|
||||||
|
|
||||||
<div v-if="loaded && !jobs.length" class="surface empty-card">
|
<div v-if="loaded && !jobs.length" class="surface empty-card">
|
||||||
<div class="empty-guide">
|
<div class="empty-guide">
|
||||||
|
|||||||
@@ -50,6 +50,7 @@ export interface EvalOptions {
|
|||||||
orderTypes: string[];
|
orderTypes: string[];
|
||||||
neighbors: number;
|
neighbors: number;
|
||||||
metricsMocked: boolean;
|
metricsMocked: boolean;
|
||||||
|
metricsNote?: string;
|
||||||
gongcanMocked: boolean;
|
gongcanMocked: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user