feat: 补齐全量网格成果并改用竞对图层名

全量包与单市场包含同类完整数据且不含 online;AOI 由报表按最大接触面积自动匹配。Excel 占比写成文本百分号,竞对信号文件和图层改用正确用字。
This commit is contained in:
nixevol
2026-09-28 11:08:16 +08:00
parent 0ad04fa638
commit 28170a7fe2
17 changed files with 723 additions and 110 deletions
+234
View File
@@ -0,0 +1,234 @@
"""把 AOI 报表按与市场网格的最大接触面积归属,生成匹配总表。"""
import csv
import math
import sqlite3
from pathlib import Path
from shapely import STRtree, make_valid, wkt
from shapely.affinity import scale
from shapely.geometry import MultiPolygon, Polygon
from . import config
from .gpkg import load_market_features, open_read_connection, quote_identifier, resolve_feature_layer
GEOMETRY_COLUMN = "空间信息(几何)"
REAL_COLUMNS = [
"移动C端采样点占比", "联通C端采样点占比", "电信C端采样点占比", "广电C端采样点占比", "电联C端采样点占比",
"移动wifi去重数占比", "联通wifi去重数占比", "电信wifi去重数占比", "广电wifi去重数占比", "其他wifi去重数占比",
"移动wifi采样点占比", "联通wifi采样点占比", "电信wifi采样点占比", "广电wifi采样点占比", "其他wifi采样点占比",
]
TEXT_COLUMNS = ["地市名称", "AOI唯一标签", "AOI名称", GEOMETRY_COLUMN]
REQUIRED_COLUMNS = ["AOI唯一标签", "AOI名称", GEOMETRY_COLUMN, *REAL_COLUMNS[:5]]
# 江门一带的局部米制缩放,只用于比较接触面积,不写入坐标。
_LAT0 = 22.5
_MX = 111_320 * math.cos(math.radians(_LAT0))
_MY = 110_540
def csv_encoding(path):
for encoding in ("utf-8-sig", "gbk"):
try:
with Path(path).open(encoding=encoding, newline="") as source:
source.readline()
return encoding
except UnicodeDecodeError:
continue
raise ValueError(f"无法识别 AOI 报表编码:{path}")
def _polygonal(geometry):
if geometry is None or geometry.is_empty:
return None
if not geometry.is_valid:
geometry = make_valid(geometry)
if geometry.geom_type == "GeometryCollection":
parts = [part for part in geometry.geoms if part.geom_type in {"Polygon", "MultiPolygon"} and not part.is_empty]
if not parts:
return None
geometry = max(parts, key=lambda part: part.area)
if isinstance(geometry, Polygon):
return MultiPolygon([geometry])
if isinstance(geometry, MultiPolygon):
return geometry
return None
def _contact_area(left, right):
overlap = left.intersection(right)
if overlap.is_empty:
return 0.0
return scale(overlap, xfact=_MX, yfact=_MY, origin=(0, 0)).area
def assign_market(geometry, markets, tree):
"""接触面积必须大于 0;面积相同取 fid 较小的市场。"""
best_name = None
best_area = 0.0
best_fid = None
for index in tree.query(geometry, predicate="intersects"):
market = markets[int(index)]
area = _contact_area(geometry, market.geometry)
if area > best_area or (area == best_area and area > 0 and (best_fid is None or market.fid < best_fid)):
best_name = market.name
best_area = area
best_fid = market.fid
return best_name
def _gpkg_blob(geometry):
return b"GP" + bytes((0, 1)) + (4326).to_bytes(4, "little") + geometry.wkb
def _srs_rows(market_gpkg):
fallback = [
("Undefined Cartesian SRS", -1, "NONE", -1, "undefined", "undefined Cartesian"),
("Undefined geographic SRS", 0, "NONE", 0, "undefined", "undefined geographic"),
("WGS 84 geodetic", 4326, "EPSG", 4326,
'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]]',
""),
]
conn = sqlite3.connect(market_gpkg)
try:
names = {row[1] for row in conn.execute("pragma table_info(gpkg_spatial_ref_sys)")}
if "srs_name" not in names:
return fallback
rows = conn.execute(
"select srs_name, srs_id, organization, organization_coordsys_id, definition, description "
"from gpkg_spatial_ref_sys where srs_id in (-1, 0, 4326) order by srs_id"
).fetchall()
except sqlite3.Error:
return fallback
finally:
conn.close()
if not any(row[1] == 4326 for row in rows):
return fallback
return rows
def _real(value):
text = "" if value is None else str(value).strip()
if not text:
return None
return float(text)
def build_matched_aoi(csv_path, market_gpkg, output_path):
"""读取 AOI 报表,写入带所属市场网格的总表。面积为 0 的仅贴边接触不归属。"""
csv_path, market_gpkg, output_path = Path(csv_path), Path(market_gpkg), Path(output_path)
encoding = csv_encoding(csv_path)
with csv_path.open(encoding=encoding, newline="") as source:
reader = csv.DictReader(source)
header = reader.fieldnames or []
missing = [name for name in REQUIRED_COLUMNS if name not in header]
if missing:
raise ValueError(f"AOI报表缺少字段:{', '.join(missing)}")
rows = list(reader)
with open_read_connection(market_gpkg) as conn:
layer = resolve_feature_layer(conn, config.MARKET_LAYER)
markets = load_market_features(conn, layer, config.MARKET_CODE_FIELD, config.MARKET_NAME_FIELD)
if not markets:
raise ValueError("市场网格为空,无法匹配 AOI")
prepared = []
for market in markets:
geometry = _polygonal(market.geometry)
if geometry is None:
continue
prepared.append(type(market)(market.fid, market.code, market.name, geometry))
if not prepared:
raise ValueError("市场网格没有可用几何,无法匹配 AOI")
tree = STRtree([market.geometry for market in prepared])
matched = unassigned = invalid = 0
records = []
extent = None
for row in rows:
config.check_cancelled()
text = (row.get(GEOMETRY_COLUMN) or "").strip()
geometry = None
if text:
try:
geometry = _polygonal(wkt.loads(text))
except Exception:
geometry = None
market_name = assign_market(geometry, prepared, tree) if geometry is not None else None
if geometry is None:
invalid += 1
unassigned += 1
elif market_name:
matched += 1
minx, miny, maxx, maxy = geometry.bounds
if extent is None:
extent = [minx, miny, maxx, maxy]
else:
extent[0] = min(extent[0], minx)
extent[1] = min(extent[1], miny)
extent[2] = max(extent[2], maxx)
extent[3] = max(extent[3], maxy)
else:
unassigned += 1
values = {name: row.get(name, "") for name in TEXT_COLUMNS}
values[config.AOI_MARKET_FIELD] = market_name
for name in REAL_COLUMNS:
values[name] = _real(row.get(name))
records.append((values, geometry))
output_path.parent.mkdir(parents=True, exist_ok=True)
temporary = output_path.with_name(f".{output_path.name}.tmp")
if temporary.exists():
temporary.unlink()
table = config.AOI_LAYER
quoted = quote_identifier(table)
columns = ["地市名称", config.AOI_MARKET_FIELD, "AOI唯一标签", "AOI名称", *REAL_COLUMNS, GEOMETRY_COLUMN]
column_sql = ", ".join(
f"{quote_identifier(name)} {'REAL' if name in REAL_COLUMNS else 'TEXT'}" for name in columns
)
conn = sqlite3.connect(temporary)
try:
conn.execute("pragma application_id = 1196444487")
conn.execute("pragma user_version = 10400")
conn.execute(
"create table gpkg_spatial_ref_sys (srs_name text not null, srs_id integer primary key, "
"organization text not null, organization_coordsys_id integer not null, definition text not null, description text)"
)
conn.executemany("insert into gpkg_spatial_ref_sys values (?,?,?,?,?,?)", _srs_rows(market_gpkg))
conn.execute(
"create table gpkg_contents (table_name text primary key, data_type text not null, identifier text unique, "
"description text default '', last_change text default (strftime('%Y-%m-%dT%H:%M:%fZ','now')), "
"min_x double, min_y double, max_x double, max_y double, srs_id integer)"
)
conn.execute(
"create table gpkg_geometry_columns (table_name text primary key, column_name text not null, "
"geometry_type_name text not null, srs_id integer not null, z integer not null, m integer not null)"
)
conn.execute("create table gpkg_ogr_contents (table_name text primary key, feature_count integer)")
conn.execute(
f"create table {quoted} (fid integer primary key autoincrement, geom blob, {column_sql})"
)
rtree = f"rtree_{table}_geom"
conn.execute(f'create virtual table "{rtree}" using rtree(id, minx, maxx, miny, maxy)')
bounds = extent or [None, None, None, None]
conn.execute(
"insert into gpkg_contents (table_name, data_type, identifier, min_x, min_y, max_x, max_y, srs_id) "
"values (?, 'features', ?, ?, ?, ?, ?, 4326)",
(table, table, *bounds),
)
conn.execute(
"insert into gpkg_geometry_columns values (?, 'geom', 'MULTIPOLYGON', 4326, 0, 0)",
(table,),
)
conn.execute("insert into gpkg_ogr_contents values (?, ?)", (table, len(records)))
placeholders = ", ".join(["?"] * (len(columns) + 1))
insert_sql = f"insert into {quoted} (geom, {', '.join(quote_identifier(name) for name in columns)}) values ({placeholders})"
for values, geometry in records:
payload = [_gpkg_blob(geometry) if geometry is not None else None]
payload.extend(values[name] for name in columns)
cursor = conn.execute(insert_sql, payload)
if geometry is not None:
minx, miny, maxx, maxy = geometry.bounds
conn.execute(f'insert into "{rtree}" values (?,?,?,?,?)', (cursor.lastrowid, minx, maxx, miny, maxy))
conn.commit()
finally:
conn.close()
temporary.replace(output_path)
return {"output": str(output_path), "rows": len(records), "matched": matched, "unassigned": unassigned, "invalid": invalid}
+16 -1
View File
@@ -4,6 +4,7 @@ from pathlib import Path
import json
import sqlite3
from datetime import datetime, timezone
from time import sleep
import xml.etree.ElementTree as ET
from .gpkg import quote_identifier
@@ -15,6 +16,18 @@ ACTIVE_THEMES = [theme for theme in THEMES if theme['key'] != 'mobile_wifi']
# ACTIVE_THEMES = THEMES # 需要恢复移动 WIFI 专题时启用这一行,并停用上一行。
def _vacuum(path):
for attempt in range(10):
try:
with closing(sqlite3.connect(path)) as conn:
conn.execute("VACUUM")
return
except PermissionError:
if attempt == 9:
raise
sleep(0.3)
def export_themes(source_path):
results = []
with closing(sqlite3.connect(source_path)) as source:
@@ -40,7 +53,9 @@ def export_themes(source_path):
(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')
# Windows 上不能在仍打开该文件的连接里 VACUUM,否则替换文件会报 WinError 32。
_vacuum(output)
with closing(sqlite3.connect(output)) as target:
count = target.execute('SELECT count(*) FROM NRBuildingsData').fetchone()[0]
results.append({'output': str(output), 'feature_count': count, 'name': theme['name']})
return results
+2 -2
View File
@@ -1,4 +1,4 @@
"""竟对信号筛选和精确栅格化。"""
"""竞对信号筛选和精确栅格化。"""
from shapely import Point
import csv
import numpy as np
@@ -300,7 +300,7 @@ def export_market_grid_outputs(
# user_count_result = None
# if user_count_path is not None:
# if grid_4g_source is None:
# raise ValueError("生成竟对用户量图层时必须提供 Grid_4G 数据源")
# raise ValueError("生成竞对用户量图层时必须提供 Grid_4G 数据源")
# grid_4g_conn, grid_4g_layer, grid_4g_rtree = grid_4g_source
# source_stats = {
# "5G": {
+11 -8
View File
@@ -4,20 +4,21 @@ from pathlib import Path
DEFAULT_SOURCE_DIR = Path("source") # 源数据目录,存放 GridMap.gpkg、Grid_5G.gpkg、Grid_4G.gpkg 等输入文件。
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;竟对信号仅使用该文件。
GRID_5G_GPKG = DEFAULT_SOURCE_DIR / "Grid_5G.gpkg" # 5G Grid;竞对信号仅使用该文件。
# 用户量图层停用;以下原代码以注释保留,便于按需恢复。
# GRID_4G_GPKG = DEFAULT_SOURCE_DIR / "Grid_4G.gpkg" # 4G Grid;仅参与竟对用户量合并。
# GRID_4G_GPKG = DEFAULT_SOURCE_DIR / "Grid_4G.gpkg" # 4G Grid;仅参与竞对用户量合并。
BUILDING_INFO_GPKG = DEFAULT_SOURCE_DIR / "BuildingInfo.gpkg" # 建筑信息 GeoPackage 文件路径,用于结果包 BuildingInfo 分割和楼宇指标 CSV 名称匹配。
NR_BUILDINGS_DATA_GPKG = DEFAULT_SOURCE_DIR / "NRBuildingsData.gpkg" # 清洗后的楼宇边界数据。
GIS_PROJECT_SOURCE = DEFAULT_SOURCE_DIR / "GIS.qgz" # 每个市场网格结果包使用的 QGIS 项目模板来源。
AOI_OUTPUT_FILENAME = "移动C端采样点比例_AOI.gpkg"
AOI_GPKG = OUTPUT_DIR / AOI_OUTPUT_FILENAME # 已完成市场归属匹配的 AOI 总表。
AOI_CSV = None # 界面传入的 AOI 报表。有值时先自动匹配,再写出 AOI_GPKG。
AOI_GPKG = DEFAULT_SOURCE_DIR / "AOI级报表_市场网格匹配.gpkg" # 带所属市场网格的 AOI 总表。
AOI_LAYER = "AOI市场网格匹配"
AOI_OUTPUT_LAYER_NAME = "移动C端采样点比例_AOI"
AOI_MARKET_FIELD = "所属市场网格"
RSRP_FIELD = "ssb_rsrp_dl" # 用于生成热力图的电信 RSRP 字段名。
# EXCELLENT_CELL_FIELD = "mro_total_dl" # 用于生成用户量热力图的字段名,值越大越红。
EXCELLENT_CELL_FIELD = "mro_total_dl" # 竟对信号筛选仍需使用的 5G 竟对总采样量字段。
EXCELLENT_CELL_FIELD = "mro_total_dl" # 竞对信号筛选仍需使用的 5G 竞对总采样量字段。
GRID_ID_FIELD = "grid20_id" # 4G/5G 用户量合并去重的唯一索引字段。
WEAK_COVER_FIELD = "rsrp_lt_neg105_dl" # 用于生成信号差用户量热力图的字段名,值越大越红。
MOBILE_TOTAL_FIELD = "mro_total_yd" # 移动采样点总数字段,用作移动弱覆盖比例分母。
@@ -44,9 +45,9 @@ HEATMAP_ALPHA = 191 # 热力图有效像元透明度;191 约等于 75% 不透
PROJECT_EXTENT_PADDING_RATIO = 0.05 # QGIS 打开后的画布留白比例;0.05 表示在 BuildingInfo 范围四周各增加 5%。
# USER_COUNT_OUTPUT_FILENAME = "用户量.tif" # 采样点数量热力图输出文件名。
USER_COUNT_OUTPUT_FILENAME = "用户量.tif" # 保留文件名,以移除旧模板中的用户量图层引用。
COMPETITOR_SIGNAL_OUTPUT_FILENAME = "竟对信号.tif" # 移动非弱覆盖区域内的竟对 MR 弱覆盖/零采样信号图。
COMPETITOR_SIGNAL_OUTPUT_FILENAME = "竞对信号.tif" # 移动非弱覆盖区域内的竞对 MR 弱覆盖/零采样信号图。
COMPETITOR_SIGNAL_MOBILE_WEAK_RATIO_MAX = 20.0 # 移动弱覆盖比例必须严格小于该百分比。
COMPETITOR_SIGNAL_WEAK_RATIO_MIN = 20.0 # 竟对 MR 弱覆盖比例必须严格大于该百分比。
COMPETITOR_SIGNAL_WEAK_RATIO_MIN = 20.0 # 竞对 MR 弱覆盖比例必须严格大于该百分比。
COMPETITOR_SIGNAL_RSRP_BREAKS = (-110.0, -104.0, -98.0, -92.0, -86.0, -80.0, -74.0) # 八档颜色的七个分界点。
COMPETITOR_SIGNAL_RSRP_COLORS = (
(253, 0, 5), # < -110,红色。
@@ -59,7 +60,7 @@ COMPETITOR_SIGNAL_RSRP_COLORS = (
(58, 14, 247), # [-74, 0],紫色。
)
SUMMARY_OUTPUT_ENABLED = True # 是否额外生成全部市场网格汇总 TIF 结果包。
SUMMARY_OUTPUT_FILENAME = "全量网格图层.zip" # 包含竟对信号 TIF、GIS.qgz 和 BuildingInfo.gpkg。
SUMMARY_OUTPUT_FILENAME = "全量网格图层.zip" # 与单市场包同类文件,数据为完整未拆分版,不含 online。
LEGACY_SUMMARY_OUTPUT_FILENAME = "所有网格汇总.zip" # 旧汇总包文件名;新包成功生成后自动清理。
SUMMARY_MARKET_CODE = "全量网格图层" # 汇总任务在日志和 summary.json 中使用的标识。
SUMMARY_MAX_RASTER_PIXELS = 100_000_000 # 汇总 TIF 最大像元数;提高该值可增强清晰度,但会增加内存、耗时和文件体积。
@@ -102,7 +103,9 @@ def apply_settings(settings):
for key, value in settings.items():
if not key.isupper() or key not in globals():
raise ValueError(f"未知出图配置:{key}")
if isinstance(globals()[key], Path):
if key == "AOI_CSV":
value = Path(value) if value else None
elif isinstance(globals()[key], Path):
value = Path(value)
globals()[key] = value
+36 -22
View File
@@ -177,20 +177,13 @@ 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,
# open_read_connection(GRID_4G_GPKG) as grid_4g_conn,
):
with open_read_connection(config.GRID_5G_GPKG) as grid_5g_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)
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)
# user_count_path = summary_dir / excellent_heatmap_raster_filename(EXCELLENT_CELL_FIELD)
competitor_signal_path = summary_dir / competitor_signal_raster_filename()
(
# _, # 原用户量结果
competitor_signal_result,
_,
) = export_market_grid_outputs(
@@ -200,28 +193,26 @@ def process_summary_grid_outputs(markets, pixel_width, pixel_height, output_dir)
summary_market,
pixel_width,
pixel_height,
# None, # 原 user_count_path
competitor_signal_path,
None,
max_raster_pixels=config.SUMMARY_MAX_RASTER_PIXELS,
)
# user_count_result = render_summary_user_count_by_market(
# (
# ("5G", grid_5g_conn, grid_5g_layer, grid_5g_rtree),
# ("4G", grid_4g_conn, grid_4g_layer, grid_4g_rtree),
# ),
# markets,
# pixel_width,
# pixel_height,
# user_count_path,
# SUMMARY_MAX_RASTER_PIXELS,
# market_user_thresholds,
# )
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:
building_info_layer = resolve_feature_layer(building_info_conn, config.BUILDING_INFO_LAYER)
building_info_extent = gpkg_layer_extent(building_info_conn, building_info_layer)
nr_buildings_path = summary_dir / config.NR_BUILDINGS_DATA_OUTPUT_FILENAME
shutil.copy2(config.NR_BUILDINGS_DATA_GPKG, nr_buildings_path)
with open_read_connection(nr_buildings_path) as nr_conn:
nr_layer = resolve_feature_layer(nr_conn)
nr_extent = gpkg_layer_extent(nr_conn, nr_layer)
nr_buildings_result = {
"extent": list(nr_extent) if nr_extent else list(building_info_extent or summary_market.geometry.bounds),
"attributes": enrich_building_attributes(
nr_buildings_path, building_info_conn, building_info_layer,
),
}
building_info_result = {
"market_code": summary_market.code,
"market_name": summary_market.name,
@@ -232,6 +223,24 @@ def process_summary_grid_outputs(markets, pixel_width, pixel_height, output_dir)
"copied_full_source": True,
"skipped": False,
}
theme_results = export_themes(nr_buildings_path)
aoi_path = summary_dir / config.AOI_OUTPUT_FILENAME
shutil.copy2(config.AOI_GPKG, aoi_path)
normalize_aoi_gpkg(aoi_path)
with open_read_connection(aoi_path) as aoi_conn:
aoi_layer = resolve_feature_layer(aoi_conn, config.AOI_LAYER)
aoi_extent = gpkg_layer_extent(aoi_conn, aoi_layer)
aoi_result = {
"output": str(aoi_path),
"layer_name": config.AOI_LAYER,
"extent": list(aoi_extent) if aoi_extent else None,
}
result_xlsx = create_result_xlsx(
summary_dir / "Result.xlsx",
next(item["output"] for item in theme_results if item["name"] == "移动C端采样点比例_楼宇"),
aoi_path,
)
nr_buildings_path.unlink()
gis_project_path = summary_dir / config.GIS_PROJECT_OUTPUT_FILENAME
gis_project_result = copy_gis_project_to_market(
config.GIS_PROJECT_SOURCE,
@@ -239,6 +248,9 @@ def process_summary_grid_outputs(markets, pixel_width, pixel_height, output_dir)
summary_market,
building_info_extent,
competitor_signal_result["raster_extent"],
aoi_result=aoi_result,
building_themes_result=nr_buildings_result,
include_online=False,
)
zip_result = write_market_zip(summary_dir, zip_path, summary_market)
legacy_zip_path = output_dir / config.LEGACY_SUMMARY_OUTPUT_FILENAME
@@ -246,13 +258,15 @@ def process_summary_grid_outputs(markets, pixel_width, pixel_height, output_dir)
remove_file_with_retry(legacy_zip_path)
return {
"market_code": summary_market.code,
# "excellent_heatmap_result": rewrite_result_for_zip(user_count_result, zip_path, summary_dir),
"competitor_signal_result": rewrite_result_for_zip(
competitor_signal_result,
zip_path,
summary_dir,
),
"building_info_result": rewrite_result_for_zip(building_info_result, zip_path, summary_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),
"gis_project_result": rewrite_result_for_zip(gis_project_result, zip_path, summary_dir),
"zip_result": zip_result,
"elapsed_seconds": perf_counter() - started_at,
+8 -8
View File
@@ -208,11 +208,11 @@ def export_market_building_metrics_csv(
"建筑名称",
"经度",
"纬度",
"竟对采样点总",
"竟对弱覆盖采样点",
"竟对平均信号值",
"竞对采样点总",
"竞对弱覆盖采样点",
"竞对平均信号值",
"移动信号",
"竟对信号",
"竞对信号",
]
csv_rows = []
matched_names = 0
@@ -242,9 +242,9 @@ def grid_metrics_headers():
"区域名称",
"经度",
"纬度",
"竟对采样点总",
"竟对弱覆盖采样点",
"竟对平均信号值",
"竞对采样点总",
"竞对弱覆盖采样点",
"竞对平均信号值",
"移动信号",
"竟对信号",
"竞对信号",
]
+10 -2
View File
@@ -33,7 +33,7 @@ def main(settings=None, progress=None):
if not 0 <= config.COMPETITOR_SIGNAL_WEAK_RATIO_MIN <= 100:
raise ValueError("COMPETITOR_SIGNAL_WEAK_RATIO_MIN 必须在 0 到 100 之间")
if len(config.COMPETITOR_SIGNAL_RSRP_COLORS) != len(config.COMPETITOR_SIGNAL_RSRP_BREAKS) + 1:
raise ValueError("竟对信号 RSRP 颜色数量必须比分界点数量多 1")
raise ValueError("竞对信号 RSRP 颜色数量必须比分界点数量多 1")
if any(
left >= right
for left, right in zip(
@@ -48,6 +48,14 @@ def main(settings=None, progress=None):
raise ValueError("SUMMARY_MAX_RASTER_PIXELS 必须大于 0")
if config.CLIP_MODE not in {"intersects", "center"}:
raise ValueError("CLIP_MODE 必须是 intersects 或 center")
if config.AOI_CSV:
from .aoi_match import build_matched_aoi
print("正在按最大接触面积匹配 AOI……")
aoi_match = build_matched_aoi(config.AOI_CSV, config.MARKET_GPKG, config.AOI_GPKG)
print(
f"AOI 匹配完成:{aoi_match['matched']} 条已归属,"
f"{aoi_match['unassigned']} 条未纳入,输出 {aoi_match['output']}"
)
required_files = (
config.MARKET_GPKG,
config.GRID_5G_GPKG,
@@ -137,7 +145,7 @@ def main(settings=None, progress=None):
print(f"BuildingInfo 图层:{layer_names['building_info']}")
print(f"像元大小:{pixel_width}, {pixel_height}")
# print(f"用户量图例:{excellent_legend_path}")
print(f"竟对信号图例:{competitor_signal_legend_path}")
print(f"竞对信号图例:{competitor_signal_legend_path}")
started_at = perf_counter()
outcomes = []
+95
View File
@@ -1,9 +1,16 @@
"""QGIS 工程图层与范围更新。"""
from pathlib import Path
import copy
import xml.etree.ElementTree as ET
import zipfile
from urllib.parse import quote
from . import config
ONLINE_LAYER_NAME = "online"
# QGIS 会把过于简单的 ID(例如 "online")换成随机 ID,导致图层树节点失联、显示为无效图层。
ONLINE_LAYER_ID = "online_5b0d6f3c_8a41_4e2b_9c7d_2f6a1e8b3d90"
BING_LAYER_NAME = "必应地图"
def set_xml_extent(extent_element, extent):
for tag, value in zip(("xmin", "ymin", "xmax", "ymax"), extent):
@@ -150,6 +157,91 @@ def add_nr_buildings_layer(root, result, fallback_extent):
legend.insert(0, legend_layer)
def online_table_name(market_name):
"""市场名称作为统计 table。只编码一次,留给 QGIS 的 {z}/{x}/{y} 不编码。"""
text = str(market_name or "").strip()
if not text or len(text) > 64 or any(ch not in "_-" and not ch.isalnum() for ch in text):
raise ValueError(f"市场名称不能作为在线统计图层标识:{market_name}")
return quote(text, safe="")
def online_tile_url(market_name):
table = online_table_name(market_name)
return f"https://xyz.asio.asia/tiles/{table}/{{z}}/{{x}}/{{y}}.png"
def online_tile_datasource(market_name):
# 与模板 GoogleCN 一致:url 整段再编码一次,QGIS 解码后仍是纯 ASCII 的 %E5...,
# 否则解码出中文,QField 会把图层判为无效。
return f"http-header:referer=&type=xyz&url={quote(online_tile_url(market_name), safe='')}"
def _insert_after(parent, existing, new):
parent.insert(list(parent).index(existing) + 1, new)
def add_online_basemap(root, market_name):
"""在必应地图下方加入默认勾选的在线统计底图。"""
datasource = online_tile_datasource(market_name)
bing = next(
(layer for layer in root.findall(".//projectlayers/maplayer") if layer.findtext("layername") == BING_LAYER_NAME),
None,
)
tree = root.find("layer-tree-group")
tree_node = None if tree is None else next(
(item for item in tree.findall("layer-tree-layer") if item.get("name") == BING_LAYER_NAME),
None,
)
if bing is None and tree_node is None:
return
if bing is None or tree_node is None:
raise ValueError("QGIS 项目模板缺少必应地图图层")
layer = copy.deepcopy(bing)
layer.find("id").text = ONLINE_LAYER_ID
layer.find("datasource").text = datasource
layer.find("layername").text = ONLINE_LAYER_NAME
_insert_after(root.find("projectlayers"), bing, layer)
new_tree = copy.deepcopy(tree_node)
new_tree.set("id", ONLINE_LAYER_ID)
new_tree.set("name", ONLINE_LAYER_NAME)
new_tree.set("source", datasource)
new_tree.set("checked", "Qt::Checked")
_insert_after(tree, tree_node, new_tree)
bing_id = tree_node.get("id")
order = tree.find("custom-order")
if order is not None:
item = ET.Element("item")
item.text = ONLINE_LAYER_ID
existing = next((child for child in order if (child.text or "").strip() == bing_id), None)
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") == bing_id), None)
new_item = ET.Element("layer", id=ONLINE_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") == BING_LAYER_NAME), None)
legend_layer = ET.Element("legendlayer", {
"name": ONLINE_LAYER_NAME, "checked": "Qt::Checked", "open": "false", "drawingOrder": "-1",
})
group = ET.SubElement(legend_layer, "filegroup", hidden="false", open="false")
ET.SubElement(group, "legendlayerfile", layerid=ONLINE_LAYER_ID, visible="1", isInOverview="0")
if existing is None:
legend.append(legend_layer)
else:
_insert_after(legend, existing, legend_layer)
def copy_gis_project_to_market(
source_path,
output_path,
@@ -160,6 +252,7 @@ def copy_gis_project_to_market(
aoi_result=None,
nr_buildings_result=None,
building_themes_result=None,
include_online=True,
):
if output_path.exists() and not config.OVERWRITE:
return {
@@ -200,6 +293,8 @@ def copy_gis_project_to_market(
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)
if include_online:
add_online_basemap(root, market.name)
canvas = root.find(".//mapcanvas[@name='theMapCanvas']")
if canvas is None:
raise ValueError("QGIS 项目模板缺少主画布 theMapCanvas")
+46 -11
View File
@@ -1,20 +1,57 @@
"""按市场成果生成 Result.xlsx。"""
from contextlib import closing
from pathlib import Path
import sqlite3
from . import config
BUILDING_COLUMNS = [
("building_id", "楼宇ID", False),
("longitude", "经度", False),
("latitude", "纬度", False),
("mro_ratio_yd", "移动采样点占比", True),
("mro_ratio_dx", "电信采样点占比", True),
("mro_ratio_lt", "联通采样点占比", True),
("mro_ratio_gd", "广电采样点占比", True),
("mro_ratio_dxlt", "电联采样点占比", True),
]
AOI_COLUMNS = [
("所属市场网格", "所属市场网格", False),
("AOI唯一标签", "AOI唯一标签", False),
("AOI名称", "AOI名称", False),
("移动C端采样点占比", "移动C端采样点占比", True),
("联通C端采样点占比", "联通C端采样点占比", True),
("电信C端采样点占比", "电信C端采样点占比", True),
("广电C端采样点占比", "广电C端采样点占比", True),
("电联C端采样点占比", "电联C端采样点占比", True),
]
def _write_sheet(workbook, title, gpkg_path, table_name, fields, widths):
def _percent_text(value):
"""源数据已是百分数,写成文本 99.65%,不依赖单元格格式。"""
if value is None or value == "":
return None
text = str(value).strip()
if text.endswith("%"):
return text
return f"{float(text):.2f}%"
def _write_sheet(workbook, title, gpkg_path, table_name, columns, widths):
from openpyxl.styles import Font, PatternFill, Border, Side, Alignment
from openpyxl.utils import get_column_letter
from openpyxl.worksheet.table import Table, TableStyleInfo
sheet = workbook.create_sheet(title[:31])
sheet.append(fields)
quoted = ', '.join('"' + field.replace('"', '""') + '"' for field in fields)
with sqlite3.connect(gpkg_path) as conn:
for row in conn.execute(f'SELECT {quoted} FROM "{table_name}"'):
sheet.append(row)
sheet.append([label for _, label, _ in columns])
quoted = ", ".join('"' + name.replace('"', '""') + '"' for name, _, _ in columns)
with closing(sqlite3.connect(gpkg_path)) as conn:
rows = list(conn.execute(f'SELECT {quoted} FROM "{table_name}"'))
percent_at = [index for index, (_, _, percent) in enumerate(columns) if percent]
for row in rows:
values = list(row)
for index in percent_at:
values[index] = _percent_text(values[index])
sheet.append(values)
header_fill = PatternFill("solid", fgColor="D9EAF7")
thin = Side(style="thin", color="D9E2F3")
for cell in sheet[1]:
@@ -24,7 +61,7 @@ def _write_sheet(workbook, title, gpkg_path, table_name, fields, widths):
cell.alignment = Alignment(vertical="center")
for index, width in enumerate(widths, 1):
sheet.column_dimensions[get_column_letter(index)].width = width
sheet.auto_filter.ref = f"A1:{get_column_letter(len(fields))}{sheet.max_row}"
sheet.auto_filter.ref = f"A1:{get_column_letter(len(columns))}{sheet.max_row}"
sheet.freeze_panes = "A2"
table = Table(displayName=f"Table{len(workbook.worksheets)}", ref=sheet.auto_filter.ref)
table.tableStyleInfo = TableStyleInfo(name="TableStyleMedium2", showFirstColumn=False, showLastColumn=False, showRowStripes=False, showColumnStripes=False)
@@ -36,10 +73,8 @@ def create_result_xlsx(output_path, building_gpkg, aoi_gpkg):
from openpyxl import Workbook
workbook = Workbook()
workbook.remove(workbook.active)
building_fields = ["building_id", "longitude", "latitude", "mro_ratio_yd", "mro_ratio_dx", "mro_ratio_lt", "mro_ratio_gd", "mro_ratio_dxlt"]
aoi_fields = ["所属市场网格", "AOI唯一标签", "AOI名称", "移动C端采样点占比", "联通C端采样点占比", "电信C端采样点占比", "广电C端采样点占比", "电联C端采样点占比"]
building_count = _write_sheet(workbook, "移动C端采样点比例_楼宇", building_gpkg, "NRBuildingsData", building_fields, [15, 12, 12, 14, 14, 14, 14, 14])
aoi_count = _write_sheet(workbook, "移动C端采样点比例_AOI", aoi_gpkg, config.AOI_LAYER, aoi_fields, [16, 18, 40, 18, 18, 18, 18, 18])
building_count = _write_sheet(workbook, "移动C端采样点比例_楼宇", building_gpkg, "NRBuildingsData", BUILDING_COLUMNS, [16, 12, 12, 16, 16, 16, 16, 16])
aoi_count = _write_sheet(workbook, "移动C端采样点比例_AOI", aoi_gpkg, config.AOI_LAYER, AOI_COLUMNS, [16, 18, 40, 20, 20, 20, 20, 20])
output_path = Path(output_path)
output_path.parent.mkdir(parents=True, exist_ok=True)
workbook.save(output_path)
+1 -1
View File
@@ -2,7 +2,7 @@
"移动C端采样点比例_楼宇": "Qt::Unchecked",
"移动WIFI设备占比图层": "Qt::Unchecked",
"移动C端采样点比例_AOI": "Qt::Unchecked",
"竟对信号": "Qt::Unchecked",
"竞对信号": "Qt::Unchecked",
"BuildInfo": "Qt::Unchecked",
"GoogleCN": "Qt::Checked",
"必应地图": "Qt::Unchecked"