235 lines
10 KiB
Python
235 lines
10 KiB
Python
"""把 AOI 报表按与市场网格的最大接触面积归属,生成匹配总表。"""
|
|
import csv
|
|
import math
|
|
import sqlite3
|
|
from pathlib import Path
|
|
|
|
from shapely import STRtree, make_valid, wkt
|
|
from shapely.affinity import scale
|
|
from shapely.geometry import MultiPolygon, Polygon
|
|
|
|
from . import config
|
|
from .gpkg import load_market_features, open_read_connection, quote_identifier, resolve_feature_layer
|
|
|
|
GEOMETRY_COLUMN = "空间信息(几何)"
|
|
REAL_COLUMNS = [
|
|
"移动C端采样点占比", "联通C端采样点占比", "电信C端采样点占比", "广电C端采样点占比", "电联C端采样点占比",
|
|
"移动wifi去重数占比", "联通wifi去重数占比", "电信wifi去重数占比", "广电wifi去重数占比", "其他wifi去重数占比",
|
|
"移动wifi采样点占比", "联通wifi采样点占比", "电信wifi采样点占比", "广电wifi采样点占比", "其他wifi采样点占比",
|
|
]
|
|
TEXT_COLUMNS = ["地市名称", "AOI唯一标签", "AOI名称", GEOMETRY_COLUMN]
|
|
REQUIRED_COLUMNS = ["AOI唯一标签", "AOI名称", GEOMETRY_COLUMN, *REAL_COLUMNS[:5]]
|
|
# 江门一带的局部米制缩放,只用于比较接触面积,不写入坐标。
|
|
_LAT0 = 22.5
|
|
_MX = 111_320 * math.cos(math.radians(_LAT0))
|
|
_MY = 110_540
|
|
|
|
|
|
def csv_encoding(path):
|
|
for encoding in ("utf-8-sig", "gbk"):
|
|
try:
|
|
with Path(path).open(encoding=encoding, newline="") as source:
|
|
source.readline()
|
|
return encoding
|
|
except UnicodeDecodeError:
|
|
continue
|
|
raise ValueError(f"无法识别 AOI 报表编码:{path}")
|
|
|
|
|
|
def _polygonal(geometry):
|
|
if geometry is None or geometry.is_empty:
|
|
return None
|
|
if not geometry.is_valid:
|
|
geometry = make_valid(geometry)
|
|
if geometry.geom_type == "GeometryCollection":
|
|
parts = [part for part in geometry.geoms if part.geom_type in {"Polygon", "MultiPolygon"} and not part.is_empty]
|
|
if not parts:
|
|
return None
|
|
geometry = max(parts, key=lambda part: part.area)
|
|
if isinstance(geometry, Polygon):
|
|
return MultiPolygon([geometry])
|
|
if isinstance(geometry, MultiPolygon):
|
|
return geometry
|
|
return None
|
|
|
|
|
|
def _contact_area(left, right):
|
|
overlap = left.intersection(right)
|
|
if overlap.is_empty:
|
|
return 0.0
|
|
return scale(overlap, xfact=_MX, yfact=_MY, origin=(0, 0)).area
|
|
|
|
|
|
def assign_market(geometry, markets, tree):
|
|
"""接触面积必须大于 0;面积相同取 fid 较小的市场。"""
|
|
best_name = None
|
|
best_area = 0.0
|
|
best_fid = None
|
|
for index in tree.query(geometry, predicate="intersects"):
|
|
market = markets[int(index)]
|
|
area = _contact_area(geometry, market.geometry)
|
|
if area > best_area or (area == best_area and area > 0 and (best_fid is None or market.fid < best_fid)):
|
|
best_name = market.name
|
|
best_area = area
|
|
best_fid = market.fid
|
|
return best_name
|
|
|
|
|
|
def _gpkg_blob(geometry):
|
|
return b"GP" + bytes((0, 1)) + (4326).to_bytes(4, "little") + geometry.wkb
|
|
|
|
|
|
def _srs_rows(market_gpkg):
|
|
fallback = [
|
|
("Undefined Cartesian SRS", -1, "NONE", -1, "undefined", "undefined Cartesian"),
|
|
("Undefined geographic SRS", 0, "NONE", 0, "undefined", "undefined geographic"),
|
|
("WGS 84 geodetic", 4326, "EPSG", 4326,
|
|
'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]]',
|
|
""),
|
|
]
|
|
conn = sqlite3.connect(market_gpkg)
|
|
try:
|
|
names = {row[1] for row in conn.execute("pragma table_info(gpkg_spatial_ref_sys)")}
|
|
if "srs_name" not in names:
|
|
return fallback
|
|
rows = conn.execute(
|
|
"select srs_name, srs_id, organization, organization_coordsys_id, definition, description "
|
|
"from gpkg_spatial_ref_sys where srs_id in (-1, 0, 4326) order by srs_id"
|
|
).fetchall()
|
|
except sqlite3.Error:
|
|
return fallback
|
|
finally:
|
|
conn.close()
|
|
if not any(row[1] == 4326 for row in rows):
|
|
return fallback
|
|
return rows
|
|
|
|
|
|
def _real(value):
|
|
text = "" if value is None else str(value).strip()
|
|
if not text:
|
|
return None
|
|
return float(text)
|
|
|
|
|
|
def build_matched_aoi(csv_path, market_gpkg, output_path):
|
|
"""读取 AOI 报表,写入带所属市场网格的总表。面积为 0 的仅贴边接触不归属。"""
|
|
csv_path, market_gpkg, output_path = Path(csv_path), Path(market_gpkg), Path(output_path)
|
|
encoding = csv_encoding(csv_path)
|
|
with csv_path.open(encoding=encoding, newline="") as source:
|
|
reader = csv.DictReader(source)
|
|
header = reader.fieldnames or []
|
|
missing = [name for name in REQUIRED_COLUMNS if name not in header]
|
|
if missing:
|
|
raise ValueError(f"AOI报表缺少字段:{', '.join(missing)}")
|
|
rows = list(reader)
|
|
|
|
with open_read_connection(market_gpkg) as conn:
|
|
layer = resolve_feature_layer(conn, config.MARKET_LAYER)
|
|
markets = load_market_features(conn, layer, config.MARKET_CODE_FIELD, config.MARKET_NAME_FIELD)
|
|
if not markets:
|
|
raise ValueError("市场网格为空,无法匹配 AOI")
|
|
prepared = []
|
|
for market in markets:
|
|
geometry = _polygonal(market.geometry)
|
|
if geometry is None:
|
|
continue
|
|
prepared.append(type(market)(market.fid, market.code, market.name, geometry))
|
|
if not prepared:
|
|
raise ValueError("市场网格没有可用几何,无法匹配 AOI")
|
|
tree = STRtree([market.geometry for market in prepared])
|
|
|
|
matched = unassigned = invalid = 0
|
|
records = []
|
|
extent = None
|
|
for row in rows:
|
|
config.check_cancelled()
|
|
text = (row.get(GEOMETRY_COLUMN) or "").strip()
|
|
geometry = None
|
|
if text:
|
|
try:
|
|
geometry = _polygonal(wkt.loads(text))
|
|
except Exception:
|
|
geometry = None
|
|
market_name = assign_market(geometry, prepared, tree) if geometry is not None else None
|
|
if geometry is None:
|
|
invalid += 1
|
|
unassigned += 1
|
|
elif market_name:
|
|
matched += 1
|
|
minx, miny, maxx, maxy = geometry.bounds
|
|
if extent is None:
|
|
extent = [minx, miny, maxx, maxy]
|
|
else:
|
|
extent[0] = min(extent[0], minx)
|
|
extent[1] = min(extent[1], miny)
|
|
extent[2] = max(extent[2], maxx)
|
|
extent[3] = max(extent[3], maxy)
|
|
else:
|
|
unassigned += 1
|
|
values = {name: row.get(name, "") for name in TEXT_COLUMNS}
|
|
values[config.AOI_MARKET_FIELD] = market_name
|
|
for name in REAL_COLUMNS:
|
|
values[name] = _real(row.get(name))
|
|
records.append((values, geometry))
|
|
|
|
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
temporary = output_path.with_name(f".{output_path.name}.tmp")
|
|
if temporary.exists():
|
|
temporary.unlink()
|
|
table = config.AOI_LAYER
|
|
quoted = quote_identifier(table)
|
|
columns = ["地市名称", config.AOI_MARKET_FIELD, "AOI唯一标签", "AOI名称", *REAL_COLUMNS, GEOMETRY_COLUMN]
|
|
column_sql = ", ".join(
|
|
f"{quote_identifier(name)} {'REAL' if name in REAL_COLUMNS else 'TEXT'}" for name in columns
|
|
)
|
|
conn = sqlite3.connect(temporary)
|
|
try:
|
|
conn.execute("pragma application_id = 1196444487")
|
|
conn.execute("pragma user_version = 10400")
|
|
conn.execute(
|
|
"create table gpkg_spatial_ref_sys (srs_name text not null, srs_id integer primary key, "
|
|
"organization text not null, organization_coordsys_id integer not null, definition text not null, description text)"
|
|
)
|
|
conn.executemany("insert into gpkg_spatial_ref_sys values (?,?,?,?,?,?)", _srs_rows(market_gpkg))
|
|
conn.execute(
|
|
"create table gpkg_contents (table_name text primary key, data_type text not null, identifier text unique, "
|
|
"description text default '', last_change text default (strftime('%Y-%m-%dT%H:%M:%fZ','now')), "
|
|
"min_x double, min_y double, max_x double, max_y double, srs_id integer)"
|
|
)
|
|
conn.execute(
|
|
"create table gpkg_geometry_columns (table_name text primary key, column_name text not null, "
|
|
"geometry_type_name text not null, srs_id integer not null, z integer not null, m integer not null)"
|
|
)
|
|
conn.execute("create table gpkg_ogr_contents (table_name text primary key, feature_count integer)")
|
|
conn.execute(
|
|
f"create table {quoted} (fid integer primary key autoincrement, geom blob, {column_sql})"
|
|
)
|
|
rtree = f"rtree_{table}_geom"
|
|
conn.execute(f'create virtual table "{rtree}" using rtree(id, minx, maxx, miny, maxy)')
|
|
bounds = extent or [None, None, None, None]
|
|
conn.execute(
|
|
"insert into gpkg_contents (table_name, data_type, identifier, min_x, min_y, max_x, max_y, srs_id) "
|
|
"values (?, 'features', ?, ?, ?, ?, ?, 4326)",
|
|
(table, table, *bounds),
|
|
)
|
|
conn.execute(
|
|
"insert into gpkg_geometry_columns values (?, 'geom', 'MULTIPOLYGON', 4326, 0, 0)",
|
|
(table,),
|
|
)
|
|
conn.execute("insert into gpkg_ogr_contents values (?, ?)", (table, len(records)))
|
|
placeholders = ", ".join(["?"] * (len(columns) + 1))
|
|
insert_sql = f"insert into {quoted} (geom, {', '.join(quote_identifier(name) for name in columns)}) values ({placeholders})"
|
|
for values, geometry in records:
|
|
payload = [_gpkg_blob(geometry) if geometry is not None else None]
|
|
payload.extend(values[name] for name in columns)
|
|
cursor = conn.execute(insert_sql, payload)
|
|
if geometry is not None:
|
|
minx, miny, maxx, maxy = geometry.bounds
|
|
conn.execute(f'insert into "{rtree}" values (?,?,?,?,?)', (cursor.lastrowid, minx, maxx, miny, maxy))
|
|
conn.commit()
|
|
finally:
|
|
conn.close()
|
|
temporary.replace(output_path)
|
|
return {"output": str(output_path), "rows": len(records), "matched": matched, "unassigned": unassigned, "invalid": invalid}
|