378 lines
14 KiB
Python
378 lines
14 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""AOI 与渠道 2 公里范围的交叠匹配。"""
|
|
|
|
import json
|
|
import os
|
|
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 = "AoiChannel"
|
|
AOI_FIELDS = ["AOI唯一标签", "AOI名称", "空间信息(几何)"]
|
|
CHANNEL_LAYER_FIELDS = [
|
|
"渠道编码", "渠道类型", "全网渠道编码", "渠道名称", "星级",
|
|
"地理经度", "地理纬度", "连锁", "头腰尾标识",
|
|
]
|
|
CHANNEL_FIELDS = ["渠道编码", "全网渠道编码", "渠道名称", "所属渠道管理员工姓名", "地理经度", "地理纬度"]
|
|
CHANNEL_READ_FIELDS = list(dict.fromkeys([*CHANNEL_LAYER_FIELDS, *CHANNEL_FIELDS]))
|
|
RADIUS_M = 2000
|
|
AREA_FIELD = "交叠面积(平方米)"
|
|
PAIR_CHUNK = 100_000
|
|
DEFAULTS = {
|
|
"AOI清单": "Source/AOI/全量AOI清单_202609.csv",
|
|
"渠道表": "Source/实体渠道匹配表/【26年11月11日】实体渠道匹配表v2s_渠道信息.xlsx",
|
|
}
|
|
|
|
|
|
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()
|
|
os.environ["GDAL_DRIVER_PATH"] = "disabled"
|
|
|
|
try:
|
|
import geopandas as gpd
|
|
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 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 text_column(series):
|
|
return series.fillna("").astype(str).str.strip()
|
|
|
|
|
|
def metric_crs(longitudes, latitudes):
|
|
longitude = float(np.nanmedian(np.asarray(longitudes, dtype=float)))
|
|
latitude = float(np.nanmedian(np.asarray(latitudes, dtype=float)))
|
|
zone = min(60, max(1, int((longitude + 180) // 6) + 1))
|
|
return f"EPSG:{32600 + zone if latitude >= 0 else 32700 + zone}"
|
|
|
|
|
|
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:
|
|
frame = pd.read_csv(path, encoding=encoding, dtype=str)
|
|
return frame
|
|
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:
|
|
layer = gpd.GeoDataFrame(columns=["AOI唯一标签", "AOI名称"], geometry=[], crs="EPSG:4326")
|
|
return layer, 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].drop(columns="空间信息(几何)").reset_index(drop=True)
|
|
layer = gpd.GeoDataFrame(frame, geometry=list(geometries[keep]), crs="EPSG:4326")
|
|
return layer, blank_count, duplicates, invalid
|
|
|
|
|
|
def channel_sheet(path):
|
|
book = pd.ExcelFile(path)
|
|
for sheet in book.sheet_names:
|
|
columns = pd.read_excel(book, sheet_name=sheet, nrows=0).columns.tolist()
|
|
if all(name in columns for name in CHANNEL_READ_FIELDS):
|
|
return sheet
|
|
raise SystemExit("渠道表中没有所需字段")
|
|
|
|
|
|
def read_channels(path):
|
|
sheet = channel_sheet(path)
|
|
frame = pd.read_excel(path, sheet_name=sheet, dtype=str)
|
|
missing = [name for name in CHANNEL_READ_FIELDS if name not in frame.columns]
|
|
if missing:
|
|
raise SystemExit("渠道表缺少字段: " + "、".join(missing))
|
|
frame = frame[CHANNEL_READ_FIELDS].copy()
|
|
for name in CHANNEL_READ_FIELDS:
|
|
frame[name] = text_column(frame[name])
|
|
blank = frame["地理经度"].eq("") | frame["地理纬度"].eq("")
|
|
blank_count = int(blank.sum())
|
|
frame = frame.loc[~blank].copy()
|
|
longitude = pd.to_numeric(frame["地理经度"], errors="coerce")
|
|
latitude = pd.to_numeric(frame["地理纬度"], errors="coerce")
|
|
valid = longitude.between(-180, 180) & latitude.between(-90, 90)
|
|
invalid = int((~valid).sum())
|
|
frame = frame.loc[valid].copy()
|
|
before = len(frame)
|
|
frame = frame.drop_duplicates(CHANNEL_READ_FIELDS).reset_index(drop=True)
|
|
if frame.empty:
|
|
points = gpd.GeoDataFrame(columns=CHANNEL_READ_FIELDS, geometry=[], crs="EPSG:4326")
|
|
return points, blank_count, before - len(frame), invalid
|
|
points = gpd.GeoDataFrame(
|
|
frame,
|
|
geometry=shapely.points(pd.to_numeric(frame["地理经度"]), pd.to_numeric(frame["地理纬度"])),
|
|
crs="EPSG:4326",
|
|
)
|
|
return points, blank_count, before - len(frame), invalid
|
|
|
|
|
|
def intersection_area(left, right):
|
|
total = len(left)
|
|
areas = np.empty(total, dtype=float)
|
|
for start in range(0, total, PAIR_CHUNK):
|
|
stop = min(start + PAIR_CHUNK, total)
|
|
areas[start:stop] = shapely.area(shapely.intersection(left[start:stop], right[start:stop]))
|
|
return areas
|
|
|
|
|
|
def overlap_tables(aoi, channels):
|
|
columns = ["AOI唯一标签", "AOI名称", *CHANNEL_FIELDS, AREA_FIELD]
|
|
channel_columns = [*CHANNEL_FIELDS, "AOI唯一标签", "AOI名称", AREA_FIELD]
|
|
empty_aoi = pd.DataFrame(columns=columns)
|
|
empty_channel = pd.DataFrame(columns=channel_columns)
|
|
if aoi.empty or channels.empty:
|
|
return empty_aoi, empty_channel, channels
|
|
|
|
longitude = pd.to_numeric(channels["地理经度"])
|
|
latitude = pd.to_numeric(channels["地理纬度"])
|
|
projected = metric_crs(longitude, latitude)
|
|
aoi_m = aoi.to_crs(projected)
|
|
channel_m = channels.to_crs(projected)
|
|
channel_m = channel_m.set_geometry(shapely.buffer(channel_m.geometry.to_numpy(), RADIUS_M, quad_segs=16))
|
|
stored = gpd.GeoDataFrame(
|
|
channels[CHANNEL_LAYER_FIELDS],
|
|
geometry=channel_m.to_crs("EPSG:4326").geometry,
|
|
crs="EPSG:4326",
|
|
)
|
|
tree = STRtree(channel_m.geometry.to_numpy())
|
|
pairs = tree.query(aoi_m.geometry.to_numpy(), predicate="intersects")
|
|
if pairs.shape[1] == 0:
|
|
return empty_aoi, empty_channel, stored
|
|
|
|
areas = intersection_area(aoi_m.geometry.to_numpy()[pairs[0]], channel_m.geometry.to_numpy()[pairs[1]])
|
|
keep = areas > 0
|
|
if not keep.any():
|
|
return empty_aoi, empty_channel, stored
|
|
left = pairs[0, keep]
|
|
right = pairs[1, keep]
|
|
table = pd.DataFrame({
|
|
"AOI唯一标签": aoi["AOI唯一标签"].to_numpy()[left],
|
|
"AOI名称": aoi["AOI名称"].to_numpy()[left],
|
|
"渠道编码": channels["渠道编码"].to_numpy()[right],
|
|
"全网渠道编码": channels["全网渠道编码"].to_numpy()[right],
|
|
"渠道名称": channels["渠道名称"].to_numpy()[right],
|
|
"所属渠道管理员工姓名": channels["所属渠道管理员工姓名"].to_numpy()[right],
|
|
"地理经度": channels["地理经度"].to_numpy()[right],
|
|
"地理纬度": channels["地理纬度"].to_numpy()[right],
|
|
AREA_FIELD: np.round(areas[keep], 2),
|
|
})
|
|
table["组最大面积"] = table.groupby("AOI唯一标签", sort=False)[AREA_FIELD].transform("max")
|
|
table = table.sort_values(
|
|
["组最大面积", "AOI唯一标签", AREA_FIELD, "渠道编码"],
|
|
ascending=[False, True, False, True],
|
|
kind="mergesort",
|
|
)
|
|
channel_aoi = table.sort_values(
|
|
["渠道编码", AREA_FIELD, "AOI唯一标签"],
|
|
ascending=[True, False, True],
|
|
kind="mergesort",
|
|
)
|
|
return table[columns], channel_aoi[channel_columns], stored
|
|
|
|
|
|
def write_gpkg(layer, path, name):
|
|
layer.to_file(path, layer=name, driver="GPKG", spatial_index=True, encoding="UTF-8")
|
|
with sqlite3.connect(path) as connection:
|
|
found = connection.execute("SELECT 1 FROM sqlite_master WHERE name LIKE 'rtree_%' LIMIT 1").fetchone()
|
|
if found is None:
|
|
raise RuntimeError(f"{path.name} 没有空间索引")
|
|
|
|
|
|
def new_stamp():
|
|
while True:
|
|
stamp = datetime.now().strftime("%Y%m%d%H%M%S")
|
|
if not (ROOT / "Output" / TOOL / stamp).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():
|
|
print(f"临时目录未完全删除: {relative(path)}")
|
|
|
|
|
|
def main():
|
|
defaults = load_defaults()
|
|
aoi_text, aoi_path = ask_file("AOI清单", defaults["AOI清单"])
|
|
channel_text, channel_path = ask_file("渠道表", defaults["渠道表"])
|
|
save_defaults({"AOI清单": aoi_text, "渠道表": channel_text})
|
|
|
|
stamp = new_stamp()
|
|
temporary = prepare_temp(stamp)
|
|
try:
|
|
aoi, aoi_blank, aoi_removed, aoi_invalid = read_aoi(aoi_path)
|
|
channels, channel_blank, channel_removed, channel_invalid = read_channels(channel_path)
|
|
aoi_channel, channel_aoi, circles = overlap_tables(aoi, channels)
|
|
staging = temporary / "out"
|
|
staging.mkdir()
|
|
write_gpkg(aoi, staging / "AOI.gpkg", "AOI")
|
|
write_gpkg(circles, staging / "Channel.gpkg", "Channel")
|
|
with pd.ExcelWriter(staging / "result.xlsx", engine="openpyxl") as writer:
|
|
aoi_channel.to_excel(writer, sheet_name="AOI-渠道", index=False)
|
|
channel_aoi.to_excel(writer, sheet_name="渠道-AOI", index=False)
|
|
output = ROOT / "Output" / TOOL / stamp
|
|
output.parent.mkdir(parents=True, exist_ok=True)
|
|
shutil.move(staging, output)
|
|
print(f"AOI {len(aoi)},丢弃空几何 {aoi_blank},去掉重复 {aoi_removed},无效几何 {aoi_invalid}")
|
|
print(f"渠道 {len(channels)},丢弃空坐标 {channel_blank},去掉重复 {channel_removed},无效坐标 {channel_invalid}")
|
|
print(f"交叠 {len(aoi_channel)}")
|
|
print(f"输出 {relative(output)}")
|
|
finally:
|
|
cleanup(temporary)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|