rsplot 0.3.1.dev3__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.
Files changed (71) hide show
  1. rsplot/atomic.py +36 -0
  2. rsplot/cli.py +282 -469
  3. rsplot/commands/common.py +113 -1
  4. rsplot/commands/fnr.py +389 -104
  5. rsplot/commands/forecast.py +24 -7
  6. rsplot/commands/meteo.py +499 -186
  7. rsplot/commands/overlay.py +292 -205
  8. rsplot/commands/radius.py +526 -0
  9. rsplot/commands/raster.py +479 -230
  10. rsplot/commands/reconstruct.py +27 -6
  11. rsplot/commands/sidecar.py +106 -0
  12. rsplot/commands/station.py +154 -42
  13. rsplot/commands/station_trend.py +259 -174
  14. rsplot/config.py +46 -16
  15. rsplot/data_files.py +253 -0
  16. rsplot/errors.py +43 -0
  17. rsplot/fnr.py +38 -46
  18. rsplot/geo/boundaries.py +317 -11
  19. rsplot/geo/footprints.py +205 -0
  20. rsplot/geo/processing.py +84 -5
  21. rsplot/geo/radius.py +205 -0
  22. rsplot/plotting/colormap_22.txt +256 -0
  23. rsplot/plotting/colormaps.py +24 -29
  24. rsplot/plotting/map_frame.py +203 -9
  25. rsplot/plotting/meteo.py +10 -3
  26. rsplot/plotting/overlay.py +36 -40
  27. rsplot/plotting/raster.py +15 -3
  28. rsplot/plotting/station.py +86 -33
  29. rsplot/plotting/station_focus.py +84 -0
  30. rsplot/plotting/station_trend.py +60 -47
  31. rsplot/plotting/styles.py +3 -5
  32. rsplot/readers/__init__.py +89 -7
  33. rsplot/readers/_tropomi.py +121 -3
  34. rsplot/readers/base.py +16 -1
  35. rsplot/readers/era5.py +110 -10
  36. rsplot/readers/era5_wind.py +3 -2
  37. rsplot/readers/gems.py +429 -0
  38. rsplot/readers/guokong.py +125 -39
  39. rsplot/readers/netcdf.py +32 -0
  40. rsplot/readers/tropomi_hcho.py +1 -1
  41. rsplot/readers/tropomi_no2.py +1 -1
  42. rsplot/readers/tropomi_nrti.py +116 -0
  43. rsplot/readers/tropomi_o3.py +1 -1
  44. rsplot/readers/tropomi_o3pr.py +1 -1
  45. rsplot/result_builders/__init__.py +0 -14
  46. rsplot/result_builders/common.py +84 -0
  47. rsplot/result_builders/envelope.py +236 -0
  48. rsplot/result_builders/fnr.py +47 -131
  49. rsplot/result_builders/forecast.py +7 -0
  50. rsplot/result_builders/provenance.py +59 -0
  51. rsplot/result_builders/reconstruct.py +7 -0
  52. rsplot/result_builders/satellite.py +240 -0
  53. rsplot/result_builders/series_layer.py +289 -0
  54. rsplot/result_builders/station.py +23 -0
  55. rsplot/result_builders/station_layer.py +326 -0
  56. rsplot/results.py +0 -12
  57. rsplot/schemas/result.schema.json +566 -0
  58. rsplot/temporal.py +146 -16
  59. rsplot-0.3.2.dev37.dist-info/METADATA +996 -0
  60. rsplot-0.3.2.dev37.dist-info/RECORD +76 -0
  61. {rsplot-0.3.1.dev3.dist-info → rsplot-0.3.2.dev37.dist-info}/WHEEL +1 -1
  62. rsplot/commands/recent.py +0 -164
  63. rsplot/recent.py +0 -404
  64. rsplot/result_builders/meteo.py +0 -171
  65. rsplot/result_builders/overlay.py +0 -75
  66. rsplot/result_builders/raster.py +0 -72
  67. rsplot/result_builders/station_trend.py +0 -229
  68. rsplot-0.3.1.dev3.dist-info/METADATA +0 -477
  69. rsplot-0.3.1.dev3.dist-info/RECORD +0 -64
  70. {rsplot-0.3.1.dev3.dist-info → rsplot-0.3.2.dev37.dist-info}/entry_points.txt +0 -0
  71. {rsplot-0.3.1.dev3.dist-info → rsplot-0.3.2.dev37.dist-info}/licenses/LICENSE +0 -0
