feat: 导出市场网格RSRP栅格图层
This commit is contained in:
@@ -4,3 +4,7 @@
|
||||
- 已在项目根目录创建 Python 虚拟环境 `.venv`,用于后续 Python 开发。
|
||||
- 当前可用系统 Python 版本为 `3.14.3`,本机未检测到 `py` 启动器。
|
||||
- `.gitignore` 已忽略 `.venv/`、Python 缓存文件,以及 `source/` 和 `output/` 本地数据/输出目录,避免误提交环境和数据产物。
|
||||
- 新增 `scripts/export_market_grid_tif.py`,用于按 `source/MarketMap.gpkg` 的市场网格裁切 `source/grid.gpkg`,并按电信 RSRP 字段导出彩色 GeoTIFF。
|
||||
- 脚本默认读取市场图层字段 `micro_grid`/`micro_gr_1` 作为输出文件编码和名称,避免使用上级 `grid_code`/`grid_name` 导致文件名重复。
|
||||
- 脚本默认使用 Grid 图层字段 `ssb_rsrp_dx` 分级着色,颜色按 RSRP 从强到弱划分;输出目录为 `output/market_grid_tif/`,同时生成 `legend.csv` 和 `summary.json`。
|
||||
- 新增 Python 依赖:`shapely` 用于几何裁切,`numpy` 用于栅格数组,`tifffile` 用于写入带 EPSG:4326 标签的 RGB GeoTIFF。
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
numpy==2.5.1
|
||||
shapely==2.1.2
|
||||
tifffile==2026.6.1
|
||||
@@ -0,0 +1,427 @@
|
||||
import argparse
|
||||
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")
|
||||
DEFAULT_OUTPUT_DIR = Path("output") / "market_grid_tif"
|
||||
DEFAULT_MARKET_GPKG = DEFAULT_SOURCE_DIR / "MarketMap.gpkg"
|
||||
DEFAULT_GRID_GPKG = DEFAULT_SOURCE_DIR / "grid.gpkg"
|
||||
DEFAULT_FIELD = "ssb_rsrp_dx"
|
||||
NODATA_COLOR = (255, 255, 255)
|
||||
|
||||
COLOR_BREAKS = [
|
||||
(-80.0, (26, 152, 80), ">= -80"),
|
||||
(-90.0, (102, 189, 99), "[-90, -80)"),
|
||||
(-100.0, (217, 239, 139), "[-100, -90)"),
|
||||
(-105.0, (254, 224, 139), "[-105, -100)"),
|
||||
(-110.0, (244, 109, 67), "[-110, -105)"),
|
||||
(-math.inf, (94, 79, 162), "< -110"),
|
||||
]
|
||||
|
||||
|
||||
@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 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 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 color_for_value(value):
|
||||
for threshold, color, _label in COLOR_BREAKS:
|
||||
if value >= threshold:
|
||||
return color
|
||||
return COLOR_BREAKS[-1][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_rgb_geotiff(path, image, minx, maxy, pixel_width, pixel_height):
|
||||
tifffile.imwrite(
|
||||
path,
|
||||
image,
|
||||
photometric="rgb",
|
||||
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, 3), NODATA_COLOR, dtype=np.uint8)
|
||||
return image, minx, maxy
|
||||
|
||||
|
||||
def pixel_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, col
|
||||
return None
|
||||
|
||||
|
||||
def export_market_tif(grid_conn, grid_layer, rtree, market, field, pixel_width, pixel_height, output_path, clip_mode):
|
||||
image, minx, maxy = create_canvas(market.geometry.bounds, pixel_width, pixel_height)
|
||||
height, width = image.shape[:2]
|
||||
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
|
||||
if target_point is None:
|
||||
target_point = grid_geom.representative_point().coords[0]
|
||||
else:
|
||||
if target_point is None:
|
||||
continue
|
||||
if not prepared_market.covers(Point(target_point)):
|
||||
continue
|
||||
|
||||
pixel = pixel_from_point(
|
||||
target_point[0],
|
||||
target_point[1],
|
||||
minx,
|
||||
maxy,
|
||||
pixel_width,
|
||||
pixel_height,
|
||||
width,
|
||||
height,
|
||||
)
|
||||
if pixel is None:
|
||||
continue
|
||||
|
||||
image[pixel] = color_for_value(value)
|
||||
painted += 1
|
||||
|
||||
write_rgb_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,
|
||||
"skipped_no_value": skipped_no_value,
|
||||
"width": width,
|
||||
"height": height,
|
||||
}
|
||||
|
||||
|
||||
def write_legend(output_dir, field):
|
||||
legend_path = output_dir / "legend.csv"
|
||||
with legend_path.open("w", newline="", encoding="utf-8-sig") as file:
|
||||
writer = csv.writer(file)
|
||||
writer.writerow(["field", "range", "red", "green", "blue", "meaning"])
|
||||
for _threshold, color, label in COLOR_BREAKS:
|
||||
writer.writerow([field, label, color[0], color[1], color[2], "strong-to-weak RSRP"])
|
||||
writer.writerow([field, "nodata", NODATA_COLOR[0], NODATA_COLOR[1], NODATA_COLOR[2], "no data"])
|
||||
return legend_path
|
||||
|
||||
|
||||
def parse_args():
|
||||
parser = argparse.ArgumentParser(description="按市场网格裁切 Grid,并导出电信 RSRP 彩色 GeoTIFF。")
|
||||
parser.add_argument("--market-gpkg", type=Path, default=DEFAULT_MARKET_GPKG)
|
||||
parser.add_argument("--grid-gpkg", type=Path, default=DEFAULT_GRID_GPKG)
|
||||
parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR)
|
||||
parser.add_argument("--field", default=DEFAULT_FIELD)
|
||||
parser.add_argument("--market-layer")
|
||||
parser.add_argument("--grid-layer")
|
||||
parser.add_argument("--market-code-field", default="micro_grid")
|
||||
parser.add_argument("--market-name-field", default="micro_gr_1")
|
||||
parser.add_argument("--pixel-width", type=float)
|
||||
parser.add_argument("--pixel-height", type=float)
|
||||
parser.add_argument("--sample-size", type=int, default=5000)
|
||||
parser.add_argument("--limit", type=int, help="只处理前 N 个市场网格,用于快速验证。")
|
||||
parser.add_argument("--clip-mode", choices=["intersects", "center"], default="intersects")
|
||||
parser.add_argument("--overwrite", action="store_true")
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main():
|
||||
args = parse_args()
|
||||
args.output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
with sqlite3.connect(args.market_gpkg) as market_conn, sqlite3.connect(args.grid_gpkg) as grid_conn:
|
||||
market_layer = resolve_feature_layer(market_conn, args.market_layer)
|
||||
grid_layer = resolve_feature_layer(grid_conn, args.grid_layer)
|
||||
if market_layer.srs_id != 4326 or grid_layer.srs_id != 4326:
|
||||
raise ValueError("当前脚本只处理 EPSG:4326 的输入图层")
|
||||
|
||||
require_columns(grid_conn, grid_layer.table_name, [args.field, "longitude", "latitude"])
|
||||
rtree = rtree_name(grid_conn, grid_layer)
|
||||
pixel_width = args.pixel_width
|
||||
pixel_height = args.pixel_height
|
||||
if pixel_width is None or pixel_height is None:
|
||||
estimated_width, estimated_height = estimate_pixel_size(grid_conn, grid_layer, args.sample_size)
|
||||
pixel_width = pixel_width or estimated_width
|
||||
pixel_height = pixel_height or estimated_height
|
||||
|
||||
markets = load_market_features(
|
||||
market_conn,
|
||||
market_layer,
|
||||
args.market_code_field,
|
||||
args.market_name_field,
|
||||
)
|
||||
if args.limit:
|
||||
markets = markets[:args.limit]
|
||||
|
||||
legend_path = write_legend(args.output_dir, args.field)
|
||||
results = []
|
||||
print(f"市场网格数量:{len(markets)}")
|
||||
print(f"Grid 图层:{grid_layer.table_name}")
|
||||
print(f"RSRP 字段:{args.field}")
|
||||
print(f"像元大小:{pixel_width}, {pixel_height}")
|
||||
print(f"图例:{legend_path}")
|
||||
|
||||
for index, market in enumerate(markets, start=1):
|
||||
filename = f"{safe_filename(market.code)}_{safe_filename(market.name)}.tif"
|
||||
output_path = args.output_dir / filename
|
||||
if output_path.exists() and not args.overwrite:
|
||||
print(f"[{index}/{len(markets)}] 跳过已存在:{output_path.name}")
|
||||
continue
|
||||
|
||||
print(f"[{index}/{len(markets)}] 导出:{market.code} {market.name}")
|
||||
result = export_market_tif(
|
||||
grid_conn,
|
||||
grid_layer,
|
||||
rtree,
|
||||
market,
|
||||
args.field,
|
||||
pixel_width,
|
||||
pixel_height,
|
||||
output_path,
|
||||
args.clip_mode,
|
||||
)
|
||||
results.append(result)
|
||||
print(f" 像素:{result['width']}x{result['height']},已着色:{result['painted_pixels']}")
|
||||
|
||||
summary_path = args.output_dir / "summary.json"
|
||||
summary = {
|
||||
"market_gpkg": str(args.market_gpkg),
|
||||
"grid_gpkg": str(args.grid_gpkg),
|
||||
"field": args.field,
|
||||
"clip_mode": args.clip_mode,
|
||||
"pixel_width": pixel_width,
|
||||
"pixel_height": pixel_height,
|
||||
"results": results,
|
||||
}
|
||||
summary_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
print(f"汇总:{summary_path}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user