feat: 合并 4G 和 5G 为采样点图层
同一市场内中心相距 8 米以内的栅格合成一条,三个采样字段分别相加, 图层放在竞对信号上面。
This commit is contained in:
@@ -5,8 +5,11 @@ DEFAULT_SOURCE_DIR = Path("source") # 源数据目录,存放 GridMap.gpkg、G
|
||||
OUTPUT_DIR = Path("output") # 输出根目录,每个市场网格会在这里生成一个 JMXXXX.zip 结果包。
|
||||
MARKET_GPKG = DEFAULT_SOURCE_DIR / "GridMap.gpkg" # 市场网格 GeoPackage 文件路径。
|
||||
GRID_5G_GPKG = DEFAULT_SOURCE_DIR / "Grid_5G.gpkg" # 5G Grid;竞对信号仅使用该文件。
|
||||
# 界面已可选。当前出图仍不打开该文件,留给后续 4G+5G 采样点统计。
|
||||
GRID_4G_GPKG = DEFAULT_SOURCE_DIR / "Grid_4G.gpkg" # 4G Grid。
|
||||
GRID_4G_GPKG = DEFAULT_SOURCE_DIR / "Grid_4G.gpkg" # 4G Grid;与 5G 合并为采样点图层。
|
||||
SAMPLE_LAYER_NAME = "采样点图层"
|
||||
SAMPLE_LAYER_FILENAME = "采样点图层.gpkg"
|
||||
SAMPLE_MATCH_METERS = 8.0 # 栅格中心相距不超过该距离时视为同一个栅格。
|
||||
SAMPLE_VALUE_FIELDS = ("mro_total_dl", "mro_total_gd", "mro_total_yd")
|
||||
# 用户量图层停用;以下原代码以注释保留,便于按需恢复。
|
||||
BUILDING_INFO_GPKG = DEFAULT_SOURCE_DIR / "BuildingInfo.gpkg" # 建筑信息 GeoPackage 文件路径,用于结果包 BuildingInfo 分割和楼宇指标 CSV 名称匹配。
|
||||
NR_BUILDINGS_DATA_GPKG = DEFAULT_SOURCE_DIR / "NRBuildingsData.gpkg" # 清洗后的楼宇边界数据。
|
||||
|
||||
+24
-1
@@ -17,6 +17,7 @@ from .competitor import export_market_grid_outputs
|
||||
from .gpkg import gpkg_layer_extent
|
||||
from .market_boundary import boundary_filename
|
||||
from .market_boundary import export_market_boundary_gpkg
|
||||
from .sample_grid import export_sample_grid
|
||||
from .files import market_zip_output_path
|
||||
from .gpkg import open_read_connection
|
||||
from .files import remove_file_with_retry
|
||||
@@ -50,15 +51,18 @@ def process_market(market, pixel_width, pixel_height, output_dir):
|
||||
|
||||
with (
|
||||
open_read_connection(config.GRID_5G_GPKG) as grid_5g_conn,
|
||||
open_read_connection(config.GRID_4G_GPKG) as grid_4g_conn,
|
||||
# open_read_connection(GRID_4G_GPKG) as grid_4g_conn,
|
||||
open_read_connection(config.BUILDING_INFO_GPKG) as building_info_conn,
|
||||
open_read_connection(config.NR_BUILDINGS_DATA_GPKG) as nr_buildings_conn,
|
||||
open_read_connection(config.AOI_GPKG) as aoi_conn,
|
||||
):
|
||||
grid_5g_layer = resolve_feature_layer(grid_5g_conn, config.GRID_5G_LAYER)
|
||||
grid_4g_layer = resolve_feature_layer(grid_4g_conn)
|
||||
# grid_4g_layer = resolve_feature_layer(grid_4g_conn, GRID_4G_LAYER)
|
||||
building_info_layer = resolve_feature_layer(building_info_conn, config.BUILDING_INFO_LAYER)
|
||||
grid_5g_rtree = rtree_name(grid_5g_conn, grid_5g_layer)
|
||||
grid_4g_rtree = rtree_name(grid_4g_conn, grid_4g_layer)
|
||||
# grid_4g_rtree = rtree_name(grid_4g_conn, grid_4g_layer)
|
||||
building_info_rtree = rtree_name(building_info_conn, building_info_layer)
|
||||
nr_buildings_layer = resolve_feature_layer(nr_buildings_conn)
|
||||
@@ -89,6 +93,11 @@ def process_market(market, pixel_width, pixel_height, output_dir):
|
||||
None,
|
||||
# (grid_4g_conn, grid_4g_layer, grid_4g_rtree),
|
||||
)
|
||||
sample_result = export_sample_grid(
|
||||
grid_5g_conn, grid_5g_layer, grid_5g_rtree,
|
||||
grid_4g_conn, grid_4g_layer, grid_4g_rtree,
|
||||
market, market_dir / config.SAMPLE_LAYER_FILENAME,
|
||||
)
|
||||
grid_elapsed = perf_counter() - grid_started_at
|
||||
|
||||
building_info_path = market_dir / config.BUILDING_INFO_OUTPUT_FILENAME
|
||||
@@ -128,6 +137,7 @@ def process_market(market, pixel_width, pixel_height, output_dir):
|
||||
aoi_result=aoi_result,
|
||||
building_themes_result=nr_buildings_result,
|
||||
boundary_result=boundary_result,
|
||||
sample_result=sample_result,
|
||||
)
|
||||
building_elapsed = perf_counter() - building_started_at
|
||||
|
||||
@@ -151,6 +161,7 @@ def process_market(market, pixel_width, pixel_height, output_dir):
|
||||
"result_xlsx": rewrite_result_for_zip(result_xlsx, zip_path, market_dir),
|
||||
"aoi_result": rewrite_result_for_zip(aoi_result, zip_path, market_dir),
|
||||
"boundary_result": rewrite_result_for_zip(boundary_result, zip_path, market_dir),
|
||||
"sample_result": rewrite_result_for_zip(sample_result, zip_path, market_dir),
|
||||
"gis_project_result": rewrite_result_for_zip(gis_project_result, zip_path, market_dir),
|
||||
"zip_result": zip_result,
|
||||
"timings": {
|
||||
@@ -181,9 +192,14 @@ def process_summary_grid_outputs(markets, pixel_width, pixel_height, output_dir)
|
||||
"elapsed_seconds": perf_counter() - started_at,
|
||||
}
|
||||
|
||||
with open_read_connection(config.GRID_5G_GPKG) as grid_5g_conn:
|
||||
with (
|
||||
open_read_connection(config.GRID_5G_GPKG) as grid_5g_conn,
|
||||
open_read_connection(config.GRID_4G_GPKG) as grid_4g_conn,
|
||||
):
|
||||
grid_5g_layer = resolve_feature_layer(grid_5g_conn, config.GRID_5G_LAYER)
|
||||
grid_4g_layer = resolve_feature_layer(grid_4g_conn)
|
||||
grid_5g_rtree = rtree_name(grid_5g_conn, grid_5g_layer)
|
||||
grid_4g_rtree = rtree_name(grid_4g_conn, grid_4g_layer)
|
||||
with tempfile.TemporaryDirectory(prefix="market_grid_summary_") as temp_dir:
|
||||
summary_dir = Path(temp_dir)
|
||||
competitor_signal_path = summary_dir / competitor_signal_raster_filename()
|
||||
@@ -201,6 +217,11 @@ def process_summary_grid_outputs(markets, pixel_width, pixel_height, output_dir)
|
||||
None,
|
||||
max_raster_pixels=config.SUMMARY_MAX_RASTER_PIXELS,
|
||||
)
|
||||
sample_result = export_sample_grid(
|
||||
grid_5g_conn, grid_5g_layer, grid_5g_rtree,
|
||||
grid_4g_conn, grid_4g_layer, grid_4g_rtree,
|
||||
summary_market, summary_dir / config.SAMPLE_LAYER_FILENAME,
|
||||
)
|
||||
building_info_path = summary_dir / config.BUILDING_INFO_OUTPUT_FILENAME
|
||||
shutil.copy2(config.BUILDING_INFO_GPKG, building_info_path)
|
||||
with open_read_connection(config.BUILDING_INFO_GPKG) as building_info_conn:
|
||||
@@ -257,6 +278,7 @@ def process_summary_grid_outputs(markets, pixel_width, pixel_height, output_dir)
|
||||
building_themes_result=nr_buildings_result,
|
||||
include_online=False,
|
||||
boundary_result=boundary_result,
|
||||
sample_result=sample_result,
|
||||
)
|
||||
zip_result = write_market_zip(summary_dir, zip_path, summary_market)
|
||||
legacy_zip_path = output_dir / config.LEGACY_SUMMARY_OUTPUT_FILENAME
|
||||
@@ -274,6 +296,7 @@ def process_summary_grid_outputs(markets, pixel_width, pixel_height, output_dir)
|
||||
"result_xlsx": rewrite_result_for_zip(result_xlsx, zip_path, summary_dir),
|
||||
"aoi_result": rewrite_result_for_zip(aoi_result, zip_path, summary_dir),
|
||||
"boundary_result": rewrite_result_for_zip(boundary_result, zip_path, summary_dir),
|
||||
"sample_result": rewrite_result_for_zip(sample_result, zip_path, summary_dir),
|
||||
"gis_project_result": rewrite_result_for_zip(gis_project_result, zip_path, summary_dir),
|
||||
"zip_result": zip_result,
|
||||
"elapsed_seconds": perf_counter() - started_at,
|
||||
|
||||
@@ -178,6 +178,98 @@ def add_market_boundary_layer(root, boundary_result):
|
||||
_insert_after(legend, existing, legend_layer)
|
||||
|
||||
|
||||
def add_sample_layer(root, sample_result):
|
||||
"""把采样点图层插到竞对信号上面,默认勾选。"""
|
||||
from .sample_grid import TABLE
|
||||
layer_id = "sample_points_4g5g"
|
||||
layer_name = sample_result["layer_name"]
|
||||
datasource = f"./{sample_result['filename']}|layername={TABLE}"
|
||||
remove_qgis_layer(root, sample_result["filename"], required=False)
|
||||
template = next(
|
||||
(
|
||||
layer
|
||||
for layer in root.findall(".//projectlayers/maplayer")
|
||||
if Path((layer.findtext("datasource") or "").replace("\\", "/").split("|", 1)[0]).name
|
||||
== config.BUILDING_INFO_OUTPUT_FILENAME
|
||||
),
|
||||
None,
|
||||
)
|
||||
if template is None:
|
||||
raise ValueError(f"QGIS 项目模板缺少 {config.BUILDING_INFO_OUTPUT_FILENAME} 图层")
|
||||
style = ET.parse(Path(__file__).with_name("styles") / "sample_points.qml").getroot()
|
||||
layer = copy.deepcopy(template)
|
||||
layer.set("labelsEnabled", "0")
|
||||
layer.set("wkbType", "Polygon")
|
||||
layer.find("id").text = layer_id
|
||||
layer.find("datasource").text = datasource
|
||||
layer.find("layername").text = layer_name
|
||||
renderer = layer.find("renderer-v2")
|
||||
replacement = style.find("renderer-v2")
|
||||
if renderer is None or replacement is None:
|
||||
raise ValueError("采样点样式缺少渲染器")
|
||||
index = list(layer).index(renderer)
|
||||
layer.remove(renderer)
|
||||
layer.insert(index, copy.deepcopy(replacement))
|
||||
for tag in (
|
||||
"fieldConfiguration", "aliases", "defaults", "constraints", "constraintExpressions",
|
||||
"expressionfields", "attributetableconfig", "conditionalstyles", "editable",
|
||||
"labelOnTop", "reuseLastValuePolicy",
|
||||
):
|
||||
for child in list(layer.findall(tag)):
|
||||
layer.remove(child)
|
||||
extent = tuple(sample_result["extent"])
|
||||
for tag in ("extent", "wgs84extent"):
|
||||
element = layer.find(tag)
|
||||
if element is None:
|
||||
element = ET.SubElement(layer, tag)
|
||||
set_xml_extent(element, extent)
|
||||
root.find("projectlayers").append(layer)
|
||||
|
||||
tree = root.find("layer-tree-group")
|
||||
signal_name = Path(config.COMPETITOR_SIGNAL_OUTPUT_FILENAME).stem
|
||||
signal_node = next((item for item in tree.findall("layer-tree-layer") if item.get("name") == signal_name), None)
|
||||
if signal_node is None:
|
||||
raise ValueError(f"QGIS 项目模板缺少 {signal_name} 图层")
|
||||
node = ET.Element("layer-tree-layer", {
|
||||
"id": layer_id, "name": layer_name, "source": datasource, "providerKey": "ogr",
|
||||
"checked": "Qt::Checked", "expanded": "0",
|
||||
})
|
||||
tree.insert(list(tree).index(signal_node), node)
|
||||
signal_id = signal_node.get("id")
|
||||
order = tree.find("custom-order")
|
||||
if order is not None:
|
||||
existing = next((child for child in order if (child.text or "").strip() == signal_id), None)
|
||||
item = ET.Element("item")
|
||||
item.text = layer_id
|
||||
if existing is None:
|
||||
order.insert(0, item)
|
||||
else:
|
||||
order.insert(list(order).index(existing), item)
|
||||
layerorder = root.find("layerorder")
|
||||
if layerorder is not None:
|
||||
existing = next((child for child in layerorder if child.get("id") == signal_id), None)
|
||||
new_item = ET.Element("layer", id=layer_id)
|
||||
if existing is None:
|
||||
layerorder.insert(0, new_item)
|
||||
else:
|
||||
layerorder.insert(list(layerorder).index(existing), new_item)
|
||||
legend = root.find("legend")
|
||||
if legend is not None:
|
||||
existing = next(
|
||||
(child for child in legend if child.tag == "legendlayer" and child.get("name") == signal_name),
|
||||
None,
|
||||
)
|
||||
legend_layer = ET.Element("legendlayer", {
|
||||
"name": layer_name, "checked": "Qt::Checked", "open": "false", "drawingOrder": "-1",
|
||||
})
|
||||
group = ET.SubElement(legend_layer, "filegroup", hidden="false", open="false")
|
||||
ET.SubElement(group, "legendlayerfile", layerid=layer_id, visible="1", isInOverview="0")
|
||||
if existing is None:
|
||||
legend.insert(0, legend_layer)
|
||||
else:
|
||||
legend.insert(list(legend).index(existing), legend_layer)
|
||||
|
||||
|
||||
def add_market_aoi_layer(root, aoi_result, fallback_extent):
|
||||
from .aoi_theme import aoi_layer_template
|
||||
template = aoi_layer_template()
|
||||
@@ -348,6 +440,7 @@ def copy_gis_project_to_market(
|
||||
building_themes_result=None,
|
||||
include_online=True,
|
||||
boundary_result=None,
|
||||
sample_result=None,
|
||||
):
|
||||
if output_path.exists() and not config.OVERWRITE:
|
||||
return {
|
||||
@@ -392,6 +485,8 @@ def copy_gis_project_to_market(
|
||||
add_online_basemap(root, market.name)
|
||||
if boundary_result is not None:
|
||||
add_market_boundary_layer(root, boundary_result)
|
||||
if sample_result is not None:
|
||||
add_sample_layer(root, sample_result)
|
||||
canvas = root.find(".//mapcanvas[@name='theMapCanvas']")
|
||||
if canvas is None:
|
||||
raise ValueError("QGIS 项目模板缺少主画布 theMapCanvas")
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
"""把同一位置的 4G、5G 栅格合并成采样点图层。"""
|
||||
from collections import defaultdict
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
import math
|
||||
import sqlite3
|
||||
|
||||
from shapely import Point, centroid, to_wkb
|
||||
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 = ("mro_total_dl", "mro_total_gd", "mro_total_yd", "总采样点数")
|
||||
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)
|
||||
_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 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 _meters(lon1, lat1, lon2, lat2):
|
||||
scale_x = 111_320 * math.cos(math.radians((lat1 + lat2) / 2))
|
||||
return math.hypot((lon1 - lon2) * scale_x, (lat1 - lat2) * 110_540)
|
||||
|
||||
|
||||
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)]
|
||||
query = f"""
|
||||
select b.{pk}, {", ".join(f"b.{name}" for name in selected)}
|
||||
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)
|
||||
centers = centroid(geometries)
|
||||
for index, row in enumerate(batch):
|
||||
if not valid[index] or not hits[index]:
|
||||
continue
|
||||
center_lon, center_lat = float(centers[index].x), float(centers[index].y)
|
||||
lon, lat = to_float(row[2]), to_float(row[3])
|
||||
# 属性里的中心点若明显不在该栅格上,改用图形中心,避免空值或 0 把不相邻的栅格拼到一起。
|
||||
if lon is None or lat is None or _meters(lon, lat, center_lon, center_lat) > 20:
|
||||
lon, lat = center_lon, center_lat
|
||||
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)]
|
||||
bounds = geometries[index].bounds
|
||||
rows.append({
|
||||
"lon": lon, "lat": lat, "dl": values[0], "gd": values[1], "yd": values[2],
|
||||
"blob": _gp_blob(geometries[index]), "bounds": bounds,
|
||||
})
|
||||
finally:
|
||||
shapely.destroy_prepared(market.geometry)
|
||||
return rows
|
||||
|
||||
|
||||
def _gp_blob(geometry):
|
||||
return b"GP" + bytes((0, 1)) + int(SRS_ID).to_bytes(4, "little", signed=True) + to_wkb(geometry)
|
||||
|
||||
|
||||
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),
|
||||
)
|
||||
for index, record in enumerate(records, start=1):
|
||||
conn.execute(
|
||||
f'INSERT INTO "{TABLE}" (fid, "{GEOM}", "mro_total_dl", "mro_total_gd", "mro_total_yd", "总采样点数") '
|
||||
"VALUES (?,?,?,?,?,?)",
|
||||
(index, record["blob"], record["dl"], record["gd"], record["yd"], record["total"]),
|
||||
)
|
||||
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()
|
||||
@@ -0,0 +1,24 @@
|
||||
<!DOCTYPE qgis PUBLIC 'http://mrcc.com/qgis.dtd' 'SYSTEM'>
|
||||
<qgis version="3.34" labelsEnabled="0">
|
||||
<renderer-v2 type="singleSymbol" symbollevels="0" forceraster="0" enableorderby="0">
|
||||
<symbols>
|
||||
<symbol type="fill" name="0" alpha="1" clip_to_extent="1" force_rhr="0">
|
||||
<layer class="SimpleFill" enabled="1" pass="0" locked="0">
|
||||
<Option type="Map">
|
||||
<Option name="border_width_map_unit_scale" type="QString" value="3x:0,0,0,0,0,0"/>
|
||||
<Option name="color" type="QString" value="0,0,0,0"/>
|
||||
<Option name="joinstyle" type="QString" value="bevel"/>
|
||||
<Option name="offset" type="QString" value="0,0"/>
|
||||
<Option name="offset_map_unit_scale" type="QString" value="3x:0,0,0,0,0,0"/>
|
||||
<Option name="offset_unit" type="QString" value="MM"/>
|
||||
<Option name="outline_color" type="QString" value="0,114,178,255"/>
|
||||
<Option name="outline_style" type="QString" value="solid"/>
|
||||
<Option name="outline_width" type="QString" value="0.26"/>
|
||||
<Option name="outline_width_unit" type="QString" value="MM"/>
|
||||
<Option name="style" type="QString" value="no"/>
|
||||
</Option>
|
||||
</layer>
|
||||
</symbol>
|
||||
</symbols>
|
||||
</renderer-v2>
|
||||
</qgis>
|
||||
Reference in New Issue
Block a user