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
+4
View File
@@ -249,3 +249,7 @@ QGIS 中竟对信号默认显示,用户量和小区数据图层均已移除。
- zip 和 `summary.json` 使用临时文件完成后原子替换,处理中断时不会先删除已有成果。
- `output/summary.json` 会记录总耗时、实际并发数以及每个市场的 Grid/Building 分阶段耗时。
### 楼宇专题图层
每个市场按空间相交筛选楼宇并匹配 floor/height 后,生成“移动C端采样点比例.gpkg”和“移动WIFI设备占比图层.gpkg”。两个文件分别保留样板中的字段、边界和空间索引,默认 QML 样式写入各自的 layer_styles;GIS.qgz 同时引用两个文件。样式与图层初始可见性来自用户确认的 20260921-152253-a6d550a2 样板,保存在 marketgrid/styles。两个专题默认不勾选,与样板一致。NRBuildingsData.gpkg 仅作为内部处理数据,不再放入市场 ZIP。旧成果不自动改写,需重新出图。
+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"
}
+24 -1
View File
@@ -170,7 +170,9 @@ class TaskIntegrationTest(unittest.TestCase):
create_gpkg(self.root / "grid.gpkg", "grid", ','.join(f'"{f}" real' for f in fields),
[(1, a, [values[f] for f in fields]), (2, b, [values[f] for f in fields])])
create_gpkg(self.root / "buildings.gpkg", "BuildingInfo", '"name" text,"floor" integer,"height" real', [(1, a, ["建筑甲", 2, 7.8]), (2, b, ["建筑乙", 3, 11.7])])
create_gpkg(self.root / "nr.gpkg", "NRBuildingsData", '"building_id" text', [(1, a, ["A"]), (2, b, ["B"])])
from marketgrid.building_themes import THEMES
nr_fields = list(dict.fromkeys(n for t in THEMES for n, _ in t["fields"] if n not in ("floor", "height")))
create_gpkg(self.root / "nr.gpkg", "NRBuildingsData", ",".join(f'"{n}" TEXT' for n in nr_fields), [(1, a, ["1"] * len(nr_fields)), (2, b, ["2"] * len(nr_fields))])
create_gpkg(self.root / "aoi.gpkg", config.AOI_LAYER,
'"所属市场网格" text,"AOI唯一标签" text,"AOI名称" text',
[(1, a, ["甲", "a", "甲AOI"]), (2, b, ["乙", "b", "乙AOI"])])
@@ -192,6 +194,27 @@ class TaskIntegrationTest(unittest.TestCase):
with zipfile.ZipFile(out / name) as archive:
self.assertIsNone(archive.testzip())
self.assertNotIn("用户量.tif", archive.namelist())
self.assertNotIn("NRBuildingsData.gpkg", archive.namelist())
if name != "全量网格图层.zip":
import xml.etree.ElementTree as ET
from marketgrid.building_themes import STYLES
with zipfile.ZipFile(io.BytesIO(archive.read('GIS.qgz'))) as project:
xml = ET.fromstring(project.read('GIS.qgs'))
for theme in THEMES:
filename = theme['name'] + '.gpkg'
self.assertIn(filename, archive.namelist())
path = self.root / filename
path.write_bytes(archive.read(filename))
with closing(sqlite3.connect(path)) as conn:
columns = {r[1] for r in conn.execute('pragma table_info(NRBuildingsData)')}
self.assertEqual(columns, {'fid', 'geom', *[n for n, _ in theme['fields']]})
self.assertEqual(conn.execute('select count(*) from rtree_NRBuildingsData_geom').fetchone()[0], 1)
style = conn.execute('select styleQML from layer_styles where useAsDefault=1').fetchone()[0]
self.assertEqual(style, (STYLES / (theme['key'] + '.qml')).read_text(encoding='utf-8'))
layer = next(l for l in xml.findall('projectlayers/maplayer') if l.findtext('layername') == theme['name'])
self.assertEqual(layer.findtext('datasource'), './' + filename + '|layername=NRBuildingsData')
self.assertEqual(layer.findtext('srs/spatialrefsys/authid'), 'OGC:CRS84')
self.assertEqual(layer.find('renderer-v2').get('type'), 'RuleRenderer')
class PageTest(unittest.TestCase):