rsplot/readers/guokong.py CHANGED
@@ -13,7 +13,9 @@ from pathlib import Path
13
13
  from typing import TYPE_CHECKING
14
14
 
15
15
  import numpy as np
16
- import xarray as xr
16
+
17
+ from rsplot.errors import RsplotError
18
+ from rsplot.readers.netcdf import open_netcdf
17
19
 
18
20
  if TYPE_CHECKING:
19
21
  from shapely.geometry.base import BaseGeometry
@@ -102,25 +104,8 @@ class RegionStationSeries:
102
104
  return int(matches[0]) if len(matches) else None
103
105
 
104
106
 
105
- def read_stations(
106
- data_dir: str,
107
- datetime_str: str,
108
- var_name: str,
109
- extent: tuple[float, float, float, float] | None = None,
110
- ) -> tuple[StationData, str]:
111
- """Read station data for a given hour and variable.
112
-
113
- Parameters
114
- ----------
115
- data_dir : directory containing {YYYYMMDDHH}.nc files.
116
- datetime_str : YYYYMMDDHH (exact hour) or YYYYMMDD (latest hour).
117
- var_name : variable name in the NC file (e.g. "AQI", "PM2.5", "O3").
118
- extent : optional (lon_min, lon_max, lat_min, lat_max) for spatial filter.
119
-
120
- Returns
121
- -------
122
- tuple of (StationData, resolved_datetime_str).
123
- """
107
+ def resolve_station_file(data_dir: str, datetime_str: str) -> Path:
108
+ """Resolve an exact local hour or the latest file on a local date."""
124
109
  if not datetime_str.isdigit() or len(datetime_str) not in (8, 10):
