Files
MarketGrid/main.py
T

1042 lines
40 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import csv
import json
import math
import re
import sqlite3
from dataclasses import dataclass
from pathlib import Path
import numpy as np
import tifffile
from shapely import Point, from_wkb
from shapely.errors import GEOSException
from shapely.prepared import prep
DEFAULT_SOURCE_DIR = Path("source") # 源数据目录,存放 MarketMap.gpkg、grid.gpkg 等输入文件。
OUTPUT_DIR = Path("output") # 输出根目录,每个市场网格会在这里生成一个 JMXXXX 文件夹。
MARKET_GPKG = DEFAULT_SOURCE_DIR / "MarketMap.gpkg" # 市场网格 GeoPackage 文件路径。
GRID_GPKG = DEFAULT_SOURCE_DIR / "grid.gpkg" # Grid 栅格指标 GeoPackage 文件路径。
BUILDING_INFO_GPKG = DEFAULT_SOURCE_DIR / "BuildingInfo.gpkg" # 建筑信息 GeoPackage 文件路径,拆分时保留原始图层和 QGIS 样式。
RSRP_FIELD = "ssb_rsrp_dl" # 用于生成热力图的电信 RSRP 字段名。
EXCELLENT_CELL_FIELD = "mro_total_dl" # 用于生成用户量热力图的字段名,值越大越红。
WEAK_COVER_FIELD = "rsrp_lt_neg105_dl" # 用于生成信号差用户量热力图的字段名,值越大越红。
MARKET_LAYER = None # 市场网格图层名;None 表示自动使用 GPKG 中第一个 feature 图层。
GRID_LAYER = None # Grid 指标图层名;None 表示自动使用 GPKG 中第一个 feature 图层。
BUILDING_INFO_LAYER = None # BuildingInfo 图层名;None 表示自动使用 GPKG 中第一个 feature 图层。
MARKET_CODE_FIELD = "micro_grid" # 市场网格编码字段,用于输出文件夹名,例如 JM010404。
MARKET_NAME_FIELD = "micro_gr_1" # 市场网格名称字段,用于日志和汇总信息。
SIGNAL_OUTPUT_FILENAME = "信号.tif" # RSRP 连续热力图输出文件名。
BUILDING_INFO_OUTPUT_FILENAME = "BuildingInfo.gpkg" # 每个市场网格目录内输出的建筑信息拆分文件名。
HEATMAP_GOOD_RSRP = -80.0 # 热力图绿色端阈值;RSRP 大于等于该值视为信号好。
HEATMAP_MID_RSRP = -95.0 # 热力图黄色中间阈值。
HEATMAP_BAD_RSRP = -110.0 # 热力图红色端阈值;RSRP 小于等于该值视为信号差。
HEATMAP_SMOOTH_RADIUS = 10 # 热力图平滑半径,数值越大边界感越弱但细节越柔。
HEATMAP_ALPHA = 191 # 热力图有效像元透明度;191 约等于 75% 不透明度。
USER_COUNT_OUTPUT_FILENAME = "用户量.tif" # 采样点数量热力图输出文件名。
WEAK_COVER_OUTPUT_FILENAME = "信号差用户量.tif" # 信号差用户量热力图输出文件名。
EXCELLENT_PERCENT_STEPS = (0.2, 0.4, 0.6) # 去重值降序分位阈值,默认按前 20%、40%、60% 作为连续渐变控制点。
EXCELLENT_COLORS = (
(255, 0, 0), # 高值端,红色。
(255, 255, 0), # 偏高值,黄色。
(0, 112, 255), # 偏低值,蓝色。
(0, 176, 80), # 低值端,绿色。
)
PIXEL_WIDTH = None # 输出像元宽度;None 表示自动按 Grid 单元宽度估算。
PIXEL_HEIGHT = None # 输出像元高度;None 表示自动按 Grid 单元高度估算。
SCALE = 5.0 # 分辨率倍数;2.0 表示像元宽高减半,放大查看更清晰。
SAMPLE_SIZE = 10000 # 自动估算像元大小时抽样读取的 Grid 要素数量。
LIMIT = 1 # 限制处理前 N 个市场网格;None 表示处理全部市场网格。
CLIP_MODE = "intersects" # 裁切方式:intersects 按几何相交裁切,center 按 Grid 中心点落入裁切。
BUILDING_INFO_ALLOWED_SRS_IDS = (4326, 100000) # BuildingInfo 允许的经纬度坐标系 ID;100000 是源文件中的 CRS84。
OVERWRITE = True # 输出文件已存在时是否覆盖。
TRANSPARENT_PIXEL = (0, 0, 0, 0) # 无数据/背景像元颜色,RGBA 中 alpha=0 表示透明。
@dataclass(frozen=True)
class LayerInfo:
table_name: str
geom_col: str
pk_col: str
srs_id: int
@dataclass(frozen=True)
class MarketFeature:
fid: int
code: str
name: str
geometry: object
def quote_identifier(name):
return '"' + str(name).replace('"', '""') + '"'
def safe_filename(value):
text = str(value or "").strip()
text = re.sub(r'[<>:"/\\|?*\s]+', "_", text)
text = text.strip("._")
return text or "unnamed"
def market_output_dir(output_dir, market):
return output_dir / safe_filename(market.code)
def heatmap_raster_filename(_field):
return SIGNAL_OUTPUT_FILENAME
def excellent_heatmap_raster_filename(_field):
return USER_COUNT_OUTPUT_FILENAME
def weak_cover_heatmap_raster_filename(_field):
return WEAK_COVER_OUTPUT_FILENAME
def building_info_output_path(output_dir, market):
return market_output_dir(output_dir, market) / BUILDING_INFO_OUTPUT_FILENAME
def gpkg_blob_to_wkb(blob):
data = bytes(blob)
if data[:2] != b"GP":
return data
flags = data[3]
envelope_code = (flags >> 1) & 0b111
envelope_sizes = {
0: 0,
1: 32,
2: 48,
3: 48,
4: 64,
}
return data[8 + envelope_sizes.get(envelope_code, 0):]
def gpkg_primary_key(conn, table_name):
for row in conn.execute(f"pragma table_info({quote_identifier(table_name)})"):
if row[5]:
return row[1]
return "fid"
def resolve_feature_layer(conn, preferred_table=None):
rows = conn.execute(
"""
select c.table_name, g.column_name, g.srs_id
from gpkg_contents c
join gpkg_geometry_columns g on c.table_name = g.table_name
where c.data_type = 'features'
order by c.table_name
"""
).fetchall()
if not rows:
raise ValueError("未找到 GeoPackage feature 图层")
if preferred_table:
for table_name, geom_col, srs_id in rows:
if table_name == preferred_table:
return LayerInfo(table_name, geom_col, gpkg_primary_key(conn, table_name), srs_id)
raise ValueError(f"未找到指定图层:{preferred_table}")
table_name, geom_col, srs_id = rows[0]
return LayerInfo(table_name, geom_col, gpkg_primary_key(conn, table_name), srs_id)
def table_columns(conn, table_name):
return [row[1] for row in conn.execute(f"pragma table_info({quote_identifier(table_name)})")]
def require_columns(conn, table_name, columns):
available = set(table_columns(conn, table_name))
missing = [column for column in columns if column not in available]
if missing:
raise ValueError(f"{table_name} 缺少字段:{', '.join(missing)}")
def rtree_name(conn, layer):
candidate = f"rtree_{layer.table_name}_{layer.geom_col}"
found = conn.execute(
"select 1 from sqlite_master where type='table' and name=?",
(candidate,),
).fetchone()
if not found:
raise ValueError(f"未找到 RTree 空间索引:{candidate}")
return candidate
def table_exists(conn, table_name):
return conn.execute(
"select 1 from sqlite_master where type = 'table' and name = ?",
(table_name,),
).fetchone() is not None
def sqlite_create_sql(conn, table_name):
row = conn.execute(
"select sql from sqlite_master where type = 'table' and name = ?",
(table_name,),
).fetchone()
if not row or not row[0]:
raise ValueError(f"未找到表结构:{table_name}")
return row[0]
def copy_all_rows(source_conn, target_conn, table_name):
if not table_exists(source_conn, table_name):
return
rows = source_conn.execute(f"select * from {quote_identifier(table_name)}").fetchall()
if not rows:
return
placeholders = ", ".join(["?"] * len(rows[0]))
target_conn.executemany(
f"insert into {quote_identifier(table_name)} values ({placeholders})",
rows,
)
def copy_matching_rows(target_conn, table_name, columns, rows):
if not rows:
return
column_sql = ", ".join(quote_identifier(column) for column in columns)
placeholders = ", ".join(["?"] * len(columns))
target_conn.executemany(
f"insert into {quote_identifier(table_name)} ({column_sql}) values ({placeholders})",
rows,
)
def create_source_table_schema(source_conn, target_conn, table_name):
if table_exists(source_conn, table_name):
target_conn.execute(sqlite_create_sql(source_conn, table_name))
def copy_gpkg_support_tables(source_conn, target_conn, layer, feature_count, extent):
support_tables = [
"gpkg_spatial_ref_sys",
"gpkg_contents",
"gpkg_geometry_columns",
"gpkg_ogr_contents",
"gpkg_extensions",
"gpkg_metadata",
"gpkg_metadata_reference",
"gpkg_tile_matrix_set",
"gpkg_tile_matrix",
"layer_styles",
]
for table_name in support_tables:
create_source_table_schema(source_conn, target_conn, table_name)
for table_name in support_tables:
copy_all_rows(source_conn, target_conn, table_name)
minx, miny, maxx, maxy = extent if extent else (None, None, None, None)
target_conn.execute(
"""
update gpkg_contents
set min_x = ?, min_y = ?, max_x = ?, max_y = ?
where table_name = ?
""",
(minx, miny, maxx, maxy, layer.table_name),
)
if table_exists(target_conn, "gpkg_ogr_contents"):
target_conn.execute(
"update gpkg_ogr_contents set feature_count = ? where table_name = ?",
(feature_count, layer.table_name),
)
def initialize_output_gpkg(source_conn, output_path, layer, feature_count, extent):
if output_path.exists():
if not OVERWRITE:
return None
output_path.unlink()
target_conn = sqlite3.connect(output_path)
target_conn.execute("pragma foreign_keys = off")
target_conn.execute(f"pragma application_id = {source_conn.execute('pragma application_id').fetchone()[0]}")
target_conn.execute(f"pragma user_version = {source_conn.execute('pragma user_version').fetchone()[0]}")
copy_gpkg_support_tables(source_conn, target_conn, layer, feature_count, extent)
target_conn.execute(sqlite_create_sql(source_conn, layer.table_name))
target_conn.execute(sqlite_create_sql(source_conn, rtree_name(source_conn, layer)))
return target_conn
def collect_intersecting_features(source_conn, layer, rtree, market):
table = quote_identifier(layer.table_name)
pk = quote_identifier(layer.pk_col)
rtree_table = quote_identifier(rtree)
columns = table_columns(source_conn, layer.table_name)
column_sql = ", ".join(f"b.{quote_identifier(column)}" for column in columns)
min_market_x, min_market_y, max_market_x, max_market_y = market.geometry.bounds
query = f"""
select {column_sql}
from {rtree_table} r
join {table} b on b.{pk} = r."id"
where r."minx" <= ?
and r."maxx" >= ?
and r."miny" <= ?
and r."maxy" >= ?
"""
geom_index = columns.index(layer.geom_col)
pk_index = columns.index(layer.pk_col)
prepared_market = prep(market.geometry)
rows = []
rtree_rows = []
extent = None
candidates = 0
for row in source_conn.execute(query, (max_market_x, min_market_x, max_market_y, min_market_y)):
candidates += 1
geom_blob = row[geom_index]
if geom_blob is None:
continue
try:
geometry = from_wkb(gpkg_blob_to_wkb(geom_blob))
except (GEOSException, ValueError):
continue
if geometry.is_empty or not prepared_market.intersects(geometry):
continue
minx, miny, maxx, maxy = geometry.bounds
rows.append(row)
rtree_rows.append((row[pk_index], minx, maxx, miny, maxy))
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)
return columns, rows, rtree_rows, tuple(extent) if extent else None, candidates
def export_market_building_info_gpkg(source_conn, layer, rtree, market, output_path):
columns, rows, rtree_rows, extent, candidates = collect_intersecting_features(
source_conn,
layer,
rtree,
market,
)
target_conn = initialize_output_gpkg(source_conn, output_path, layer, len(rows), extent)
if target_conn is None:
return {
"market_code": market.code,
"market_name": market.name,
"output": str(output_path),
"candidates": candidates,
"feature_count": None,
"skipped": True,
}
try:
copy_matching_rows(target_conn, layer.table_name, columns, rows)
if rtree_rows:
target_conn.executemany(
f"insert into {quote_identifier(rtree)} values (?, ?, ?, ?, ?)",
rtree_rows,
)
target_conn.commit()
finally:
target_conn.close()
return {
"market_code": market.code,
"market_name": market.name,
"output": str(output_path),
"candidates": candidates,
"feature_count": len(rows),
"skipped": False,
}
def load_market_features(conn, layer, code_field, name_field):
require_columns(conn, layer.table_name, [code_field, name_field])
table = quote_identifier(layer.table_name)
pk = quote_identifier(layer.pk_col)
geom = quote_identifier(layer.geom_col)
code = quote_identifier(code_field)
name = quote_identifier(name_field)
query = f"select {pk}, {code}, {name}, {geom} from {table} order by {pk}"
features = []
for fid, market_code, market_name, geom_blob in conn.execute(query):
if geom_blob is None:
continue
try:
geometry = from_wkb(gpkg_blob_to_wkb(geom_blob))
except (GEOSException, ValueError):
continue
if not geometry.is_empty:
features.append(MarketFeature(fid, str(market_code or fid), str(market_name or fid), geometry))
return features
def estimate_pixel_size(conn, layer, sample_size):
table = quote_identifier(layer.table_name)
geom = quote_identifier(layer.geom_col)
widths = []
heights = []
query = f"select {geom} from {table} where {geom} is not null limit ?"
for (geom_blob,) in conn.execute(query, (sample_size,)):
try:
geometry = from_wkb(gpkg_blob_to_wkb(geom_blob))
except (GEOSException, ValueError):
continue
minx, miny, maxx, maxy = geometry.bounds
width = maxx - minx
height = maxy - miny
if width > 0 and height > 0:
widths.append(width)
heights.append(height)
if not widths or not heights:
raise ValueError("无法从 Grid 图层估算像元大小")
return float(np.median(widths)), float(np.median(heights))
def interpolate_color(start_color, end_color, ratio):
ratio = np.clip(ratio, 0.0, 1.0)[..., np.newaxis]
start = np.array(start_color, dtype=np.float32)
end = np.array(end_color, dtype=np.float32)
return start + (end - start) * ratio
def heatmap_rgb_for_values(values):
red = (255, 0, 0)
yellow = (255, 255, 191)
green = (26, 152, 80)
result = np.zeros((*values.shape, 3), dtype=np.float32)
lower = values < HEATMAP_MID_RSRP
upper = ~lower
if np.any(lower):
ratio = (values[lower] - HEATMAP_BAD_RSRP) / (HEATMAP_MID_RSRP - HEATMAP_BAD_RSRP)
result[lower] = interpolate_color(red, yellow, ratio)
if np.any(upper):
ratio = (values[upper] - HEATMAP_MID_RSRP) / (HEATMAP_GOOD_RSRP - HEATMAP_MID_RSRP)
result[upper] = interpolate_color(yellow, green, ratio)
return np.clip(result, 0, 255).astype(np.uint8)
def percentile_thresholds_from_unique(values, percent_steps):
unique_values = sorted({value for value in values if value is not None}, reverse=True)
if not unique_values:
return []
thresholds = []
for percent in percent_steps:
index = max(0, math.ceil(len(unique_values) * percent) - 1)
index = min(index, len(unique_values) - 1)
thresholds.append(unique_values[index])
return thresholds
def excellent_rgb_for_values(values, thresholds):
result = np.zeros((*values.shape, 3), dtype=np.float32)
if len(thresholds) < 3:
result[:] = EXCELLENT_COLORS[-1]
return result.astype(np.uint8)
red_threshold, yellow_threshold, blue_threshold = thresholds[:3]
red, yellow, blue, green = EXCELLENT_COLORS
high = values >= red_threshold
high_middle = (values < red_threshold) & (values >= yellow_threshold)
low_middle = (values < yellow_threshold) & (values >= blue_threshold)
low = values < blue_threshold
if np.any(high):
result[high] = red
if np.any(high_middle):
ratio = (values[high_middle] - yellow_threshold) / max(red_threshold - yellow_threshold, 1e-9)
result[high_middle] = interpolate_color(yellow, red, ratio)
if np.any(low_middle):
ratio = (values[low_middle] - blue_threshold) / max(yellow_threshold - blue_threshold, 1e-9)
result[low_middle] = interpolate_color(blue, yellow, ratio)
if np.any(low):
min_value = float(np.min(values[low])) if np.any(low) else blue_threshold
ratio = (values[low] - min_value) / max(blue_threshold - min_value, 1e-9)
result[low] = interpolate_color(green, blue, ratio)
return np.clip(result, 0, 255).astype(np.uint8)
def gaussian_kernel(radius):
if radius <= 0:
return np.array([1.0], dtype=np.float32)
sigma = max(radius / 2.0, 0.1)
x = np.arange(-radius, radius + 1, dtype=np.float32)
kernel = np.exp(-(x * x) / (2.0 * sigma * sigma))
return kernel / kernel.sum()
def convolve_axis(array, kernel, axis):
if kernel.size == 1:
return array
radius = kernel.size // 2
pad_width = [(0, 0)] * array.ndim
pad_width[axis] = (radius, radius)
padded = np.pad(array, pad_width, mode="edge")
moved = np.moveaxis(padded, axis, 0)
output = np.empty_like(np.moveaxis(array, axis, 0), dtype=np.float32)
for index in range(output.shape[0]):
window = moved[index:index + kernel.size]
output[index] = np.tensordot(kernel, window, axes=(0, 0))
return np.moveaxis(output, 0, axis)
def gaussian_blur(array, radius):
kernel = gaussian_kernel(radius)
blurred = convolve_axis(array.astype(np.float32), kernel, axis=0)
return convolve_axis(blurred, kernel, axis=1)
def to_float(value):
if value is None:
return None
try:
text = str(value).strip()
if not text:
return None
return float(text)
except ValueError:
return None
def geotiff_extratags(minx, maxy, pixel_width, pixel_height):
model_pixel_scale = (pixel_width, pixel_height, 0.0)
model_tiepoint = (0.0, 0.0, 0.0, minx, maxy, 0.0)
geo_key_directory = (
1, 1, 0, 4,
1024, 0, 1, 2,
1025, 0, 1, 1,
2048, 0, 1, 4326,
2054, 0, 1, 9102,
)
return [
(33550, "d", 3, model_pixel_scale, False),
(33922, "d", 6, model_tiepoint, False),
(34735, "H", len(geo_key_directory), geo_key_directory, False),
]
def write_rgba_geotiff(path, image, minx, maxy, pixel_width, pixel_height):
tifffile.imwrite(
path,
image,
photometric="rgb",
extrasamples=["unassalpha"],
metadata=None,
extratags=geotiff_extratags(minx, maxy, pixel_width, pixel_height),
)
def create_canvas(bounds, pixel_width, pixel_height):
minx, miny, maxx, maxy = bounds
width = max(1, int(math.ceil((maxx - minx) / pixel_width)))
height = max(1, int(math.ceil((maxy - miny) / pixel_height)))
image = np.full((height, width, 4), TRANSPARENT_PIXEL, dtype=np.uint8)
return image, minx, maxy
def pixel_window_for_bounds(bounds, minx, maxy, pixel_width, pixel_height, width, height):
geom_minx, geom_miny, geom_maxx, geom_maxy = bounds
col_start = max(0, int(math.floor((geom_minx - minx) / pixel_width)))
col_stop = min(width, int(math.ceil((geom_maxx - minx) / pixel_width)))
row_start = max(0, int(math.floor((maxy - geom_maxy) / pixel_height)))
row_stop = min(height, int(math.ceil((maxy - geom_miny) / pixel_height)))
if row_start >= row_stop or col_start >= col_stop:
return None
return row_start, row_stop, col_start, col_stop
def pixel_window_from_point(x, y, minx, maxy, pixel_width, pixel_height, width, height):
col = int((x - minx) / pixel_width)
row = int((maxy - y) / pixel_height)
if 0 <= row < height and 0 <= col < width:
return row, row + 1, col, col + 1
return None
def export_market_heatmap_tif(grid_conn, grid_layer, rtree, market, field, pixel_width, pixel_height, output_path):
image, minx, maxy = create_canvas(market.geometry.bounds, pixel_width, pixel_height)
height, width = image.shape[:2]
value_sum = np.zeros((height, width), dtype=np.float32)
value_weight = np.zeros((height, width), dtype=np.float32)
prepared_market = prep(market.geometry)
table = quote_identifier(grid_layer.table_name)
geom = quote_identifier(grid_layer.geom_col)
pk = quote_identifier(grid_layer.pk_col)
rtree_table = quote_identifier(rtree)
field_expr = quote_identifier(field)
lon_expr = quote_identifier("longitude")
lat_expr = quote_identifier("latitude")
min_market_x, min_market_y, max_market_x, max_market_y = market.geometry.bounds
query = f"""
select b.{pk}, b.{geom}, b.{field_expr}, b.{lon_expr}, b.{lat_expr}
from {rtree_table} r
join {table} b on b.{pk} = r."id"
where r."minx" <= ?
and r."maxx" >= ?
and r."miny" <= ?
and r."maxy" >= ?
"""
params = (max_market_x, min_market_x, max_market_y, min_market_y)
total = 0
painted = 0
skipped_no_value = 0
for _fid, geom_blob, raw_value, raw_lon, raw_lat in grid_conn.execute(query, params):
total += 1
value = to_float(raw_value)
if value is None:
skipped_no_value += 1
continue
lon = to_float(raw_lon)
lat = to_float(raw_lat)
target_point = None
if lon is not None and lat is not None:
target_point = (lon, lat)
if CLIP_MODE == "intersects":
if geom_blob is None:
continue
try:
grid_geom = from_wkb(gpkg_blob_to_wkb(geom_blob))
except (GEOSException, ValueError):
continue
if not prepared_market.intersects(grid_geom):
continue
window = pixel_window_for_bounds(
grid_geom.bounds,
minx,
maxy,
pixel_width,
pixel_height,
width,
height,
)
else:
if target_point is None:
continue
if not prepared_market.covers(Point(target_point)):
continue
window = pixel_window_from_point(
target_point[0],
target_point[1],
minx,
maxy,
pixel_width,
pixel_height,
width,
height,
)
if window is None:
continue
row_start, row_stop, col_start, col_stop = window
value_sum[row_start:row_stop, col_start:col_stop] += value
value_weight[row_start:row_stop, col_start:col_stop] += 1.0
painted += 1
data_mask = value_weight > 0
if np.any(data_mask):
smoothed_sum = gaussian_blur(value_sum, HEATMAP_SMOOTH_RADIUS)
smoothed_weight = gaussian_blur(value_weight, HEATMAP_SMOOTH_RADIUS)
smoothed_value = np.zeros_like(value_sum)
np.divide(smoothed_sum, smoothed_weight, out=smoothed_value, where=smoothed_weight > 0)
smoothed_value = np.clip(smoothed_value, HEATMAP_BAD_RSRP, HEATMAP_GOOD_RSRP)
image[data_mask, :3] = heatmap_rgb_for_values(smoothed_value)[data_mask]
image[data_mask, 3] = HEATMAP_ALPHA
write_rgba_geotiff(output_path, image, minx, maxy, pixel_width, pixel_height)
return {
"market_code": market.code,
"market_name": market.name,
"output": str(output_path),
"candidates": total,
"painted_pixels": painted,
"data_pixels": int(np.count_nonzero(data_mask)),
"skipped_no_value": skipped_no_value,
"smooth_radius": HEATMAP_SMOOTH_RADIUS,
"width": width,
"height": height,
}
def export_market_excellent_heatmap_tif(
grid_conn,
grid_layer,
rtree,
market,
field,
pixel_width,
pixel_height,
output_path,
):
image, minx, maxy = create_canvas(market.geometry.bounds, pixel_width, pixel_height)
height, width = image.shape[:2]
value_sum = np.zeros((height, width), dtype=np.float32)
value_weight = np.zeros((height, width), dtype=np.float32)
prepared_market = prep(market.geometry)
table = quote_identifier(grid_layer.table_name)
geom = quote_identifier(grid_layer.geom_col)
pk = quote_identifier(grid_layer.pk_col)
rtree_table = quote_identifier(rtree)
field_expr = quote_identifier(field)
lon_expr = quote_identifier("longitude")
lat_expr = quote_identifier("latitude")
min_market_x, min_market_y, max_market_x, max_market_y = market.geometry.bounds
query = f"""
select b.{pk}, b.{geom}, b.{field_expr}, b.{lon_expr}, b.{lat_expr}
from {rtree_table} r
join {table} b on b.{pk} = r."id"
where r."minx" <= ?
and r."maxx" >= ?
and r."miny" <= ?
and r."maxy" >= ?
"""
params = (max_market_x, min_market_x, max_market_y, min_market_y)
candidates = 0
skipped_no_value = 0
matched_values = []
for _fid, geom_blob, raw_value, raw_lon, raw_lat in grid_conn.execute(query, params):
candidates += 1
value = to_float(raw_value)
if value is None:
skipped_no_value += 1
continue
lon = to_float(raw_lon)
lat = to_float(raw_lat)
target_point = None
if lon is not None and lat is not None:
target_point = (lon, lat)
if CLIP_MODE == "intersects":
if geom_blob is None:
continue
try:
grid_geom = from_wkb(gpkg_blob_to_wkb(geom_blob))
except (GEOSException, ValueError):
continue
if not prepared_market.intersects(grid_geom):
continue
window = pixel_window_for_bounds(
grid_geom.bounds,
minx,
maxy,
pixel_width,
pixel_height,
width,
height,
)
else:
if target_point is None:
continue
if not prepared_market.covers(Point(target_point)):
continue
window = pixel_window_from_point(
target_point[0],
target_point[1],
minx,
maxy,
pixel_width,
pixel_height,
width,
height,
)
if window is None:
continue
row_start, row_stop, col_start, col_stop = window
value_sum[row_start:row_stop, col_start:col_stop] += value
value_weight[row_start:row_stop, col_start:col_stop] += 1.0
matched_values.append(value)
thresholds = percentile_thresholds_from_unique(matched_values, EXCELLENT_PERCENT_STEPS)
data_mask = value_weight > 0
if np.any(data_mask):
smoothed_sum = gaussian_blur(value_sum, HEATMAP_SMOOTH_RADIUS)
smoothed_weight = gaussian_blur(value_weight, HEATMAP_SMOOTH_RADIUS)
smoothed_value = np.zeros_like(value_sum)
np.divide(smoothed_sum, smoothed_weight, out=smoothed_value, where=smoothed_weight > 0)
image[data_mask, :3] = excellent_rgb_for_values(smoothed_value, thresholds)[data_mask]
image[data_mask, 3] = HEATMAP_ALPHA
write_rgba_geotiff(output_path, image, minx, maxy, pixel_width, pixel_height)
return {
"market_code": market.code,
"market_name": market.name,
"output": str(output_path),
"candidates": candidates,
"painted_cells": len(matched_values),
"data_pixels": int(np.count_nonzero(image[..., 3] > 0)),
"skipped_no_value": skipped_no_value,
"unique_value_count": len(set(matched_values)),
"thresholds": thresholds,
"percent_steps": list(EXCELLENT_PERCENT_STEPS),
"width": width,
"height": height,
}
def write_heatmap_legend(output_dir, field):
legend_path = output_dir / "heatmap_legend.csv"
with legend_path.open("w", newline="", encoding="utf-8-sig") as file:
writer = csv.writer(file)
writer.writerow(["field", "rsrp", "red", "green", "blue", "alpha", "meaning"])
writer.writerow([field, HEATMAP_GOOD_RSRP, 26, 152, 80, HEATMAP_ALPHA, "good signal"])
writer.writerow([field, HEATMAP_MID_RSRP, 255, 255, 191, HEATMAP_ALPHA, "middle signal"])
writer.writerow([field, HEATMAP_BAD_RSRP, 255, 0, 0, HEATMAP_ALPHA, "bad signal"])
writer.writerow([field, "nodata", 0, 0, 0, 0, "transparent no data"])
return legend_path
def write_excellent_heatmap_legend(output_dir, field):
legend_path = output_dir / "excellent_heatmap_legend.csv"
with legend_path.open("w", newline="", encoding="utf-8-sig") as file:
writer = csv.writer(file)
writer.writerow(["field", "control_point", "red", "green", "blue", "alpha", "meaning"])
writer.writerow([field, "threshold_20_percent", *EXCELLENT_COLORS[0], HEATMAP_ALPHA, "high end"])
writer.writerow([field, "threshold_40_percent", *EXCELLENT_COLORS[1], HEATMAP_ALPHA, "high-middle control"])
writer.writerow([field, "threshold_60_percent", *EXCELLENT_COLORS[2], HEATMAP_ALPHA, "low-middle control"])
writer.writerow([field, "minimum", *EXCELLENT_COLORS[3], HEATMAP_ALPHA, "low end"])
writer.writerow([field, "nodata", 0, 0, 0, 0, "transparent no data"])
return legend_path
def write_weak_cover_heatmap_legend(output_dir, field):
legend_path = output_dir / "weak_cover_heatmap_legend.csv"
with legend_path.open("w", newline="", encoding="utf-8-sig") as file:
writer = csv.writer(file)
writer.writerow(["field", "control_point", "red", "green", "blue", "alpha", "meaning"])
writer.writerow([field, "threshold_20_percent", *EXCELLENT_COLORS[0], HEATMAP_ALPHA, "high end"])
writer.writerow([field, "threshold_40_percent", *EXCELLENT_COLORS[1], HEATMAP_ALPHA, "high-middle control"])
writer.writerow([field, "threshold_60_percent", *EXCELLENT_COLORS[2], HEATMAP_ALPHA, "low-middle control"])
writer.writerow([field, "minimum", *EXCELLENT_COLORS[3], HEATMAP_ALPHA, "low end"])
writer.writerow([field, "nodata", 0, 0, 0, 0, "transparent no data"])
return legend_path
def main():
if SCALE <= 0:
raise ValueError("SCALE 必须大于 0")
if CLIP_MODE not in {"intersects", "center"}:
raise ValueError("CLIP_MODE 必须是 intersects 或 center")
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
with (
sqlite3.connect(MARKET_GPKG) as market_conn,
sqlite3.connect(GRID_GPKG) as grid_conn,
sqlite3.connect(BUILDING_INFO_GPKG) as building_info_conn,
):
market_layer = resolve_feature_layer(market_conn, MARKET_LAYER)
grid_layer = resolve_feature_layer(grid_conn, GRID_LAYER)
building_info_layer = resolve_feature_layer(building_info_conn, BUILDING_INFO_LAYER)
if market_layer.srs_id != 4326 or grid_layer.srs_id != 4326:
raise ValueError("当前脚本只处理 EPSG:4326 的输入图层")
if building_info_layer.srs_id not in BUILDING_INFO_ALLOWED_SRS_IDS:
raise ValueError(f"BuildingInfo 图层坐标系不在允许范围内:{building_info_layer.srs_id}")
require_columns(
grid_conn,
grid_layer.table_name,
[RSRP_FIELD, EXCELLENT_CELL_FIELD, WEAK_COVER_FIELD, "longitude", "latitude"],
)
grid_rtree = rtree_name(grid_conn, grid_layer)
building_info_rtree = rtree_name(building_info_conn, building_info_layer)
pixel_width = PIXEL_WIDTH
pixel_height = PIXEL_HEIGHT
if pixel_width is None or pixel_height is None:
estimated_width, estimated_height = estimate_pixel_size(grid_conn, grid_layer, SAMPLE_SIZE)
pixel_width = pixel_width or estimated_width
pixel_height = pixel_height or estimated_height
pixel_width = pixel_width / SCALE
pixel_height = pixel_height / SCALE
markets = load_market_features(
market_conn,
market_layer,
MARKET_CODE_FIELD,
MARKET_NAME_FIELD,
)
if LIMIT:
markets = markets[:LIMIT]
heatmap_legend_path = write_heatmap_legend(OUTPUT_DIR, RSRP_FIELD)
excellent_legend_path = write_excellent_heatmap_legend(OUTPUT_DIR, EXCELLENT_CELL_FIELD)
weak_cover_legend_path = write_weak_cover_heatmap_legend(OUTPUT_DIR, WEAK_COVER_FIELD)
heatmap_results = []
excellent_heatmap_results = []
weak_cover_heatmap_results = []
building_info_results = []
print(f"市场网格数量:{len(markets)}")
print(f"Grid 图层:{grid_layer.table_name}")
print(f"BuildingInfo 图层:{building_info_layer.table_name}")
print(f"RSRP 字段:{RSRP_FIELD}")
print(f"采样点字段:{EXCELLENT_CELL_FIELD}")
print(f"信号差用户量字段:{WEAK_COVER_FIELD}")
print(f"分辨率倍数:{SCALE}")
print(f"像元大小:{pixel_width}, {pixel_height}")
print(f"热力图图例:{heatmap_legend_path}")
print(f"采样点热力图图例:{excellent_legend_path}")
print(f"信号差用户量热力图图例:{weak_cover_legend_path}")
for index, market in enumerate(markets, start=1):
market_dir = market_output_dir(OUTPUT_DIR, market)
market_dir.mkdir(parents=True, exist_ok=True)
heatmap_path = market_dir / heatmap_raster_filename(RSRP_FIELD)
if heatmap_path.exists() and not OVERWRITE:
print(f"[{index}/{len(markets)}] 跳过已存在热力图:{market.code}/{heatmap_path.name}")
heatmap_results.append(
{
"market_code": market.code,
"market_name": market.name,
"market_dir": str(market_dir),
"output": str(heatmap_path),
"skipped": True,
}
)
else:
print(f"[{index}/{len(markets)}] 导出热力图:{market.code} {market.name}")
heatmap_result = export_market_heatmap_tif(
grid_conn,
grid_layer,
grid_rtree,
market,
RSRP_FIELD,
pixel_width,
pixel_height,
heatmap_path,
)
heatmap_result["market_dir"] = str(market_dir)
heatmap_result["skipped"] = False
heatmap_results.append(heatmap_result)
print(
f" 热力图像素:{heatmap_result['width']}x{heatmap_result['height']},"
f"有效像素:{heatmap_result['data_pixels']}"
)
excellent_path = market_dir / excellent_heatmap_raster_filename(EXCELLENT_CELL_FIELD)
if excellent_path.exists() and not OVERWRITE:
print(f" 跳过已存在采样点热力图:{excellent_path.name}")
excellent_heatmap_results.append(
{
"market_code": market.code,
"market_name": market.name,
"market_dir": str(market_dir),
"output": str(excellent_path),
"skipped": True,
}
)
else:
print(f" 导出采样点热力图:{excellent_path.name}")
excellent_result = export_market_excellent_heatmap_tif(
grid_conn,
grid_layer,
grid_rtree,
market,
EXCELLENT_CELL_FIELD,
pixel_width,
pixel_height,
excellent_path,
)
excellent_result["market_dir"] = str(market_dir)
excellent_result["skipped"] = False
excellent_heatmap_results.append(excellent_result)
print(
f" 采样点热力图像素:{excellent_result['width']}x{excellent_result['height']},"
f"阈值:{excellent_result['thresholds']}"
)
weak_cover_path = market_dir / weak_cover_heatmap_raster_filename(WEAK_COVER_FIELD)
if weak_cover_path.exists() and not OVERWRITE:
print(f" 跳过已存在信号差用户量热力图:{weak_cover_path.name}")
weak_cover_heatmap_results.append(
{
"market_code": market.code,
"market_name": market.name,
"market_dir": str(market_dir),
"output": str(weak_cover_path),
"skipped": True,
}
)
else:
print(f" 导出信号差用户量热力图:{weak_cover_path.name}")
weak_cover_result = export_market_excellent_heatmap_tif(
grid_conn,
grid_layer,
grid_rtree,
market,
WEAK_COVER_FIELD,
pixel_width,
pixel_height,
weak_cover_path,
)
weak_cover_result["market_dir"] = str(market_dir)
weak_cover_result["skipped"] = False
weak_cover_heatmap_results.append(weak_cover_result)
print(
f" 信号差用户量热力图像素:{weak_cover_result['width']}x{weak_cover_result['height']},"
f"阈值:{weak_cover_result['thresholds']}"
)
building_info_path = building_info_output_path(OUTPUT_DIR, market)
print(f" 拆分 BuildingInfo:{building_info_path.name}")
building_info_result = export_market_building_info_gpkg(
building_info_conn,
building_info_layer,
building_info_rtree,
market,
building_info_path,
)
building_info_result["market_dir"] = str(market_dir)
building_info_results.append(building_info_result)
print(
f" BuildingInfo 要素:{building_info_result['feature_count']},"
f"候选:{building_info_result['candidates']}"
)
summary_path = OUTPUT_DIR / "summary.json"
summary = {
"market_gpkg": str(MARKET_GPKG),
"grid_gpkg": str(GRID_GPKG),
"building_info_gpkg": str(BUILDING_INFO_GPKG),
"rsrp_field": RSRP_FIELD,
"excellent_cell_field": EXCELLENT_CELL_FIELD,
"weak_cover_field": WEAK_COVER_FIELD,
"clip_mode": CLIP_MODE,
"scale": SCALE,
"pixel_width": pixel_width,
"pixel_height": pixel_height,
"heatmap_results": heatmap_results,
"excellent_heatmap_results": excellent_heatmap_results,
"weak_cover_heatmap_results": weak_cover_heatmap_results,
"building_info_results": building_info_results,
}
summary_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
print(f"汇总:{summary_path}")
if __name__ == "__main__":
main()