feat: 工参小区按制式拆成 CellData_4G、CellData_5G;即席查询补上页面必带参数
两张表列名沿用平台工参表,已有快照由迁移 0008 原样搬过去。即席查询的 result 补 tableParams、columnname,计数补 indexcount=0,缺这些服务端会返回 stat 0。
This commit is contained in:
@@ -15,11 +15,11 @@ from collections.abc import Awaitable, Callable
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import delete, exists, insert, select, update
|
||||
from sqlalchemy import delete, exists, insert, or_, select, update
|
||||
from sqlalchemy.engine import Engine
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app.models import GongcanCell, GongcanSnapshot, utcnow
|
||||
from app.models import CellData4G, CellData5G, GongcanSnapshot, utcnow
|
||||
from app.nqi import adhoc
|
||||
from app.nqi.client import NqiClient, NqiError
|
||||
from app.nqi.opencode import EFFECTIVE, ExportFile, OpenCode, snapshot_where, task_session
|
||||
@@ -30,11 +30,13 @@ TECHS = ("4G", "5G")
|
||||
ADHOC_TABLES = {"4G": "appdbv3.v_a_common_cfg_lte_cellant_d", "5G": "appdbv3.a_common_cfg_nr_cellant_d"}
|
||||
PLATFORM_TABLES = {"4G": "appdbv3.a_common_cfg_lte_cellant_d", "5G": "appdbv3.a_common_cfg_nr_cellant_d"}
|
||||
KEYS = {"4G": ("cgi",), "5G": ("ncgi", "cgi")}
|
||||
NAMED_FIELDS = {
|
||||
"4G": {"cell_name": "cell_name", "site_name": "station_name", "node_id": "enodeb_id", "node_name": "enodeb_name"},
|
||||
"5G": {"cell_name": "nrcell_name", "site_name": "station_name", "node_id": "gnodeb_id", "node_name": "gnodeb_name"},
|
||||
}
|
||||
KEY_COLUMN = {"4G": "cgi", "5G": "ncgi"}
|
||||
SHARED_FIELDS = ("network_type", "area", "town", "state", "cover_type", "frequency_band", "vendor", "azimuth")
|
||||
ATTRIBUTES = {
|
||||
"4G": ("cell_name", "station_name", "enodeb_id", "enodeb_name") + SHARED_FIELDS,
|
||||
"5G": ("nrcell_name", "station_name", "gnodeb_id", "gnodeb_name") + SHARED_FIELDS,
|
||||
}
|
||||
CELL_TABLES = {"4G": CellData4G.__table__, "5G": CellData5G.__table__}
|
||||
COORDS = ("longitude", "latitude")
|
||||
MATCH_RATIO = 0.98
|
||||
FAILED_COOLDOWN = timedelta(minutes=10)
|
||||
@@ -66,7 +68,7 @@ class Target:
|
||||
|
||||
|
||||
def attribute_columns(tech: str) -> tuple[str, ...]:
|
||||
return tuple(NAMED_FIELDS[tech].values()) + SHARED_FIELDS
|
||||
return ATTRIBUTES[tech]
|
||||
|
||||
|
||||
def adhoc_fields(tech: str) -> tuple[str, ...]:
|
||||
@@ -124,21 +126,38 @@ def coordinates(rows: list[dict], tech: str) -> dict[str, tuple[float, float]]:
|
||||
|
||||
|
||||
def build_cells(attr_rows: list[dict], coord_rows: list[dict], tech: str) -> list[dict]:
|
||||
"""按 CellData_4G / CellData_5G 的列名组成一行一个小区。"""
|
||||
coords = coordinates(coord_rows, tech)
|
||||
mapping = {**NAMED_FIELDS[tech], **{name: name for name in SHARED_FIELDS}}
|
||||
cells: dict[str, dict] = {}
|
||||
for row in attr_rows:
|
||||
key = key_of(row, tech)
|
||||
if not key or key in cells:
|
||||
continue
|
||||
lat, lon = coords.get(key, (None, None))
|
||||
cell = {"tech": tech, "cgi": key, "latitude": lat, "longitude": lon}
|
||||
for target, source in mapping.items():
|
||||
cell[target] = str(row.get(source) or "").strip()
|
||||
cell = {KEY_COLUMN[tech]: key, "latitude": lat, "longitude": lon}
|
||||
for column in ATTRIBUTES[tech]:
|
||||
cell[column] = str(row.get(column) or "").strip()
|
||||
cells[key] = cell
|
||||
return list(cells.values())
|
||||
|
||||
|
||||
def unified(row, tech: str) -> dict:
|
||||
"""两张表的行换成同一套字段,邻站等计算不用分制式。"""
|
||||
name, site, node_id, node_name = ATTRIBUTES[tech][:4]
|
||||
item = {
|
||||
"tech": tech,
|
||||
"cgi": row[KEY_COLUMN[tech]],
|
||||
"cell_name": row[name],
|
||||
"site_name": row[site],
|
||||
"node_id": row[node_id],
|
||||
"node_name": row[node_name],
|
||||
"latitude": row["latitude"],
|
||||
"longitude": row["longitude"],
|
||||
}
|
||||
item.update({column: row[column] for column in SHARED_FIELDS})
|
||||
return item
|
||||
|
||||
|
||||
def key_overlap(attr_rows: list[dict], coord_rows: list[dict], tech: str) -> float:
|
||||
left = {key_of(row, tech) for row in attr_rows} - {""}
|
||||
right = {key_of(row, tech) for row in coord_rows} - {""}
|
||||
@@ -147,8 +166,8 @@ def key_overlap(attr_rows: list[dict], coord_rows: list[dict], tech: str) -> flo
|
||||
return len(left & right) / len(left | right)
|
||||
|
||||
|
||||
async def fetch_snapshot(nqi: NqiClient, oc: OpenCode, city: str, day: date, *, use_adhoc: bool = True) -> tuple[list[dict], str]:
|
||||
"""从大数据平台取一份快照,返回小区列表和属性来源(adhoc / opencode)。"""
|
||||
async def fetch_snapshot(nqi: NqiClient, oc: OpenCode, city: str, day: date, *, use_adhoc: bool = True) -> tuple[dict[str, list[dict]], str]:
|
||||
"""从大数据平台取一份快照,返回按制式分开的小区行和属性来源(adhoc / opencode)。"""
|
||||
attrs: dict[str, list[dict]] | None = None
|
||||
if use_adhoc:
|
||||
try:
|
||||
@@ -171,14 +190,13 @@ async def fetch_snapshot(nqi: NqiClient, oc: OpenCode, city: str, day: date, *,
|
||||
rows = {tech: tables[item.key].rows for tech, item in zip(TECHS, files)}
|
||||
source = "adhoc" if attrs is not None else "opencode"
|
||||
attrs = attrs if attrs is not None else rows
|
||||
cells = [cell for tech in TECHS for cell in build_cells(attrs[tech], rows[tech], tech)]
|
||||
if not any(cell["tech"] == "4G" for cell in cells) or not any(cell["tech"] == "5G" for cell in cells):
|
||||
cells = {tech: build_cells(attrs[tech], rows[tech], tech) for tech in TECHS}
|
||||
if not all(cells.values()):
|
||||
raise GongcanError(f"{city} {day} 的工参是空的")
|
||||
return cells, source
|
||||
|
||||
|
||||
_SNAPSHOT = GongcanSnapshot.__table__
|
||||
_CELL = GongcanCell.__table__
|
||||
|
||||
|
||||
def _aware(value: datetime) -> datetime:
|
||||
@@ -212,20 +230,22 @@ def claim_snapshot(engine: Engine, city: str, day: date, now: datetime) -> int |
|
||||
return int(row.id) if taken.rowcount == 1 else None
|
||||
|
||||
|
||||
def save_snapshot(engine: Engine, snapshot_id: int, cells: list[dict], source: str, now: datetime) -> None:
|
||||
def save_snapshot(engine: Engine, snapshot_id: int, cells: dict[str, list[dict]], source: str, now: datetime) -> None:
|
||||
with engine.begin() as connection:
|
||||
connection.execute(delete(_CELL).where(_CELL.c.snapshot_id == snapshot_id))
|
||||
for start in range(0, len(cells), 2000):
|
||||
connection.execute(insert(_CELL), [{**cell, "snapshot_id": snapshot_id} for cell in cells[start:start + 2000]])
|
||||
for tech, table in CELL_TABLES.items():
|
||||
rows = cells.get(tech) or []
|
||||
connection.execute(delete(table).where(table.c.snapshot_id == snapshot_id))
|
||||
for start in range(0, len(rows), 2000):
|
||||
connection.execute(insert(table), [{**row, "snapshot_id": snapshot_id} for row in rows[start:start + 2000]])
|
||||
connection.execute(
|
||||
update(_SNAPSHOT)
|
||||
.where(_SNAPSHOT.c.id == snapshot_id)
|
||||
.values(
|
||||
status="ready",
|
||||
attr_source=source,
|
||||
lte_cells=sum(1 for cell in cells if cell["tech"] == "4G"),
|
||||
nr_cells=sum(1 for cell in cells if cell["tech"] == "5G"),
|
||||
located_cells=sum(1 for cell in cells if cell["latitude"] is not None),
|
||||
lte_cells=len(cells.get("4G") or []),
|
||||
nr_cells=len(cells.get("5G") or []),
|
||||
located_cells=sum(1 for rows in cells.values() for row in rows if row["latitude"] is not None),
|
||||
error="",
|
||||
updated_at=now,
|
||||
)
|
||||
@@ -238,8 +258,11 @@ def fail_snapshot(engine: Engine, snapshot_id: int, error: str, now: datetime) -
|
||||
|
||||
|
||||
def _has_target(target: Target):
|
||||
condition = _CELL.c.site_name == target.site if target.site else _CELL.c.cgi.in_(target.cgis)
|
||||
return exists(select(_CELL.c.id).where(_CELL.c.snapshot_id == _SNAPSHOT.c.id, condition))
|
||||
found = []
|
||||
for tech, table in CELL_TABLES.items():
|
||||
condition = table.c.station_name == target.site if target.site else table.c[KEY_COLUMN[tech]].in_(target.cgis)
|
||||
found.append(exists(select(table.c.id).where(table.c.snapshot_id == _SNAPSHOT.c.id, condition)))
|
||||
return or_(*found)
|
||||
|
||||
|
||||
def _ready(city: str, start: date, end: date):
|
||||
@@ -252,7 +275,7 @@ class GongcanStore:
|
||||
def __init__(
|
||||
self,
|
||||
engine: Engine,
|
||||
loader: Callable[[str, date], Awaitable[tuple[list[dict], str]]],
|
||||
loader: Callable[[str, date], Awaitable[tuple[dict[str, list[dict]], str]]],
|
||||
*,
|
||||
poll_seconds: float = 10.0,
|
||||
wait_timeout: timedelta = timedelta(minutes=45),
|
||||
@@ -278,10 +301,16 @@ class GongcanStore:
|
||||
return bool(self.dates_with_target(city, target, day, day + timedelta(days=1)))
|
||||
|
||||
def cells(self, city: str, day: date) -> list[dict]:
|
||||
columns = [column for column in _CELL.c if column.name not in ("id", "snapshot_id")]
|
||||
"""当天快照里 4G、5G 的全部小区,字段见 unified。"""
|
||||
with self.engine.connect() as connection:
|
||||
query = select(*columns).join(_SNAPSHOT, _SNAPSHOT.c.id == _CELL.c.snapshot_id).where(*_ready(city, day, day + timedelta(days=1)))
|
||||
return [dict(row._mapping) for row in connection.execute(query)]
|
||||
snapshot_id = connection.execute(select(_SNAPSHOT.c.id).where(*_ready(city, day, day + timedelta(days=1)))).scalar()
|
||||
if snapshot_id is None:
|
||||
return []
|
||||
return [
|
||||
unified(row, tech)
|
||||
for tech, table in CELL_TABLES.items()
|
||||
for row in connection.execute(select(table).where(table.c.snapshot_id == snapshot_id)).mappings()
|
||||
]
|
||||
|
||||
def _state(self, city: str, day: date):
|
||||
with self.engine.connect() as connection:
|
||||
@@ -314,13 +343,13 @@ class GongcanStore:
|
||||
except BaseException as exc:
|
||||
fail_snapshot(self.engine, snapshot_id, f"{type(exc).__name__}: {exc}", self.clock())
|
||||
raise
|
||||
logger.info("工参快照 %s %s 已入库:%s 个小区,属性来自 %s", city, day, len(cells), source)
|
||||
logger.info("工参快照 %s %s 已入库:4G %s 个、5G %s 个小区,属性来自 %s", city, day, len(cells.get("4G") or []), len(cells.get("5G") or []), source)
|
||||
|
||||
|
||||
def platform_loader(nqi: NqiClient, *, use_adhoc: bool = True) -> Callable[[str, date], Awaitable[tuple[list[dict], str]]]:
|
||||
def platform_loader(nqi: NqiClient, *, use_adhoc: bool = True) -> Callable[[str, date], Awaitable[tuple[dict[str, list[dict]], str]]]:
|
||||
oc = OpenCode(nqi)
|
||||
|
||||
async def load(city: str, day: date) -> tuple[list[dict], str]:
|
||||
async def load(city: str, day: date) -> tuple[dict[str, list[dict]], str]:
|
||||
return await fetch_snapshot(nqi, oc, city, day, use_adhoc=use_adhoc)
|
||||
|
||||
return load
|
||||
|
||||
Reference in New Issue
Block a user