Files
MarketGrid/marketgrid/nrdata.py
T

96 lines
6.1 KiB
Python

"""楼宇查询结果清洗、轮廓回填和 GeoPackage 生成。"""
import csv
import sqlite3
from pathlib import Path
from shapely import wkt, to_wkb
DROP_COLUMNS = {"输入行号", "查询状态", "错误信息"}
LAYER_NAME = "NRBuildingsData"
GEOM_COLUMN = "geom"
SRS_ID = 100000
CRS84 = (
"WGS 84 (CRS84)", SRS_ID, "NONE", SRS_ID,
'GEOGCS["WGS 84 (CRS84)",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],'
'PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],'
'AXIS["Longitude",EAST],AXIS["Latitude",NORTH]]',
"",
)
def _encoding(path):
for enc in ("gbk", "utf-8-sig", "utf-8"):
try:
with Path(path).open(encoding=enc, newline="") as f:
next(csv.reader(f))
return enc
except (UnicodeDecodeError, StopIteration):
continue
raise ValueError("无法识别楼宇结果 CSV 编码")
def _gpkg_blob(geometry):
return b"GP" + bytes((0, 1)) + SRS_ID.to_bytes(4, "little") + to_wkb(geometry)
def build_gpkg(data_csv, polygon_csv, output_path):
data_csv, polygon_csv, output_path = map(Path, (data_csv, polygon_csv, output_path))
polygons = {}
with polygon_csv.open(encoding=_encoding(polygon_csv), newline="") as f:
for row in csv.DictReader(f):
try: geometry = wkt.loads(row["WKT"])
except Exception: continue
if not geometry.is_empty and geometry.is_valid:
polygons.setdefault(str(row["building_id"]), geometry)
data_encoding = _encoding(data_csv)
with data_csv.open(encoding=data_encoding, newline="") as f:
reader = csv.DictReader(f)
fields = list(dict.fromkeys(x for x in (reader.fieldnames or []) if x not in DROP_COLUMNS))
if "building_id" not in fields: raise ValueError("楼宇结果 CSV 缺少 building_id 字段")
if "WKT" not in fields:
fields.append("WKT")
rows=[]
for row in reader:
geometry=polygons.get(str(row.get("building_id", "")).strip())
if not geometry or (row.get("查询状态", "").strip() and row.get("查询状态", "").strip() not in {"成功", "命中"}): continue
clean={x:row.get(x, "") for x in fields if x != "WKT"}; clean["WKT"]=geometry.wkt; rows.append((clean,geometry))
# 先原子回写清洗后的 CSV,避免中途失败破坏原文件。
temporary_csv = data_csv.with_name(f".{data_csv.name}.tmp")
with temporary_csv.open("w", encoding=data_encoding, newline="") as f:
writer = csv.DictWriter(f, fieldnames=fields)
writer.writeheader()
writer.writerows(clean for clean, _ in rows)
temporary_csv.replace(data_csv)
output_path.parent.mkdir(parents=True, exist_ok=True)
if output_path.exists(): output_path.unlink()
conn=sqlite3.connect(output_path)
try:
conn.execute("pragma application_id = 1196444487")
conn.execute("pragma user_version = 10400")
conn.executescript("""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); CREATE TABLE gpkg_contents (table_name TEXT PRIMARY KEY, data_type TEXT NOT NULL, identifier TEXT UNIQUE, description TEXT DEFAULT '', last_change DATETIME NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), min_x DOUBLE, min_y DOUBLE, max_x DOUBLE, max_y DOUBLE, srs_id INTEGER); 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 TINYINT NOT NULL, m TINYINT NOT NULL);""")
crs = CRS84
building_info = Path(__file__).resolve().parents[1] / "source" / "BuildingInfo.gpkg"
if building_info.is_file():
with sqlite3.connect(building_info) as source:
crs = source.execute(
"select srs_name, srs_id, organization, organization_coordsys_id, definition, description "
"from gpkg_spatial_ref_sys where srs_id = ?", (SRS_ID,),
).fetchone() or CRS84
conn.executemany("insert into gpkg_spatial_ref_sys values (?,?,?,?,?,?)", [
("Undefined Cartesian SRS", -1, "NONE", -1, "undefined", "undefined Cartesian coordinate reference system"),
("Undefined geographic SRS", 0, "NONE", 0, "undefined", "undefined geographic coordinate reference system"),
crs,
])
esc=lambda x:'"'+x.replace('"','""')+'"'
conn.execute(f'CREATE TABLE {esc(LAYER_NAME)} (fid INTEGER PRIMARY KEY AUTOINCREMENT, '+', '.join(esc(x)+' TEXT' for x in fields)+f', {esc(GEOM_COLUMN)} BLOB NOT NULL)')
conn.execute('CREATE VIRTUAL TABLE rtree_NRBuildingsData_geom USING rtree(id,minx,maxx,miny,maxy)')
conn.execute('CREATE TABLE gpkg_ogr_contents (table_name TEXT PRIMARY KEY, feature_count INTEGER)')
conn.execute('CREATE TABLE gpkg_extensions (table_name TEXT, column_name TEXT, extension_name TEXT NOT NULL, definition TEXT NOT NULL, scope TEXT NOT NULL, CONSTRAINT ge_tce UNIQUE (table_name, column_name, extension_name))')
conn.execute('INSERT INTO gpkg_ogr_contents VALUES (?,?)', (LAYER_NAME, len(rows)))
conn.execute('INSERT INTO gpkg_extensions VALUES (?,?,?,?,?)', (LAYER_NAME, GEOM_COLUMN, 'gpkg_rtree_index', 'http://www.geopackage.org/spec120/#extension_rtree', 'write-only'))
conn.execute('INSERT INTO gpkg_contents(table_name,data_type,identifier,srs_id) VALUES (?,?,?,?)',(LAYER_NAME,'features',LAYER_NAME,SRS_ID))
conn.execute('INSERT INTO gpkg_geometry_columns VALUES (?,?,?,?,?,?)',(LAYER_NAME,GEOM_COLUMN,'MULTIPOLYGON',SRS_ID,0,0))
cols=','.join(esc(x) for x in fields)
for clean,geometry in rows:
vals=[clean[x] for x in fields]+[_gpkg_blob(geometry)]; cur=conn.execute(f'INSERT INTO {esc(LAYER_NAME)} ({cols},{esc(GEOM_COLUMN)}) VALUES ({",".join("?" for _ in vals)})',vals); fid=cur.lastrowid; x1,y1,x2,y2=geometry.bounds; conn.execute('INSERT INTO rtree_NRBuildingsData_geom VALUES (?,?,?,?,?)',(fid,x1,x2,y1,y2))
conn.commit()
finally: conn.close()
return {"output":str(output_path),"feature_count":len(rows)}