feat: 退网评估后端:单个或清单提交,按逻辑站点并行评估并写入固定模板
每个逻辑站点一个排队任务,与采集共用并行数量;工参按拆除前后规则取本系统快照,指标暂用模拟数据;全部站点结束后写频段清退、低效拆除两份结果表。去掉原来的通用导出任务。
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""退网评估:用户提交单个站点/小区或一份拆站清单,后台按逻辑站点并行取数、算周边站,写成固定模板的结果表。"""
|
||||
@@ -0,0 +1,315 @@
|
||||
"""单个逻辑站点的评估:选拆除前后的工参日期、定位待拆站点、找最近的周边站、取停闭前后的指标。
|
||||
|
||||
结果整理成可存进数据库的字典,汇总时再写入模板;字段名用模板里的中文表头,写入时按表头找列。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
from dataclasses import replace
|
||||
from datetime import date, timedelta
|
||||
|
||||
from app.collect.gongcan import GongcanMissing, Target, evaluable, nearest_sites, target_center
|
||||
from app.evaluate.demand import DemandRow, SiteGroup
|
||||
from app.evaluate.sources import GongcanSource, MetricSource
|
||||
|
||||
NEIGHBOR_SITES = 3
|
||||
WINDOW_DAYS = 30
|
||||
EXCLUDE_KEYWORDS = ("微小",)
|
||||
|
||||
|
||||
class EvalFailure(Exception):
|
||||
pass
|
||||
|
||||
|
||||
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))
|
||||
start = removal + timedelta(days=1)
|
||||
last = today - timedelta(days=1)
|
||||
if start > last:
|
||||
return before, None
|
||||
return before, (start, min(removal + timedelta(days=WINDOW_DAYS), last))
|
||||
|
||||
|
||||
def norm_freq(value: object) -> str:
|
||||
"""频点写成模板「频段」列的样子:E1/D7/A频段 → E/D/A;F1、F2、FDD1800、FDD900、3D-MIMO 原样。"""
|
||||
text = str(value or "").strip().upper().replace(" ", "").replace("(", "(").replace(")", ")")
|
||||
if not text:
|
||||
return ""
|
||||
if "3D-MIMO" in text or "3DMIMO" in text:
|
||||
return "3D-MIMO"
|
||||
for prefix in ("FDD1800", "FDD900"):
|
||||
if text.startswith(prefix):
|
||||
return prefix
|
||||
if text in ("F1", "F2"):
|
||||
return text
|
||||
return re.sub(r"\d+$", "", re.sub(r"(频段)+$", "", text))
|
||||
|
||||
|
||||
def equiv_carriers(freq: object, freq_band: object, bandwidth: object) -> float | None:
|
||||
"""等效 20M 载波数:TDD 为带宽/20,FDD 再乘 1.5,使用频段含 3D-MIMO 的固定 2.5;缺频点或带宽时不算。"""
|
||||
band = norm_freq(freq)
|
||||
usage = str(freq_band or "").upper().replace(" ", "")
|
||||
if band == "3D-MIMO" or "3D-MIMO" in usage or "3DMIMO" in usage:
|
||||
return 2.5
|
||||
if not band or bandwidth in (None, ""):
|
||||
return None
|
||||
try:
|
||||
width = float(bandwidth)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
factor = 1.5 if band in ("FDD1800", "FDD900") else 1.0
|
||||
return round(width / 20 * factor, 4)
|
||||
|
||||
|
||||
def site_type(logical_site: str) -> str:
|
||||
"""逻辑站点名结尾 H 是宏站,W 是室分。"""
|
||||
tail = (logical_site or "").strip().upper()
|
||||
if tail.endswith("H"):
|
||||
return "宏站"
|
||||
if tail.endswith("W"):
|
||||
return "室分"
|
||||
return ""
|
||||
|
||||
|
||||
def evaluate_site(
|
||||
group: SiteGroup,
|
||||
city: str,
|
||||
today: date,
|
||||
gongcan: GongcanSource,
|
||||
metrics: MetricSource,
|
||||
*,
|
||||
neighbor_k: int = NEIGHBOR_SITES,
|
||||
stage: Callable[[str], None] = lambda _text: None,
|
||||
) -> dict:
|
||||
target = Target(site=group.site) if group.site else Target(cgis=tuple(group.cgis))
|
||||
stage("确定拆除前工参")
|
||||
try:
|
||||
before_day = gongcan.before_day(city, target, group.removal)
|
||||
except GongcanMissing as exc:
|
||||
raise EvalFailure(str(exc)) from exc
|
||||
stage("确定拆除后工参")
|
||||
after = gongcan.after_pick(city, target, group.removal, today)
|
||||
|
||||
stage("定位待拆站点")
|
||||
before_cells = gongcan.cells(city, before_day)
|
||||
if target.site:
|
||||
targets = [cell for cell in before_cells if cell.get("site_name") == target.site]
|
||||
else:
|
||||
wanted = set(target.cgis)
|
||||
targets = [cell for cell in before_cells if cell["cgi"] in wanted]
|
||||
if not targets:
|
||||
raise EvalFailure(f"{before_day} 的工参里找不到{target.label}")
|
||||
rows = _filled_rows(group, targets)
|
||||
notes: list[str] = []
|
||||
if not target.site:
|
||||
missing = [cgi for cgi in group.cgis if cgi not in {cell["cgi"] for cell in targets}]
|
||||
if missing:
|
||||
notes.append(f"{before_day} 的工参里没有 {'、'.join(missing)}")
|
||||
pool = gongcan.cells(city, after.day) if after is not None and after.day != before_day else before_cells
|
||||
center = target_center(targets)
|
||||
neighbors: list[tuple[str, float]] = []
|
||||
if center is None:
|
||||
notes.append("待拆小区在工参里没有经纬度,算不了周边站")
|
||||
else:
|
||||
exclude = {cell["site_name"] for cell in targets if cell.get("site_name")}
|
||||
neighbors = nearest_sites(pool, center[0], center[1], exclude=exclude, k=neighbor_k, exclude_keywords=EXCLUDE_KEYWORDS)
|
||||
if len(neighbors) < neighbor_k:
|
||||
notes.append(f"工参里只找到 {len(neighbors)} 个周边站")
|
||||
|
||||
stage("查询停闭前后指标")
|
||||
before_window, after_window = windows(group.removal, today)
|
||||
if after_window is None:
|
||||
notes.append("拆除日期还没过,没有停闭后的指标")
|
||||
by_site: dict[str, list[dict]] = {}
|
||||
for cell in pool:
|
||||
name = cell.get("cell_name") or ""
|
||||
if evaluable(cell) and not any(word in name for word in EXCLUDE_KEYWORDS):
|
||||
by_site.setdefault(cell.get("site_name") or "", []).append(cell)
|
||||
picked: list[tuple[str, float, dict]] = []
|
||||
for site, distance in neighbors:
|
||||
for cell in sorted(by_site.get(site, []), key=lambda item: (item.get("tech") != "4G", item.get("cell_name") or "")):
|
||||
picked.append((site, distance, cell))
|
||||
picked_cells = [cell for _site, _distance, cell in picked]
|
||||
before_metrics = metrics.window(picked_cells, *before_window) if picked_cells else {}
|
||||
after_metrics = metrics.window(picked_cells, *after_window) if picked_cells and after_window else {}
|
||||
item2 = [
|
||||
{
|
||||
"cell": cell.get("cell_name") or cell["cgi"],
|
||||
"cgi": cell["cgi"],
|
||||
"tech": cell.get("tech") or "",
|
||||
"site": site,
|
||||
"distance": round(distance, 1),
|
||||
"before": before_metrics.get(cell["cgi"], {}),
|
||||
"after": after_metrics.get(cell["cgi"], {}),
|
||||
}
|
||||
for site, distance, cell in picked
|
||||
]
|
||||
logical = next((row.logical_site for row in rows if row.logical_site), "") or group.key
|
||||
payload = {
|
||||
"kind": group.kind,
|
||||
"site": logical,
|
||||
"removal": group.removal.isoformat(),
|
||||
"beforeDay": before_day.isoformat(),
|
||||
"afterDay": after.day.isoformat() if after is not None else None,
|
||||
"afterPresent": after.target_present if after is not None else None,
|
||||
"windows": {
|
||||
"before": [before_window[0].isoformat(), before_window[1].isoformat()],
|
||||
"after": [after_window[0].isoformat(), after_window[1].isoformat()] if after_window else None,
|
||||
},
|
||||
"locatable": center is not None,
|
||||
"rows": [row.to_json() for row in rows],
|
||||
"neighbors": [
|
||||
{"site": site, "distance": round(distance, 1), "cells": len(by_site.get(site, []))} for site, distance in neighbors
|
||||
],
|
||||
"item2": item2,
|
||||
"notes": notes,
|
||||
}
|
||||
if group.kind == "dixiao":
|
||||
stage("查询扇区指标")
|
||||
section1, sectors, sector_notes = _dixiao_sections(rows, targets, before_cells, metrics, before_window, after_window)
|
||||
payload["section1"] = section1
|
||||
payload["sectors"] = sectors
|
||||
notes.extend(sector_notes)
|
||||
stage("完成")
|
||||
return payload
|
||||
|
||||
|
||||
def _filled_rows(group: SiteGroup, targets: list[dict]) -> list[DemandRow]:
|
||||
"""按站点提交时用工参里的小区作为清单行;清单没写小区名的从工参补上。"""
|
||||
if group.site:
|
||||
template = group.rows[0] if group.rows else DemandRow(line=0, cgi="", order_type=group.order_type, need_date=group.removal)
|
||||
ordered = sorted(targets, key=lambda cell: (cell.get("tech") != "4G", cell.get("cell_name") or ""))
|
||||
return [
|
||||
replace(template, line=index, cgi=cell["cgi"], cell_name=cell.get("cell_name") or "", need_date=group.removal)
|
||||
for index, cell in enumerate(ordered, start=1)
|
||||
]
|
||||
names = {cell["cgi"]: cell.get("cell_name") or "" for cell in targets}
|
||||
return [row if row.cell_name else replace(row, cell_name=names.get(row.cgi, "")) for row in group.rows]
|
||||
|
||||
|
||||
def _dixiao_sections(
|
||||
rows: list[DemandRow],
|
||||
targets: list[dict],
|
||||
pool: list[dict],
|
||||
metrics: MetricSource,
|
||||
before_window: tuple[date, date],
|
||||
after_window: tuple[date, date] | None,
|
||||
) -> tuple[list[dict], list[dict], list[str]]:
|
||||
notes: list[str] = []
|
||||
profile_day = before_window[1]
|
||||
own = metrics.profile(targets, profile_day)
|
||||
section1 = []
|
||||
for row in rows:
|
||||
item = own.get(row.cgi, {})
|
||||
logical = row.logical_site or row.cell_name
|
||||
section1.append(
|
||||
{
|
||||
"逻辑站点名称": logical,
|
||||
"小区名称": row.cell_name,
|
||||
"扇区名称": item.get("sector_name"),
|
||||
"站点类型": site_type(logical),
|
||||
"日均4G流量(GB)": item.get("traffic_gb"),
|
||||
"自忙时有效RRC连接最大数": item.get("rrc_max"),
|
||||
"自忙时RRC连接最大数": item.get("rrc_max_abs"),
|
||||
"自忙时峰值利用率": item.get("util_peak"),
|
||||
"是否高流量预警小区": item.get("high_traffic_warn"),
|
||||
"是否高负荷待扩容小区": item.get("high_load_expand"),
|
||||
"是否高流量感知问题小区": "否",
|
||||
"(移动)总采样点数": item.get("mr_total"),
|
||||
"(移动)采样点数量(大于-110)": item.get("mr_good_cnt"),
|
||||
"(移动)弱覆盖采样点大于-110占比": item.get("mr_cover_pct"),
|
||||
"移动联通竞对采样点大于-110占比": item.get("unicom_cov"),
|
||||
"移动电信竞对采样点大于-110占比": item.get("telecom_cov"),
|
||||
"是否弱覆盖小区": item.get("weak_cell"),
|
||||
"是否劣化于联通": item.get("worse_unicom"),
|
||||
"是否劣化于电信": item.get("worse_telecom"),
|
||||
"取数期间是否存在退服情况": "否",
|
||||
"前三月是否为热点投诉": "否",
|
||||
"是否人有我无区域": "否",
|
||||
"方案库聚类问题点编号(必填)": "无",
|
||||
"详细问题点类型": "无",
|
||||
"聚类问题点工单状态": "无",
|
||||
"方案库聚类问题点是否已解决": "无",
|
||||
"评估结果": "通过",
|
||||
}
|
||||
)
|
||||
|
||||
own_cgis = {row.cgi for row in rows}
|
||||
by_sector: dict[str, list[DemandRow]] = {}
|
||||
for row in rows:
|
||||
sector = str((own.get(row.cgi) or {}).get("sector_name") or "").strip()
|
||||
if sector:
|
||||
by_sector.setdefault(sector, []).append(row)
|
||||
else:
|
||||
notes.append(f"{row.cell_name or row.cgi} 没有共站同覆盖区域名,第 2 节未纳入")
|
||||
members = metrics.sector_members(set(by_sector), profile_day, pool) if by_sector else {}
|
||||
sectors: list[dict] = []
|
||||
for sector, sector_rows in by_sector.items():
|
||||
everyone = members.get(sector, [])
|
||||
remain = sorted((cell for cell in everyone if cell["cgi"] not in own_cgis), key=lambda cell: cell.get("cell_name") or cell["cgi"])
|
||||
if not remain:
|
||||
notes.append(f"扇区 {sector} 除待拆小区外没有其他小区,第 2 节未纳入")
|
||||
continue
|
||||
profile = metrics.profile(remain, profile_day)
|
||||
later = metrics.profile(remain, after_window[1]) if after_window else {}
|
||||
before = metrics.window(remain, *before_window)
|
||||
after = metrics.window(remain, *after_window) if after_window else {}
|
||||
sectors.append(_sector_group(sector, sector_rows, len(everyone), remain, profile, later, before, after))
|
||||
return section1, sectors, notes
|
||||
|
||||
|
||||
def _sector_group(sector, sector_rows, total, remain, profile, later, before, after) -> dict:
|
||||
cells = []
|
||||
for cell in remain:
|
||||
cgi = cell["cgi"]
|
||||
info = profile.get(cgi, {})
|
||||
nr = cell.get("tech") == "5G"
|
||||
cells.append(
|
||||
{
|
||||
"cell": cell.get("cell_name") or cgi,
|
||||
"cgi": cgi,
|
||||
"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")),
|
||||
"traffic_b": (before.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_a": (after.get(cgi) or {}).get("util_peak"),
|
||||
"cover_b": info.get("mr_cover_pct"),
|
||||
"cover_a": (later.get(cgi) or {}).get("mr_cover_pct"),
|
||||
}
|
||||
)
|
||||
equiv_sum = sum(cell["equiv"] for cell in cells if cell["equiv"] is not None)
|
||||
|
||||
def total_of(key):
|
||||
values = [cell[key] for cell in cells if cell[key] is not None]
|
||||
return round(sum(values), 4) if values else None
|
||||
|
||||
def weighted(key):
|
||||
pairs = [(cell[key], cell["equiv"]) for cell in cells if cell[key] is not None and cell["equiv"]]
|
||||
weight = sum(equiv for _value, equiv in pairs)
|
||||
return round(sum(value * equiv for value, equiv in pairs) / weight, 4) if weight else None
|
||||
|
||||
def average(key):
|
||||
values = [cell[key] for cell in cells if cell[key] is not None]
|
||||
return round(sum(values) / len(values), 4) if values else None
|
||||
|
||||
traffic_b, traffic_a = total_of("traffic_b"), total_of("traffic_a")
|
||||
return {
|
||||
"sector": sector,
|
||||
"site": "、".join(dict.fromkeys(row.logical_site or row.cell_name for row in sector_rows)),
|
||||
"total": total,
|
||||
"base": len(remain),
|
||||
"cells": cells,
|
||||
"equiv": round(equiv_sum, 4) if equiv_sum else None,
|
||||
"traffic_b": traffic_b,
|
||||
"traffic_a": traffic_a,
|
||||
"single_b": round(traffic_b / equiv_sum, 4) if traffic_b is not None and equiv_sum else None,
|
||||
"single_a": round(traffic_a / equiv_sum, 4) if traffic_a is not None and equiv_sum else None,
|
||||
"util_b": weighted("util_b"),
|
||||
"util_a": weighted("util_a"),
|
||||
"cover_b": average("cover_b"),
|
||||
"cover_a": average("cover_a"),
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
"""拆站清单:读取上传的清单或单个提交的表单,校验后按逻辑站点分组。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import io
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
from openpyxl import Workbook, load_workbook
|
||||
from openpyxl.styles import Alignment, Font, PatternFill
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
from app.collect.io import decode_text
|
||||
|
||||
SHEET = "拆站清单"
|
||||
MAX_ROWS = 5000
|
||||
MAX_BYTES = 10 * 1024 * 1024
|
||||
DIXIAO_KEYWORD = "低效拆除"
|
||||
ORDER_TYPES = ("频段清退", "低效拆除")
|
||||
KIND_LABELS = {"pinduan": "频段清退评估", "dixiao": "低效拆除评估"}
|
||||
FIELDS: dict[str, tuple[str, ...]] = {
|
||||
"county": ("区县", "县区"),
|
||||
"cell_name": ("小区名", "小区名称"),
|
||||
"cgi": ("CGI", "NCGI", "小区CGI"),
|
||||
"sector": ("扇区",),
|
||||
"site_name": ("物理站名(综资站点)", "物理站名", "综资站点"),
|
||||
"applicant": ("发起人", "申请人"),
|
||||
"retire_reason": ("是否已发邮件安排拆除", "退网原因"),
|
||||
"need_date": ("需求日期", "计划退网时间", "拆除日期"),
|
||||
"order_type": ("退网工单类型", "工单类型"),
|
||||
}
|
||||
TEMPLATE_COLUMNS = (
|
||||
("区县", "", "台山市"),
|
||||
("小区名", "建议填写;为空时按 CGI 从工参补齐", "江门台山现代技术学校F-ZLH-1"),
|
||||
("CGI", "必填,如 460-00-679584-1", "460-00-679584-1"),
|
||||
("扇区", "", ""),
|
||||
("物理站名(综资站点)", "", ""),
|
||||
("发起人", "", ""),
|
||||
("是否已发邮件安排拆除", "写入结果表的「退网原因」", "站点搬迁"),
|
||||
("需求日期", "必填,按拆除日期确定拆除前后的工参", "2026-10-15"),
|
||||
("退网工单类型", "必填;含「低效拆除」的写入低效拆除评估,其余写入频段清退评估", "频段清退"),
|
||||
)
|
||||
CGI_PATTERN = re.compile(r"^\d{3}-\d{2}-\d+-\d+$")
|
||||
EXCEL_EPOCH = date(1899, 12, 30)
|
||||
|
||||
|
||||
class DemandError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class DemandRow:
|
||||
line: int
|
||||
cgi: str
|
||||
order_type: str
|
||||
need_date: date | None
|
||||
cell_name: str = ""
|
||||
county: str = ""
|
||||
sector: str = ""
|
||||
site_name: str = ""
|
||||
applicant: str = ""
|
||||
retire_reason: str = ""
|
||||
|
||||
@property
|
||||
def logical_site(self) -> str:
|
||||
return re.sub(r"-\d+$", "", self.cell_name.strip())
|
||||
|
||||
def to_json(self) -> dict:
|
||||
return {
|
||||
"line": self.line,
|
||||
"cgi": self.cgi,
|
||||
"orderType": self.order_type,
|
||||
"needDate": self.need_date.isoformat() if self.need_date else None,
|
||||
"cellName": self.cell_name,
|
||||
"county": self.county,
|
||||
"sector": self.sector,
|
||||
"siteName": self.site_name,
|
||||
"applicant": self.applicant,
|
||||
"retireReason": self.retire_reason,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, data: dict) -> "DemandRow":
|
||||
need = data.get("needDate")
|
||||
return cls(
|
||||
line=int(data.get("line") or 0),
|
||||
cgi=str(data.get("cgi") or ""),
|
||||
order_type=str(data.get("orderType") or ""),
|
||||
need_date=date.fromisoformat(need) if need else None,
|
||||
cell_name=str(data.get("cellName") or ""),
|
||||
county=str(data.get("county") or ""),
|
||||
sector=str(data.get("sector") or ""),
|
||||
site_name=str(data.get("siteName") or ""),
|
||||
applicant=str(data.get("applicant") or ""),
|
||||
retire_reason=str(data.get("retireReason") or ""),
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class DemandSheet:
|
||||
rows: list[DemandRow]
|
||||
errors: list[dict]
|
||||
sheet: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class SiteGroup:
|
||||
"""一个评估对象:一个逻辑站点(清单里同站的几行),或按站点名提交的整站。"""
|
||||
|
||||
key: str
|
||||
kind: str
|
||||
order_type: str
|
||||
removal: date
|
||||
rows: list[DemandRow] = field(default_factory=list)
|
||||
site: str = ""
|
||||
|
||||
@property
|
||||
def cgis(self) -> list[str]:
|
||||
return [row.cgi for row in self.rows if row.cgi]
|
||||
|
||||
|
||||
def kind_of(order_type: str) -> str:
|
||||
return "dixiao" if DIXIAO_KEYWORD in (order_type or "") else "pinduan"
|
||||
|
||||
|
||||
def base_id(cgi: str) -> str:
|
||||
"""CGI 去掉最后一段就是基站 ID,如 460-00-679584-1 → 460-00-679584。"""
|
||||
match = re.match(r"^(\d+-\d+-\d+)-\d+$", (cgi or "").strip())
|
||||
return match.group(1) if match else (cgi or "")
|
||||
|
||||
|
||||
def parse_date(value: object) -> date | None:
|
||||
if value is None or value == "":
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
return value.date()
|
||||
if isinstance(value, date):
|
||||
return value
|
||||
if isinstance(value, (int, float)):
|
||||
return _serial_date(float(value))
|
||||
text = str(value).strip().replace("\t", "")
|
||||
if not text:
|
||||
return None
|
||||
if re.fullmatch(r"\d+(\.\d+)?", text) and len(text) != 8:
|
||||
return _serial_date(float(text))
|
||||
text = re.sub(r"[年月]", "-", text).replace("日", "").replace("/", "-").replace(".", "-")
|
||||
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d", "%Y%m%d"):
|
||||
try:
|
||||
return datetime.strptime(text, fmt).date()
|
||||
except ValueError:
|
||||
continue
|
||||
raise ValueError(str(value))
|
||||
|
||||
|
||||
def _serial_date(number: float) -> date | None:
|
||||
if number < 1 or number > 2958465:
|
||||
raise ValueError(str(number))
|
||||
return EXCEL_EPOCH + timedelta(days=int(number))
|
||||
|
||||
|
||||
def _norm(name: object) -> str:
|
||||
return (
|
||||
str(name or "")
|
||||
.replace("\u3000", "")
|
||||
.replace(" ", "")
|
||||
.replace("\t", "")
|
||||
.replace("(", "(")
|
||||
.replace(")", ")")
|
||||
.strip()
|
||||
)
|
||||
|
||||
|
||||
def _clean(value: object) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
if isinstance(value, float) and value.is_integer():
|
||||
value = int(value)
|
||||
return str(value).replace("\t", "").strip()
|
||||
|
||||
|
||||
def _column_map(headers: list[object]) -> dict[str, int]:
|
||||
normalized = [_norm(header) for header in headers]
|
||||
found: dict[str, int] = {}
|
||||
for key, aliases in FIELDS.items():
|
||||
for alias in aliases:
|
||||
target = _norm(alias)
|
||||
if target in normalized:
|
||||
found[key] = normalized.index(target)
|
||||
break
|
||||
return found
|
||||
|
||||
|
||||
def parse_demand(name: str, content: bytes) -> DemandSheet:
|
||||
if len(content) > MAX_BYTES:
|
||||
raise DemandError("清单文件超过 10MB")
|
||||
lowered = (name or "").lower()
|
||||
if lowered.endswith(".xlsx") or lowered.endswith(".xlsm"):
|
||||
sheet, table = _read_xlsx(content)
|
||||
elif lowered.endswith(".csv"):
|
||||
sheet = ""
|
||||
table = [(line, list(values)) for line, values in enumerate(csv.reader(io.StringIO(decode_text(content))), start=1)]
|
||||
elif lowered.endswith(".xls"):
|
||||
raise DemandError("请把 xls 另存为 xlsx 后再导入")
|
||||
else:
|
||||
raise DemandError("清单只支持 xlsx 或 csv")
|
||||
return _rows_from_table(sheet, table)
|
||||
|
||||
|
||||
def _read_xlsx(content: bytes) -> tuple[str, list[tuple[int, list[object]]]]:
|
||||
"""按行号读出每一行,空行不会让后面的行号错位。"""
|
||||
try:
|
||||
workbook = load_workbook(io.BytesIO(content), data_only=True)
|
||||
except Exception as exc:
|
||||
raise DemandError("清单文件打不开,请确认是 xlsx") from exc
|
||||
names = workbook.sheetnames
|
||||
target = next((sheet for sheet in names if _norm(sheet) == SHEET), names[0] if names else None)
|
||||
if target is None:
|
||||
raise DemandError("清单里没有工作表")
|
||||
table = [(cells[0].row, [cell.value for cell in cells]) for cells in workbook[target].iter_rows() if cells]
|
||||
return target, table
|
||||
|
||||
|
||||
def _rows_from_table(sheet: str, table: list[tuple[int, list[object]]]) -> DemandSheet:
|
||||
header_index = None
|
||||
columns: dict[str, int] = {}
|
||||
for index, (_line, row) in enumerate(table[:10]):
|
||||
mapped = _column_map(list(row))
|
||||
if "cgi" in mapped:
|
||||
header_index, columns = index, mapped
|
||||
break
|
||||
if header_index is None:
|
||||
raise DemandError("清单表头里没有找到 CGI 列")
|
||||
missing = [label for key, label in (("order_type", "退网工单类型"), ("need_date", "需求日期")) if key not in columns]
|
||||
if missing:
|
||||
raise DemandError(f"清单缺少列:{'、'.join(missing)}")
|
||||
rows: list[DemandRow] = []
|
||||
errors: list[dict] = []
|
||||
seen: dict[str, int] = {}
|
||||
for offset, raw in table[header_index + 1:]:
|
||||
values = {key: (raw[col] if col < len(raw) else None) for key, col in columns.items()}
|
||||
if all(_clean(value) == "" for value in values.values()):
|
||||
continue
|
||||
if len(rows) + len(errors) >= MAX_ROWS:
|
||||
raise DemandError(f"一次最多导入 {MAX_ROWS} 行")
|
||||
problems: list[str] = []
|
||||
cgi = _clean(values.get("cgi"))
|
||||
if not cgi:
|
||||
problems.append("缺少 CGI")
|
||||
elif not CGI_PATTERN.match(cgi):
|
||||
problems.append(f"CGI 格式不对:{cgi}")
|
||||
elif cgi in seen:
|
||||
problems.append(f"CGI 与第 {seen[cgi]} 行重复")
|
||||
order_type = _clean(values.get("order_type"))
|
||||
if not order_type:
|
||||
problems.append("缺少退网工单类型")
|
||||
need_date = None
|
||||
try:
|
||||
need_date = parse_date(values.get("need_date"))
|
||||
if need_date is None:
|
||||
problems.append("缺少需求日期")
|
||||
except ValueError:
|
||||
problems.append(f"需求日期看不懂:{_clean(values.get('need_date'))}")
|
||||
if problems:
|
||||
errors.append({"line": offset, "cgi": cgi, "message": ";".join(problems)})
|
||||
continue
|
||||
seen[cgi] = offset
|
||||
rows.append(
|
||||
DemandRow(
|
||||
line=offset,
|
||||
cgi=cgi,
|
||||
order_type=order_type,
|
||||
need_date=need_date,
|
||||
cell_name=_clean(values.get("cell_name")),
|
||||
county=_clean(values.get("county")),
|
||||
sector=_clean(values.get("sector")),
|
||||
site_name=_clean(values.get("site_name")),
|
||||
applicant=_clean(values.get("applicant")),
|
||||
retire_reason=_clean(values.get("retire_reason")),
|
||||
)
|
||||
)
|
||||
if not rows and not errors:
|
||||
raise DemandError("清单里没有数据行")
|
||||
return DemandSheet(rows=rows, errors=errors, sheet=sheet)
|
||||
|
||||
|
||||
def group_rows(rows: list[DemandRow]) -> list[SiteGroup]:
|
||||
"""同一逻辑站点、同一类评估的行归为一组;拆除日期取组内最早的一个。
|
||||
|
||||
没写小区名的行先跟同基站、有小区名的行归到一起,都没有小区名时按基站 ID 归组。
|
||||
"""
|
||||
named = {base_id(row.cgi): row.logical_site for row in rows if row.logical_site}
|
||||
groups: dict[tuple[str, str], SiteGroup] = {}
|
||||
for row in rows:
|
||||
kind = kind_of(row.order_type)
|
||||
key = row.logical_site or named.get(base_id(row.cgi)) or base_id(row.cgi)
|
||||
group = groups.get((kind, key))
|
||||
if group is None:
|
||||
groups[(kind, key)] = SiteGroup(key=key, kind=kind, order_type=row.order_type, removal=row.need_date, rows=[row])
|
||||
continue
|
||||
group.rows.append(row)
|
||||
if row.need_date and row.need_date < group.removal:
|
||||
group.removal = row.need_date
|
||||
return list(groups.values())
|
||||
|
||||
|
||||
def summarize(groups: list[SiteGroup]) -> dict:
|
||||
return {
|
||||
"sites": len(groups),
|
||||
"pinduan": sum(1 for group in groups if group.kind == "pinduan"),
|
||||
"dixiao": sum(1 for group in groups if group.kind == "dixiao"),
|
||||
"cells": sum(len(group.rows) for group in groups),
|
||||
}
|
||||
|
||||
|
||||
def template_workbook() -> bytes:
|
||||
"""给用户下载的清单模板:表头 + 一行示例 + 填写说明。"""
|
||||
workbook = Workbook()
|
||||
sheet = workbook.active
|
||||
sheet.title = SHEET
|
||||
head_fill = PatternFill(fill_type="solid", start_color="DDEBF7", end_color="DDEBF7")
|
||||
for col, (header, _hint, example) in enumerate(TEMPLATE_COLUMNS, start=1):
|
||||
cell = sheet.cell(row=1, column=col, value=header)
|
||||
cell.font = Font(bold=True)
|
||||
cell.fill = head_fill
|
||||
cell.alignment = Alignment(horizontal="center", vertical="center")
|
||||
sheet.cell(row=2, column=col, value=example)
|
||||
sheet.column_dimensions[get_column_letter(col)].width = max(12, len(header) * 2 + 4)
|
||||
sheet.column_dimensions["B"].width = 36
|
||||
sheet.column_dimensions["C"].width = 20
|
||||
sheet.freeze_panes = "A2"
|
||||
notes = workbook.create_sheet("填写说明")
|
||||
notes.append(["列", "说明"])
|
||||
for header, hint, _example in TEMPLATE_COLUMNS:
|
||||
notes.append([header, hint or "选填"])
|
||||
notes.append([])
|
||||
notes.append(["分组", "同一逻辑站点(小区名去掉末尾 -数字)的几行作为一个评估对象;没有小区名时按 CGI 的基站 ID 归组。"])
|
||||
notes.column_dimensions["A"].width = 22
|
||||
notes.column_dimensions["B"].width = 72
|
||||
for cell in notes[1]:
|
||||
cell.font = Font(bold=True)
|
||||
buffer = io.BytesIO()
|
||||
workbook.save(buffer)
|
||||
return buffer.getvalue()
|
||||
@@ -0,0 +1,302 @@
|
||||
"""把评估结果写进两份固定模板:频段清退评估、低效拆除评估。
|
||||
|
||||
模板版式不改,只按数据扩缩示例行。各块按表头文字定位,不依赖固定行号。判定列沿用模板里的公式,
|
||||
停闭后还没有数据时判定写「/」,评估结果写「拆除后再评估」。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
from openpyxl import load_workbook
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
from app.evaluate.demand import base_id
|
||||
from app.evaluate.xlsx import (
|
||||
MISSING,
|
||||
ZEBRA,
|
||||
apply_style,
|
||||
block_end,
|
||||
clear_row,
|
||||
find_row,
|
||||
fill_rows,
|
||||
fit_block,
|
||||
header_map,
|
||||
merge_down,
|
||||
put,
|
||||
row_style,
|
||||
text,
|
||||
unmerge_within,
|
||||
)
|
||||
|
||||
TEMPLATES = Path(__file__).with_name("templates")
|
||||
NEIGHBOR_LAST_COL = 24
|
||||
SECTOR_LAST_COL = 25
|
||||
BEFORE_KEYS = ("traffic_gb", "rrc_max", "high_load", "mr_weak_pct", "access_rate", "drop_rate")
|
||||
LATER = "拆除后再评估"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Item1:
|
||||
county: str
|
||||
logical_site: str
|
||||
cell_name: str
|
||||
cgi: str
|
||||
retire_reason: str
|
||||
applicant: str
|
||||
need_date: date | None
|
||||
locatable: bool = True
|
||||
|
||||
|
||||
@dataclass
|
||||
class NeighborGroup:
|
||||
site: str
|
||||
cells: list[dict] = field(default_factory=list)
|
||||
|
||||
|
||||
def write_pinduan(item1: list[Item1], groups: list[NeighborGroup]) -> bytes:
|
||||
workbook = load_workbook(TEMPLATES / "pinduan.xlsx")
|
||||
sheet = workbook.worksheets[0]
|
||||
_write_item1(sheet, item1)
|
||||
_write_neighbors(sheet, _neighbor_leaf(sheet), groups)
|
||||
return _save(workbook)
|
||||
|
||||
|
||||
def write_dixiao(item1: list[Item1], section1: list[dict], sectors: list[dict], groups: list[NeighborGroup]) -> bytes:
|
||||
workbook = load_workbook(TEMPLATES / "dixiao.xlsx")
|
||||
sheet = workbook["低效评估模板"] if "低效评估模板" in workbook.sheetnames else workbook.worksheets[0]
|
||||
_write_item1(sheet, item1)
|
||||
_write_section1(sheet, section1)
|
||||
_write_sectors(sheet, sectors)
|
||||
_write_neighbors(sheet, _neighbor_leaf(sheet), groups)
|
||||
return _save(workbook)
|
||||
|
||||
|
||||
def _save(workbook) -> bytes:
|
||||
workbook.calculation.fullCalcOnLoad = True
|
||||
buffer = io.BytesIO()
|
||||
workbook.save(buffer)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def _write_item1(ws, items: list[Item1]) -> None:
|
||||
"""退网站点审核信息:清单逐行;整个逻辑站点都定位不到的行标红。"""
|
||||
head = find_row(ws, lambda row: text(ws, row, 1) == "区县" and text(ws, row, 2) == "逻辑站点名称")
|
||||
if head is None:
|
||||
raise ValueError("模板里没有找到退网站点审核信息的表头")
|
||||
columns = header_map(ws, head)
|
||||
last_col = max(columns.values())
|
||||
first = head + 1
|
||||
style = row_style(ws, first, last_col)
|
||||
fit_block(ws, first, block_end(ws, first, last_col), len(items))
|
||||
for index, item in enumerate(items):
|
||||
row = first + index
|
||||
apply_style(ws, row, style)
|
||||
clear_row(ws, row, last_col)
|
||||
values = {
|
||||
"区县": item.county,
|
||||
"逻辑站点名称": item.logical_site,
|
||||
"小区名称": item.cell_name,
|
||||
"基站ID": base_id(item.cgi),
|
||||
"CGI": item.cgi,
|
||||
"退网原因": item.retire_reason,
|
||||
"是否VIP小区": "否",
|
||||
"申请人": item.applicant,
|
||||
"地市优化、维护组长审核结果": "通过",
|
||||
"计划退网时间": item.need_date,
|
||||
}
|
||||
for label, value in values.items():
|
||||
col = columns.get(label)
|
||||
if col:
|
||||
put(ws, row, col, value, "yyyy-mm-dd" if label == "计划退网时间" else None)
|
||||
if not item.locatable:
|
||||
fill_rows(ws, row, row, last_col, MISSING)
|
||||
|
||||
|
||||
def _neighbor_leaf(ws) -> int:
|
||||
leaf = find_row(ws, lambda row: text(ws, row, 2) == "日均流量(GB)" and text(ws, row, 3) == "日均有效RRC连接最大数")
|
||||
if leaf is None:
|
||||
raise ValueError("模板里没有找到(5G、LTE)网管统计指标评估的表头")
|
||||
return leaf
|
||||
|
||||
|
||||
def _write_neighbors(ws, leaf: int, groups: list[NeighborGroup]) -> None:
|
||||
"""(5G、LTE)网管统计指标评估:每个逻辑站点一组,周边小区逐行,组尾汇总;评估结果、备注按组合并。"""
|
||||
summary = find_row(ws, lambda row: text(ws, row, 1) == "汇总", start=leaf + 1)
|
||||
if summary is None:
|
||||
raise ValueError("模板里没有找到(5G、LTE)汇总行")
|
||||
first = leaf + 1
|
||||
cell_style = row_style(ws, first, NEIGHBOR_LAST_COL)
|
||||
sum_style = row_style(ws, summary, NEIGHBOR_LAST_COL)
|
||||
unmerge_within(ws, first, summary)
|
||||
needed = sum(len(group.cells) + 1 for group in groups if group.cells)
|
||||
fit_block(ws, first, summary, needed or 2)
|
||||
if not needed:
|
||||
apply_style(ws, first, cell_style)
|
||||
clear_row(ws, first, NEIGHBOR_LAST_COL)
|
||||
put(ws, first, 1, "没有可评估的周边站")
|
||||
apply_style(ws, first + 1, sum_style)
|
||||
clear_row(ws, first + 1, NEIGHBOR_LAST_COL)
|
||||
put(ws, first + 1, 1, "汇总")
|
||||
return
|
||||
row = first
|
||||
shown = 0
|
||||
for group in groups:
|
||||
if not group.cells:
|
||||
continue
|
||||
group_first = row
|
||||
for cell in group.cells:
|
||||
apply_style(ws, row, cell_style)
|
||||
clear_row(ws, row, NEIGHBOR_LAST_COL)
|
||||
put(ws, row, 1, cell["cell"])
|
||||
for offset, key in enumerate(BEFORE_KEYS):
|
||||
put(ws, row, 2 + offset, (cell.get("before") or {}).get(key))
|
||||
put(ws, row, 9 + offset, (cell.get("after") or {}).get(key))
|
||||
put(ws, row, 8, 0)
|
||||
put(ws, row, 15, 0 if cell.get("after") else None)
|
||||
for col in (16, 17, 18):
|
||||
put(ws, row, col, "/")
|
||||
for col, formula in _row_checks(row).items():
|
||||
put(ws, row, col, formula)
|
||||
row += 1
|
||||
_neighbor_summary(ws, row, group_first, row - 1, sum_style)
|
||||
border = ws.cell(row=group_first, column=22).border
|
||||
merge_down(ws, 23, group_first, row, _verdict("P", "V", row), border_from=border)
|
||||
merge_down(ws, 24, group_first, row, group.site, wrap=True, border_from=border)
|
||||
if shown % 2 == 1:
|
||||
fill_rows(ws, group_first, row, NEIGHBOR_LAST_COL, ZEBRA)
|
||||
shown += 1
|
||||
row += 1
|
||||
|
||||
|
||||
def _row_checks(row: int) -> dict[int, str]:
|
||||
after = f"COUNT(I{row}:N{row})=0"
|
||||
return {
|
||||
19: f'=IF({after},"/",IF(L{row}>10,"N",IF((L{row}-E{row})>5,"N","Y")))',
|
||||
20: f'=IF({after},"/",IF(M{row}<97,"N",IF((F{row}-M{row})>1,"N","Y")))',
|
||||
21: f'=IF({after},"/",IF(N{row}<0.3,"Y","N"))',
|
||||
22: f'=IF({after},"/",IF(O{row}<0.3,"Y","N"))',
|
||||
}
|
||||
|
||||
|
||||
def _neighbor_summary(ws, row: int, first: int, last: int, style) -> None:
|
||||
apply_style(ws, row, style)
|
||||
clear_row(ws, row, NEIGHBOR_LAST_COL)
|
||||
put(ws, row, 1, "汇总")
|
||||
for col in (2, 3, 5, 6, 7, 9, 10, 12, 13, 14):
|
||||
letter = get_column_letter(col)
|
||||
put(ws, row, col, f"=IFERROR(AVERAGE({letter}{first}:{letter}{last}),\"\")")
|
||||
for col in (4, 11):
|
||||
letter = get_column_letter(col)
|
||||
put(ws, row, col, f'=IF(COUNT({letter}{first}:{letter}{last})=0,"",SUM({letter}{first}:{letter}{last}))')
|
||||
put(ws, row, 8, 0)
|
||||
put(ws, row, 15, f'=IF(COUNT(I{first}:I{last})=0,"",0)')
|
||||
put(ws, row, 16, f'=IF(OR(COUNT(B{row},I{row})<2,N(B{row})=0),"/",IF(((B{row}-I{row})/B{row})<0.1,"Y","N"))')
|
||||
put(ws, row, 17, f'=IF(OR(COUNT(C{row},J{row})<2,N(C{row})=0),"/",IF(((C{row}-J{row})/C{row})<0.1,"Y","N"))')
|
||||
put(ws, row, 18, f'=IF(COUNT(D{row},K{row})<2,"/",IF((K{row}-D{row})<2,"Y","N"))')
|
||||
for col, formula in _row_checks(row).items():
|
||||
put(ws, row, col, formula)
|
||||
|
||||
|
||||
def _verdict(first_col: str, last_col: str, row: int) -> str:
|
||||
area = f"{first_col}{row}:{last_col}{row}"
|
||||
return f'=IF(COUNTIF({area},"N")>0,"不通过",IF(COUNTIF({area},"/")>0,"{LATER}","通过"))'
|
||||
|
||||
|
||||
def _write_section1(ws, rows: list[dict]) -> None:
|
||||
"""低效拆除第 1 节:待拆小区自身的容量、覆盖和问题点情况,按表头填。"""
|
||||
title = find_row(ws, lambda row: text(ws, row, 1).startswith("1、评估本站退服"))
|
||||
if title is None:
|
||||
return
|
||||
leaf = find_row(ws, lambda row: text(ws, row, 1) == "逻辑站点名称", start=title + 1, stop=title + 6)
|
||||
if leaf is None:
|
||||
return
|
||||
columns = header_map(ws, leaf)
|
||||
for label, col in header_map(ws, leaf - 1).items():
|
||||
columns.setdefault(label, col)
|
||||
last_col = max(columns.values())
|
||||
first = leaf + 1
|
||||
style = row_style(ws, first, last_col)
|
||||
fit_block(ws, first, block_end(ws, first, last_col), len(rows))
|
||||
for index, values in enumerate(rows or [{}]):
|
||||
row = first + index
|
||||
apply_style(ws, row, style)
|
||||
clear_row(ws, row, last_col)
|
||||
for label, value in values.items():
|
||||
col = columns.get(label)
|
||||
if col:
|
||||
put(ws, row, col, value)
|
||||
|
||||
|
||||
def _write_sectors(ws, sectors: list[dict]) -> None:
|
||||
"""低效拆除第 2 节:同扇区去掉待拆小区后的基础覆盖层,停闭前后指标与扇区汇总评估。"""
|
||||
title = find_row(ws, lambda row: text(ws, row, 1).startswith("2、评估拆除站点是否满足低效原则"))
|
||||
if title is None:
|
||||
return
|
||||
leaf = find_row(ws, lambda row: text(ws, row, 1) == "扇区名称" and text(ws, row, 2) == "小区名称" and text(ws, row, 3) == "CGI", start=title + 1)
|
||||
if leaf is None:
|
||||
return
|
||||
summary = find_row(ws, lambda row: text(ws, row, 2) == "扇区汇总评估", start=leaf + 1)
|
||||
if summary is None:
|
||||
return
|
||||
first = leaf + 1
|
||||
cell_style = row_style(ws, first, SECTOR_LAST_COL)
|
||||
sum_style = row_style(ws, summary, SECTOR_LAST_COL)
|
||||
unmerge_within(ws, first, summary)
|
||||
needed = sum(len(sector["cells"]) + 1 for sector in sectors)
|
||||
fit_block(ws, first, summary, needed or 2)
|
||||
if not needed:
|
||||
apply_style(ws, first, cell_style)
|
||||
clear_row(ws, first, SECTOR_LAST_COL)
|
||||
put(ws, first, 1, "没有可评估的扇区")
|
||||
apply_style(ws, first + 1, sum_style)
|
||||
clear_row(ws, first + 1, SECTOR_LAST_COL)
|
||||
put(ws, first + 1, 2, "扇区汇总评估")
|
||||
return
|
||||
row = first
|
||||
for index, sector in enumerate(sectors):
|
||||
group_first = row
|
||||
for cell in sector["cells"]:
|
||||
apply_style(ws, row, cell_style)
|
||||
clear_row(ws, row, SECTOR_LAST_COL)
|
||||
equiv = cell["equiv"] if cell["equiv"] is not None else "/"
|
||||
values = (
|
||||
None, cell["cell"], cell["cgi"], cell["band"], sector["total"], sector["base"],
|
||||
cell["traffic_b"], cell["util_b"], equiv, sector["single_b"], sector["util_b"], cell["cover_b"],
|
||||
cell["traffic_a"], cell["util_a"], equiv, sector["single_a"], sector["util_a"], cell["cover_a"],
|
||||
"/", "/", "/", "/", "/",
|
||||
)
|
||||
for col, value in enumerate(values, start=1):
|
||||
if col > 1:
|
||||
put(ws, row, col, value)
|
||||
row += 1
|
||||
apply_style(ws, row, sum_style)
|
||||
clear_row(ws, row, SECTOR_LAST_COL)
|
||||
equiv_sum = sector["equiv"] if sector["equiv"] is not None else "/"
|
||||
totals = (
|
||||
None, "扇区汇总评估", "/", 0, sector["total"], sector["base"],
|
||||
sector["traffic_b"], "/", equiv_sum, sector["single_b"], sector["util_b"], sector["cover_b"],
|
||||
sector["traffic_a"], "/", equiv_sum, sector["single_a"], sector["util_a"], sector["cover_a"],
|
||||
)
|
||||
for col, value in enumerate(totals, start=1):
|
||||
if col > 1:
|
||||
put(ws, row, col, value)
|
||||
checks = {
|
||||
19: f'=IF(N(E{row})>=3,"Y","N")',
|
||||
20: f'=IF(ISNUMBER(J{row}),IF(J{row}<=20,"Y","N"),"/")',
|
||||
21: f'=IF(ISNUMBER(K{row}),IF(K{row}<=20,"Y","N"),"/")',
|
||||
22: f'=IF(ISNUMBER(Q{row}),IF(Q{row}<=40,"Y","N"),"/")',
|
||||
23: f'=IF(AND(ISNUMBER(L{row}),ISNUMBER(R{row})),IF((L{row}-R{row})<5,"Y","N"),"/")',
|
||||
}
|
||||
for col, formula in checks.items():
|
||||
put(ws, row, col, formula)
|
||||
border = ws.cell(row=group_first, column=12).border
|
||||
merge_down(ws, 1, group_first, row, sector["sector"], wrap=True, border_from=border)
|
||||
merge_down(ws, 24, group_first, row, _verdict("S", "W", row), border_from=border)
|
||||
merge_down(ws, 25, group_first, row, sector["site"], wrap=True, border_from=border)
|
||||
if index % 2 == 1:
|
||||
fill_rows(ws, group_first, row, SECTOR_LAST_COL, ZEBRA)
|
||||
row += 1
|
||||
@@ -0,0 +1,278 @@
|
||||
"""评估任务的排队执行:每个逻辑站点一个排队任务,和采集共用并行数量;站点都结束后汇总写结果表。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
import shutil
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.collect.gongcan import GongcanError, china_today
|
||||
from app.config import result_dir
|
||||
from app.db import session_scope
|
||||
from app.evaluate.compute import EvalFailure, evaluate_site
|
||||
from app.evaluate.demand import KIND_LABELS, DemandRow, SiteGroup
|
||||
from app.evaluate.report import Item1, NeighborGroup, write_dixiao, write_pinduan
|
||||
from app.evaluate.sources import METRICS_MOCKED, build_sources
|
||||
from app.models import EvalJob, EvalTask, utcnow
|
||||
|
||||
logger = logging.getLogger("decom")
|
||||
JOB_FINAL = ("done", "partial", "failed")
|
||||
MOCK_NOTICE = "流量和质量指标暂为模拟数据,接入即席查询后替换"
|
||||
MAX_WARNINGS = 300
|
||||
|
||||
|
||||
def create_job(
|
||||
session: Session,
|
||||
*,
|
||||
owner_kind: str,
|
||||
owner_id: str,
|
||||
owner_name: str,
|
||||
mode: str,
|
||||
title: str,
|
||||
city: str,
|
||||
groups: list[SiteGroup],
|
||||
source_name: str = "",
|
||||
) -> EvalJob:
|
||||
job = EvalJob(
|
||||
owner_kind=owner_kind,
|
||||
owner_id=owner_id,
|
||||
owner_name=owner_name,
|
||||
mode=mode,
|
||||
title=title[:255],
|
||||
city=city,
|
||||
source_name=source_name[:255],
|
||||
status="queued",
|
||||
total=len(groups),
|
||||
results=[],
|
||||
warnings=[],
|
||||
)
|
||||
session.add(job)
|
||||
session.flush()
|
||||
for seq, group in enumerate(groups):
|
||||
session.add(
|
||||
EvalTask(
|
||||
job_id=job.id,
|
||||
seq=seq,
|
||||
site_key=group.key[:255],
|
||||
kind=group.kind,
|
||||
order_type=group.order_type[:64],
|
||||
removal_date=group.removal,
|
||||
target={"cgis": group.cgis, "site": group.site},
|
||||
rows=[row.to_json() for row in group.rows],
|
||||
status="queued",
|
||||
payload={},
|
||||
)
|
||||
)
|
||||
session.flush()
|
||||
return job
|
||||
|
||||
|
||||
def dispatch(job_id: int) -> None:
|
||||
with session_scope() as session:
|
||||
task_ids = session.scalars(select(EvalTask.id).where(EvalTask.job_id == job_id).order_by(EvalTask.seq)).all()
|
||||
for task_id in task_ids:
|
||||
enqueue_eval_task(task_id)
|
||||
|
||||
|
||||
def enqueue_eval_task(task_id: int) -> None:
|
||||
from app.tasks.runner import _defer, _run_inline
|
||||
|
||||
if _defer("decom_eval_task", task_id=task_id):
|
||||
return
|
||||
_run_inline(execute_task, task_id)
|
||||
|
||||
|
||||
def enqueue_finalize(job_id: int) -> None:
|
||||
from app.tasks.runner import _defer, _run_inline
|
||||
|
||||
if _defer("decom_eval_finalize", job_id=job_id):
|
||||
return
|
||||
_run_inline(finalize_job, job_id)
|
||||
|
||||
|
||||
def execute_task(task_id: int) -> None:
|
||||
with session_scope() as session:
|
||||
task = session.get(EvalTask, task_id)
|
||||
if task is None or task.status not in ("queued", "running"):
|
||||
return
|
||||
job = session.get(EvalJob, task.job_id)
|
||||
if job is None:
|
||||
return
|
||||
task.status = "running"
|
||||
task.stage = "开始"
|
||||
task.started_at = utcnow()
|
||||
task.error = ""
|
||||
if job.status == "queued":
|
||||
job.status = "running"
|
||||
group = SiteGroup(
|
||||
key=task.site_key,
|
||||
kind=task.kind,
|
||||
order_type=task.order_type,
|
||||
removal=task.removal_date,
|
||||
rows=[DemandRow.from_json(item) for item in task.rows or []],
|
||||
site=str((task.target or {}).get("site") or ""),
|
||||
)
|
||||
job_id, city, owner_kind, owner_id = job.id, job.city, job.owner_kind, job.owner_id
|
||||
try:
|
||||
if group.removal is None:
|
||||
raise EvalFailure("缺少拆除日期")
|
||||
gongcan, metrics = build_sources(owner_kind, owner_id)
|
||||
payload = evaluate_site(group, city, china_today(), gongcan, metrics, stage=lambda label: _stage(task_id, label))
|
||||
_finish_task(task_id, "done", payload=payload)
|
||||
except (EvalFailure, GongcanError) as exc:
|
||||
_finish_task(task_id, "failed", error=str(exc) or "评估失败")
|
||||
except Exception as exc:
|
||||
logger.exception("评估站点 %s 出错", task_id)
|
||||
_finish_task(task_id, "failed", error=f"评估出错:{exc}")
|
||||
_after_task(job_id)
|
||||
|
||||
|
||||
def _stage(task_id: int, label: str) -> None:
|
||||
with session_scope() as session:
|
||||
task = session.get(EvalTask, task_id)
|
||||
if task is not None:
|
||||
task.stage = label
|
||||
|
||||
|
||||
def _finish_task(task_id: int, status: str, *, payload: dict | None = None, error: str = "") -> None:
|
||||
with session_scope() as session:
|
||||
task = session.get(EvalTask, task_id)
|
||||
if task is None:
|
||||
return
|
||||
task.status = status
|
||||
task.stage = "完成" if status == "done" else "失败"
|
||||
task.error = error[:1000]
|
||||
task.finished_at = utcnow()
|
||||
if payload is not None:
|
||||
task.payload = payload
|
||||
task.before_date = date.fromisoformat(payload["beforeDay"])
|
||||
task.after_date = date.fromisoformat(payload["afterDay"]) if payload.get("afterDay") else None
|
||||
task.after_present = payload.get("afterPresent")
|
||||
|
||||
|
||||
def _after_task(job_id: int) -> None:
|
||||
"""更新进度;最后一个站点结束的那次负责发起汇总。"""
|
||||
start = False
|
||||
with session_scope() as session:
|
||||
job = session.scalar(select(EvalJob).where(EvalJob.id == job_id).with_for_update())
|
||||
if job is None:
|
||||
return
|
||||
counts = dict(
|
||||
session.execute(
|
||||
select(EvalTask.status, func.count()).where(EvalTask.job_id == job_id).group_by(EvalTask.status)
|
||||
).all()
|
||||
)
|
||||
job.failed = counts.get("failed", 0)
|
||||
job.finished = counts.get("done", 0) + job.failed
|
||||
if job.finished >= job.total and job.status in ("queued", "running"):
|
||||
job.status = "writing"
|
||||
start = True
|
||||
if start:
|
||||
enqueue_finalize(job_id)
|
||||
|
||||
|
||||
def finalize_job(job_id: int) -> None:
|
||||
with session_scope() as session:
|
||||
job = session.get(EvalJob, job_id)
|
||||
if job is None or job.status != "writing":
|
||||
return
|
||||
title = job.title
|
||||
tasks = session.scalars(select(EvalTask).where(EvalTask.job_id == job_id).order_by(EvalTask.seq)).all()
|
||||
entries = [
|
||||
{"kind": task.kind, "status": task.status, "key": task.site_key, "payload": dict(task.payload or {}), "rows": list(task.rows or []), "error": task.error}
|
||||
for task in tasks
|
||||
]
|
||||
try:
|
||||
results, warnings = _write_results(job_id, title, entries)
|
||||
status = "failed" if not results else ("done" if all(entry["status"] == "done" for entry in entries) else "partial")
|
||||
error = "" if results else "所有站点都没有评估成功"
|
||||
except Exception as exc:
|
||||
logger.exception("评估结果 %s 写入出错", job_id)
|
||||
results, warnings, status, error = [], [], "failed", f"结果表写入出错:{exc}"
|
||||
with session_scope() as session:
|
||||
job = session.get(EvalJob, job_id)
|
||||
if job is None:
|
||||
return
|
||||
job.results = results
|
||||
job.warnings = warnings[:MAX_WARNINGS]
|
||||
job.status = status
|
||||
job.error = error
|
||||
job.finished_at = utcnow()
|
||||
|
||||
|
||||
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 []
|
||||
for entry in entries:
|
||||
site = entry["payload"].get("site") or entry["key"]
|
||||
if entry["status"] == "failed":
|
||||
warnings.append(f"{site}:{entry['error']}")
|
||||
warnings.extend(f"{site}:{note}" for note in entry["payload"].get("notes", []))
|
||||
folder = result_dir() / "eval" / str(job_id)
|
||||
results: list[dict] = []
|
||||
stamp = f"{china_today():%Y%m%d}"
|
||||
for kind in ("pinduan", "dixiao"):
|
||||
chosen = [entry for entry in entries if entry["kind"] == kind]
|
||||
if not chosen:
|
||||
continue
|
||||
if not any(entry["status"] == "done" for entry in chosen):
|
||||
warnings.append(f"{KIND_LABELS[kind]}的站点都没有评估成功,没有生成这份表")
|
||||
continue
|
||||
item1: list[Item1] = []
|
||||
groups: list[NeighborGroup] = []
|
||||
section1: list[dict] = []
|
||||
sectors: list[dict] = []
|
||||
for entry in chosen:
|
||||
payload = entry["payload"]
|
||||
done = entry["status"] == "done"
|
||||
rows = [DemandRow.from_json(item) for item in (payload.get("rows") if done else entry["rows"]) or []]
|
||||
fallback = payload.get("site") or entry["key"]
|
||||
item1.extend(
|
||||
Item1(
|
||||
county=row.county,
|
||||
logical_site=row.logical_site or fallback,
|
||||
cell_name=row.cell_name,
|
||||
cgi=row.cgi,
|
||||
retire_reason=row.retire_reason,
|
||||
applicant=row.applicant,
|
||||
need_date=row.need_date,
|
||||
locatable=done and bool(payload.get("locatable", True)),
|
||||
)
|
||||
for row in rows
|
||||
)
|
||||
if done:
|
||||
groups.append(NeighborGroup(site=payload.get("site") or entry["key"], cells=payload.get("item2", [])))
|
||||
section1.extend(payload.get("section1", []))
|
||||
sectors.extend(payload.get("sectors", []))
|
||||
content = write_pinduan(item1, groups) if kind == "pinduan" else write_dixiao(item1, section1, sectors, groups)
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
(folder / f"{kind}.xlsx").write_bytes(content)
|
||||
results.append(
|
||||
{
|
||||
"kind": kind,
|
||||
"label": KIND_LABELS[kind],
|
||||
"name": f"{KIND_LABELS[kind]}-{_safe(title)}-{stamp}.xlsx",
|
||||
"file": f"eval/{job_id}/{kind}.xlsx",
|
||||
}
|
||||
)
|
||||
return results, list(dict.fromkeys(warnings))
|
||||
|
||||
|
||||
def _safe(value: str) -> str:
|
||||
cleaned = re.sub(r'[\\/:*?"<>|\s]+', "_", value or "").strip("_")
|
||||
return cleaned[:60] or "评估"
|
||||
|
||||
|
||||
def result_path(entry: dict) -> Path | None:
|
||||
relative = str(entry.get("file") or "")
|
||||
if not re.fullmatch(r"eval/\d+/(pinduan|dixiao)\.xlsx", relative):
|
||||
return None
|
||||
return result_dir() / relative
|
||||
|
||||
|
||||
def remove_files(job_id: int) -> None:
|
||||
shutil.rmtree(result_dir() / "eval" / str(job_id), ignore_errors=True)
|
||||
@@ -0,0 +1,262 @@
|
||||
"""评估取数。
|
||||
|
||||
工参:本系统的工参快照(CellData_4G/5G),拆除前后按 pick_before / pick_after 选日期,库里没有的日期
|
||||
用提交人的大数据平台凭证经 OpenCode 补取;本系统账号没有凭证时借号池里的账号。
|
||||
指标:流量、质量、扇区等还没接即席查询,先用模拟数据,同一小区同一时间段每次结果相同。
|
||||
环境变量 DECOM_EVAL_SOURCE=mock 时工参也用模拟数据,便于本地演示。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import math
|
||||
import os
|
||||
from collections.abc import Callable, Iterator
|
||||
from contextlib import contextmanager
|
||||
from datetime import date, timedelta
|
||||
from typing import Protocol
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.collect.accounts import borrow_account, release_account
|
||||
from app.collect.gongcan import AfterPick, GongcanError, GongcanStore, Target, fetch_snapshot, month_start, pick_after, pick_before
|
||||
from app.db import engine, session_scope
|
||||
from app.models import NqiAccount
|
||||
from app.nqi.client import NqiAuthError, NqiClient
|
||||
from app.nqi.opencode import OpenCode
|
||||
|
||||
METRIC_KEYS = ("traffic_gb", "rrc_max", "high_load", "mr_weak_pct", "access_rate", "drop_rate", "util_peak")
|
||||
METRICS_MOCKED = True
|
||||
|
||||
|
||||
class GongcanSource(Protocol):
|
||||
def before_day(self, city: str, target: Target, removal: date) -> date: ...
|
||||
|
||||
def after_pick(self, city: str, target: Target, removal: date, today: date) -> AfterPick | None: ...
|
||||
|
||||
def cells(self, city: str, day: date) -> list[dict]: ...
|
||||
|
||||
|
||||
class MetricSource(Protocol):
|
||||
def window(self, cells: list[dict], start: date, end: date) -> dict[str, dict]:
|
||||
"""每个小区在 [start, end] 的日均指标,键见 METRIC_KEYS。"""
|
||||
|
||||
def profile(self, cells: list[dict], day: date) -> dict[str, dict]:
|
||||
"""每个小区截至 day 的最近一个月的属性:扇区、频点、带宽、月均流量、MR 采样、竞对覆盖和各类是否标志。"""
|
||||
|
||||
def sector_members(self, sectors: set[str], day: date, pool: list[dict]) -> dict[str, list[dict]]:
|
||||
"""每个共站同覆盖区域(扇区)里的全部小区。"""
|
||||
|
||||
|
||||
def eval_mode() -> str:
|
||||
return "mock" if os.environ.get("DECOM_EVAL_SOURCE", "").strip().lower() == "mock" else "live"
|
||||
|
||||
|
||||
def build_sources(owner_kind: str, owner_id: str) -> tuple[GongcanSource, MetricSource]:
|
||||
gongcan: GongcanSource = MockGongcan() if eval_mode() == "mock" else StoreGongcan(owner_kind, owner_id)
|
||||
return gongcan, MockMetrics()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def platform_cookies(owner_kind: str, owner_id: str) -> Iterator[tuple[list, Callable[..., None]]]:
|
||||
"""优先用提交人自己的大数据平台凭证;本系统账号或凭证失效时借号池里的账号。"""
|
||||
if owner_kind == "nqi":
|
||||
with session_scope() as session:
|
||||
account = session.scalar(select(NqiAccount).where(NqiAccount.login_id == owner_id))
|
||||
own = list(account.cookies or []) if account is not None and account.credential_valid else []
|
||||
if own:
|
||||
yield own, lambda invalid=False: None
|
||||
return
|
||||
borrowed = borrow_account()
|
||||
if borrowed is None:
|
||||
raise GongcanError("号池里没有可用的大数据平台账号,补取不了工参")
|
||||
account_id, cookies = borrowed
|
||||
marks = {"invalid": False}
|
||||
|
||||
def mark(invalid: bool = False) -> None:
|
||||
marks["invalid"] = marks["invalid"] or invalid
|
||||
|
||||
try:
|
||||
yield cookies, mark
|
||||
finally:
|
||||
release_account(account_id, invalid=marks["invalid"])
|
||||
|
||||
|
||||
class StoreGongcan:
|
||||
"""工参快照库;缺的日期由 OpenCode 补取后入库,别的任务取同一天时会等它。"""
|
||||
|
||||
def __init__(self, owner_kind: str, owner_id: str):
|
||||
self.owner_kind = owner_kind
|
||||
self.owner_id = owner_id
|
||||
self.store = GongcanStore(engine(), self._load)
|
||||
|
||||
async def _load(self, city: str, day: date) -> dict[str, list[dict]]:
|
||||
with platform_cookies(self.owner_kind, self.owner_id) as (cookies, mark):
|
||||
client = NqiClient()
|
||||
client.import_cookies(cookies)
|
||||
try:
|
||||
return await fetch_snapshot(OpenCode(client), city, day)
|
||||
except NqiAuthError as exc:
|
||||
mark(True)
|
||||
raise GongcanError("大数据平台登录已失效,请重新登录后再提交") from exc
|
||||
finally:
|
||||
await client.aclose()
|
||||
|
||||
def before_day(self, city: str, target: Target, removal: date) -> date:
|
||||
return asyncio.run(pick_before(self.store, city, target, removal))
|
||||
|
||||
def after_pick(self, city: str, target: Target, removal: date, today: date) -> AfterPick | None:
|
||||
return asyncio.run(pick_after(self.store, city, target, removal, today))
|
||||
|
||||
def cells(self, city: str, day: date) -> list[dict]:
|
||||
return self.store.cells(city, day)
|
||||
|
||||
|
||||
def _unit(*parts: object) -> float:
|
||||
digest = hashlib.sha256("|".join(str(part) for part in parts).encode("utf-8")).digest()
|
||||
return int.from_bytes(digest[:8], "big") / 2**64
|
||||
|
||||
|
||||
def _between(low: float, high: float, *parts: object) -> float:
|
||||
return low + (high - low) * _unit(*parts)
|
||||
|
||||
|
||||
class MockGongcan:
|
||||
"""演示用工参:待拆小区放在一处,周围散布模拟站点,拆除前取上个月 1 号、拆除后取昨天。"""
|
||||
|
||||
SITES = 24
|
||||
|
||||
def __init__(self):
|
||||
self.targets: dict[str, str] = {}
|
||||
|
||||
def before_day(self, city: str, target: Target, removal: date) -> date:
|
||||
for cgi in target.cgis:
|
||||
self.targets.setdefault(cgi, target.site)
|
||||
if target.site:
|
||||
self.targets.setdefault(f"site:{target.site}", target.site)
|
||||
return month_start(removal, -1)
|
||||
|
||||
def after_pick(self, city: str, target: Target, removal: date, today: date) -> AfterPick | None:
|
||||
yesterday = today - timedelta(days=1)
|
||||
return None if yesterday <= removal else AfterPick(yesterday, False)
|
||||
|
||||
def cells(self, city: str, day: date) -> list[dict]:
|
||||
seed = sorted(self.targets)[0] if self.targets else city
|
||||
base_lat = 22.2 + _between(0, 0.4, seed, "lat")
|
||||
base_lon = 112.6 + _between(0, 0.5, seed, "lon")
|
||||
cells: list[dict] = []
|
||||
target_site = next((site for site in self.targets.values() if site), "") or "模拟待拆站点"
|
||||
cgis = [key for key in self.targets if not key.startswith("site:")] or ["460-00-990000-1", "460-00-990000-2"]
|
||||
for index, cgi in enumerate(cgis, start=1):
|
||||
cells.append(_mock_cell(cgi, f"{target_site}-{index}", target_site, base_lat, base_lon, "4G"))
|
||||
node = cgis[0].rsplit("-", 1)[0]
|
||||
taken = set(cgis)
|
||||
for sector in range(4, 10):
|
||||
cgi = f"{node}-{sector}"
|
||||
if cgi not in taken:
|
||||
cells.append(_mock_cell(cgi, f"{target_site}-共站{sector}", target_site, base_lat, base_lon, "4G"))
|
||||
for number in range(1, self.SITES + 1):
|
||||
angle = _between(0, 2 * math.pi, seed, number, "angle")
|
||||
meters = _between(180, 3500, seed, number, "dist")
|
||||
lat = base_lat + meters * math.cos(angle) / 111_000
|
||||
lon = base_lon + meters * math.sin(angle) / (111_000 * math.cos(math.radians(base_lat)))
|
||||
site = f"模拟站点{number:02d}F-ZLH"
|
||||
node = 900000 + number
|
||||
for sector in range(1, 4):
|
||||
cells.append(_mock_cell(f"460-00-{node}-{sector}", f"{site}-{sector}", site, lat, lon, "4G"))
|
||||
if number % 2 == 0:
|
||||
for sector in range(1, 3):
|
||||
cells.append(_mock_cell(f"460-00-{12000000 + number * 10}-{sector}", f"{site}-NR-{sector}", site, lat, lon, "5G"))
|
||||
return cells
|
||||
|
||||
|
||||
def _mock_cell(cgi: str, name: str, site: str, lat: float, lon: float, tech: str) -> dict:
|
||||
return {
|
||||
"tech": tech,
|
||||
"cgi": cgi,
|
||||
"cell_name": name,
|
||||
"site_name": site,
|
||||
"node_id": cgi.rsplit("-", 1)[0],
|
||||
"node_name": site,
|
||||
"latitude": round(lat, 6),
|
||||
"longitude": round(lon, 6),
|
||||
"network_type": "NR" if tech == "5G" else "TDD",
|
||||
"area": "",
|
||||
"town": "",
|
||||
"state": "现网有业务",
|
||||
"cover_type": "室外",
|
||||
"frequency_band": "",
|
||||
"vendor": "",
|
||||
"azimuth": "",
|
||||
}
|
||||
|
||||
|
||||
class MockMetrics:
|
||||
"""模拟指标。数值范围按现网常见水平,拆除后周边小区流量略有上升。"""
|
||||
|
||||
FREQS_4G = ("D1", "D2", "E1", "F1", "FDD1800", "FDD900", "A")
|
||||
|
||||
def window(self, cells: list[dict], start: date, end: date) -> dict[str, dict]:
|
||||
result: dict[str, dict] = {}
|
||||
for cell in cells:
|
||||
cgi = cell["cgi"]
|
||||
base_traffic = _between(1.5, 55.0, cgi, "traffic")
|
||||
result[cgi] = {
|
||||
"traffic_gb": round(base_traffic * (1 + _between(-0.15, 0.25, cgi, start, "t")), 2),
|
||||
"rrc_max": int(_between(8, 160, cgi, start, "rrc")),
|
||||
"high_load": 1 if _unit(cgi, start, "load") < 0.04 else 0,
|
||||
"mr_weak_pct": round(_between(0.3, 8.5, cgi, start, "weak"), 2),
|
||||
"access_rate": round(_between(99.2, 99.99, cgi, start, "access"), 2),
|
||||
"drop_rate": round(_between(0.01, 0.26, cgi, start, "drop"), 3),
|
||||
"util_peak": round(_between(5, 68, cgi, start, "util"), 2),
|
||||
}
|
||||
return result
|
||||
|
||||
def profile(self, cells: list[dict], day: date) -> dict[str, dict]:
|
||||
month = day.replace(day=1)
|
||||
result: dict[str, dict] = {}
|
||||
for cell in cells:
|
||||
cgi = cell["cgi"]
|
||||
nr = cell.get("tech") == "5G"
|
||||
freq = "N41" if nr else self.FREQS_4G[int(_unit(cgi, "freq") * len(self.FREQS_4G))]
|
||||
mr_total = int(_between(300_000, 1_800_000, cgi, month, "mr"))
|
||||
cover = round(_between(91.5, 99.8, cgi, month, "cover"), 2)
|
||||
result[cgi] = {
|
||||
"sector_name": mock_sector(cell),
|
||||
"freq": freq,
|
||||
"freq_band": "2.6G" if nr else ("3D-MIMO" if _unit(cgi, "mimo") < 0.08 else ""),
|
||||
"bandwidth": 100 if nr else (15 if freq.startswith("FDD") and _unit(cgi, "bw") < 0.5 else 20),
|
||||
"traffic_gb": round(_between(1.5, 55.0, cgi, "traffic"), 2),
|
||||
"rrc_max": int(_between(8, 160, cgi, month, "rrc")),
|
||||
"rrc_max_abs": int(_between(12, 220, cgi, month, "rrcabs")),
|
||||
"util_peak": round(_between(5, 68, cgi, month, "util"), 2),
|
||||
"high_traffic_warn": "是" if _unit(cgi, month, "warn") < 0.05 else "否",
|
||||
"high_load_expand": "是" if _unit(cgi, month, "expand") < 0.04 else "否",
|
||||
"mr_total": mr_total,
|
||||
"mr_good_cnt": int(mr_total * cover / 100),
|
||||
"mr_cover_pct": cover,
|
||||
"unicom_cov": round(_between(93, 99.6, cgi, month, "unicom"), 2),
|
||||
"telecom_cov": round(_between(93, 99.6, cgi, month, "telecom"), 2),
|
||||
"weak_cell": "是" if cover < 93 else "否",
|
||||
"worse_unicom": "否",
|
||||
"worse_telecom": "否",
|
||||
}
|
||||
return result
|
||||
|
||||
def sector_members(self, sectors: set[str], day: date, pool: list[dict]) -> dict[str, list[dict]]:
|
||||
members: dict[str, list[dict]] = {sector: [] for sector in sectors}
|
||||
for cell in pool:
|
||||
sector = mock_sector(cell)
|
||||
if sector in members:
|
||||
members[sector].append(cell)
|
||||
return members
|
||||
|
||||
|
||||
def mock_sector(cell: dict) -> str:
|
||||
"""模拟的共站同覆盖区域名:同站同扇区号(CGI 末段除以 3 取余)的小区归一个扇区。"""
|
||||
try:
|
||||
number = int(str(cell["cgi"]).rsplit("-", 1)[1])
|
||||
except (IndexError, ValueError):
|
||||
number = 0
|
||||
return f"{cell.get('site_name') or ''}-扇区{number % 3 + 1}"
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,208 @@
|
||||
"""在固定模板上就地扩行、删行、套样式和合并单元格。
|
||||
|
||||
openpyxl 自带的 insert_rows / delete_rows 不移动合并区、行高和条件格式,模板版式会乱,这里自己移动。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
from collections.abc import Callable
|
||||
|
||||
from openpyxl.cell.cell import MergedCell
|
||||
from openpyxl.formatting.formatting import ConditionalFormattingList
|
||||
from openpyxl.styles import Alignment, Font, PatternFill
|
||||
from openpyxl.utils import get_column_letter
|
||||
from openpyxl.utils.cell import range_boundaries
|
||||
|
||||
ZEBRA = PatternFill(fill_type="solid", start_color="F2F6FC", end_color="F2F6FC")
|
||||
MISSING = PatternFill(fill_type="solid", start_color="FFC7CE", end_color="FFC7CE")
|
||||
|
||||
|
||||
def text(ws, row: int, col: int) -> str:
|
||||
value = ws.cell(row=row, column=col).value
|
||||
return str(value).strip() if value is not None else ""
|
||||
|
||||
|
||||
def find_row(ws, test: Callable[[int], bool], start: int = 1, stop: int | None = None) -> int | None:
|
||||
for row in range(start, (stop or ws.max_row) + 1):
|
||||
if test(row):
|
||||
return row
|
||||
return None
|
||||
|
||||
|
||||
def header_map(ws, row: int) -> dict[str, int]:
|
||||
found: dict[str, int] = {}
|
||||
for col in range(1, ws.max_column + 1):
|
||||
label = text(ws, row, col)
|
||||
if label:
|
||||
found.setdefault(label, col)
|
||||
return found
|
||||
|
||||
|
||||
def row_empty(ws, row: int, last_col: int) -> bool:
|
||||
return all(text(ws, row, col) == "" for col in range(1, last_col + 1))
|
||||
|
||||
|
||||
def block_end(ws, first: int, last_col: int) -> int:
|
||||
"""从 first 起连续的非空行,返回最后一行。"""
|
||||
row = first
|
||||
while row + 1 <= ws.max_row and not row_empty(ws, row + 1, last_col):
|
||||
row += 1
|
||||
return row
|
||||
|
||||
|
||||
def _map_row(row: int, at: int, delta: int) -> int | None:
|
||||
if delta > 0:
|
||||
return row + delta if row >= at else row
|
||||
end = at - delta
|
||||
if row < at:
|
||||
return row
|
||||
if row < end:
|
||||
return None
|
||||
return row + delta
|
||||
|
||||
|
||||
def _map_span(first: int, last: int, at: int, delta: int) -> tuple[int, int] | None:
|
||||
if delta > 0:
|
||||
return (first + delta if first >= at else first), (last + delta if last >= at else last)
|
||||
end = at - delta
|
||||
if first >= at and last < end:
|
||||
return None
|
||||
new_first = first if first < at else (at if first < end else first + delta)
|
||||
new_last = last if last < at else (at - 1 if last < end else last + delta)
|
||||
return (new_first, new_last) if new_last >= new_first else None
|
||||
|
||||
|
||||
def remap_conditional(ws, mapper: Callable[[int, int], tuple[int, int] | None]) -> None:
|
||||
entries = [(str(item.sqref), list(item.rules)) for item in ws.conditional_formatting]
|
||||
if not entries:
|
||||
return
|
||||
fresh = ConditionalFormattingList()
|
||||
for sqref, rules in entries:
|
||||
parts = []
|
||||
for part in sqref.split():
|
||||
min_col, min_row, max_col, max_row = range_boundaries(part)
|
||||
span = mapper(min_row, max_row)
|
||||
if span is not None:
|
||||
parts.append(f"{get_column_letter(min_col)}{span[0]}:{get_column_letter(max_col)}{span[1]}")
|
||||
for rule in rules if parts else []:
|
||||
fresh.add(" ".join(parts), rule)
|
||||
ws.conditional_formatting = fresh
|
||||
|
||||
|
||||
def shift_rows(ws, at: int, delta: int) -> None:
|
||||
"""delta > 0 时在第 at 行前插入 delta 行;delta < 0 时从第 at 行起删掉 -delta 行。"""
|
||||
if delta == 0:
|
||||
return
|
||||
merges = [(item.min_row, item.min_col, item.max_row, item.max_col) for item in ws.merged_cells.ranges]
|
||||
for item in list(ws.merged_cells.ranges):
|
||||
ws.unmerge_cells(str(item))
|
||||
cells = ws._cells
|
||||
if delta < 0:
|
||||
for key in [key for key in cells if at <= key[0] < at - delta]:
|
||||
del cells[key]
|
||||
start = at if delta > 0 else at - delta
|
||||
for key in sorted((key for key in cells if key[0] >= start), reverse=delta > 0):
|
||||
cell = cells.pop(key)
|
||||
cell.row = key[0] + delta
|
||||
cells[(cell.row, key[1])] = cell
|
||||
heights = {row: (dim.height, dim.hidden) for row, dim in ws.row_dimensions.items()}
|
||||
for row in list(ws.row_dimensions.keys()):
|
||||
del ws.row_dimensions[row]
|
||||
for row, (height, hidden) in heights.items():
|
||||
moved = _map_row(row, at, delta)
|
||||
if moved is None:
|
||||
continue
|
||||
dim = ws.row_dimensions[moved]
|
||||
if height is not None:
|
||||
dim.height = height
|
||||
if hidden:
|
||||
dim.hidden = True
|
||||
for min_row, min_col, max_row, max_col in merges:
|
||||
span = _map_span(min_row, max_row, at, delta)
|
||||
if span is None or (span[0] == span[1] and min_col == max_col):
|
||||
continue
|
||||
ws.merge_cells(start_row=span[0], start_column=min_col, end_row=span[1], end_column=max_col)
|
||||
remap_conditional(ws, lambda first, last: _map_span(first, last, at, delta))
|
||||
|
||||
|
||||
def fit_block(ws, first: int, last: int, want: int) -> int:
|
||||
"""把 first..last 这段调整成 want 行,返回新的最后一行。扩出的行样式由调用方再套。"""
|
||||
want = max(want, 1)
|
||||
have = last - first + 1
|
||||
if want > have:
|
||||
shift_rows(ws, last + 1, want - have)
|
||||
remap_conditional(ws, lambda lo, hi: (lo, first + want - 1) if lo >= first and hi == last else (lo, hi))
|
||||
elif want < have:
|
||||
shift_rows(ws, first + want, want - have)
|
||||
return first + want - 1
|
||||
|
||||
|
||||
def unmerge_within(ws, first: int, last: int) -> None:
|
||||
for item in [str(item) for item in ws.merged_cells.ranges if item.min_row >= first and item.max_row <= last]:
|
||||
ws.unmerge_cells(item)
|
||||
|
||||
|
||||
def row_style(ws, row: int, last_col: int) -> tuple[list, float | None]:
|
||||
styles = []
|
||||
for col in range(1, last_col + 1):
|
||||
cell = ws._cells.get((row, col))
|
||||
styles.append(copy.copy(cell._style) if cell is not None and not isinstance(cell, MergedCell) else None)
|
||||
return styles, ws.row_dimensions[row].height
|
||||
|
||||
|
||||
def apply_style(ws, row: int, style: tuple[list, float | None]) -> None:
|
||||
styles, height = style
|
||||
for col, value in enumerate(styles, start=1):
|
||||
if value is not None:
|
||||
ws.cell(row=row, column=col)._style = copy.copy(value)
|
||||
if height:
|
||||
ws.row_dimensions[row].height = height
|
||||
|
||||
|
||||
def clear_row(ws, row: int, last_col: int) -> None:
|
||||
for col in range(1, last_col + 1):
|
||||
cell = ws._cells.get((row, col))
|
||||
if cell is not None and not isinstance(cell, MergedCell):
|
||||
cell.value = None
|
||||
|
||||
|
||||
def put(ws, row: int, col: int, value, number_format: str | None = None) -> None:
|
||||
"""写值;填进去的数据不加粗(模板示例行有的带粗体)。"""
|
||||
cell = ws.cell(row=row, column=col)
|
||||
if isinstance(cell, MergedCell):
|
||||
return
|
||||
cell.value = value
|
||||
if number_format:
|
||||
cell.number_format = number_format
|
||||
font = cell.font
|
||||
if font is not None and font.bold:
|
||||
cell.font = Font(
|
||||
name=font.name,
|
||||
size=font.size,
|
||||
bold=False,
|
||||
italic=font.italic,
|
||||
underline=font.underline,
|
||||
strike=font.strike,
|
||||
vertAlign=font.vertAlign,
|
||||
color=copy.copy(font.color),
|
||||
)
|
||||
|
||||
|
||||
def merge_down(ws, col: int, first: int, last: int, value, *, wrap: bool = False, border_from=None) -> None:
|
||||
"""纵向合并 first..last;合并区的边框取左上角单元格,所以先设边框再合并。"""
|
||||
anchor = ws.cell(row=first, column=col)
|
||||
if border_from is not None:
|
||||
anchor.border = copy.copy(border_from)
|
||||
anchor.value = value
|
||||
anchor.alignment = Alignment(horizontal="center", vertical="center", wrap_text=wrap)
|
||||
if last > first:
|
||||
ws.merge_cells(start_row=first, start_column=col, end_row=last, end_column=col)
|
||||
|
||||
|
||||
def fill_rows(ws, first: int, last: int, last_col: int, fill: PatternFill) -> None:
|
||||
for row in range(first, last + 1):
|
||||
for col in range(1, last_col + 1):
|
||||
cell = ws._cells.get((row, col))
|
||||
if cell is not None and not isinstance(cell, MergedCell):
|
||||
cell.fill = fill
|
||||
Reference in New Issue
Block a user