Files
MarketGrid/marketgrid/sample_grid.py
T

254 lines
11 KiB
Python

"""把同一位置的 4G、5G 栅格合并成采样点图层。"""
from collections import defaultdict
from datetime import datetime, timezone
from pathlib import Path
import math
import sqlite3
from shapely import Point
import shapely
from . import config
from .gpkg import iter_geometry_batches, quote_identifier, require_columns
from .raster_math import to_float
TABLE = "采样点图层"
GEOM = "geom"
SRS_ID = 4326
FIELDS = ("电联采样点", "广电采样点", "移动采样点", "总采样点数", "rank")
OPACITY_MIN = 10.0
OPACITY_MAX = 70.0
STYLES = Path(__file__).with_name("styles")
WGS84 = (
'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,'
'AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,'
'AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],'
'AXIS["Latitude",NORTH],AXIS["Longitude",EAST],AUTHORITY["EPSG","4326"]]'
)
def export_sample_grid(grid_5g_conn, grid_5g_layer, grid_5g_rtree, grid_4g_conn, grid_4g_layer, grid_4g_rtree, market, output_path):
five = _collect(grid_5g_conn, grid_5g_layer, grid_5g_rtree, market)
four = _collect(grid_4g_conn, grid_4g_layer, grid_4g_rtree, market)
lat0 = (market.geometry.bounds[1] + market.geometry.bounds[3]) / 2
merged = merge_sample_records(five, four, lat0, config.SAMPLE_MATCH_METERS)
opacity = opacity_by_total(record["total"] for record in merged)
for record in merged:
record["opacity"] = opacity[record["total"]]
_write(output_path, merged, market.geometry.bounds)
return {
"market_code": market.code,
"market_name": market.name,
"layer_name": config.SAMPLE_LAYER_NAME,
"filename": Path(output_path).name,
"output": str(output_path),
"extent": list(_extent(merged, market.geometry.bounds)),
"feature_count": len(merged),
"source_5g_count": len(five),
"source_4g_count": len(four),
"match_meters": config.SAMPLE_MATCH_METERS,
"skipped": False,
}
def opacity_by_total(totals):
"""总采样点数的名次映射到 10–70。越多越高,最多为 70;相同数量同一档。"""
levels = sorted(set(totals))
if not levels:
return {}
if len(levels) == 1:
return {levels[0]: OPACITY_MAX}
span = len(levels) - 1
return {
value: OPACITY_MIN + index / span * (OPACITY_MAX - OPACITY_MIN)
for index, value in enumerate(levels)
}
def merge_sample_records(five, four, latitude, meters):
"""中心相距不超过 meters 的 4G、5G 栅格合成一条,图形保留 5G。"""
scale_x = 111_320 * math.cos(math.radians(latitude))
scale_y = 110_540
bins = defaultdict(list)
located = []
for record in five:
x, y = record["lon"] * scale_x, record["lat"] * scale_y
located.append((x, y))
bins[_bin(x, y, meters)].append(len(located) - 1)
totals = [[record["dl"], record["gd"], record["yd"]] for record in five]
used = [False] * len(four)
for index, record in enumerate(four):
x, y = record["lon"] * scale_x, record["lat"] * scale_y
ix, iy = _bin(x, y, meters)
nearest = None
nearest_distance = None
for nx in (ix - 1, ix, ix + 1):
for ny in (iy - 1, iy, iy + 1):
for candidate in bins.get((nx, ny), ()):
ox, oy = located[candidate]
distance = math.hypot(x - ox, y - oy)
if distance <= meters and (nearest_distance is None or distance < nearest_distance):
nearest, nearest_distance = candidate, distance
if nearest is None:
continue
used[index] = True
totals[nearest][0] += record["dl"]
totals[nearest][1] += record["gd"]
totals[nearest][2] += record["yd"]
merged = []
for index, record in enumerate(five):
dl, gd, yd = totals[index]
merged.append({**record, "dl": dl, "gd": gd, "yd": yd, "total": dl + gd + yd})
for index, record in enumerate(four):
if used[index]:
continue
merged.append({**record, "total": record["dl"] + record["gd"] + record["yd"]})
return merged
def _bin(x, y, meters):
return math.floor(x / meters), math.floor(y / meters)
def _collect(conn, layer, rtree, market):
value_fields = config.SAMPLE_VALUE_FIELDS
columns = ["longitude", "latitude", *value_fields]
require_columns(conn, layer.table_name, columns)
table = quote_identifier(layer.table_name)
pk = quote_identifier(layer.pk_col)
geom = quote_identifier(layer.geom_col)
selected = [geom, *(quote_identifier(name) for name in columns)]
# 栅格是轴对齐矩形,空间索引的外接框就是图形范围,不必把每个图形拆成 Shapely 再写回。
query = f"""
select b.{pk}, {", ".join(f"b.{name}" for name in selected)},
r."minx", r."maxx", r."miny", r."maxy"
from {quote_identifier(rtree)} r
join {table} b on b.{pk} = r."id"
where r."minx" <= ? and r."maxx" >= ? and r."miny" <= ? and r."maxy" >= ?
"""
minx, miny, maxx, maxy = market.geometry.bounds
rows = []
shapely.prepare(market.geometry)
try:
cursor = conn.execute(query, (maxx, minx, maxy, miny))
for batch, geometries, valid in iter_geometry_batches(cursor, 1):
hits = valid & shapely.intersects(market.geometry, geometries)
for index, row in enumerate(batch):
if not hits[index] or row[1] is None:
continue
bounds = (row[7], row[9], row[8], row[10])
lon, lat = to_float(row[2]), to_float(row[3])
# 属性里的中心点若落在格子外面,改用外接框中心,避免空值或 0 把不相邻的栅格拼到一起。
if lon is None or lat is None or not (bounds[0] <= lon <= bounds[2] and bounds[1] <= lat <= bounds[3]):
lon = (bounds[0] + bounds[2]) / 2
lat = (bounds[1] + bounds[3]) / 2
if config.CLIP_MODE == "center" and not market.geometry.covers(Point(lon, lat)):
continue
values = [to_float(row[offset]) or 0.0 for offset in range(4, 7)]
rows.append({
"lon": lon, "lat": lat, "dl": values[0], "gd": values[1], "yd": values[2],
"blob": row[1], "bounds": bounds,
})
finally:
shapely.destroy_prepared(market.geometry)
return rows
def _extent(records, fallback):
if not records:
return fallback
minx = min(item["bounds"][0] for item in records)
miny = min(item["bounds"][1] for item in records)
maxx = max(item["bounds"][2] for item in records)
maxy = max(item["bounds"][3] for item in records)
return minx, miny, maxx, maxy
def _write(output_path, records, fallback_extent):
output_path = Path(output_path)
output_path.parent.mkdir(parents=True, exist_ok=True)
if output_path.exists():
output_path.unlink()
minx, miny, maxx, maxy = _extent(records, fallback_extent)
qml = (STYLES / "sample_points.qml").read_text(encoding="utf-8")
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 NOT NULL 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 NOT NULL 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 NOT NULL, column_name TEXT NOT NULL, geometry_type_name TEXT NOT NULL,
srs_id INTEGER NOT NULL, z TINYINT NOT NULL, m TINYINT NOT NULL,
CONSTRAINT pk_geom_cols PRIMARY KEY (table_name, column_name));
CREATE TABLE gpkg_ogr_contents (table_name TEXT NOT NULL PRIMARY KEY, feature_count INTEGER);
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));
CREATE TABLE layer_styles (
id INTEGER PRIMARY KEY, f_table_catalog TEXT, f_table_schema TEXT,
f_table_name TEXT, f_geometry_column TEXT, styleName TEXT, styleQML TEXT,
styleSLD TEXT, useAsDefault BOOLEAN, description TEXT, owner TEXT, ui TEXT,
update_time DATETIME);
"""
)
quoted_fields = ", ".join(f'"{name}" REAL' for name in FIELDS)
conn.execute(f'CREATE TABLE "{TABLE}" (fid INTEGER PRIMARY KEY, "{GEOM}" POLYGON, {quoted_fields})')
conn.execute(f'CREATE VIRTUAL TABLE "rtree_{TABLE}_{GEOM}" USING rtree(id, minx, maxx, miny, maxy)')
now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%fZ")
conn.executemany(
"INSERT INTO gpkg_spatial_ref_sys VALUES (?,?,?,?,?,?)",
[
("Undefined Cartesian", -1, "NONE", -1, "undefined", "undefined cartesian"),
("Undefined geographic", 0, "NONE", 0, "undefined", "undefined geographic"),
("WGS 84", SRS_ID, "EPSG", SRS_ID, WGS84, "WGS 84"),
],
)
conn.execute(
"INSERT INTO gpkg_contents VALUES (?,?,?,?,?,?,?,?,?,?)",
(TABLE, "features", TABLE, "", now, minx, miny, maxx, maxy, SRS_ID),
)
conn.execute(
"INSERT INTO gpkg_geometry_columns VALUES (?,?,?,?,?,?)",
(TABLE, GEOM, "POLYGON", SRS_ID, 0, 0),
)
conn.execute("INSERT INTO gpkg_ogr_contents VALUES (?,?)", (TABLE, len(records)))
conn.execute(
"INSERT INTO gpkg_extensions VALUES (?,?,?,?,?)",
(TABLE, GEOM, "gpkg_rtree_index", "http://www.geopackage.org/spec120/#extension_rtree", "read-write"),
)
conn.execute(
"INSERT INTO layer_styles (f_table_catalog,f_table_schema,f_table_name,f_geometry_column,"
"styleName,styleQML,styleSLD,useAsDefault,description,owner,ui,update_time) "
"VALUES ('','',?,?,?,?,?,1,'','',NULL,?)",
(TABLE, GEOM, "Default", qml, "", now),
)
columns = ", ".join(f'"{name}"' for name in FIELDS)
placeholders = ", ".join(["?"] * (2 + len(FIELDS)))
for index, record in enumerate(records, start=1):
conn.execute(
f'INSERT INTO "{TABLE}" (fid, "{GEOM}", {columns}) VALUES ({placeholders})',
(
index, record["blob"], record["dl"], record["gd"], record["yd"],
record["total"], record["opacity"],
),
)
minx, miny, maxx, maxy = record["bounds"]
conn.execute(
f'INSERT INTO "rtree_{TABLE}_{GEOM}" VALUES (?,?,?,?,?)',
(index, minx, maxx, miny, maxy),
)
conn.commit()
finally:
conn.close()