feat: 楼宇查询改为按轮廓 WKT 计算内部点查询
This commit is contained in:
+54
-23
@@ -1,9 +1,11 @@
|
||||
"""异步批量查询楼宇 WFS,由独占写入线程实时保存 CSV。独立运行。"""
|
||||
"""异步批量查询楼宇 WFS,由独占写入线程实时保存 CSV。独立运行。
|
||||
|
||||
输入为楼宇轮廓 WKT;每个楼宇先计算一个保证落在轮廓内部的查询点,再按点查询。
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import csv
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from itertools import islice
|
||||
import json
|
||||
from pathlib import Path
|
||||
@@ -13,6 +15,9 @@ from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit, quote
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
import aiohttp
|
||||
from shapely import make_valid, wkt as shapely_wkt
|
||||
from shapely.errors import ShapelyError
|
||||
from shapely.ops import polylabel
|
||||
|
||||
|
||||
# 填完整 WFS URL(包含 ak、sig 等参数);原 CQL_FILTER 会自动替换。
|
||||
@@ -21,13 +26,12 @@ URL = "https://nqi.gmcc.net:20443/pro-gis-tenant/gmcc-wyzc/prod-api/api/HRvjYUm1
|
||||
# 填完整 Cookie 头内容,例如 CASTGC=...;不要加 Cookie: 前缀。
|
||||
COOKIES = "CASTGC=TGT-1071858-toWWSoGzu8ASDB-dF69kh7rTnxZHt1nWd45MsLeTt0lHrzWC8n8Hwz3BjZjGRcIxbRkmas-auth-center-7d87cd5c9d-xd94d"
|
||||
REFERER = "https://nqi.gmcc.net:20443/pro-problem-warehouse-web/"
|
||||
INPUT_CSV = Path(__file__).resolve().parent / "source" / "NRBuildingsPoint.csv"
|
||||
INPUT_CSV = Path(__file__).resolve().parent / "source" / "NRBuildPolygon.csv"
|
||||
OUTPUT_CSV = Path(__file__).resolve().parent / "output" / "NRBuildingsData.csv"
|
||||
INPUT_ENCODING = "gb18030" # 当前源文件为 GBK;UTF-8 文件可改为 utf-8-sig。
|
||||
INPUT_ENCODING = "utf-8-sig" # 当前源文件为 UTF-8 BOM;GBK 文件可改为 gb18030。
|
||||
OUTPUT_ENCODING = "gbk" # 供 Excel/传统工具直接打开;无法编码的字符用 errors=replace。
|
||||
ID_COLUMN = "序号"
|
||||
LONGITUDE_COLUMN = "经度"
|
||||
LATITUDE_COLUMN = "维度" # 源文件实际写的是“维度”。
|
||||
ID_COLUMN = "building_id"
|
||||
WKT_COLUMN = "WKT" # 楼宇轮廓,MULTIPOLYGON/POLYGON WKT,经纬度 EPSG:4326。
|
||||
GEOMETRY_FIELD = "the_geom"
|
||||
START_ROW = 1 # 从第几条数据开始,不计表头。
|
||||
LIMIT = 1000 # 最多查询的坐标数;None 表示处理剩余全部。
|
||||
@@ -36,7 +40,7 @@ TIMEOUT = 30 # 每次请求超时秒数。
|
||||
MAX_RETRIES = 2 # 网络异常、429 或 5xx 的重试次数;空结果不重试。
|
||||
REQUEST_INTERVAL = 0.2 # 每个查询协程两次请求之间的等待秒数。
|
||||
PROGRESS_EVERY = 100
|
||||
QUERY_COLUMNS = ["查询序号", "查询经度", "查询纬度", "查询状态", "命中数量", "要素ID", "错误信息"]
|
||||
QUERY_COLUMNS = ["输入行号", "查询序号", "查询经度", "查询纬度", "查询状态", "命中数量", "要素ID", "错误信息"]
|
||||
|
||||
|
||||
class QueryError(Exception):
|
||||
@@ -47,14 +51,39 @@ class AuthenticationError(QueryError):
|
||||
pass
|
||||
|
||||
|
||||
def coordinate(value, lower, upper):
|
||||
def interior_point(text):
|
||||
"""返回一定位于轮廓内部的 (经度, 纬度) 字符串。
|
||||
|
||||
不使用外包框中心或质心:凹形、L 形楼宇的这两个点都可能落在轮廓外。
|
||||
主方案是 polylabel(离边界最远的内部点,天然在图形内且远离边缘);
|
||||
多部件时取面积最大的部件。计算结果再用 within 校验,不通过时回退到
|
||||
GEOS 的 representative_point,它同样保证在几何内部。
|
||||
"""
|
||||
try:
|
||||
number = Decimal(str(value).strip())
|
||||
except InvalidOperation:
|
||||
raise ValueError("经纬度不是有效数字") from None
|
||||
if not number.is_finite() or not lower <= number <= upper:
|
||||
geometry = shapely_wkt.loads(str(text or "").strip())
|
||||
except (ShapelyError, ValueError, TypeError):
|
||||
raise ValueError("WKT 无法解析") from None
|
||||
if geometry.is_empty or geometry.geom_type not in ("Polygon", "MultiPolygon"):
|
||||
raise ValueError("WKT 不是多边形或为空")
|
||||
if not geometry.is_valid:
|
||||
geometry = make_valid(geometry)
|
||||
parts = [part for part in getattr(geometry, "geoms", [geometry]) if part.geom_type == "Polygon" and part.area > 0]
|
||||
if not parts:
|
||||
raise ValueError("轮廓没有有效面积")
|
||||
largest = max(parts, key=lambda part: part.area)
|
||||
x1, y1, x2, y2 = largest.bounds
|
||||
point = None
|
||||
try:
|
||||
point = polylabel(largest, tolerance=max(max(x2 - x1, y2 - y1) / 100, 1e-9))
|
||||
except (ShapelyError, ValueError):
|
||||
point = None
|
||||
if point is None or not point.within(geometry):
|
||||
point = largest.representative_point()
|
||||
if not point.within(geometry):
|
||||
raise ValueError("无法计算轮廓内部点")
|
||||
if not (-180 <= point.x <= 180 and -90 <= point.y <= 90):
|
||||
raise ValueError("经纬度超出有效范围")
|
||||
return format(number, "f")
|
||||
return f"{point.x:.8f}", f"{point.y:.8f}"
|
||||
|
||||
|
||||
def query_url(longitude, latitude):
|
||||
@@ -201,15 +230,16 @@ async def async_main(*, handle_signals=True, should_stop=None, progress=None):
|
||||
request_stop()
|
||||
break
|
||||
# 同一事件循环中读取下一行,无 await,不会并发推进 CSV 迭代器。
|
||||
point = next(selected, None)
|
||||
if point is None:
|
||||
item = next(selected, None)
|
||||
if item is None:
|
||||
break
|
||||
metadata = {"查询序号": point.get(ID_COLUMN), "查询经度": point.get(LONGITUDE_COLUMN),
|
||||
"查询纬度": point.get(LATITUDE_COLUMN), "命中数量": 0, "要素ID": "", "错误信息": ""}
|
||||
row_number, building = item
|
||||
metadata = {"输入行号": row_number, "查询序号": building.get(ID_COLUMN), "查询经度": "",
|
||||
"查询纬度": "", "命中数量": 0, "要素ID": "", "错误信息": ""}
|
||||
features = []
|
||||
try:
|
||||
lon = coordinate(point.get(LONGITUDE_COLUMN), -180, 180)
|
||||
lat = coordinate(point.get(LATITUDE_COLUMN), -90, 90)
|
||||
lon, lat = interior_point(building.get(WKT_COLUMN))
|
||||
metadata.update(查询经度=lon, 查询纬度=lat)
|
||||
features = await fetch_features(session, lon, lat)
|
||||
if any(set(feature["properties"]) & set(QUERY_COLUMNS) for feature in features):
|
||||
raise QueryError("properties 字段与查询信息列重名")
|
||||
@@ -217,7 +247,7 @@ async def async_main(*, handle_signals=True, should_stop=None, progress=None):
|
||||
metadata["命中数量"] = len(features)
|
||||
except ValueError as exc:
|
||||
features = []
|
||||
metadata.update(查询状态="坐标无效", 错误信息=str(exc))
|
||||
metadata.update(查询状态="轮廓无效", 错误信息=str(exc))
|
||||
except QueryError as exc:
|
||||
features = []
|
||||
metadata.update(查询状态="请求失败", 错误信息=str(exc))
|
||||
@@ -253,10 +283,11 @@ async def async_main(*, handle_signals=True, should_stop=None, progress=None):
|
||||
|
||||
with input_path.open("r", encoding=INPUT_ENCODING, newline="") as source:
|
||||
reader = csv.DictReader(source)
|
||||
required = {ID_COLUMN, LONGITUDE_COLUMN, LATITUDE_COLUMN}
|
||||
required = {ID_COLUMN, WKT_COLUMN}
|
||||
if not required.issubset(reader.fieldnames or []):
|
||||
raise ValueError(f"输入 CSV 必须包含列:{', '.join(sorted(required))}")
|
||||
selected = islice(reader, START_ROW - 1, None if LIMIT is None else START_ROW - 1 + LIMIT)
|
||||
# 输入行号从 1 计(不含表头),便于按行号断点重跑和区分重复 building_id。
|
||||
selected = islice(enumerate(reader, 1), START_ROW - 1, None if LIMIT is None else START_ROW - 1 + LIMIT)
|
||||
old_signal_handler = None
|
||||
if handle_signals:
|
||||
old_signal_handler = signal.signal(signal.SIGINT, lambda *_: loop.call_soon_threadsafe(request_stop))
|
||||
|
||||
Reference in New Issue
Block a user