feat: 成果包加入当前市场边界图层

每个市场包和全量包写入「市场名称+边界」GPKG,沿用用户样板的无填充紫色描边,
在 GIS.qgz 中放在 BuildInfo 下方并默认勾选。
This commit is contained in:
nixevol
2026-10-15 10:38:23 +08:00
parent 95a515453d
commit dda408bc6a
6 changed files with 669 additions and 1 deletions
+8 -1
View File
@@ -10,12 +10,13 @@ from .aoi_theme import normalize_aoi_gpkg
from .result_xlsx import create_result_xlsx
from .gpkg import build_summary_market
from .files import competitor_signal_raster_filename
from .files import copy_full_source_file
from .qgis import copy_gis_project_to_market
from .gpkg import export_market_aoi_gpkg
from .gpkg import export_market_building_info_gpkg
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 .files import market_zip_output_path
from .gpkg import open_read_connection
from .files import remove_file_with_retry
@@ -117,6 +118,7 @@ def process_market(market, pixel_width, pixel_height, output_dir):
market_dir / config.AOI_OUTPUT_FILENAME,
)
nr_buildings_path.unlink()
boundary_result = export_market_boundary_gpkg(market, market_dir / boundary_filename(market))
gis_project_result = copy_gis_project_to_market(
config.GIS_PROJECT_SOURCE,
gis_project_path,
@@ -125,6 +127,7 @@ def process_market(market, pixel_width, pixel_height, output_dir):
competitor_signal_result["raster_extent"],
aoi_result=aoi_result,
building_themes_result=nr_buildings_result,
boundary_result=boundary_result,
)
building_elapsed = perf_counter() - building_started_at
@@ -147,6 +150,7 @@ def process_market(market, pixel_width, pixel_height, output_dir):
"building_theme_results": [rewrite_result_for_zip(r, zip_path, market_dir) for r in theme_results],
"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),
"gis_project_result": rewrite_result_for_zip(gis_project_result, zip_path, market_dir),
"zip_result": zip_result,
"timings": {
@@ -241,6 +245,7 @@ def process_summary_grid_outputs(markets, pixel_width, pixel_height, output_dir)
aoi_path,
)
nr_buildings_path.unlink()
boundary_result = export_market_boundary_gpkg(summary_market, summary_dir / boundary_filename(summary_market))
gis_project_path = summary_dir / config.GIS_PROJECT_OUTPUT_FILENAME
gis_project_result = copy_gis_project_to_market(
config.GIS_PROJECT_SOURCE,
@@ -251,6 +256,7 @@ def process_summary_grid_outputs(markets, pixel_width, pixel_height, output_dir)
aoi_result=aoi_result,
building_themes_result=nr_buildings_result,
include_online=False,
boundary_result=boundary_result,
)
zip_result = write_market_zip(summary_dir, zip_path, summary_market)
legacy_zip_path = output_dir / config.LEGACY_SUMMARY_OUTPUT_FILENAME
@@ -267,6 +273,7 @@ def process_summary_grid_outputs(markets, pixel_width, pixel_height, output_dir)
"building_theme_results": [rewrite_result_for_zip(r, zip_path, summary_dir) for r in theme_results],
"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),
"gis_project_result": rewrite_result_for_zip(gis_project_result, zip_path, summary_dir),
"zip_result": zip_result,
"elapsed_seconds": perf_counter() - started_at,
+148
View File
@@ -0,0 +1,148 @@
"""把当前市场网格边界写成带统一样式的 GeoPackage。"""
from datetime import datetime, timezone
from pathlib import Path
import sqlite3
from shapely import make_valid, to_wkb
from shapely.geometry import MultiPolygon, Polygon
from .files import safe_filename
TABLE = "MarketBoundary"
GEOM = "geometry"
SRS_ID = 100000
STYLES = Path(__file__).with_name("styles")
CRS84 = (
'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],AUTHORITY["OGC","CRS84"]]'
)
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 boundary_layer_name(market):
name = str(market.name or market.code or market.fid).strip()
return f"{name}边界"
def boundary_filename(market):
return f"{safe_filename(boundary_layer_name(market))}.gpkg"
def export_market_boundary_gpkg(market, output_path):
output_path = Path(output_path)
geometry = _multipolygon(market.geometry)
minx, miny, maxx, maxy = geometry.bounds
qml = (STYLES / "market_boundary.qml").read_text(encoding="utf-8")
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 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);
"""
)
conn.execute(
f'CREATE TABLE "{TABLE}" (fid INTEGER PRIMARY KEY, "{GEOM}" MULTIPOLYGON, name TEXT)'
)
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", 4326, "EPSG", 4326, WGS84, "WGS 84"),
("WGS 84 (CRS84)", SRS_ID, "NONE", SRS_ID, CRS84, "longitude/latitude"),
],
)
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, "MULTIPOLYGON", SRS_ID, 0, 0),
)
conn.execute("INSERT INTO gpkg_ogr_contents VALUES (?,?)", (TABLE, 1))
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),
)
blob = b"GP" + bytes((0, 1)) + int(SRS_ID).to_bytes(4, "little", signed=True) + to_wkb(geometry)
conn.execute(f'INSERT INTO "{TABLE}" (fid, "{GEOM}", name) VALUES (?,?,?)', (1, blob, market.name))
conn.execute(
f'INSERT INTO "rtree_{TABLE}_{GEOM}" VALUES (?,?,?,?,?)',
(1, minx, maxx, miny, maxy),
)
conn.commit()
finally:
conn.close()
return {
"market_code": market.code,
"market_name": market.name,
"layer_name": boundary_layer_name(market),
"filename": output_path.name,
"output": str(output_path),
"extent": [minx, miny, maxx, maxy],
"feature_count": 1,
"skipped": False,
}
def _multipolygon(geometry):
geometry = make_valid(geometry)
if geometry is None or geometry.is_empty:
raise ValueError("市场边界为空,无法写入边界图层。")
if isinstance(geometry, Polygon):
return MultiPolygon([geometry])
if isinstance(geometry, MultiPolygon):
return geometry
parts = []
for item in getattr(geometry, "geoms", ()):
if isinstance(item, Polygon):
parts.append(item)
elif isinstance(item, MultiPolygon):
parts.extend(item.geoms)
if not parts:
raise ValueError("市场边界不是面,无法写入边界图层。")
return MultiPolygon(parts)
+97
View File
@@ -84,6 +84,100 @@ def remove_qgis_layer(root, datasource_filename, required=True):
return layer_id
def add_market_boundary_layer(root, boundary_result):
"""在 BuildInfo 下方加入当前市场边界,默认勾选。"""
from .market_boundary import TABLE
layer_id = "market_grid_boundary"
layer_name = boundary_result["layer_name"]
datasource = f"./{boundary_result['filename']}|layername={TABLE}"
remove_qgis_layer(root, boundary_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") / "market_boundary.qml").getroot()
layer = copy.deepcopy(template)
layer.set("labelsEnabled", "0")
layer.set("wkbType", "MultiPolygon")
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(boundary_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")
build_node = next(
(item for item in tree.findall("layer-tree-layer") if item.get("name") == "BuildInfo"),
None,
)
if build_node is None:
raise ValueError("QGIS 项目模板缺少 BuildInfo 图层")
node = ET.Element("layer-tree-layer", {
"id": layer_id, "name": layer_name, "source": datasource, "providerKey": "ogr",
"checked": "Qt::Checked", "expanded": "0",
})
_insert_after(tree, build_node, node)
build_id = build_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() == build_id), None)
item = ET.Element("item")
item.text = layer_id
if existing is None:
order.append(item)
else:
_insert_after(order, existing, item)
layerorder = root.find("layerorder")
if layerorder is not None:
existing = next((child for child in layerorder if child.get("id") == build_id), None)
new_item = ET.Element("layer", id=layer_id)
if existing is None:
layerorder.append(new_item)
else:
_insert_after(layerorder, 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") == "BuildInfo"),
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.append(legend_layer)
else:
_insert_after(legend, existing, legend_layer)
def add_market_aoi_layer(root, aoi_result, fallback_extent):
from .aoi_theme import aoi_layer_template
template = aoi_layer_template()
@@ -253,6 +347,7 @@ def copy_gis_project_to_market(
nr_buildings_result=None,
building_themes_result=None,
include_online=True,
boundary_result=None,
):
if output_path.exists() and not config.OVERWRITE:
return {
@@ -295,6 +390,8 @@ def copy_gis_project_to_market(
add_theme_layers(root, building_themes_result.get('extent') or market.geometry.bounds)
if include_online:
add_online_basemap(root, market.name)
if boundary_result is not None:
add_market_boundary_layer(root, boundary_result)
canvas = root.find(".//mapcanvas[@name='theMapCanvas']")
if canvas is None:
raise ValueError("QGIS 项目模板缺少主画布 theMapCanvas")
+341
View File
@@ -0,0 +1,341 @@
<!DOCTYPE qgis PUBLIC 'http://mrcc.com/qgis.dtd' 'SYSTEM'>
<qgis autoRefreshMode="Disabled" autoRefreshTime="0" hasScaleBasedVisibilityFlag="0" labelsEnabled="0" layerType="Vector" maxScale="0" minScale="100000000" readOnly="0" simplifyAlgorithm="0" simplifyDrawingHints="1" simplifyDrawingTol="1" simplifyLocal="1" simplifyMaxScale="1" styleCategories="AllStyleCategories" symbologyReferenceScale="-1" version="4.2.2-Belém do Pará">
<flags>
<Identifiable>1</Identifiable>
<Removable>1</Removable>
<Searchable>1</Searchable>
<Private>0</Private>
</flags>
<temporal accumulate="0" durationField="fid" durationUnit="min" enabled="0" endExpression="" endField="" fixedDuration="0" limitMode="0" mode="0" startExpression="" startField="">
<fixedRange>
<start></start>
<end></end>
</fixedRange>
</temporal>
<elevation binding="Centroid" clamping="Terrain" customToleranceEnabled="1" extrusion="0" extrusionEnabled="0" respectLayerSymbol="1" showMarkerSymbolInSurfacePlots="0" symbology="Line" type="IndividualFeatures" zoffset="0" zscale="1">
<data-defined-properties>
<Option type="Map">
<Option name="name" type="QString" value=""/>
<Option name="properties"/>
<Option name="type" type="QString" value="collection"/>
</Option>
</data-defined-properties>
<profileLineSymbol>
<symbol alpha="1" clip_to_extent="1" force_rhr="0" frame_rate="10" is_animated="0" name="" type="line">
<data_defined_properties>
<Option type="Map">
<Option name="name" type="QString" value=""/>
<Option name="properties"/>
<Option name="type" type="QString" value="collection"/>
</Option>
</data_defined_properties>
<layer class="SimpleLine" enabled="1" id="{b84e6983-5a09-430d-8cb8-484e4666ba75}" locked="0" pass="0">
<Option type="Map">
<Option name="align_dash_pattern" type="QString" value="0"/>
<Option name="capstyle" type="QString" value="square"/>
<Option name="customdash" type="QString" value="5;2"/>
<Option name="customdash_map_unit_scale" type="QString" value="3x:0,0,0,0,0,0"/>
<Option name="customdash_unit" type="QString" value="MM"/>
<Option name="dash_pattern_offset" type="QString" value="0"/>
<Option name="dash_pattern_offset_map_unit_scale" type="QString" value="3x:0,0,0,0,0,0"/>
<Option name="dash_pattern_offset_unit" type="QString" value="MM"/>
<Option name="draw_inside_polygon" type="QString" value="0"/>
<Option name="joinstyle" type="QString" value="bevel"/>
<Option name="line_color" type="QString" value="255,158,23,255,rgb:1,0.6196079,0.0901961,1"/>
<Option name="line_style" type="QString" value="solid"/>
<Option name="line_width" type="QString" value="0.6"/>
<Option name="line_width_unit" type="QString" value="MM"/>
<Option name="offset" type="QString" value="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="ring_filter" type="QString" value="0"/>
<Option name="trim_distance_end" type="QString" value="0"/>
<Option name="trim_distance_end_map_unit_scale" type="QString" value="3x:0,0,0,0,0,0"/>
<Option name="trim_distance_end_unit" type="QString" value="MM"/>
<Option name="trim_distance_start" type="QString" value="0"/>
<Option name="trim_distance_start_map_unit_scale" type="QString" value="3x:0,0,0,0,0,0"/>
<Option name="trim_distance_start_unit" type="QString" value="MM"/>
<Option name="tweak_dash_pattern_on_corners" type="QString" value="0"/>
<Option name="use_custom_dash" type="QString" value="0"/>
<Option name="width_map_unit_scale" type="QString" value="3x:0,0,0,0,0,0"/>
</Option>
<data_defined_properties>
<Option type="Map">
<Option name="name" type="QString" value=""/>
<Option name="properties"/>
<Option name="type" type="QString" value="collection"/>
</Option>
</data_defined_properties>
</layer>
</symbol>
</profileLineSymbol>
<profileFillSymbol>
<symbol alpha="1" clip_to_extent="1" force_rhr="0" frame_rate="10" is_animated="0" name="" type="fill">
<data_defined_properties>
<Option type="Map">
<Option name="name" type="QString" value=""/>
<Option name="properties"/>
<Option name="type" type="QString" value="collection"/>
</Option>
</data_defined_properties>
<layer class="SimpleFill" enabled="1" id="{9ad6ad11-06aa-4ba4-9219-d851495d362d}" locked="0" pass="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="255,158,23,255,rgb:1,0.6196079,0.0901961,1"/>
<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="182,113,16,255,rgb:0.7142748,0.4425269,0.0644236,1"/>
<Option name="outline_style" type="QString" value="solid"/>
<Option name="outline_width" type="QString" value="0.2"/>
<Option name="outline_width_unit" type="QString" value="MM"/>
<Option name="style" type="QString" value="solid"/>
</Option>
<data_defined_properties>
<Option type="Map">
<Option name="name" type="QString" value=""/>
<Option name="properties"/>
<Option name="type" type="QString" value="collection"/>
</Option>
</data_defined_properties>
</layer>
</symbol>
</profileFillSymbol>
<profileMarkerSymbol>
<symbol alpha="1" clip_to_extent="1" force_rhr="0" frame_rate="10" is_animated="0" name="" type="marker">
<data_defined_properties>
<Option type="Map">
<Option name="name" type="QString" value=""/>
<Option name="properties"/>
<Option name="type" type="QString" value="collection"/>
</Option>
</data_defined_properties>
<layer class="SimpleMarker" enabled="1" id="{e97b7df0-654f-4367-bba9-dc9ff8c3d4ec}" locked="0" pass="0">
<Option type="Map">
<Option name="angle" type="QString" value="0"/>
<Option name="cap_style" type="QString" value="square"/>
<Option name="color" type="QString" value="255,158,23,255,rgb:1,0.6196079,0.0901961,1"/>
<Option name="horizontal_anchor_point" type="QString" value="1"/>
<Option name="joinstyle" type="QString" value="bevel"/>
<Option name="name" type="QString" value="diamond"/>
<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="182,113,16,255,rgb:0.7142748,0.4425269,0.0644236,1"/>
<Option name="outline_style" type="QString" value="solid"/>
<Option name="outline_width" type="QString" value="0.2"/>
<Option name="outline_width_map_unit_scale" type="QString" value="3x:0,0,0,0,0,0"/>
<Option name="outline_width_unit" type="QString" value="MM"/>
<Option name="scale_method" type="QString" value="diameter"/>
<Option name="size" type="QString" value="3"/>
<Option name="size_map_unit_scale" type="QString" value="3x:0,0,0,0,0,0"/>
<Option name="size_unit" type="QString" value="MM"/>
<Option name="vertical_anchor_point" type="QString" value="1"/>
</Option>
<data_defined_properties>
<Option type="Map">
<Option name="name" type="QString" value=""/>
<Option name="properties"/>
<Option name="type" type="QString" value="collection"/>
</Option>
</data_defined_properties>
</layer>
</symbol>
</profileMarkerSymbol>
</elevation>
<renderer-v2 enableorderby="0" forceraster="0" referencescale="-1" symbollevels="0" type="singleSymbol">
<symbols>
<symbol alpha="1" clip_to_extent="1" force_rhr="0" frame_rate="10" is_animated="0" name="0" type="fill">
<data_defined_properties>
<Option type="Map">
<Option name="name" type="QString" value=""/>
<Option name="properties"/>
<Option name="type" type="QString" value="collection"/>
</Option>
</data_defined_properties>
<layer class="SimpleFill" enabled="1" id="{231f2052-1139-4fd7-8115-b4497b1794dd}" locked="0" pass="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="183,72,75,255,rgb:0.7176471,0.282353,0.2941177,1"/>
<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="193,0,206,255,hsv:0.82319444417953491,1,0.80738538503646851,1"/>
<Option name="outline_style" type="QString" value="solid"/>
<Option name="outline_width" type="QString" value="0.8"/>
<Option name="outline_width_unit" type="QString" value="MM"/>
<Option name="style" type="QString" value="no"/>
</Option>
<data_defined_properties>
<Option type="Map">
<Option name="name" type="QString" value=""/>
<Option name="properties"/>
<Option name="type" type="QString" value="collection"/>
</Option>
</data_defined_properties>
</layer>
</symbol>
</symbols>
<rotation/>
<sizescale/>
<data-defined-properties>
<Option type="Map">
<Option name="name" type="QString" value=""/>
<Option name="properties"/>
<Option name="type" type="QString" value="collection"/>
</Option>
</data-defined-properties>
</renderer-v2>
<selection mode="Default">
<selectionColor invalid="1"/>
<selectionSymbol>
<symbol alpha="1" clip_to_extent="1" force_rhr="0" frame_rate="10" is_animated="0" name="" type="fill">
<data_defined_properties>
<Option type="Map">
<Option name="name" type="QString" value=""/>
<Option name="properties"/>
<Option name="type" type="QString" value="collection"/>
</Option>
</data_defined_properties>
<layer class="SimpleFill" enabled="1" id="{02c5902b-675b-4906-b226-d554dae8e43e}" locked="0" pass="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,255,255,rgb:0,0,1,1"/>
<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="35,35,35,255,rgb:0.1372549,0.1372549,0.1372549,1"/>
<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="solid"/>
</Option>
<data_defined_properties>
<Option type="Map">
<Option name="name" type="QString" value=""/>
<Option name="properties"/>
<Option name="type" type="QString" value="collection"/>
</Option>
</data_defined_properties>
</layer>
</symbol>
</selectionSymbol>
</selection>
<customproperties>
<Option type="Map">
<Option name="dualview/previewExpressions" type="List">
<Option type="QString" value="COALESCE( &quot;name&quot;, '&lt;NULL>' )"/>
</Option>
<Option name="embeddedWidgets/count" type="int" value="0"/>
<Option name="variableNames"/>
<Option name="variableValues"/>
</Option>
</customproperties>
<blendMode>0</blendMode>
<featureBlendMode>0</featureBlendMode>
<layerOpacity>1</layerOpacity>
<geometryOptions geometryPrecision="0" removeDuplicateNodes="0">
<activeChecks/>
<checkConfiguration type="Map">
<Option name="QgsGeometryGapCheck" type="Map">
<Option name="allowedGapsBuffer" type="double" value="0"/>
<Option name="allowedGapsEnabled" type="bool" value="false"/>
<Option name="allowedGapsLayer" type="QString" value=""/>
</Option>
</checkConfiguration>
</geometryOptions>
<legend showLabelLegend="0" type="default-vector"/>
<referencedLayers/>
<referencingLayers/>
<fieldConfiguration>
<field configurationFlags="0" name="fid">
<editWidget type="TextEdit">
<config>
<Option/>
</config>
</editWidget>
</field>
<field configurationFlags="0" name="name">
<editWidget type="TextEdit">
<config>
<Option/>
</config>
</editWidget>
</field>
</fieldConfiguration>
<aliases>
<alias field="fid" index="0" name=""/>
<alias field="name" index="1" name=""/>
</aliases>
<defaults>
<default applyOnUpdate="0" expression="" field="fid"/>
<default applyOnUpdate="0" expression="" field="name"/>
</defaults>
<constraints>
<constraint constraints="3" exp_strength="0" field="fid" notnull_strength="1" unique_strength="1"/>
<constraint constraints="0" exp_strength="0" field="name" notnull_strength="0" unique_strength="0"/>
</constraints>
<constraintExpressions>
<constraint desc="" exp="" field="fid"/>
<constraint desc="" exp="" field="name"/>
</constraintExpressions>
<expressionfields/>
<attributeactions>
<defaultAction key="Canvas" value="{00000000-0000-0000-0000-000000000000}"/>
</attributeactions>
<attributetableconfig actionWidgetStyle="dropDown" sortExpression="" sortOrder="0">
<columns>
<column hidden="0" name="fid" type="field" width="-1"/>
<column hidden="0" name="name" type="field" width="-1"/>
<column hidden="1" type="actions" width="-1"/>
</columns>
</attributetableconfig>
<conditionalstyles>
<rowstyles/>
<fieldstyles/>
</conditionalstyles>
<storedexpressions/>
<editform tolerant="1"></editform>
<editforminit/>
<editforminitcodesource>0</editforminitcodesource>
<editforminitfilepath></editforminitfilepath>
<editforminitcode><![CDATA[# -*- 编码: utf-8 -*-
"""
QGIS表单含有一个Python函数,该函数在打开表单时被调用。
使用此函数为您的表单添加扩展逻辑。
在 "Python Init function" 字段中输入函数名。
示例如下:
"""
from qgis.PyQt.QtWidgets import QWidget
def my_form_open(dialog, layer, feature):
geom = feature.geometry()
control = dialog.findChild(QWidget, "MyLineEdit")
]]></editforminitcode>
<featformsuppress>0</featformsuppress>
<editorlayout>generatedlayout</editorlayout>
<editable>
<field editable="1" name="fid"/>
<field editable="1" name="name"/>
</editable>
<labelOnTop>
<field labelOnTop="0" name="fid"/>
<field labelOnTop="0" name="name"/>
</labelOnTop>
<reuseLastValuePolicy>
<field name="fid" reuseLastValuePolicy="NotAllowed"/>
<field name="name" reuseLastValuePolicy="NotAllowed"/>
</reuseLastValuePolicy>
<dataDefinedFieldProperties/>
<widgets/>
<previewExpression>COALESCE( "name", '&lt;NULL>' )</previewExpression>
<mapTip enabled="1"></mapTip>
<layerGeometryType>2</layerGeometryType>
</qgis>
+70
View File
@@ -0,0 +1,70 @@
"""市场边界图层的几何、样式和工程位置。"""
from pathlib import Path
import sqlite3
import tempfile
import unittest
import zipfile
import xml.etree.ElementTree as ET
from shapely import from_wkb
from shapely.geometry import box
from marketgrid import config, gpkg, qgis
from marketgrid.market_boundary import STYLES, export_market_boundary_gpkg
from marketgrid.models import MarketFeature
class MarketBoundaryTests(unittest.TestCase):
def test_gpkg_uses_outline_style_and_market_geometry(self):
market = MarketFeature(7, "7-测试网格", "测试网格", box(112.1, 22.2, 112.4, 22.5))
with tempfile.TemporaryDirectory() as temp_dir:
path = Path(temp_dir) / "测试网格边界.gpkg"
result = export_market_boundary_gpkg(market, path)
self.assertEqual(result["layer_name"], "测试网格边界")
conn = sqlite3.connect(path)
try:
qml = conn.execute("select styleQML from layer_styles where useAsDefault=1").fetchone()[0]
self.assertEqual(qml, (STYLES / "market_boundary.qml").read_text(encoding="utf-8"))
blob, name = conn.execute('select geometry, name from "MarketBoundary"').fetchone()
self.assertEqual(name, "测试网格")
self.assertEqual(conn.execute("select srs_id from gpkg_contents where table_name='MarketBoundary'").fetchone()[0], 100000)
finally:
conn.close()
geometry = from_wkb(gpkg.gpkg_blob_to_wkb(blob))
self.assertEqual(geometry.bounds, (112.1, 22.2, 112.4, 22.5))
renderer = ET.fromstring(qml).find("renderer-v2")
options = {
item.get("name"): item.get("value")
for item in renderer.iter("Option")
}
self.assertEqual(options["style"], "no")
self.assertEqual(options["outline_width"], "0.8")
def test_project_places_checked_boundary_under_buildinfo(self):
market = MarketFeature(1, "1-测试网格", "测试网格", box(0, 0, 1, 1))
boundary = {
"filename": "测试网格边界.gpkg",
"layer_name": "测试网格边界",
"extent": [0, 0, 1, 1],
}
with tempfile.TemporaryDirectory() as temp_dir:
output = Path(temp_dir) / "GIS.qgz"
qgis.copy_gis_project_to_market(
config.GIS_PROJECT_SOURCE, output, market, None, boundary_result=boundary,
)
with zipfile.ZipFile(output) as archive:
root = ET.fromstring(archive.read("GIS.qgs"))
names = [item.get("name") for item in root.findall("./layer-tree-group/layer-tree-layer")]
self.assertEqual(names[names.index("BuildInfo") + 1], "测试网格边界")
node = root.find("./layer-tree-group/layer-tree-layer[@name='测试网格边界']")
self.assertEqual(node.get("checked"), "Qt::Checked")
self.assertEqual(node.get("source"), "./测试网格边界.gpkg|layername=MarketBoundary")
self.assertEqual(names[-3:], ["GoogleCN", "必应地图", "online"])
layer = next(item for item in root.findall(".//projectlayers/maplayer") if item.findtext("layername") == "测试网格边界")
options = {item.get("name"): item.get("value") for item in layer.find("renderer-v2").iter("Option")}
self.assertEqual(options["style"], "no")
self.assertEqual(options["outline_width"], "0.8")
if __name__ == "__main__":
unittest.main()
+5
View File
@@ -210,6 +210,11 @@ class TaskIntegrationTest(unittest.TestCase):
with zipfile.ZipFile(io.BytesIO(archive.read('GIS.qgz'))) as project:
xml = ET.fromstring(project.read('GIS.qgs'))
names = [item.get("name") for item in xml.iter("layer-tree-layer")]
boundary_name = "全量网格图层边界" if name == "全量网格图层.zip" else ("甲边界" if name.startswith("31") else "乙边界")
self.assertEqual(names[names.index("BuildInfo") + 1], boundary_name)
boundary = next(item for item in xml.iter("layer-tree-layer") if item.get("name") == boundary_name)
self.assertEqual(boundary.get("checked"), "Qt::Checked")
self.assertIn(boundary_name + ".gpkg", members)
if name == "全量网格图层.zip":
self.assertNotIn("online", names)
expected_count = 2