125
110
  raise ValueError(
126
111
  f"datetime 参数 '{datetime_str}' 格式不正确,"
@@ -143,21 +128,113 @@ def read_stations(
143
128
  None,
144
129
  )
145
130
  if path is None:
146
- raise FileNotFoundError(
131
+ raise RsplotError(
132
+ "data_not_found",
147
133
  f"未找到 {datetime_str} 当天的站点数据文件: {pattern}\n"
148
- f"请检查日期和 --data-dir 路径。"
134
+ "请检查日期和配置 [paths.data_dirs].guokong 路径。",
135
+ details={"path": pattern},
149
136
  )
150
137
  datetime_str = path.stem
151
138
  else:
152
139
  path = root / f"{datetime_str}.nc"
140
+ if not path.exists():
141
+ before, after = nearest_station_hours(root, datetime_str)
142
+ raise RsplotError(
143
+ "data_not_found",
144
+ f"未找到站点数据文件: {path};"
145
+ f"{NEAREST_HOURS} 小时内最近可用: 之前 {before or '无'},"
146
+ f"之后 {after or '无'}。",
147
+ details={
148
+ "path": str(path),
149
+ "nearest_before": before,
150
+ "nearest_after": after,
151
+ "search_hours": NEAREST_HOURS,
152
+ },
153
+ )
153
154
 
154
- try:
155
- ds = xr.open_dataset(path)
156
- except FileNotFoundError as e:
157
- raise FileNotFoundError(
158
- f"未找到站点数据文件: {path}\n"
159
- f"请检查 datetime 参数和 --data-dir 路径。"
160
- ) from e
155
+ return path
156
+
157
+
158
+ # How far either side of a missing hour to look for available files.
159
+ NEAREST_HOURS = 48
160
+
161
+
162
+ def nearest_station_hours(
163
+ root: Path, datetime_str: str
164
+ ) -> tuple[str | None, str | None]:
165
+ """Nearest existing hourly files before and after a missing hour.
166
+
167
+ Probes exact ``YYYYMMDDHH.nc`` paths hour by hour rather than listing
168
+ the archive, which holds ~100k files. Reports only; never selects.
169
+ """
170
+ from datetime import datetime, timedelta
171
+
172
+ hour = datetime.strptime(datetime_str, "%Y%m%d%H")
173
+
174
+ def nearest(step: int) -> str | None:
175
+ for offset in range(1, NEAREST_HOURS + 1):
176
+ stamp = (hour + timedelta(hours=step * offset)).strftime(
177
+ "%Y%m%d%H"
178
+ )
179
+ if (root / f"{stamp}.nc").exists():
180
+ return stamp
181
+ return None
182
+
183
+ return nearest(-1), nearest(1)
184
+
185
+
186
+ @dataclass(frozen=True)
187
+ class StationLocations:
188
+ """Station coordinates from one hourly snapshot, without observations."""
189
+
190
+ id: np.ndarray
191
+ lon: np.ndarray
192
+ lat: np.ndarray
193
+ source_file: str
194
+ datetime: str
195
+
196
+
197
+ def read_station_locations(
198
+ data_dir: str,
199
+ datetime_str: str,
200
+ ) -> StationLocations:
201
+ """Read locations even when pollutant variables are absent or missing."""
202
+ path = resolve_station_file(data_dir, datetime_str)
203
+ with open_netcdf(path) as ds:
204
+ for name in ("id", "lon", "lat"):
205
+ if name not in ds:
206
+ raise ValueError(f"站点文件缺少 {name}: {path}")
207
+ ids = np.char.upper(_normalize_station_ids(ds["id"].values))
208
+ lon = ds["lon"].values.astype(float).ravel()
209
+ lat = ds["lat"].values.astype(float).ravel()
210
+ if not (len(ids) == len(lon) == len(lat)):
211
+ raise ValueError(f"站点 ID 与坐标数量不一致: {path}")
212
+ return StationLocations(ids, lon, lat, str(path), path.stem)
213
+
214
+
215
+ def read_stations(
216
+ data_dir: str,
217
+ datetime_str: str,
218
+ var_name: str,
219
+ extent: tuple[float, float, float, float] | None = None,
220
+ ) -> tuple[StationData, str]:
221
+ """Read station data for a given hour and variable.
222
+
223
+ Parameters
224
+ ----------
225
+ data_dir : directory containing {YYYYMMDDHH}.nc files.
226
+ datetime_str : YYYYMMDDHH (exact hour) or YYYYMMDD (latest hour).
227
+ var_name : variable name in the NC file (e.g. "AQI", "PM2.5", "O3").
228
+ extent : optional (lon_min, lon_max, lat_min, lat_max) for spatial filter.
229
+
230
+ Returns
231
+ -------
232
+ tuple of (StationData, resolved_datetime_str).
233
+ """
234
+ path = resolve_station_file(data_dir, datetime_str)
235
+ datetime_str = path.stem
236
+
237
+ ds = open_netcdf(path)
161
238
 
162
239
  try:
163
240
  lon = ds["lon"].values.astype(float)
@@ -165,6 +242,8 @@ def read_stations(
165
242
  station_id = ds["id"].values
166
243
 
167
244
  # Read variable — xarray auto-applies scale_factor/add_offset for CO
245
+ if var_name not in ds:
246
+ raise ValueError(f"站点文件缺少变量 {var_name}: {path}")
168
247
  raw = ds[var_name].values.astype(float)
169
248
  finally:
170
249
  ds.close()
@@ -235,7 +314,7 @@ def read_station_series(
235
314
  continue
236
315
 
237
316
  try:
238
- with xr.open_dataset(path) as ds:
317
+ with open_netcdf(path) as ds:
239
318
  opened_files += 1
240
319
  required = ("id", "lon", "lat", var_name)
241
320
  missing_vars = [name for name in required if name not in ds]
@@ -268,9 +347,11 @@ def read_station_series(
268
347
  failed_files[timestamp] = str(error).splitlines()[0]
269
348
 
270
349
  if opened_files == 0:
271
- raise FileNotFoundError(
350
+ raise RsplotError(
351
+ "data_not_found",
272
352
  f"窗口 {dates[0]}~{dates[-1]} 内未找到可读取的站点文件: "
273
- f"{root}/YYYYMMDDHH.nc"
353
+ f"{root}/YYYYMMDDHH.nc",
354
+ details={"path": f"{root}/YYYYMMDDHH.nc"},
274
355
  )
275
356
  if canonical_id is None or station_lon is None or station_lat is None:
276
357
  if failed_files and not station_missing_hours:
@@ -278,12 +359,15 @@ def read_station_series(
278
359
  f"{timestamp}: {message}"
279
360
  for timestamp, message in list(failed_files.items())[:3]
280
361
  )
281
- raise ValueError(
362
+ raise RsplotError(
363
+ "read_failed",
282
364
  f"窗口 {dates[0]}~{dates[-1]} 内无法读取变量 "
283
- f"'{var_name}': {examples}"
365
+ f"'{var_name}': {examples}",
284
366
  )
285
- raise ValueError(
286
- f"窗口 {dates[0]}~{dates[-1]} 内未找到站点 '{station_id}'"
367
+ raise RsplotError(
368
+ "region_not_found",
369
+ f"窗口 {dates[0]}~{dates[-1]} 内未找到站点 '{station_id}'",
370
+ details={"station_id": station_id},
287
371
  )
288
372
 
289
373
  return StationSeries(
@@ -336,7 +420,7 @@ def read_region_station_series(
336
420
 
337
421
  existing_files += 1
338
422
  try:
339
- with xr.open_dataset(path) as ds:
423
+ with open_netcdf(path) as ds:
340
424
  required = ("id", "lon", "lat", var_name)
341
425
  missing_vars = [name for name in required if name not in ds]
342
426
  if missing_vars:
@@ -376,9 +460,11 @@ def read_region_station_series(
376
460
  hourly_values.append({})
377
461
 
378
462
  if existing_files == 0:
379
- raise FileNotFoundError(
463
+ raise RsplotError(
464
+ "data_not_found",
380
465
  f"窗口 {dates[0]}~{dates[-1]} 内未找到可读取的站点文件: "
381
- f"{root}/YYYYMMDDHH.nc"
466
+ f"{root}/YYYYMMDDHH.nc",
467
+ details={"path": f"{root}/YYYYMMDDHH.nc"},
382
468
  )
383
469
  if not source_files:
384
470
  examples = "; ".join(
@@ -0,0 +1,32 @@
1
+ """Open single NetCDF inputs with coded, one-line failures."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ import xarray as xr
9
+
10
+ from rsplot.errors import RsplotError
11
+
12
+
13
+ def open_netcdf(path: str | Path, **kwargs: Any) -> xr.Dataset:
14
+ """Open ``path``; a missing or unreadable file names itself.
15
+
16
+ xarray reports a corrupt file as a ValueError with a paragraph about IO
17
+ backends; agents get ``read_failed`` and the path instead.
18
+ """
19
+ try:
20
+ return xr.open_dataset(path, **kwargs)
21
+ except FileNotFoundError as error:
22
+ raise RsplotError(
23
+ "data_not_found",
24
+ f"未找到文件: {path}",
25
+ details={"path": str(path)},
26
+ ) from error
27
+ except (OSError, ValueError) as error:
28
+ raise RsplotError(
29
+ "read_failed",
30
+ f"无法读取 NetCDF 文件 {path}:文件损坏或不是 NetCDF 格式。",
31
+ details={"path": str(path), "reason": type(error).__name__},
32
+ ) from error
@@ -21,7 +21,7 @@ _SPEC = TropomiReaderSpec(
21
21
  value_name=VALUE_NAME,
22
22
  unit_conversion=UNIT_CONVERSION,
23
23
  progress_description="[cyan]读取 HCHO 轨道...",
24
- not_found_message="未找到匹配文件: \n {patterns}\n请检查 --hcho-dir / --data-dir 和 --date={date}。",
24
+ not_found_message="未找到匹配文件: \n {patterns}\n请检查配置 [paths.data_dirs] 中的数据目录和日期 {date}。",
25
25
  no_valid_data_message="{date} 当天 HCHO 无有效数据覆盖目标区域 {extent}。\n共扫描 {n_files} 个文件,损坏 {n_broken} 个;可尝试放宽 --qa 阈值。",
26
26
  )
27
27
 
@@ -22,7 +22,7 @@ _SPEC = TropomiReaderSpec(
22
22
  value_name=VALUE_NAME,
23
23
  unit_conversion=UNIT_CONVERSION,
24
24
  progress_description="[cyan]读取轨道数据...",
25
- not_found_message="未找到匹配文件:\n {patterns}\n请检查 --data-dir 和 --date 参数。",
25
+ not_found_message="未找到匹配文件:\n {patterns}\n请检查配置 [paths.data_dirs] 中的数据目录和日期。",
26
26
  no_valid_data_message="{date} 当天无有效数据覆盖目标区域 {extent}。\n共扫描 {n_files} 个文件,损坏 {n_broken} 个。",
27
27
  )
28
28
 
@@ -0,0 +1,116 @@
1
+ """Observation identity and provenance for TROPOMI NRTI granules."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass
7
+ from datetime import datetime, timezone
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import numpy as np
12
+ import xarray as xr
13
+
14
+ _FILENAME = re.compile(
15
+ r"^S5P_NRTI_L2__.{7}(\d{8}T\d{6})_(\d{8}T\d{6})_"
16
+ r"(\d{5})_\d{2}_\d{6}_(\d{8}T\d{6})\.nc(?:\.zip)?$"
17
+ )
18
+ IDENTITY_DTYPE = np.dtype(
19
+ [("orbit", "i8"), ("time_ms", "i8"), ("ground_pixel", "i8")]
20
+ )
21
+
22
+
23
+ class NrtiReadError(ValueError):
24
+ """A failed day whose per-file diagnostics can still reach sidecars."""
25
+
26
+ def __init__(self, message: str, metadata: dict[str, Any]):
27
+ super().__init__(message)
28
+ self.metadata = metadata
29
+
30
+
31
+ def granule_identity(path: str) -> tuple[int, str]:
32
+ """Return orbit and production timestamp from the standard filename."""
33
+ match = _FILENAME.fullmatch(Path(path).name)
34
+ if match is None:
35
+ raise ValueError(
36
+ f"NRTI 文件名无法识别轨道与生成时间: {Path(path).name}"
37
+ )
38
+ for value in (match[1], match[2], match[4]):
39
+ datetime.strptime(value, "%Y%m%dT%H%M%S")
40
+ return int(match[3]), match[4]
41
+
42
+
43
+ def _utc_milliseconds(values: np.ndarray, units: str) -> np.ndarray:
44
+ match = re.fullmatch(r"(milliseconds|seconds) since (.+)", units)
45
+ if match is None:
46
+ raise ValueError(f"NRTI delta_time 单位不支持: {units}")
47
+ origin = datetime.fromisoformat(match[2].replace("Z", "+00:00"))
48
+ if origin.tzinfo is None:
49
+ origin = origin.replace(tzinfo=timezone.utc)
50
+ epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
51
+ offset_ms = round((origin - epoch).total_seconds() * 1000)
52
+ factor = 1 if match[1] == "milliseconds" else 1000
53
+ milliseconds = np.asarray(values, dtype=float) * factor + offset_ms
54
+ if not np.all(np.isfinite(milliseconds)):
55
+ raise ValueError("NRTI 观测时间包含缺失或非有限值")
56
+ if np.any(np.abs(milliseconds) >= np.iinfo(np.int64).max):
57
+ raise ValueError("NRTI 观测时间超出范围")
58
+ return np.rint(milliseconds).astype(np.int64)
59
+
60
+
61
+ @dataclass
62
+ class NrtiObservations:
63
+ keys: np.ndarray
64
+ processor_version: str | None
65
+ product_version: str | None
66
+
67
+
68
+ def read_nrti_observations(
69
+ path: str, shape: tuple[int, ...]
70
+ ) -> NrtiObservations:
71
+ """Read real pixel IDs; never substitute file-local scanline indices.
72
+
73
+ delta_time is either per scanline (NO2/O3PR) or per pixel (HCHO/O3).
74
+ Its CF units already contain the UTC reference epoch, so adding the
75
+ separate PRODUCT/time value again would double-count that epoch.
76
+ """
77
+ orbit, _ = granule_identity(path)
78
+ errors = []
79
+ with xr.open_dataset(path, decode_times=False) as root:
80
+ processor = root.attrs.get("processor_version")
81
+ version = root.attrs.get("product_version")
82
+ for group, prefix in ((None, "PRODUCT_"), ("PRODUCT", "")):
83
+ try:
84
+ kwargs = {} if group is None else {"group": group}
85
+ with xr.open_dataset(path, decode_times=False, **kwargs) as ds:
86
+ delta = ds[f"{prefix}delta_time"]
87
+ times = _utc_milliseconds(
88
+ delta.values.squeeze(), delta.attrs.get("units", "")
89
+ )
90
+ columns = ds[f"{prefix}ground_pixel"].values.squeeze()
91
+ if len(shape) == 2 and times.ndim == 1:
92
+ times = times[:, None]
93
+ times = np.broadcast_to(times, shape)
94
+ columns = np.broadcast_to(columns, shape)
95
+ if not np.all(np.isfinite(columns)) or np.any(
96
+ columns != np.floor(columns)
97
+ ):
98
+ raise ValueError("NRTI ground_pixel 索引无效")
99
+ keys = np.empty(shape, dtype=IDENTITY_DTYPE)
100
+ keys["orbit"] = orbit
101
+ keys["time_ms"] = times
102
+ keys["ground_pixel"] = columns
103
+ return NrtiObservations(keys, processor, version)
104
+ except (OSError, ValueError, KeyError) as error:
105
+ errors.append(str(error).splitlines()[0])
106
+ raise ValueError("无法读取 NRTI 观测身份: " + "; ".join(errors))
107
+
108
+
109
+ def observation_range(keys: np.ndarray) -> dict[str, str] | None:
110
+ if not keys.size:
111
+ return None
112
+ times = keys["time_ms"]
113
+ return {
114
+ label: str(np.datetime64(int(value), "ms")) + "Z"
115
+ for label, value in (("start", times.min()), ("end", times.max()))
116
+ }
@@ -24,7 +24,7 @@ _SPEC = TropomiReaderSpec(
24
24
  value_name=VALUE_NAME,
25
25
  unit_conversion=UNIT_CONVERSION,
26
26
  progress_description="[cyan]读取轨道数据...",
27
- not_found_message="未找到匹配文件:\n {patterns}\n请检查 --data-dir 和 --date 参数。",
27
+ not_found_message="未找到匹配文件:\n {patterns}\n请检查配置 [paths.data_dirs] 中的数据目录和日期。",
28
28
  no_valid_data_message="{date} 当天无有效数据覆盖目标区域 {extent}。\n共扫描 {n_files} 个文件,损坏 {n_broken} 个。",
29
29
  )
30
30
 
@@ -22,7 +22,7 @@ _SPEC = TropomiReaderSpec(
22
22
  value_name=VALUE_NAME,
23
23
  unit_conversion=UNIT_CONVERSION,
24
24
  progress_description="[cyan]读取 O3PR 轨道...",
25
- not_found_message="未找到匹配文件:\n {patterns}\n请检查 --data-dir 和 --date 参数。",
25
+ not_found_message="未找到匹配文件:\n {patterns}\n请检查配置 [paths.data_dirs] 中的数据目录和日期。",
26
26
  no_valid_data_message="{date} 当天 O3PR 无有效数据覆盖目标区域 {extent}。\n共扫描 {n_files} 个文件,损坏 {n_broken} 个。",
27
27
  )
28
28
 
@@ -1,25 +1,11 @@
1
1
  """Domain-specific builders for rsplot's stable JSON sidecars."""
2
2
 
3
- from rsplot.result_builders.fnr import build_fnr_result
4
3
  from rsplot.result_builders.forecast import build_forecast_result
5
- from rsplot.result_builders.meteo import build_meteo_result
6
- from rsplot.result_builders.overlay import build_overlay_result
7
- from rsplot.result_builders.raster import build_raster_result
8
4
  from rsplot.result_builders.reconstruct import build_reconstruct_result
9
5
  from rsplot.result_builders.station import build_station_result
10
- from rsplot.result_builders.station_trend import (
11
- build_region_trend_result,
12
- build_station_trend_result,
13
- )
14
6
 
15
7
  __all__ = [
16
- "build_fnr_result",
17
8
  "build_forecast_result",
18
- "build_meteo_result",
19
- "build_overlay_result",
20
- "build_raster_result",
21
9
  "build_reconstruct_result",
22
- "build_region_trend_result",
23
10
  "build_station_result",
24
- "build_station_trend_result",
25
11
  ]
@@ -21,10 +21,65 @@ def serialize_region(region: RegionInfo) -> dict[str, Any]:
21
21
  "level": region.level,
22
22
  "extent": [round(value, 3) for value in region.extent],
23
23
  }
24
+ if region.geometry_kind != "administrative":
25
+ result["geometry_kind"] = region.geometry_kind
26
+ result["level"] = None
24
27
  if region.administrative_level not in (None, region.level):
25
28
  result["administrative_level"] = region.administrative_level
26
29
  if region.subdivision_level is not None:
27
30
  result["subdivision_level"] = region.subdivision_level
31
+ if region.members:
32
+ result["members"] = [
33
+ serialize_member(member) for member in region.members
34
+ ]
35
+ return result
36
+
37
+
38
+ def serialize_member(member: RegionInfo) -> dict[str, Any]:
39
+ """Identify a selected member with its canonical, qualified name."""
40
+ result = serialize_region(member)
41
+ result["name"] = member.qualified_name or member.name
42
+ result.setdefault(
43
+ "administrative_level", member.administrative_level or member.level
44
+ )
45
+ return result
46
+
47
+
48
+ def member_basic_stats(values: np.ndarray) -> dict[str, Any]:
49
+ """Explicit null summaries retain members with no valid observations."""
50
+ result = basic_stats(values)
51
+ if result:
52
+ return result
53
+ return {
54
+ "n": 0,
55
+ **dict.fromkeys(
56
+ ("min", "max", "mean", "median", "p10", "p25", "p75", "p90")
57
+ ),
58
+ }
59
+
60
+
61
+ def grid_member_stats(
62
+ lon: np.ndarray,
63
+ lat: np.ndarray,
64
+ grid: np.ndarray,
65
+ region: RegionInfo,
66
+ ) -> list[dict[str, Any]]:
67
+ """Select each member on the same statistical grid, never sum overlaps."""
68
+ from rsplot.geo.gridding import mask_to_region
69
+
70
+ result = []
71
+ for member in region.members:
72
+ selected = mask_to_region(lon, lat, grid, member.geometry)
73
+ stats = grid_stats(
74
+ lon,
75
+ lat,
76
+ selected,
77
+ member,
78
+ valid_key="valid_region_pixels",
79
+ total_key="total_region_pixels",
80
+ )
81
+ stats.update(member_basic_stats(selected))
82
+ result.append({"region": serialize_member(member), "stats": stats})
28
83
  return result
29
84
 
30
85
 
@@ -136,3 +191,32 @@ def grid_stats(
136
191
  total_key: total,
137
192
  **basic_stats(grid),
138
193
  }
194
+
195
+
196
+ def grid_boundary_policy(
197
+ lon: np.ndarray,
198
+ lat: np.ndarray,
199
+ display_grid: np.ndarray,
200
+ region: RegionInfo,
201
+ ) -> dict[str, Any]:
202
+ """Describe distinct display and statistics spatial selection rules."""
203
+ from rsplot.geo.gridding import region_grid_mask
204
+ from rsplot.geo.processing import region_cell_mask
205
+
206
+ visible = np.isfinite(display_grid) & region_cell_mask(
207
+ lon, lat, region.geometry
208
+ )
209
+ inside = region_grid_mask(lon, lat, region.geometry)
210
+ return {
211
+ "statistics": {
212
+ "selection": "grid_center_strictly_inside",
213
+ "weighting": "equal_cells",
214
+ "coverage": "valid_center_count / total_center_count",
215
+ },
216
+ "display": {
217
+ "selection": "valid_cells_intersecting_region",
218
+ "clip": f"{region.geometry_kind}_geometry",
219
+ "n_valid_intersecting_cells": int(visible.sum()),
220
+ "n_cells_with_centers_outside": int((visible & ~inside).sum()),
221
+ },
222
+ }