commit
This commit is contained in:
@@ -0,0 +1,567 @@
|
||||
"""导出服务:清单 + 工参 + 流量 → 评估模板.xlsx(按退网工单类型分模板)。
|
||||
|
||||
模板选择
|
||||
--------
|
||||
* 退网工单类型**包含「低效拆除」** → ``低效拆除评估模板.xlsx``(低效三步走版式);
|
||||
* 其余(含「频段清退」及未识别类型)→ ``频段清退评估模板.xlsx``,逻辑与
|
||||
本地版 HTML 工具一致,保持原行为不变。
|
||||
|
||||
频段清退模板填写规则
|
||||
--------------------
|
||||
第一项(退网站点审核信息):清单逐行填写;整个逻辑站的小区 CGI 全都定位不到时整站标红。
|
||||
第二项(临时停闭后评估拆除站对周边的影响):清单 CGI → 工参站点 → 最近 3 个**其它**
|
||||
站点(排除本站)的全部小区(4G + 5G)逐行填「停闭前 / 停闭后」指标,每个逻辑站一组。
|
||||
|
||||
低效拆除模板填写规则(详见 template_DIXiao.py)
|
||||
-------------------------------------------------
|
||||
第 1 节填清单小区的基础/容量字段(扇区名称取流量库「所属共站同覆盖区域名」);
|
||||
第 2 节按该扇区名称找同扇区全部小区、去掉清单小区(5G 用容量周报 PRB 利用率、
|
||||
等效20M载波数填「/」;基础覆盖层覆盖率 = MR 弱覆盖占比);
|
||||
第 3 节与频段清退第二项同逻辑(GSM 块保持原样)。未引用到的字段一律留空。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import json
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import polars as pl
|
||||
|
||||
from . import config
|
||||
from .db import Database
|
||||
from .geo import SiteIndex
|
||||
from .readers import FLOW_EXTRA, FLOW_METRICS, equiv_carriers, norm_freq, read_demand
|
||||
from .template_DIXiao import build_workbook_daiXiao
|
||||
from .template_PinDuan import Item1Record, Item2Record, build_workbook
|
||||
|
||||
Progress = Callable[[str, int], None]
|
||||
|
||||
# 参与前后对比的指标:流量五项 + 高负荷标志(低效模板 col4/col11 用)
|
||||
PAIR_METRICS = (*FLOW_METRICS, "high_load_num", "util_peak")
|
||||
|
||||
# 「生成静态字段」:每个 CGI 取时间最新一条的非空值(扇区名称/频点/两个是否标志等)
|
||||
_STATIC_COLS = (*FLOW_EXTRA, "traffic_gb", "rrc_max", "mr_weak_pct")
|
||||
|
||||
FLOW_QUERY_COLS = (
|
||||
"ts", "cgi", "traffic_gb", "rrc_max", "mr_weak_pct", "access_rate", "drop_rate",
|
||||
"freq", "freq_band", "bandwidth", "sector_name", "high_traffic_warn", "high_load_expand",
|
||||
"rrc_max_abs", "util_peak", "mr_total", "mr_weak_cnt",
|
||||
"unicom_cov", "telecom_cov", "weak_cell", "worse_unicom", "worse_telecom",
|
||||
)
|
||||
|
||||
|
||||
def _noop(_m: str, _p: int) -> None: # pragma: no cover
|
||||
return None
|
||||
|
||||
|
||||
def load_demand_file(path: str | Path, order_prefix: str | None = None) -> list[dict]:
|
||||
"""读取「生成评估模板」里选中的清单文件,返回与 ``demand`` 表同构的行列表。
|
||||
|
||||
该文件**不入库**:调用方拿到行列表后直接交给 :func:`run_export`,
|
||||
库里的 ``demand`` 表保持原样,随时可以切回"使用数据库清单"。
|
||||
"""
|
||||
df = read_demand(path)
|
||||
if order_prefix:
|
||||
df = df.filter(pl.col("order_type").fill_null("").str.starts_with(order_prefix))
|
||||
return df.to_dicts()
|
||||
|
||||
|
||||
def _metric_pairs(flow: pl.DataFrame, cgis: list[str]) -> dict[str, dict[str, dict[str, float | None]]]:
|
||||
"""按 CGI 汇总每个指标的「时间在前 / 时间在后」两个值。
|
||||
|
||||
不同报表的时间粒度不同(月/周),同一 CGI 的同一指标在不同 ts 上出现,
|
||||
因此逐指标取最早与最晚的非空值,正好满足"时间在前的放到时间在前的行"。
|
||||
"""
|
||||
if flow.height == 0 or not cgis:
|
||||
return {}
|
||||
f = flow.filter(pl.col("cgi").is_in(cgis)).sort("ts")
|
||||
if f.height == 0:
|
||||
return {}
|
||||
aggs: list[pl.Expr] = []
|
||||
for c in PAIR_METRICS:
|
||||
aggs.append(pl.col(c).drop_nulls().first().alias(f"{c}__b"))
|
||||
aggs.append(pl.col(c).drop_nulls().last().alias(f"{c}__a"))
|
||||
g = f.group_by("cgi", maintain_order=True).agg(aggs)
|
||||
out: dict[str, dict[str, dict[str, float | None]]] = {}
|
||||
for row in g.iter_rows(named=True):
|
||||
before = {c: row.get(f"{c}__b") for c in PAIR_METRICS}
|
||||
after = {c: row.get(f"{c}__a") for c in PAIR_METRICS}
|
||||
out[row["cgi"]] = {"before": before, "after": after}
|
||||
return out
|
||||
|
||||
|
||||
def _static_lookup(flow: pl.DataFrame) -> dict[str, dict]:
|
||||
"""每个 CGI 取时间最新一条的非空静态字段(扇区名称/频点/是否标志/最新指标)。"""
|
||||
if flow.height == 0:
|
||||
return {}
|
||||
g = flow.sort("ts").group_by("cgi", maintain_order=True).agg(
|
||||
[pl.col(c).drop_nulls().last().alias(c) for c in _STATIC_COLS]
|
||||
)
|
||||
return {row["cgi"]: row for row in g.iter_rows(named=True)}
|
||||
|
||||
|
||||
def _sector_groups(
|
||||
dx_rows: list[dict],
|
||||
static: dict[str, dict],
|
||||
gc: pl.DataFrame,
|
||||
flow: pl.DataFrame,
|
||||
) -> tuple[list[dict], list[str]]:
|
||||
"""第 2 节的扇区分组。
|
||||
|
||||
对清单小区按「扇区名称」(所属共站同覆盖区域名)归组,找出流量库里同扇区的
|
||||
全部小区,**去掉清单里的小区**后作为该组的行(基础覆盖层小区)。
|
||||
每个小区取流量「时间在前 / 时间在后」两套指标(停闭前 / 停闭后)。
|
||||
返回 (分组列表, 找不到扇区的小区名)。
|
||||
"""
|
||||
name_by_cgi = dict(zip(gc["cgi"].to_list(), gc["cell_name"].to_list()))
|
||||
dx_cgis = {r["cgi"] for r in dx_rows if r.get("cgi")}
|
||||
|
||||
# 扇区 → 流量库中全部小区
|
||||
sector_cells: dict[str, set[str]] = {}
|
||||
for cgi, st in static.items():
|
||||
s = str(st.get("sector_name") or "").strip()
|
||||
if s:
|
||||
sector_cells.setdefault(s, set()).add(cgi)
|
||||
|
||||
# 清单涉及到的扇区(按清单行的扇区名称)
|
||||
touched: dict[str, None] = {}
|
||||
missing: list[str] = []
|
||||
for r in dx_rows:
|
||||
st = static.get(r.get("cgi") or "")
|
||||
s = str((st or {}).get("sector_name") or "").strip()
|
||||
if s:
|
||||
touched.setdefault(s, None)
|
||||
else:
|
||||
missing.append(r.get("cell_name") or r.get("cgi") or "")
|
||||
|
||||
# 剩余小区的「时间在前/在后」指标(停闭前/停闭后)
|
||||
remains: dict[str, list[str]] = {}
|
||||
for sector in touched:
|
||||
all_cgis = sector_cells.get(sector, set())
|
||||
remain = sorted(
|
||||
(c for c in all_cgis if c not in dx_cgis),
|
||||
key=lambda c: name_by_cgi.get(c, c),
|
||||
)
|
||||
if remain:
|
||||
remains[sector] = remain
|
||||
pairs = _metric_pairs(flow, list({c for rs in remains.values() for c in rs})) if remains else {}
|
||||
|
||||
groups: list[dict] = []
|
||||
for sector, remain in remains.items():
|
||||
cells = []
|
||||
traffic_sum_b = traffic_sum_a = 0.0
|
||||
equiv_sum = 0.0
|
||||
cov_sum = cov_n = 0
|
||||
# 扇区等效单波利用率 = Σ(小区利用率×等效载波数) / Σ(等效载波数)
|
||||
wnum_b = wnum_a = wden = 0.0
|
||||
has_traffic_b = has_traffic_a = False
|
||||
for cgi in remain:
|
||||
st = static.get(cgi, {})
|
||||
p = pairs.get(cgi, {})
|
||||
before = p.get("before", {})
|
||||
after = p.get("after", {})
|
||||
equiv = equiv_carriers(st.get("freq"), st.get("freq_band"), st.get("bandwidth"))
|
||||
traffic_b = before.get("traffic_gb")
|
||||
traffic_a = after.get("traffic_gb")
|
||||
util_b = before.get("util_peak")
|
||||
util_a = after.get("util_peak")
|
||||
cov = st.get("mr_weak_pct") # 基础覆盖层覆盖率 = MR 弱覆盖占比(4G←MR月报 / 5G←MRO)
|
||||
cells.append(
|
||||
{
|
||||
"cell_name": name_by_cgi.get(cgi) or cgi,
|
||||
"cgi": cgi,
|
||||
"band": norm_freq(st.get("freq")) or st.get("freq_band") or None,
|
||||
"traffic_b": traffic_b,
|
||||
"traffic_a": traffic_a,
|
||||
"util_b": util_b,
|
||||
"util_a": util_a,
|
||||
"equiv": equiv,
|
||||
"cov": cov,
|
||||
}
|
||||
)
|
||||
if traffic_b is not None:
|
||||
traffic_sum_b += traffic_b
|
||||
has_traffic_b = True
|
||||
if traffic_a is not None:
|
||||
traffic_sum_a += traffic_a
|
||||
has_traffic_a = True
|
||||
if equiv is not None:
|
||||
equiv_sum += equiv
|
||||
if util_b is not None and equiv not in (None, 0):
|
||||
wnum_b += util_b * equiv
|
||||
wden += equiv
|
||||
if util_a is not None and equiv not in (None, 0):
|
||||
wnum_a += util_a * equiv
|
||||
if cov is not None:
|
||||
cov_sum += cov
|
||||
cov_n += 1
|
||||
total = len(sector_cells.get(sector, set()))
|
||||
base_cnt = len(remain)
|
||||
groups.append(
|
||||
{
|
||||
"sector": sector,
|
||||
"total": total, # 共扇区小区数(含清单小区)
|
||||
"base_cnt": base_cnt, # 基础覆盖层小区数(扇区 - 清单小区)
|
||||
"cells": cells,
|
||||
"traffic_sum_b": round(traffic_sum_b, 4) if has_traffic_b else None,
|
||||
"traffic_sum_a": round(traffic_sum_a, 4) if has_traffic_a else None,
|
||||
"equiv_sum": round(equiv_sum, 4) if equiv_sum else None,
|
||||
# 物理扇区等效单载波流量 = 扇区流量 / 扇区等效载波数
|
||||
"single_load_b": round(traffic_sum_b / equiv_sum, 4)
|
||||
if has_traffic_b and equiv_sum else None,
|
||||
"single_load_a": round(traffic_sum_a / equiv_sum, 4)
|
||||
if has_traffic_a and equiv_sum else None,
|
||||
"util_wavg_b": round(wnum_b / wden, 4) if wden else None,
|
||||
"util_wavg_a": round(wnum_a / wden, 4) if wden else None,
|
||||
# 基础覆盖层覆盖率(汇总)= 组内小区 MR 弱覆盖占比均值
|
||||
"cov_avg": round(cov_sum / cov_n, 4) if cov_n else None,
|
||||
}
|
||||
)
|
||||
return groups, missing
|
||||
|
||||
|
||||
def _site_key(row: dict) -> str:
|
||||
"""清单行的逻辑站点归属键:逻辑站点名称优先,为空时退化为小区名称。
|
||||
|
||||
分组与"整站标红"必须用同一个键,否则会算错站。
|
||||
"""
|
||||
return row["logical_site"] or row["cell_name"] or ""
|
||||
|
||||
|
||||
def _derive_county(row: dict) -> str:
|
||||
# 区县直接取清单「区县」列,不做推导
|
||||
return str(row.get("county") or "").strip()
|
||||
|
||||
|
||||
def _site_type(logical_site: str) -> str:
|
||||
"""第 1 节「站点类型」:逻辑站名结尾 H → 宏站,W → 室分,其余留空。"""
|
||||
s = str(logical_site or "").strip().upper()
|
||||
if s.endswith("H"):
|
||||
return "宏站"
|
||||
if s.endswith("W"):
|
||||
return "室分"
|
||||
return ""
|
||||
|
||||
|
||||
def _unique_path(directory: Path, name: str) -> Path:
|
||||
p = directory / name
|
||||
if not p.exists():
|
||||
return p
|
||||
stem, suffix = p.stem, p.suffix
|
||||
i = 2
|
||||
while True:
|
||||
cand = directory / f"{stem}({i}){suffix}"
|
||||
if not cand.exists():
|
||||
return cand
|
||||
i += 1
|
||||
|
||||
|
||||
def run_export(
|
||||
db: Database,
|
||||
*,
|
||||
template_path: str | Path | None = None,
|
||||
output_dir: str | Path | None = None,
|
||||
order_prefix: str | None = None,
|
||||
neighbor_k: int | None = None,
|
||||
progress: Progress | None = None,
|
||||
demands: list[dict] | None = None,
|
||||
demand_source: str | None = None,
|
||||
) -> dict:
|
||||
"""生成模板。
|
||||
|
||||
``demands`` 传入时直接用它(来自「生成评估模板」里选择的清单文件,已经按
|
||||
``order_prefix`` 过滤过),不再查 ``demand`` 表;``demand_source`` 仅用于
|
||||
在任务消息里标注清单来源。
|
||||
"""
|
||||
progress = progress or _noop
|
||||
template_path = Path(template_path or (config.DATA_DIR / config.TEMPLATE_FILENAME))
|
||||
output_dir = Path(output_dir or config.OUTPUT_DIR)
|
||||
order_prefix = order_prefix if order_prefix is not None else config.ORDER_TYPE_PREFIX
|
||||
neighbor_k = neighbor_k or config.NEIGHBOR_SITES
|
||||
warnings: list[str] = []
|
||||
|
||||
if not template_path.exists():
|
||||
raise FileNotFoundError(f"模板不存在:{template_path}")
|
||||
|
||||
if demands is None:
|
||||
progress("读取需求清单", 5)
|
||||
if order_prefix:
|
||||
demands = db.query(
|
||||
"SELECT * FROM demand WHERE order_type LIKE ? ORDER BY id", (f"{order_prefix}%",)
|
||||
)
|
||||
else:
|
||||
# 前缀留空 = 不筛选,清单里所有退网工单类型都进模板
|
||||
demands = db.query("SELECT * FROM demand ORDER BY id")
|
||||
demand_source = demand_source or "数据库清单"
|
||||
else:
|
||||
progress(f"使用所选清单({len(demands)} 行)", 5)
|
||||
demand_source = demand_source or "所选清单文件"
|
||||
|
||||
if not demands:
|
||||
raise ValueError(
|
||||
f"需求清单中没有「{order_prefix}」类记录,请先导入清单或确认退网工单类型"
|
||||
if order_prefix
|
||||
else "需求清单为空,请先导入清单或选择一份清单文件"
|
||||
)
|
||||
|
||||
progress("读取工参并建立站点索引", 15)
|
||||
gc = db.query_frame(
|
||||
"SELECT cgi, cell_name, lat, lon, site_name, tech, version FROM gongcan"
|
||||
)
|
||||
if gc.height == 0:
|
||||
raise ValueError("工参表为空,请先入库 4G/5G 工参")
|
||||
|
||||
# 定位索引:全量。表里除了最新版本的工参,还包含「旧版本补进来的、新版本已删除的小区」,
|
||||
# 退网清单点名的待拆站往往就在这部分里,必须能查到坐标。
|
||||
locator = SiteIndex(gc)
|
||||
|
||||
# 邻站候选池:只取每个制式的**最新版本**(已拆除的小区不该再作为别人的周边站),
|
||||
# 再按「小区名称包含 微小」排除微小站。
|
||||
if gc["version"].null_count() == gc.height:
|
||||
pool_df = gc # 老库没有版本列,退回全量
|
||||
else:
|
||||
latest = (
|
||||
gc.filter(pl.col("version").is_not_null())
|
||||
.group_by("tech")
|
||||
.agg(pl.col("version").max().alias("_v"))
|
||||
)
|
||||
pool_df = (
|
||||
gc.join(latest, on="tech", how="inner")
|
||||
.filter(pl.col("version") == pl.col("_v"))
|
||||
.drop("_v")
|
||||
)
|
||||
pool = SiteIndex(pool_df, exclude_keywords=config.NEIGHBOR_EXCLUDE_KEYWORDS)
|
||||
|
||||
# ---- 按退网工单类型分模板:含「低效拆除」走低效模板,其余(含频段清退)走频段清退模板
|
||||
keyword = config.DAI_XIAO_ORDER_KEYWORD
|
||||
dx_rows = [r for r in demands if keyword in (r["order_type"] or "")]
|
||||
pq_rows = [r for r in demands if keyword not in (r["order_type"] or "")]
|
||||
|
||||
progress(f"匹配周边站(频段清退 {len(pq_rows)} 行 / 低效拆除 {len(dx_rows)} 行)", 30)
|
||||
|
||||
def _match(rows: list[dict]) -> tuple[dict[str, list[dict]], list, list[str]]:
|
||||
groups: dict[str, list[dict]] = {}
|
||||
for row in rows:
|
||||
groups.setdefault(_site_key(row), []).append(row)
|
||||
plan: list[tuple[str, list[dict], list[tuple[str, float]]]] = []
|
||||
no_geo: list[str] = []
|
||||
for site_logical, srows in groups.items():
|
||||
center: tuple[float, float] | None = None
|
||||
exclude: set[str] = set()
|
||||
for r in srows:
|
||||
cgi = r["cgi"] or ""
|
||||
site = locator.site_of_cgi.get(cgi)
|
||||
if site:
|
||||
c = locator.site_center(site)
|
||||
if c:
|
||||
center, exclude = c, {site}
|
||||
break
|
||||
if center is None:
|
||||
no_geo.append(site_logical)
|
||||
plan.append((site_logical, [], []))
|
||||
continue
|
||||
neighbors = pool.nearest(center[0], center[1], k=neighbor_k, exclude=exclude)
|
||||
plan.append((site_logical, srows, neighbors))
|
||||
return groups, plan, no_geo
|
||||
|
||||
pq_groups, pq_plan, pq_no_geo = _match(pq_rows)
|
||||
dx_groups, dx_plan, dx_no_geo = _match(dx_rows)
|
||||
for no_geo, label in ((pq_no_geo, "频段清退"), (dx_no_geo, "低效拆除")):
|
||||
if no_geo:
|
||||
warnings.append(
|
||||
f"{label}:{len(no_geo)} 个逻辑站点在工参中找不到 CGI 或经纬度,"
|
||||
"第三项未生成:"
|
||||
+ "、".join(no_geo[:8])
|
||||
+ ("…" if len(no_geo) > 8 else "")
|
||||
)
|
||||
|
||||
# 收集需要取数的 CGI(两份模板的周边站并集)
|
||||
wanted: list[str] = []
|
||||
for _plan in (pq_plan, dx_plan):
|
||||
for _site, _rows, neighbors in _plan:
|
||||
for name, _dist in neighbors:
|
||||
for cell in pool.cells.get(name, []):
|
||||
wanted.append(cell["cgi"])
|
||||
wanted = list(dict.fromkeys(wanted))
|
||||
|
||||
progress(f"读取流量数据({len(wanted)} 个小区)", 55)
|
||||
flow = db.query_frame(
|
||||
f"SELECT {', '.join(FLOW_QUERY_COLS)} FROM flow"
|
||||
)
|
||||
# 高负荷标志 → 数值 0/1(低效模板 col4/col11 用;频段清退 writer 不读该键,行为不变)
|
||||
if flow.height and "high_load_expand" in flow.columns:
|
||||
flow = flow.with_columns(
|
||||
pl.when(pl.col("high_load_expand") == "是")
|
||||
.then(1.0)
|
||||
.when(pl.col("high_load_expand") == "否")
|
||||
.then(0.0)
|
||||
.otherwise(None)
|
||||
.alias("high_load_num")
|
||||
)
|
||||
else:
|
||||
flow = flow.with_columns(pl.lit(None, dtype=pl.Float64).alias("high_load_num"))
|
||||
pairs = _metric_pairs(flow, wanted)
|
||||
static = _static_lookup(flow)
|
||||
|
||||
def _build_item2(plan) -> tuple[list[Item2Record], int]:
|
||||
item2: list[Item2Record] = []
|
||||
missing_flow = 0
|
||||
for site_logical, _rows, neighbors in plan:
|
||||
for name, dist in neighbors:
|
||||
cells = sorted(
|
||||
pool.cells.get(name, []),
|
||||
key=lambda c: (0 if c["tech"] == "4G" else 1, c["cell_name"] or ""),
|
||||
)
|
||||
for cell in cells:
|
||||
p = pairs.get(cell["cgi"], {})
|
||||
if not p:
|
||||
missing_flow += 1
|
||||
item2.append(
|
||||
Item2Record(
|
||||
logical_site=site_logical,
|
||||
cell_name=cell["cell_name"] or cell["cgi"],
|
||||
tech=cell["tech"],
|
||||
before=p.get("before", {}),
|
||||
after=p.get("after", {}),
|
||||
site_name=name,
|
||||
distance=round(dist, 1),
|
||||
)
|
||||
)
|
||||
return item2, missing_flow
|
||||
|
||||
def _build_item1(rows: list[dict], no_geo: list[str]) -> list[Item1Record]:
|
||||
# 标红口径(仅频段清退模板):整个逻辑站的小区 CGI 全部匹配不到才标红
|
||||
unmatched_sites = set(no_geo)
|
||||
return [
|
||||
Item1Record(
|
||||
county=_derive_county(r),
|
||||
logical_site=r["logical_site"] or "",
|
||||
cell_name=r["cell_name"] or "",
|
||||
cgi=r["cgi"] or "",
|
||||
retire_reason=r["retire_reason"] or "",
|
||||
applicant=r["applicant"] or "",
|
||||
need_date=r["need_date"],
|
||||
locatable=_site_key(r) not in unmatched_sites,
|
||||
)
|
||||
for r in rows
|
||||
]
|
||||
|
||||
progress("生成模板数据", 70)
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
today = f"{datetime.now():%Y%m%d}" # ---- 频段清退模板(保持原有行为;清单为空时跳过该文件)
|
||||
result_pq: dict = {}
|
||||
if pq_rows:
|
||||
item1 = _build_item1(pq_rows, pq_no_geo)
|
||||
missing_rows = sum(1 for rec in item1 if not rec.locatable)
|
||||
if missing_rows:
|
||||
warnings.append(
|
||||
f"频段清退:第一项有 {len(set(pq_no_geo))} 个逻辑站共 {missing_rows} 行,"
|
||||
"站内所有小区的 CGI 在工参中都找不到(或经纬度为空),"
|
||||
"已整站标红(这些行不会生成第二项)"
|
||||
)
|
||||
item2, missing_flow = _build_item2(pq_plan)
|
||||
if missing_flow:
|
||||
warnings.append(f"频段清退:第二项有 {missing_flow} 个周边小区没有匹配到流量数据,指标列留空")
|
||||
out = _unique_path(output_dir, f"频段清退评估模板-{today}.xlsx")
|
||||
result_pq = build_workbook(template_path, out, item1, item2)
|
||||
|
||||
# ---- 低效拆除模板
|
||||
result_dx: dict = {}
|
||||
if dx_rows:
|
||||
dx_template = Path(config.DATA_DIR / config.DAI_XIAO_TEMPLATE_FILENAME)
|
||||
if not dx_template.exists():
|
||||
raise FileNotFoundError(
|
||||
f"清单里有「{keyword}」类记录,但低效拆除模板不存在:{dx_template}"
|
||||
)
|
||||
item1_dx = _build_item1(dx_rows, dx_no_geo)
|
||||
item2_dx, missing_flow_dx = _build_item2(dx_plan)
|
||||
if missing_flow_dx:
|
||||
warnings.append(f"低效拆除:第三项有 {missing_flow_dx} 个周边小区没有匹配到流量数据,指标列留空")
|
||||
|
||||
# 第 1 节:清单小区逐行(扇区名称/最新流量/两个是否标志来自流量库;
|
||||
# 退服/投诉/人有我无/方案库问题点各列按固定口径填写)
|
||||
section1 = []
|
||||
for rec in item1_dx:
|
||||
st = static.get(rec.cgi, {})
|
||||
section1.append(
|
||||
{
|
||||
"logical_site": rec.logical_site,
|
||||
"cell_name": rec.cell_name,
|
||||
"sector_name": str(st.get("sector_name") or "").strip()
|
||||
or None, # 扇区名称 = 流量库「所属共站同覆盖区域名」
|
||||
"site_type": _site_type(rec.logical_site),
|
||||
"traffic_gb": st.get("traffic_gb"),
|
||||
"rrc_max": st.get("rrc_max"),
|
||||
"high_warn": st.get("high_traffic_warn"),
|
||||
"high_load": st.get("high_load_expand"),
|
||||
"high_perception": "否", # 是否高流量感知问题小区固定填否
|
||||
# 第 1 节新增列(LTE 周报 / MR 月报提供)
|
||||
"rrc_max_abs": st.get("rrc_max_abs"),
|
||||
"util_peak": st.get("util_peak"),
|
||||
"mr_total": st.get("mr_total"),
|
||||
"mr_weak_cnt": st.get("mr_weak_cnt"),
|
||||
"mr_weak": st.get("mr_weak_pct"),
|
||||
"unicom_cov": st.get("unicom_cov"),
|
||||
"telecom_cov": st.get("telecom_cov"),
|
||||
"weak_cell": st.get("weak_cell"),
|
||||
"worse_unicom": st.get("worse_unicom"),
|
||||
"worse_telecom": st.get("worse_telecom"),
|
||||
# 固定值列
|
||||
"no_retire": "否",
|
||||
"no_complaint": "否",
|
||||
"no_area": "否",
|
||||
"issue_num": "无",
|
||||
"issue_type": "无",
|
||||
"issue_status": "无",
|
||||
"issue_solved": "无",
|
||||
"sec1_result": "通过",
|
||||
}
|
||||
)
|
||||
|
||||
sector_groups, missing_sector = _sector_groups(dx_rows, static, gc, flow)
|
||||
if missing_sector:
|
||||
uniq = list(dict.fromkeys(missing_sector))
|
||||
warnings.append(
|
||||
f"低效拆除:{len(uniq)} 个小区在流量数据中没有「所属共站同覆盖区域名」,"
|
||||
"第 2 节未纳入:"
|
||||
+ "、".join(uniq[:8])
|
||||
+ ("…" if len(uniq) > 8 else "")
|
||||
)
|
||||
|
||||
out_dx = _unique_path(output_dir, f"低效拆除评估模板-{today}.xlsx")
|
||||
result_dx = build_workbook_daiXiao(
|
||||
dx_template, out_dx, item1_dx, item2_dx, section1, sector_groups
|
||||
)
|
||||
|
||||
progress("完成", 100)
|
||||
if not result_pq and not result_dx:
|
||||
raise ValueError("没有任何可生成的模板(清单为空)")
|
||||
|
||||
primary = result_pq or result_dx
|
||||
outputs = [r["path"] for r in (result_pq, result_dx) if r]
|
||||
return {
|
||||
"output_path": primary["path"],
|
||||
"output_name": Path(primary["path"]).name,
|
||||
"outputs": outputs,
|
||||
"demand_count": len(demands),
|
||||
"demand_source": demand_source,
|
||||
"pinDuan_rows": result_pq.get("item1_rows", 0),
|
||||
"pinDuan_item2_rows": result_pq.get("item2_rows", 0),
|
||||
"pinDuan_sites": len(pq_groups),
|
||||
"daiXiao_path": result_dx.get("path"),
|
||||
"daiXiao_name": Path(result_dx["path"]).name if result_dx else None,
|
||||
"daiXiao_rows": result_dx.get("item1_rows", 0),
|
||||
"daiXiao_item2_rows": result_dx.get("item2_rows", 0),
|
||||
"daiXiao_sites": len(dx_groups),
|
||||
"daiXiao_sec1_rows": result_dx.get("sec1_rows", 0),
|
||||
"daiXiao_sec2_groups": result_dx.get("sec2_groups", 0),
|
||||
"daiXiao_sec2_rows": result_dx.get("sec2_rows", 0),
|
||||
"logical_sites": len(pq_groups) + len(dx_groups),
|
||||
"item2_sites": len(pq_groups) - len(pq_no_geo) + len(dx_groups) - len(dx_no_geo),
|
||||
"item1_rows": primary.get("item1_rows", 0),
|
||||
"item2_rows": primary.get("item2_rows", 0),
|
||||
"neighbor_sites": neighbor_k,
|
||||
"warnings": warnings,
|
||||
}
|
||||
Reference in New Issue
Block a user