feat: 按样板输出移动采样和WIFI楼宇专题

This commit is contained in:
nixevol
2026-09-21 16:53:41 +08:00
parent 8533814df6
commit d578ffe587
12 changed files with 5297 additions and 3 deletions
+82
View File
@@ -0,0 +1,82 @@
"""按用户样板生成两个楼宇专题及其默认 QGIS 样式。"""
from contextlib import closing
from pathlib import Path
import json
import sqlite3
from datetime import datetime, timezone
import xml.etree.ElementTree as ET
from .gpkg import quote_identifier
STYLES = Path(__file__).with_name('styles')
THEMES = json.loads((STYLES / 'themes.json').read_text(encoding='utf-8'))
def export_themes(source_path):
results = []
with closing(sqlite3.connect(source_path)) as source:
available = {r[1] for r in source.execute('pragma table_info(NRBuildingsData)')}
for theme in THEMES:
fields = ['fid', *[name for name, _ in theme['fields']], 'geom']
missing = set(fields) - available
if missing:
raise ValueError(f"{theme['name']} 缺少字段:{', '.join(sorted(missing))}")
output = Path(source_path).with_name(theme['name'] + '.gpkg')
with closing(sqlite3.connect(output)) as target:
source.backup(target)
target.execute('PRAGMA application_id=1196444487')
target.execute('PRAGMA user_version=10400')
with target:
# 保留源几何、主键、索引和 CRS,仅精简业务字段。
for name in available - set(fields):
target.execute(f'ALTER TABLE NRBuildingsData DROP COLUMN {quote_identifier(name)}')
target.execute('DROP TABLE IF EXISTS layer_styles')
target.execute('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)')
target.execute('INSERT INTO layer_styles VALUES (1,?,?,?,?,?,?,?,?,?,?,?,?)',
('', '', 'NRBuildingsData', 'geom', theme['style_name'],
(STYLES / (theme['key'] + '.qml')).read_text(encoding='utf-8'),
'', 1, '', '', None, datetime.now(timezone.utc).isoformat()))
target.execute("INSERT OR REPLACE INTO gpkg_contents(table_name,data_type,srs_id) VALUES ('layer_styles','attributes',0)")
target.execute('VACUUM')
count = target.execute('SELECT count(*) FROM NRBuildingsData').fetchone()[0]
results.append({'output': str(output), 'feature_count': count, 'name': theme['name']})
return results
def add_theme_layers(root, extent):
from .qgis import remove_qgis_layer, set_xml_extent
remove_qgis_layer(root, 'NRBuildingsData.gpkg', required=False)
tree = root.find('layer-tree-group')
# 倒序插入,保持样板中 C 端在 WIFI 上方。
for theme in reversed(THEMES):
filename = theme['name'] + '.gpkg'
remove_qgis_layer(root, filename, required=False)
layer = ET.parse(STYLES / (theme['key'] + '.xml')).getroot()
layer_id = 'market_' + theme['key']
layer.find('id').text = layer_id
datasource = './' + filename + '|layername=NRBuildingsData'
layer.find('datasource').text = datasource
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.insert(0, ET.Element('layer-tree-layer', id=layer_id, name=theme['name'], source=datasource,
providerKey='ogr', checked=theme['checked'], expanded='0'))
order = tree.find('custom-order')
if order is not None:
item = ET.Element('item'); item.text = layer_id; order.insert(0, item)
order = root.find('layerorder')
if order is not None:
order.insert(0, ET.Element('layer', id=layer_id))
visibility = json.loads((STYLES / 'visibility.json').read_text(encoding='utf-8'))
for element in tree.iter('layer-tree-layer'):
if element.get('name') in visibility:
element.set('checked', visibility[element.get('name')])
for element in root.findall('legend/legendlayer'):
if element.get('name') in visibility:
checked = visibility[element.get('name')]
element.set('checked', checked)
for child in element.iter('legendlayerfile'):
child.set('visible', '1' if checked == 'Qt::Checked' else '0')
+5 -2
View File
@@ -5,6 +5,7 @@ import shutil
import tempfile
from . import config
from .building_attributes import enrich_building_attributes
from .building_themes import export_themes
from .gpkg import build_summary_market
from .files import competitor_signal_raster_filename
from .files import copy_full_source_file
@@ -103,6 +104,8 @@ def process_market(market, pixel_width, pixel_height, output_dir):
nr_buildings_result["attributes"] = enrich_building_attributes(
nr_buildings_path, building_info_conn, building_info_layer,
)
theme_results = export_themes(nr_buildings_path)
nr_buildings_path.unlink()
aoi_result = export_market_aoi_gpkg(
aoi_conn, aoi_layer, aoi_rtree, market, market_dir / config.AOI_OUTPUT_FILENAME,
)
@@ -113,7 +116,7 @@ def process_market(market, pixel_width, pixel_height, output_dir):
building_info_result["extent"],
competitor_signal_result["raster_extent"],
aoi_result=aoi_result,
nr_buildings_result=nr_buildings_result,
building_themes_result=nr_buildings_result,
)
building_elapsed = perf_counter() - building_started_at
@@ -133,7 +136,7 @@ def process_market(market, pixel_width, pixel_height, output_dir):
market_dir,
),
"building_info_result": rewrite_result_for_zip(building_info_result, zip_path, market_dir),
"nr_buildings_result": rewrite_result_for_zip(nr_buildings_result, zip_path, market_dir),
"building_theme_results": [rewrite_result_for_zip(r, zip_path, market_dir) for r in theme_results],
"aoi_result": rewrite_result_for_zip(aoi_result, zip_path, market_dir),
"gis_project_result": rewrite_result_for_zip(gis_project_result, zip_path, market_dir),
"zip_result": zip_result,
+3
View File
@@ -264,6 +264,9 @@ def main(settings=None, progress=None):
for summary_key, outcome_key in result_mappings.items():
summary[summary_key] = [outcome[outcome_key] for outcome in outcomes if outcome_key in outcome]
summary["summary_grid_result"] = summary_grid_result
summary["building_theme_results"] = [
item for outcome in outcomes for item in outcome.get("building_theme_results", [])
]
summary_path = config.OUTPUT_DIR / "summary.json"
temp_summary_path = summary_path.with_name(f".{summary_path.name}.tmp")
+4
View File
@@ -197,6 +197,7 @@ def copy_gis_project_to_market(
include_cell_data=False,
aoi_result=None,
nr_buildings_result=None,
building_themes_result=None,
):
if output_path.exists() and not config.OVERWRITE:
return {
@@ -234,6 +235,9 @@ def copy_gis_project_to_market(
add_market_aoi_layer(root, aoi_result, market.geometry.bounds)
if nr_buildings_result is not None:
add_nr_buildings_layer(root, nr_buildings_result, market.geometry.bounds)
if building_themes_result is not None:
from .building_themes import add_theme_layers
add_theme_layers(root, building_themes_result.get('extent') or market.geometry.bounds)
canvas = root.find(".//mapcanvas[@name='theMapCanvas']")
if canvas is None:
raise ValueError("QGIS 项目模板缺少主画布 theMapCanvas")
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+110
View File
@@ -0,0 +1,110 @@
[
{
"key": "mobile_samples",
"name": "移动C端采样点比例",
"fields": [
[
"building_id",
"TEXT"
],
[
"longitude",
"TEXT"
],
[
"latitude",
"TEXT"
],
[
"mro_ratio_yd",
"TEXT"
],
[
"mro_ratio_dx",
"TEXT"
],
[
"mro_ratio_lt",
"TEXT"
],
[
"mro_ratio_gd",
"TEXT"
],
[
"mro_ratio_dxlt",
"TEXT"
],
[
"floor",
"REAL"
],
[
"height",
"REAL"
]
],
"checked": "Qt::Unchecked",
"style_name": "移动C端采样点比例"
},
{
"key": "mobile_wifi",
"name": "移动WIFI设备占比图层",
"fields": [
[
"building_id",
"TEXT"
],
[
"longitude",
"TEXT"
],
[
"latitude",
"TEXT"
],
[
"wgrid_code",
"TEXT"
],
[
"wifi_dedup_count_yd",
"TEXT"
],
[
"wifi_dedup_count_lt",
"TEXT"
],
[
"wifi_dedup_count_dx",
"TEXT"
],
[
"wifi_dedup_count_gd",
"TEXT"
],
[
"wifi_dedup_count_other",
"TEXT"
],
[
"wifi_dedup_ratio_yd",
"TEXT"
],
[
"wifi_dedup_count_all",
"TEXT"
],
[
"floor",
"REAL"
],
[
"height",
"REAL"
]
],
"checked": "Qt::Unchecked",
"style_name": "移动WIFI设备比例"
}
]
+9
View File
@@ -0,0 +1,9 @@
{
"移动C端采样点比例": "Qt::Unchecked",
"移动WIFI设备占比图层": "Qt::Unchecked",
"AOI市场网格匹配": "Qt::Unchecked",
"竟对信号": "Qt::Unchecked",
"BuildInfo": "Qt::Unchecked",
"GoogleCN": "Qt::Checked",
"必应地图": "Qt::Unchecked"
}