rsplot 0.3.2.dev4__py3-none-any.whl → 0.3.2.dev37__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- rsplot/atomic.py +36 -0
- rsplot/cli.py +272 -497
- rsplot/commands/common.py +52 -3
- rsplot/commands/fnr.py +389 -104
- rsplot/commands/forecast.py +0 -2
- rsplot/commands/meteo.py +499 -186
- rsplot/commands/overlay.py +284 -326
- rsplot/commands/radius.py +526 -0
- rsplot/commands/raster.py +418 -293
- rsplot/commands/reconstruct.py +0 -1
- rsplot/commands/sidecar.py +106 -0
- rsplot/commands/station.py +154 -42
- rsplot/commands/station_trend.py +259 -174
- rsplot/config.py +43 -16
- rsplot/data_files.py +253 -0
- rsplot/errors.py +43 -0
- rsplot/fnr.py +38 -46
- rsplot/geo/boundaries.py +212 -9
- rsplot/geo/footprints.py +3 -0
- rsplot/geo/processing.py +2 -5
- rsplot/geo/radius.py +205 -0
- rsplot/plotting/colormap_22.txt +256 -0
- rsplot/plotting/colormaps.py +24 -29
- rsplot/plotting/map_frame.py +84 -6
- rsplot/plotting/meteo.py +10 -3
- rsplot/plotting/overlay.py +31 -40
- rsplot/plotting/raster.py +10 -3
- rsplot/plotting/station.py +86 -33
- rsplot/plotting/station_focus.py +84 -0
- rsplot/plotting/station_trend.py +60 -47
- rsplot/plotting/styles.py +3 -5
- rsplot/readers/__init__.py +52 -4
- rsplot/readers/_tropomi.py +121 -3
- rsplot/readers/era5.py +110 -10
- rsplot/readers/era5_wind.py +3 -2
- rsplot/readers/gems.py +11 -8
- rsplot/readers/guokong.py +125 -39
- rsplot/readers/netcdf.py +32 -0
- rsplot/readers/tropomi_hcho.py +1 -1
- rsplot/readers/tropomi_no2.py +1 -1
- rsplot/readers/tropomi_nrti.py +116 -0
- rsplot/readers/tropomi_o3.py +1 -1
- rsplot/readers/tropomi_o3pr.py +1 -1
- rsplot/result_builders/__init__.py +0 -14
- rsplot/result_builders/common.py +4 -1
- rsplot/result_builders/envelope.py +236 -0
- rsplot/result_builders/fnr.py +47 -131
- rsplot/result_builders/provenance.py +59 -0
- rsplot/result_builders/satellite.py +240 -0
- rsplot/result_builders/series_layer.py +289 -0
- rsplot/result_builders/station.py +23 -0
- rsplot/result_builders/station_layer.py +326 -0
- rsplot/results.py +0 -12
- rsplot/schemas/result.schema.json +566 -0
- rsplot/temporal.py +7 -0
- {rsplot-0.3.2.dev4.dist-info → rsplot-0.3.2.dev37.dist-info}/METADATA +426 -121
- rsplot-0.3.2.dev37.dist-info/RECORD +76 -0
- {rsplot-0.3.2.dev4.dist-info → rsplot-0.3.2.dev37.dist-info}/WHEEL +1 -1
- rsplot/commands/recent.py +0 -186
- rsplot/recent.py +0 -447
- rsplot/result_builders/meteo.py +0 -171
- rsplot/result_builders/overlay.py +0 -105
- rsplot/result_builders/raster.py +0 -104
- rsplot/result_builders/station_trend.py +0 -229
- rsplot-0.3.2.dev4.dist-info/RECORD +0 -66
- {rsplot-0.3.2.dev4.dist-info → rsplot-0.3.2.dev37.dist-info}/entry_points.txt +0 -0
- {rsplot-0.3.2.dev4.dist-info → rsplot-0.3.2.dev37.dist-info}/licenses/LICENSE +0 -0
rsplot/geo/boundaries.py
CHANGED
|
@@ -9,6 +9,7 @@ from __future__ import annotations
|
|
|
9
9
|
import re
|
|
10
10
|
from dataclasses import dataclass
|
|
11
11
|
from functools import lru_cache
|
|
12
|
+
from pathlib import Path
|
|
12
13
|
from typing import TYPE_CHECKING
|
|
13
14
|
|
|
14
15
|
import geopandas as gpd
|
|
@@ -21,8 +22,11 @@ from rsplot.config import (
|
|
|
21
22
|
LevelParams,
|
|
22
23
|
SubdivisionSource,
|
|
23
24
|
)
|
|
25
|
+
from rsplot.errors import RsplotError
|
|
24
26
|
|
|
25
27
|
if TYPE_CHECKING:
|
|
28
|
+
from collections.abc import Iterable
|
|
29
|
+
|
|
26
30
|
from shapely.geometry.base import BaseGeometry
|
|
27
31
|
|
|
28
32
|
|
|
@@ -35,6 +39,11 @@ NAME_FIELD = "name"
|
|
|
35
39
|
|
|
36
40
|
# 直辖市 — resolved as province but displayed with county-level sub-boundaries
|
|
37
41
|
MUNICIPALITIES = {"北京市", "天津市", "上海市", "重庆市"}
|
|
42
|
+
# Municipalities present in both the province and city files resolve as
|
|
43
|
+
# cities; 重庆市 (and same-name entries such as 香港) stay provinces.
|
|
44
|
+
CITY_MUNICIPALITIES = {"北京市", "天津市", "上海市"}
|
|
45
|
+
# Placeholder features in the boundary files, never a region.
|
|
46
|
+
PLACEHOLDER_NAMES = {"境界线"}
|
|
38
47
|
|
|
39
48
|
|
|
40
49
|
@dataclass
|
|
@@ -60,10 +69,85 @@ class RegionInfo:
|
|
|
60
69
|
subdivision_level: str | None = None
|
|
61
70
|
qualified_name: str | None = None
|
|
62
71
|
members: tuple[RegionInfo, ...] = ()
|
|
72
|
+
geometry_kind: str = "administrative"
|
|
73
|
+
projection_center: tuple[float, float] | None = None
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
# China's 56 ethnic groups, as written in autonomous-area names.
|
|
77
|
+
_ETHNIC_GROUPS = [
|
|
78
|
+
"汉",
|
|
79
|
+
"蒙古",
|
|
80
|
+
"回",
|
|
81
|
+
"藏",
|
|
82
|
+
"维吾尔",
|
|
83
|
+
"苗",
|
|
84
|
+
"彝",
|
|
85
|
+
"壮",
|
|
86
|
+
"布依",
|
|
87
|
+
"朝鲜",
|
|
88
|
+
"满",
|
|
89
|
+
"侗",
|
|
90
|
+
"瑶",
|
|
91
|
+
"白",
|
|
92
|
+
"土家",
|
|
93
|
+
"哈尼",
|
|
94
|
+
"哈萨克",
|
|
95
|
+
"傣",
|
|
96
|
+
"黎",
|
|
97
|
+
"傈僳",
|
|
98
|
+
"佤",
|
|
99
|
+
"畲",
|
|
100
|
+
"高山",
|
|
101
|
+
"拉祜",
|
|
102
|
+
"水",
|
|
103
|
+
"东乡",
|
|
104
|
+
"纳西",
|
|
105
|
+
"景颇",
|
|
106
|
+
"柯尔克孜",
|
|
107
|
+
"土",
|
|
108
|
+
"达斡尔",
|
|
109
|
+
"仫佬",
|
|
110
|
+
"羌",
|
|
111
|
+
"布朗",
|
|
112
|
+
"撒拉",
|
|
113
|
+
"毛南",
|
|
114
|
+
"仡佬",
|
|
115
|
+
"锡伯",
|
|
116
|
+
"阿昌",
|
|
117
|
+
"普米",
|
|
118
|
+
"塔吉克",
|
|
119
|
+
"怒",
|
|
120
|
+
"乌孜别克",
|
|
121
|
+
"俄罗斯",
|
|
122
|
+
"鄂温克",
|
|
123
|
+
"德昂",
|
|
124
|
+
"保安",
|
|
125
|
+
"裕固",
|
|
126
|
+
"京",
|
|
127
|
+
"塔塔尔",
|
|
128
|
+
"独龙",
|
|
129
|
+
"鄂伦春",
|
|
130
|
+
"赫哲",
|
|
131
|
+
"门巴",
|
|
132
|
+
"珞巴",
|
|
133
|
+
"基诺",
|
|
134
|
+
]
|
|
135
|
+
# One or more groups right before the autonomous suffix: 广西壮族自治区 ->
|
|
136
|
+
# 广西自治区, 黔东南苗族侗族自治州 -> 黔东南自治州. Groups carry 族, except
|
|
137
|
+
# 维吾尔 in 新疆维吾尔自治区; 内蒙古 and 西藏 are place names, not groups.
|
|
138
|
+
_ETHNIC_DESIGNATION = re.compile(
|
|
139
|
+
r"(?:(?:"
|
|
140
|
+
+ "|".join(sorted(_ETHNIC_GROUPS, key=len, reverse=True))
|
|
141
|
+
+ r")族|维吾尔)+(?=自治[区州县旗]$)"
|
|
142
|
+
)
|
|
63
143
|
|
|
64
144
|
|
|
65
145
|
def _strip_suffix(name: str) -> str:
|
|
66
|
-
|
|
146
|
+
stripped = _ETHNIC_DESIGNATION.sub("", name)
|
|
147
|
+
if stripped.startswith("自治"):
|
|
148
|
+
# The whole name is the ethnic designation (鄂伦春自治旗).
|
|
149
|
+
stripped = name
|
|
150
|
+
return _SUFFIXES.sub("", stripped)
|
|
67
151
|
|
|
68
152
|
|
|
69
153
|
def _fuzzy_match(
|
|
@@ -93,19 +177,30 @@ def _fuzzy_match(
|
|
|
93
177
|
# ---------------------------------------------------------------------------
|
|
94
178
|
# GeoJSON loaders (cached)
|
|
95
179
|
# ---------------------------------------------------------------------------
|
|
180
|
+
def _read_boundary_file(path: str) -> gpd.GeoDataFrame:
|
|
181
|
+
"""Read a configured boundary file; a missing one is a config error."""
|
|
182
|
+
if not Path(path).is_file():
|
|
183
|
+
raise RsplotError(
|
|
184
|
+
"config_invalid",
|
|
185
|
+
f"边界文件不存在: {path};请检查配置 [paths].geojson_dir。",
|
|
186
|
+
details={"path": path},
|
|
187
|
+
)
|
|
188
|
+
return gpd.read_file(path)
|
|
189
|
+
|
|
190
|
+
|
|
96
191
|
@lru_cache(maxsize=1)
|
|
97
192
|
def _load_province(geojson_dir: str) -> gpd.GeoDataFrame:
|
|
98
|
-
return
|
|
193
|
+
return _read_boundary_file(f"{geojson_dir}/中国_省.geojson")
|
|
99
194
|
|
|
100
195
|
|
|
101
196
|
@lru_cache(maxsize=1)
|
|
102
197
|
def _load_city(geojson_dir: str) -> gpd.GeoDataFrame:
|
|
103
|
-
return
|
|
198
|
+
return _read_boundary_file(f"{geojson_dir}/中国_市.geojson")
|
|
104
199
|
|
|
105
200
|
|
|
106
201
|
@lru_cache(maxsize=1)
|
|
107
202
|
def _load_county(geojson_dir: str) -> gpd.GeoDataFrame:
|
|
108
|
-
return
|
|
203
|
+
return _read_boundary_file(f"{geojson_dir}/中国_县.geojson")
|
|
109
204
|
|
|
110
205
|
|
|
111
206
|
@lru_cache(maxsize=16)
|
|
@@ -256,7 +351,12 @@ def _resolve_qualified_county(
|
|
|
256
351
|
city_name, county_name = name.split("/", 1)
|
|
257
352
|
city_match = _fuzzy_match(city_name, cities)
|
|
258
353
|
if city_match is None:
|
|
259
|
-
|
|
354
|
+
suggestions = suggest_region_names(city_name, [cities])
|
|
355
|
+
raise RsplotError(
|
|
356
|
+
"region_not_found",
|
|
357
|
+
f"无法识别城市 '{city_name}'。{_did_you_mean(suggestions)}",
|
|
358
|
+
details={"region": name, "suggestions": suggestions},
|
|
359
|
+
)
|
|
260
360
|
canonical_city_name = city_match.iloc[0][NAME_FIELD]
|
|
261
361
|
city_geometry = unary_union(city_match.geometry)
|
|
262
362
|
configured = _city_subdivisions(
|
|
@@ -387,6 +487,84 @@ def _resolve_city(
|
|
|
387
487
|
)
|
|
388
488
|
|
|
389
489
|
|
|
490
|
+
def _matched_name(query: str, candidates: gpd.GeoDataFrame) -> str | None:
|
|
491
|
+
match = _fuzzy_match(query, candidates)
|
|
492
|
+
if match is None:
|
|
493
|
+
return None
|
|
494
|
+
name = match.iloc[0][NAME_FIELD]
|
|
495
|
+
return None if name in PLACEHOLDER_NAMES else name
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def _resolve_named_place(
|
|
499
|
+
name: str,
|
|
500
|
+
cfg: AppConfig,
|
|
501
|
+
provinces: gpd.GeoDataFrame,
|
|
502
|
+
cities: gpd.GeoDataFrame,
|
|
503
|
+
counties: gpd.GeoDataFrame,
|
|
504
|
+
) -> RegionInfo | None:
|
|
505
|
+
"""Resolve a province or city name without guessing between them.
|
|
506
|
+
|
|
507
|
+
A full name selects its own level; a short name matching different
|
|
508
|
+
places at both levels is rejected with the candidates.
|
|
509
|
+
"""
|
|
510
|
+
province = _matched_name(name, provinces)
|
|
511
|
+
city = _matched_name(name, cities)
|
|
512
|
+
if province is not None and province == city:
|
|
513
|
+
use_city = province in CITY_MUNICIPALITIES
|
|
514
|
+
elif province is not None and city is not None:
|
|
515
|
+
if (province == name) == (city == name):
|
|
516
|
+
raise RsplotError(
|
|
517
|
+
"region_ambiguous",
|
|
518
|
+
f"区域名 '{name}' 同时匹配 {province}(省级)和 "
|
|
519
|
+
f"{city}(市级),请写全称。",
|
|
520
|
+
details={"region": name, "candidates": [province, city]},
|
|
521
|
+
)
|
|
522
|
+
use_city = city == name
|
|
523
|
+
elif province is not None or city is not None:
|
|
524
|
+
use_city = city is not None
|
|
525
|
+
else:
|
|
526
|
+
return None
|
|
527
|
+
if use_city:
|
|
528
|
+
return _resolve_city(city, cfg, cities, counties)
|
|
529
|
+
return _resolve_province(province, provinces, cities, counties)
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def suggest_region_names(
|
|
533
|
+
query: str,
|
|
534
|
+
frames: list[gpd.GeoDataFrame],
|
|
535
|
+
extra: Iterable[str] = (),
|
|
536
|
+
*,
|
|
537
|
+
limit: int = 5,
|
|
538
|
+
) -> list[str]:
|
|
539
|
+
"""Close full names for a misspelled region, most similar first.
|
|
540
|
+
|
|
541
|
+
Compares both the full and the suffix-stripped names, so 安微 finds
|
|
542
|
+
安徽省. Ties keep the order of ``frames`` (provinces before cities),
|
|
543
|
+
then the extra names (key regions).
|
|
544
|
+
"""
|
|
545
|
+
from difflib import SequenceMatcher
|
|
546
|
+
|
|
547
|
+
stripped = _strip_suffix(query)
|
|
548
|
+
groups = [frame[NAME_FIELD].tolist() for frame in frames] + [list(extra)]
|
|
549
|
+
scored: dict[str, tuple[float, int]] = {}
|
|
550
|
+
for rank, names in enumerate(groups):
|
|
551
|
+
for full in names:
|
|
552
|
+
if full in PLACEHOLDER_NAMES or full in scored:
|
|
553
|
+
continue
|
|
554
|
+
score = max(
|
|
555
|
+
SequenceMatcher(None, query, full).ratio(),
|
|
556
|
+
SequenceMatcher(None, stripped, _strip_suffix(full)).ratio(),
|
|
557
|
+
)
|
|
558
|
+
if score >= 0.5:
|
|
559
|
+
scored[full] = (-score, rank)
|
|
560
|
+
ranked = sorted(scored, key=lambda full: (*scored[full], full))
|
|
561
|
+
return ranked[:limit]
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
def _did_you_mean(suggestions: list[str]) -> str:
|
|
565
|
+
return f"是否指: {'、'.join(suggestions)}?" if suggestions else ""
|
|
566
|
+
|
|
567
|
+
|
|
390
568
|
def resolve_region(
|
|
391
569
|
name: str,
|
|
392
570
|
cfg: AppConfig,
|
|
@@ -422,7 +600,32 @@ def resolve_region(
|
|
|
422
600
|
if key_region is not None:
|
|
423
601
|
return key_region
|
|
424
602
|
|
|
425
|
-
if level_override is None
|
|
603
|
+
if level_override is None:
|
|
604
|
+
assert provinces is not None
|
|
605
|
+
named = _resolve_named_place(
|
|
606
|
+
name,
|
|
607
|
+
cfg,
|
|
608
|
+
provinces,
|
|
609
|
+
load_city_boundaries(geojson_dir),
|
|
610
|
+
load_county_boundaries(geojson_dir),
|
|
611
|
+
)
|
|
612
|
+
if named is not None:
|
|
613
|
+
return named
|
|
614
|
+
suggestions = suggest_region_names(
|
|
615
|
+
name,
|
|
616
|
+
[provinces, load_city_boundaries(geojson_dir)],
|
|
617
|
+
cfg.key_regions,
|
|
618
|
+
)
|
|
619
|
+
raise RsplotError(
|
|
620
|
+
"region_not_found",
|
|
621
|
+
f"无法识别区域 '{name}'。{_did_you_mean(suggestions)}"
|
|
622
|
+
"请使用中文全称或简称,县区写成 城市/区县,如 合肥/蜀山。",
|
|
623
|
+
details={"region": name, "suggestions": suggestions},
|
|
624
|
+
)
|
|
625
|
+
|
|
626
|
+
# The level filter below serves only the disabled forecast and
|
|
627
|
+
# reconstruct commands; enabled commands resolve by name alone.
|
|
628
|
+
if level_override == "province":
|
|
426
629
|
assert provinces is not None
|
|
427
630
|
cities = load_city_boundaries(geojson_dir)
|
|
428
631
|
counties = load_county_boundaries(geojson_dir)
|
|
@@ -430,7 +633,7 @@ def resolve_region(
|
|
|
430
633
|
if province is not None:
|
|
431
634
|
return province
|
|
432
635
|
|
|
433
|
-
if level_override
|
|
636
|
+
if level_override == "city":
|
|
434
637
|
cities = load_city_boundaries(geojson_dir)
|
|
435
638
|
counties = load_county_boundaries(geojson_dir)
|
|
436
639
|
city = _resolve_city(name, cfg, cities, counties)
|
|
@@ -444,8 +647,8 @@ def resolve_region(
|
|
|
444
647
|
)
|
|
445
648
|
|
|
446
649
|
raise ValueError(
|
|
447
|
-
f"无法识别区域 '{name}'
|
|
448
|
-
"
|
|
650
|
+
f"无法识别区域 '{name}'。请使用中文行政区名称或重点区域名,"
|
|
651
|
+
"区县写作 城市/区县,如 合肥/蜀山。"
|
|
449
652
|
)
|
|
450
653
|
|
|
451
654
|
|
rsplot/geo/footprints.py
CHANGED
|
@@ -181,6 +181,9 @@ def prepare_footprint_display(
|
|
|
181
181
|
prepared = prepare_display_grid(
|
|
182
182
|
lon, lat, values, geometry, smooth_sigma=smooth_sigma
|
|
183
183
|
)
|
|
184
|
+
if display_res == analysis_res:
|
|
185
|
+
# Use the already remapped target grid directly: no second remapping.
|
|
186
|
+
return FootprintDisplay(lon, lat, prepared, support)
|
|
184
187
|
x = grid_edges(lon[0], analysis_res)
|
|
185
188
|
y = grid_edges(lat[:, 0], analysis_res)
|
|
186
189
|
display_lon, display_lat = regular_grid(
|
rsplot/geo/processing.py
CHANGED
|
@@ -103,10 +103,8 @@ def prepare_swath_grid(
|
|
|
103
103
|
read_extent: tuple[float, float, float, float],
|
|
104
104
|
resolution: float,
|
|
105
105
|
geometry: BaseGeometry,
|
|
106
|
-
*,
|
|
107
|
-
smooth_sigma: float | None = None,
|
|
108
106
|
) -> PreparedGrid:
|
|
109
|
-
"""Grid a swath
|
|
107
|
+
"""Grid a swath into observed cells only; filling is display-only."""
|
|
110
108
|
lon, lat, raw = grid_data(
|
|
111
109
|
swath_lon,
|
|
112
110
|
swath_lat,
|
|
@@ -119,8 +117,7 @@ def prepare_swath_grid(
|
|
|
119
117
|
lat,
|
|
120
118
|
raw,
|
|
121
119
|
geometry,
|
|
122
|
-
fill_gaps=
|
|
123
|
-
smooth_sigma=smooth_sigma,
|
|
120
|
+
fill_gaps=False,
|
|
124
121
|
)
|
|
125
122
|
|
|
126
123
|
|
rsplot/geo/radius.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""Geodesic station neighborhoods with independent administrative context."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from dataclasses import replace
|
|
7
|
+
|
|
8
|
+
import geopandas as gpd
|
|
9
|
+
import numpy as np
|
|
10
|
+
import pandas as pd
|
|
11
|
+
from pyproj import Geod
|
|
12
|
+
from shapely.geometry import Point, Polygon, box
|
|
13
|
+
|
|
14
|
+
from rsplot.config import LEVEL_DEFAULTS, AppConfig
|
|
15
|
+
from rsplot.geo.boundaries import (
|
|
16
|
+
RegionInfo,
|
|
17
|
+
_city_subdivisions,
|
|
18
|
+
load_city_boundaries,
|
|
19
|
+
load_county_boundaries,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
GEOD = Geod(ellps="WGS84")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def geodesic_square(lon: float, lat: float, km: float) -> Polygon:
|
|
26
|
+
"""Build a north-oriented square in station-centered WGS84 AEQD meters."""
|
|
27
|
+
if not math.isfinite(km) or km <= 0:
|
|
28
|
+
raise ValueError("--km 必须是大于 0 的有限数字。")
|
|
29
|
+
if not (np.isfinite(lon) and np.isfinite(lat)):
|
|
30
|
+
raise ValueError("中心站坐标不是有效数字。")
|
|
31
|
+
if not (-180 <= lon <= 180 and -90 < lat < 90):
|
|
32
|
+
raise ValueError("中心站坐标超出有效经纬度范围。")
|
|
33
|
+
half_width = km * 1000
|
|
34
|
+
outline = box(-half_width, -half_width, half_width, half_width)
|
|
35
|
+
xy = np.asarray(outline.segmentize(half_width / 32).exterior.coords)
|
|
36
|
+
azimuth = np.degrees(np.arctan2(xy[:, 0], xy[:, 1]))
|
|
37
|
+
x, y, _ = GEOD.fwd(
|
|
38
|
+
np.full(len(xy), lon),
|
|
39
|
+
np.full(len(xy), lat),
|
|
40
|
+
azimuth,
|
|
41
|
+
np.hypot(xy[:, 0], xy[:, 1]),
|
|
42
|
+
)
|
|
43
|
+
square = Polygon(zip(x, y, strict=True))
|
|
44
|
+
# The existing rectilinear plotting pipeline cannot wrap the dateline.
|
|
45
|
+
pole_distance = min(
|
|
46
|
+
GEOD.inv(lon, lat, lon, 90)[2],
|
|
47
|
+
GEOD.inv(lon, lat, lon, -90)[2],
|
|
48
|
+
)
|
|
49
|
+
if (
|
|
50
|
+
km * 1000 * math.sqrt(2) >= pole_distance
|
|
51
|
+
or np.ptp(x) > 180
|
|
52
|
+
or not square.is_valid
|
|
53
|
+
):
|
|
54
|
+
raise ValueError("正方形范围跨越极点或日期变更线,当前地图不支持。")
|
|
55
|
+
return square
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def station_distances(
|
|
59
|
+
lon: float,
|
|
60
|
+
lat: float,
|
|
61
|
+
station_lon: np.ndarray,
|
|
62
|
+
station_lat: np.ndarray,
|
|
63
|
+
) -> np.ndarray:
|
|
64
|
+
"""Return WGS84 distances in km; invalid coordinates remain NaN."""
|
|
65
|
+
valid = (
|
|
66
|
+
np.isfinite(station_lon)
|
|
67
|
+
& np.isfinite(station_lat)
|
|
68
|
+
& (np.abs(station_lon) <= 180)
|
|
69
|
+
& (np.abs(station_lat) <= 90)
|
|
70
|
+
)
|
|
71
|
+
distances = np.full(station_lon.shape, np.nan)
|
|
72
|
+
_, _, meters = GEOD.inv(
|
|
73
|
+
np.full(valid.sum(), lon),
|
|
74
|
+
np.full(valid.sum(), lat),
|
|
75
|
+
station_lon[valid],
|
|
76
|
+
station_lat[valid],
|
|
77
|
+
)
|
|
78
|
+
distances[valid] = meters / 1000
|
|
79
|
+
return distances
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def station_offsets_km(
|
|
83
|
+
lon: float,
|
|
84
|
+
lat: float,
|
|
85
|
+
station_lon: np.ndarray,
|
|
86
|
+
station_lat: np.ndarray,
|
|
87
|
+
) -> tuple[np.ndarray, np.ndarray]:
|
|
88
|
+
"""East and north offsets from the centre, in km, along the geodesic."""
|
|
89
|
+
azimuth, _, meters = GEOD.inv(
|
|
90
|
+
np.full(station_lon.shape, lon),
|
|
91
|
+
np.full(station_lat.shape, lat),
|
|
92
|
+
station_lon,
|
|
93
|
+
station_lat,
|
|
94
|
+
)
|
|
95
|
+
angle = np.radians(azimuth)
|
|
96
|
+
return meters * np.sin(angle) / 1000, meters * np.cos(angle) / 1000
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def station_square_mask(
|
|
100
|
+
lon: float,
|
|
101
|
+
lat: float,
|
|
102
|
+
km: float,
|
|
103
|
+
station_lon: np.ndarray,
|
|
104
|
+
station_lat: np.ndarray,
|
|
105
|
+
) -> np.ndarray:
|
|
106
|
+
"""Select the square including its edges, rather than a radial disk."""
|
|
107
|
+
x_km, y_km = station_offsets_km(lon, lat, station_lon, station_lat)
|
|
108
|
+
x, y = x_km * 1000, y_km * 1000
|
|
109
|
+
return (
|
|
110
|
+
np.isfinite(x)
|
|
111
|
+
& np.isfinite(y)
|
|
112
|
+
& (np.abs(station_lon) <= 180)
|
|
113
|
+
& (np.abs(station_lat) <= 90)
|
|
114
|
+
& (np.abs(x) <= km * 1000 + 1e-6)
|
|
115
|
+
& (np.abs(y) <= km * 1000 + 1e-6)
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def resolve_radius_region(
|
|
120
|
+
station_id: str,
|
|
121
|
+
lon: float,
|
|
122
|
+
lat: float,
|
|
123
|
+
km: float,
|
|
124
|
+
cfg: AppConfig,
|
|
125
|
+
) -> RegionInfo:
|
|
126
|
+
"""Resolve visible city and county/township context around a square."""
|
|
127
|
+
square = geodesic_square(lon, lat, km)
|
|
128
|
+
west, south, east, north = square.bounds
|
|
129
|
+
view = square
|
|
130
|
+
if not cfg.geojson_dir:
|
|
131
|
+
raise ValueError("请配置行政边界目录 geojson_dir。")
|
|
132
|
+
cities = load_city_boundaries(cfg.geojson_dir).to_crs("EPSG:4326")
|
|
133
|
+
counties = load_county_boundaries(cfg.geojson_dir).to_crs("EPSG:4326")
|
|
134
|
+
cities = cities[cities.geometry.intersects(view)].copy()
|
|
135
|
+
layers = []
|
|
136
|
+
for _, city in cities.iterrows():
|
|
137
|
+
override = _city_subdivisions(
|
|
138
|
+
city["name"],
|
|
139
|
+
city.geometry,
|
|
140
|
+
cities.crs,
|
|
141
|
+
cfg,
|
|
142
|
+
)
|
|
143
|
+
if override is None:
|
|
144
|
+
layer = counties[
|
|
145
|
+
counties.geometry.intersects(city.geometry)
|
|
146
|
+
& counties.geometry.intersects(view)
|
|
147
|
+
].copy()
|
|
148
|
+
layer["administrative_level"] = "county"
|
|
149
|
+
else:
|
|
150
|
+
layer, level = override
|
|
151
|
+
layer = layer[layer.geometry.intersects(view)].copy()
|
|
152
|
+
layer["administrative_level"] = level
|
|
153
|
+
# Clip contextual units to their city, avoiding border-touch neighbors.
|
|
154
|
+
layer.geometry = layer.geometry.intersection(city.geometry)
|
|
155
|
+
layer = layer[
|
|
156
|
+
(~layer.geometry.is_empty)
|
|
157
|
+
& (layer.geometry.to_crs("EPSG:6933").area > 0)
|
|
158
|
+
]
|
|
159
|
+
layer["city"] = city["name"]
|
|
160
|
+
layers.append(layer)
|
|
161
|
+
subdivisions = (
|
|
162
|
+
gpd.GeoDataFrame(pd.concat(layers, ignore_index=True), crs=cities.crs)
|
|
163
|
+
if layers
|
|
164
|
+
else None
|
|
165
|
+
)
|
|
166
|
+
return RegionInfo(
|
|
167
|
+
name=f"{station_id} 上下左右各 {km:g} km",
|
|
168
|
+
level="county",
|
|
169
|
+
geometry=square,
|
|
170
|
+
extent=(west, east, south, north),
|
|
171
|
+
params=replace(LEVEL_DEFAULTS["county"], pad=0, basemap=False),
|
|
172
|
+
main_boundary_gdf=cities,
|
|
173
|
+
sub_boundary_gdf=subdivisions,
|
|
174
|
+
geometry_kind="station_radius",
|
|
175
|
+
projection_center=(lon, lat),
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def administrative_context(region: RegionInfo, lon: float, lat: float) -> dict:
|
|
180
|
+
"""Describe the center's affiliations and the visible administrative units."""
|
|
181
|
+
point = Point(lon, lat)
|
|
182
|
+
cities = region.main_boundary_gdf
|
|
183
|
+
subdivisions = region.sub_boundary_gdf
|
|
184
|
+
visible_cities = [] if cities is None else cities["name"].tolist()
|
|
185
|
+
center_cities = (
|
|
186
|
+
[]
|
|
187
|
+
if cities is None
|
|
188
|
+
else cities[cities.geometry.covers(point)]["name"].tolist()
|
|
189
|
+
)
|
|
190
|
+
units = []
|
|
191
|
+
if subdivisions is not None:
|
|
192
|
+
for _, row in subdivisions.iterrows():
|
|
193
|
+
units.append(
|
|
194
|
+
{
|
|
195
|
+
"name": row["name"],
|
|
196
|
+
"city": row["city"],
|
|
197
|
+
"level": row["administrative_level"],
|
|
198
|
+
"contains_center": bool(row.geometry.covers(point)),
|
|
199
|
+
}
|
|
200
|
+
)
|
|
201
|
+
return {
|
|
202
|
+
"center_cities": center_cities,
|
|
203
|
+
"visible_cities": visible_cities,
|
|
204
|
+
"subdivisions": units,
|
|
205
|
+
}
|