feat: 增加按 AOI 统计各月移动采样点占比的工具

This commit is contained in:
2026-11-13 15:43:18 +08:00
parent adffcecdb9
commit d2e52e7105
6 changed files with 506 additions and 0 deletions
+1
View File
@@ -18,3 +18,4 @@
| 工具 | 说明 | 运行 | 数据源 |
| --- | --- | --- | --- |
| AoiChannel | AOI 与渠道 2 公里范围交叠 | `python Scripts/AoiChannel.py` | `Source/AOI/`、`Source/实体渠道匹配表/` |
| AoiSample | 按 AOI 统计各月移动采样点占比 | `python Scripts/AoiSample.py` | `Source/AOI/`、`Source/众测数据/Grids/` |
+485
View File
@@ -0,0 +1,485 @@
# -*- coding: utf-8 -*-
"""按 AOI 统计各月 4G、5G 移动采样点占比。"""
import json
import os
import re
import shutil
import sqlite3
import sys
import tempfile
import time
from datetime import datetime
from pathlib import Path
import numpy as np
ROOT = Path(__file__).resolve().parents[1]
TOOL = "AoiSample"
AOI_FIELDS = ["AOI唯一标签", "AOI名称", "空间信息(几何)"]
COUNT_FIELDS = ["mro_total_dx", "mro_total_lt", "mro_total_gd", "mro_total_yd"]
READ_FIELDS = ["longitude", "latitude", *COUNT_FIELDS]
CHUNK = 200_000
MONTH_TEXT = re.compile(r"20\d{4}")
DEFAULTS = {
"AOI清单": "Source/AOI/全量AOI清单_202609.csv",
"栅格目录": "Source/众测数据/Grids",
}
def ensure_venv():
python = ROOT / ".venv" / "Scripts" / "python.exe"
if not python.is_file():
return
if Path(sys.executable).resolve() == python.resolve():
return
os.execv(str(python), [str(python), *sys.argv])
ensure_venv()
try:
import pandas as pd
import shapely
from shapely import STRtree, from_wkt, make_valid
from shapely.geometry import GeometryCollection, MultiPolygon, Polygon
from shapely.ops import unary_union
except ImportError:
sys.exit("缺少依赖。请在项目根目录用 .venv 安装 requirements.txt")
def report(text):
print(text, flush=True)
def load_defaults():
path = ROOT / "Local" / f"{TOOL}.json"
if not path.is_file():
return dict(DEFAULTS)
saved = json.loads(path.read_text(encoding="utf-8"))
values = dict(DEFAULTS)
values.update({key: saved[key] for key in DEFAULTS if key in saved and saved[key]})
return values
def save_defaults(values):
path = ROOT / "Local" / f"{TOOL}.json"
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(values, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
def resolve_path(text):
path = Path(text)
if not path.is_absolute():
path = ROOT / path
return path
def ask_file(title, default):
while True:
suffix = f" [{default}]" if default else ""
entered = input(f"{title}{suffix}: ").strip()
text = entered or default
if not text:
print("需要填写路径")
continue
path = resolve_path(text)
if not path.is_file():
print("文件不存在")
continue
return text, path
def ask_dir(title, default):
while True:
suffix = f" [{default}]" if default else ""
entered = input(f"{title}{suffix}: ").strip()
text = entered or default
if not text:
print("需要填写路径")
continue
path = resolve_path(text)
if not path.is_dir():
print("目录不存在")
continue
return text, path
def text_column(series):
return series.fillna("").astype(str).str.strip()
def polygonal(geom):
if geom is None or geom.is_empty:
return None
if not geom.is_valid:
geom = make_valid(geom)
if isinstance(geom, (Polygon, MultiPolygon)):
return None if geom.is_empty else geom
if isinstance(geom, GeometryCollection):
parts = [polygonal(part) for part in geom.geoms]
parts = [part for part in parts if part is not None]
if not parts:
return None
merged = unary_union(parts)
return None if merged.is_empty else merged
return None
def empty_geometry_mask(geometries):
geometries = np.asarray(geometries, dtype=object)
if len(geometries) == 0:
return np.zeros(0, dtype=bool)
missing = shapely.is_missing(geometries)
empty = missing.copy()
present = ~missing
if present.any():
empty[present] = shapely.is_empty(geometries[present])
return empty
def as_polygons(geometries):
geometries = np.asarray(geometries, dtype=object)
if len(geometries) == 0:
return geometries, np.zeros(0, dtype=bool)
missing = shapely.is_missing(geometries)
if (~missing).any():
present = geometries[~missing]
invalid = ~shapely.is_valid(present)
if invalid.any():
present = np.array(present, dtype=object, copy=True)
present[invalid] = make_valid(present[invalid])
geometries = np.array(geometries, dtype=object, copy=True)
geometries[~missing] = present
geometries = shapely.force_2d(geometries)
type_id = shapely.get_type_id(geometries)
for index in np.flatnonzero(type_id == 7):
geometries[index] = polygonal(geometries[index])
type_id = shapely.get_type_id(geometries)
present = ~shapely.is_missing(geometries)
empty = np.ones(len(geometries), dtype=bool)
if present.any():
empty[present] = shapely.is_empty(geometries[present])
keep = np.isin(type_id, (3, 6)) & ~empty
return geometries, keep
def read_table(path):
last_error = None
for encoding in ("utf-8-sig", "utf-8", "gbk"):
try:
return pd.read_csv(path, encoding=encoding, dtype=str)
except UnicodeDecodeError as exc:
last_error = exc
raise SystemExit(f"AOI清单无法读取: {last_error}")
def read_aoi(path):
frame = read_table(path)
missing = [name for name in AOI_FIELDS if name not in frame.columns]
if missing:
raise SystemExit("AOI清单缺少字段: " + "、".join(missing))
frame = frame[AOI_FIELDS].copy()
for name in AOI_FIELDS:
frame[name] = text_column(frame[name])
geometry_text = frame["空间信息(几何)"]
blank = geometry_text.eq("") | geometry_text.str.contains(r"\bEMPTY\b", case=False, regex=True)
blank_count = int(blank.sum())
frame = frame.loc[~blank].copy()
before = len(frame)
frame = frame.drop_duplicates(AOI_FIELDS).reset_index(drop=True)
duplicates = before - len(frame)
if frame.empty:
return np.array([], dtype=object), np.array([], dtype=object), np.array([], dtype=object), blank_count, duplicates, 0
parsed = from_wkt(frame["空间信息(几何)"].to_numpy(), on_invalid="ignore")
empty = empty_geometry_mask(parsed)
blank_count += int(empty.sum())
frame = frame.loc[~empty].reset_index(drop=True)
parsed = parsed[~empty]
geometries, keep = as_polygons(parsed)
invalid = int((~keep).sum())
frame = frame.loc[keep].reset_index(drop=True)
return (
frame["AOI唯一标签"].to_numpy(),
frame["AOI名称"].to_numpy(),
geometries[keep],
blank_count,
duplicates,
invalid,
)
def quote_name(name):
return '"' + name.replace('"', '""') + '"'
def feature_table(connection, path):
rows = connection.execute("SELECT table_name FROM gpkg_contents WHERE data_type = 'features'").fetchall()
names = [row[0] for row in rows]
if path.stem in names:
return path.stem
if len(names) == 1:
return names[0]
raise SystemExit(f"{path.name} 里有多张图层,无法确定使用哪一张")
def month_of(path):
found = MONTH_TEXT.findall(path.stem)
if not found:
return None
if len(set(found)) != 1:
raise SystemExit(f"文件名月份不一致: {path.name}")
return found[0]
def discover_grids(root):
found = {"4G": {}, "5G": {}}
for network in found:
folder = root / network
if not folder.is_dir():
raise SystemExit(f"缺少目录 {network}")
for path in sorted(folder.glob("*.gpkg")):
if path.name.startswith("~$"):
continue
month = month_of(path)
if month is None:
continue
if month in found[network]:
raise SystemExit(f"{network} {month} 有多份文件")
found[network][month] = path
months = sorted(set(found["4G"]) | set(found["5G"]))
if not months:
raise SystemExit("栅格目录里没有月份数据")
return found, months
def numeric_column(values):
return pd.to_numeric(pd.Series(values), errors="coerce").to_numpy(dtype=np.float64)
def check_month(connection, table, path, month):
columns = {row[1] for row in connection.execute(f"PRAGMA table_info({quote_name(table)})")}
missing = [name for name in ["intmonthid", *READ_FIELDS] if name not in columns]
if missing:
raise SystemExit(f"{path.name} 缺少字段: " + "、".join(missing))
row = connection.execute(f"SELECT intmonthid FROM {quote_name(table)} LIMIT 1").fetchone()
if row is None:
return
value = str(row[0]).strip()
if value and value != month:
raise SystemExit(f"{path.name} 的 intmonthid 是 {value},文件名月份是 {month}")
def open_grid(path):
return sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True)
def fetch_rows(connection, table, start, stop):
selected = ", ".join(quote_name(name) for name in READ_FIELDS)
return connection.execute(
f"SELECT {selected} FROM {quote_name(table)} WHERE rowid BETWEEN ? AND ?",
(start, stop),
).fetchall()
def read_span(path, table, start, stop):
connection = open_grid(path)
try:
return fetch_rows(connection, table, start, stop), 0
except sqlite3.DatabaseError:
if start == stop:
return [], 1
mid = (start + stop) // 2
left_rows, left_skipped = read_span(path, table, start, mid)
right_rows, right_skipped = read_span(path, table, mid + 1, stop)
return left_rows + right_rows, left_skipped + right_skipped
finally:
connection.close()
def add_rows(rows, tree, bounds, total, mobile):
if not rows:
return 0, 0
values = np.asarray(rows, dtype=object)
longitude = numeric_column(values[:, 0])
latitude = numeric_column(values[:, 1])
counts = np.column_stack([numeric_column(values[:, index]) for index in range(2, 6)])
counts = np.nan_to_num(counts, nan=0.0)
valid = np.isfinite(longitude) & np.isfinite(latitude)
dropped = int((~valid).sum())
minx, miny, maxx, maxy = bounds
valid &= (longitude >= minx) & (longitude <= maxx) & (latitude >= miny) & (latitude <= maxy)
if not valid.any():
return dropped, 0
points = shapely.points(longitude[valid], latitude[valid])
pairs = tree.query(points, predicate="intersects")
if pairs.shape[1] == 0:
return dropped, 0
point_index = pairs[0]
aoi_index = pairs[1]
chosen = counts[valid]
np.add.at(total, aoi_index, chosen[point_index].sum(axis=1))
np.add.at(mobile, aoi_index, chosen[point_index, 3])
return dropped, int(np.unique(point_index).size)
def accumulate(path, tree, bounds, total, mobile):
connection = open_grid(path)
try:
table = feature_table(connection, path)
check_month(connection, table, path, month_of(path))
max_row = connection.execute(f"SELECT MAX(rowid) FROM {quote_name(table)}").fetchone()[0] or 0
grids = 0
dropped = 0
inside = 0
skipped = 0
start = 1
while start <= max_row:
stop = min(start + CHUNK - 1, max_row)
try:
rows = fetch_rows(connection, table, start, stop)
broken = 0
except sqlite3.DatabaseError:
connection.close()
rows, broken = read_span(path, table, start, stop)
connection = open_grid(path)
skipped += broken
dropped_now, inside_now = add_rows(rows, tree, bounds, total, mobile)
grids += len(rows)
dropped += dropped_now
inside += inside_now
start = stop + 1
return grids, dropped, inside, skipped
finally:
connection.close()
def count_values(values):
nearest = np.rint(values)
if len(values) == 0 or np.max(np.abs(values - nearest)) < 1e-4:
return nearest.astype(np.int64)
return np.round(values, 2)
def share_values(mobile, total):
share = np.full(len(total), np.nan, dtype=np.float64)
positive = total > 0
share[positive] = mobile[positive] / total[positive]
return share
def result_frame(labels, names, months, total, mobile):
data = {"AOI唯一标签": labels, "AOI名称": names}
for index, month in enumerate(months):
data[f"{month}采样点总数"] = count_values(total[index])
data[f"{month}移动采样点数量"] = count_values(mobile[index])
data[f"{month}移动采样点占比"] = share_values(mobile[index], total[index])
return pd.DataFrame(data)
def write_book(path, frames):
with pd.ExcelWriter(path, engine="openpyxl") as writer:
for name, frame in frames.items():
frame.to_excel(writer, sheet_name=name, index=False)
sheet = writer.sheets[name]
percent = [index for index, column in enumerate(frame.columns, 1) if str(column).endswith("移动采样点占比")]
for column in percent:
for cell in sheet.iter_cols(min_col=column, max_col=column, min_row=2, max_row=sheet.max_row):
cell[0].number_format = "0.00%"
for cell in sheet[1]:
sheet.column_dimensions[cell.column_letter].width = max(12, len(str(cell.value)) * 2 + 2)
sheet.freeze_panes = "C2"
sheet.auto_filter.ref = sheet.dimensions
def new_stamp():
while True:
stamp = datetime.now().strftime("%Y%m%d%H%M%S")
target = ROOT / "Output" / TOOL / f"AOI-移动采样点占比_{stamp}.xlsx"
if not target.exists():
return stamp
time.sleep(1)
def prepare_temp(stamp):
path = ROOT / "Temp" / TOOL / stamp
if path.exists():
shutil.rmtree(path)
path.mkdir(parents=True)
os.environ["TEMP"] = str(path)
os.environ["TMP"] = str(path)
tempfile.tempdir = str(path)
return path
def relative(path):
try:
return path.relative_to(ROOT).as_posix()
except ValueError:
return str(path)
def cleanup(path):
if path.exists():
shutil.rmtree(path, ignore_errors=True)
if path.exists():
report(f"临时目录未完全删除: {relative(path)}")
def main():
defaults = load_defaults()
aoi_text, aoi_path = ask_file("AOI清单", defaults["AOI清单"])
grid_text, grid_root = ask_dir("栅格目录", defaults["栅格目录"])
save_defaults({"AOI清单": aoi_text, "栅格目录": grid_text})
files, months = discover_grids(grid_root)
labels, names, geometries, blank_count, duplicates, invalid = read_aoi(aoi_path)
if len(labels) == 0:
raise SystemExit("没有可统计的 AOI")
order = np.argsort(labels, kind="mergesort")
labels = labels[order]
names = names[order]
geometries = geometries[order]
tree = STRtree(geometries)
bounds = shapely.total_bounds(geometries)
total = {network: np.zeros((len(months), len(labels)), dtype=np.float64) for network in ("4G", "5G")}
mobile = {network: np.zeros((len(months), len(labels)), dtype=np.float64) for network in ("4G", "5G")}
report("月份 " + "、".join(months))
stamp = new_stamp()
temporary = prepare_temp(stamp)
try:
for network in ("4G", "5G"):
for index, month in enumerate(months):
path = files[network].get(month)
if path is None:
report(f"{network} {month}:没有文件,按 0 计")
continue
started = time.perf_counter()
grids, dropped, inside, skipped = accumulate(
path, tree, bounds, total[network][index], mobile[network][index]
)
damaged = f",跳过损坏记录 {skipped}" if skipped else ""
report(
f"{network} {month}:栅格 {grids},丢弃空坐标 {dropped},落入 AOI {inside}{damaged},"
f"用时 {time.perf_counter() - started:.1f} 秒"
)
frames = {
"4G": result_frame(labels, names, months, total["4G"], mobile["4G"]),
"5G": result_frame(labels, names, months, total["5G"], mobile["5G"]),
"汇总": result_frame(labels, names, months, total["4G"] + total["5G"], mobile["4G"] + mobile["5G"]),
}
staging = temporary / f"AOI-移动采样点占比_{stamp}.xlsx"
write_book(staging, frames)
output_dir = ROOT / "Output" / TOOL
output_dir.mkdir(parents=True, exist_ok=True)
output = output_dir / staging.name
shutil.move(staging, output)
report(f"AOI {len(labels)},丢弃空几何 {blank_count},去掉重复 {duplicates},无效几何 {invalid}")
report(f"输出 {relative(output)}")
finally:
cleanup(temporary)
if __name__ == "__main__":
main()
+2
View File
@@ -10,3 +10,5 @@
| --- | --- | --- | --- |
| AoiChannel | `Source/AOI/全量AOI清单_202609.csv` | CSV,WKT 多边形 | [AoiChannel](../docs/数据源/AoiChannel.md) |
| AoiChannel | `Source/实体渠道匹配表/【26年11月11日】实体渠道匹配表v2s_渠道信息.xlsx` | xlsx,经纬度点,生成 2 公里圆 | [AoiChannel](../docs/数据源/AoiChannel.md) |
| AoiSample | `Source/AOI/全量AOI清单_202609.csv` | CSV,WKT 多边形 | [AoiSample](../docs/数据源/AoiSample.md) |
| AoiSample | `Source/众测数据/Grids/4G/`、`Source/众测数据/Grids/5G/` | 按月 GPKG 栅格,采样点数量 | [AoiSample](../docs/数据源/AoiSample.md) |
+18
View File
@@ -0,0 +1,18 @@
# AoiSample
按 AOI 统计目录中每个月份的采样点总数、移动采样点数量和移动采样点占比。4G、5G 分开统计,汇总表把两边的采样点数相加。
## AOI清单
字段和去重规则与 [AoiChannel](AoiChannel.md) 的 AOI清单相同。本工具使用 AOI唯一标签、AOI名称、空间信息(几何)。图形为空的记录先丢弃。
- 存放路径:`Source/AOI/全量AOI清单_202609.csv`
- 命名格式:`全量AOI清单_*.csv`
## 众测栅格
- 存放路径:`Source/众测数据/Grids/4G/`、`Source/众测数据/Grids/5G/`
- 命名格式:文件名包含 6 位月份,如 `202607`。当前文件是 `mr_lte_zc_grid20_jm_202604_202604.gpkg`、`mr_nr_zc_grid20_jm_202604_202604.gpkg` 这一类。同一个网络同一个月只保留一份。
- 数据格式:GPKG,20 米栅格,坐标系 EPSG:4326。属性按文本存放。
- 字段:longitude、latitude、intmonthid、mro_total_dx、mro_total_lt、mro_total_gd、mro_total_yd
- 说明:longitude、latitude 是栅格中心点。采样点总数是电信、联通、广电、移动四家 `mro_total` 之和。移动采样点数量是 `mro_total_yd`。`mro_total_dl` 是电联,等于电信加联通,不加入分母。中心点经纬度为空的栅格先丢弃。中心点落在 AOI 内才计入该 AOI;AOI 互相重叠时,同一个栅格分别计入每个 AOI。四家合计为 0 时,占比留空。文件里读不出来的记录会跳过,并在运行时提示数量。