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.
Files changed (67) hide show
  1. rsplot/atomic.py +36 -0
  2. rsplot/cli.py +272 -497
  3. rsplot/commands/common.py +52 -3
  4. rsplot/commands/fnr.py +389 -104
  5. rsplot/commands/forecast.py +0 -2
  6. rsplot/commands/meteo.py +499 -186
  7. rsplot/commands/overlay.py +284 -326
  8. rsplot/commands/radius.py +526 -0
  9. rsplot/commands/raster.py +418 -293
  10. rsplot/commands/reconstruct.py +0 -1
  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 +43 -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 +212 -9
  19. rsplot/geo/footprints.py +3 -0
  20. rsplot/geo/processing.py +2 -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 +84 -6
  25. rsplot/plotting/meteo.py +10 -3
  26. rsplot/plotting/overlay.py +31 -40
  27. rsplot/plotting/raster.py +10 -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 +52 -4
  33. rsplot/readers/_tropomi.py +121 -3
  34. rsplot/readers/era5.py +110 -10
  35. rsplot/readers/era5_wind.py +3 -2
  36. rsplot/readers/gems.py +11 -8
  37. rsplot/readers/guokong.py +125 -39
  38. rsplot/readers/netcdf.py +32 -0
  39. rsplot/readers/tropomi_hcho.py +1 -1
  40. rsplot/readers/tropomi_no2.py +1 -1
  41. rsplot/readers/tropomi_nrti.py +116 -0
  42. rsplot/readers/tropomi_o3.py +1 -1
  43. rsplot/readers/tropomi_o3pr.py +1 -1
  44. rsplot/result_builders/__init__.py +0 -14
  45. rsplot/result_builders/common.py +4 -1
  46. rsplot/result_builders/envelope.py +236 -0
  47. rsplot/result_builders/fnr.py +47 -131
  48. rsplot/result_builders/provenance.py +59 -0
  49. rsplot/result_builders/satellite.py +240 -0
  50. rsplot/result_builders/series_layer.py +289 -0
  51. rsplot/result_builders/station.py +23 -0
  52. rsplot/result_builders/station_layer.py +326 -0
  53. rsplot/results.py +0 -12
  54. rsplot/schemas/result.schema.json +566 -0
  55. rsplot/temporal.py +7 -0
  56. {rsplot-0.3.2.dev4.dist-info → rsplot-0.3.2.dev37.dist-info}/METADATA +426 -121
  57. rsplot-0.3.2.dev37.dist-info/RECORD +76 -0
  58. {rsplot-0.3.2.dev4.dist-info → rsplot-0.3.2.dev37.dist-info}/WHEEL +1 -1
  59. rsplot/commands/recent.py +0 -186
  60. rsplot/recent.py +0 -447
  61. rsplot/result_builders/meteo.py +0 -171
  62. rsplot/result_builders/overlay.py +0 -105
  63. rsplot/result_builders/raster.py +0 -104
  64. rsplot/result_builders/station_trend.py +0 -229
  65. rsplot-0.3.2.dev4.dist-info/RECORD +0 -66
  66. {rsplot-0.3.2.dev4.dist-info → rsplot-0.3.2.dev37.dist-info}/entry_points.txt +0 -0
  67. {rsplot-0.3.2.dev4.dist-info → rsplot-0.3.2.dev37.dist-info}/licenses/LICENSE +0 -0
rsplot/commands/meteo.py CHANGED
@@ -3,10 +3,10 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import math
6
- from typing import TYPE_CHECKING
6
+ from pathlib import Path
7
+ from typing import TYPE_CHECKING, Any
7
8
 
8
9
  import numpy as np
9
- import typer
10
10
 
11
11
  from rsplot.commands.common import (
12
12
  load_fallback_city_boundaries,
@@ -16,23 +16,32 @@ from rsplot.commands.common import (
16
16
  warn_missing_tianditu_key,
17
17
  )
18
18
  from rsplot.config import AppConfig
19
- from rsplot.temporal import DEFAULT_INPUT_TIMEZONE
19
+ from rsplot.errors import RsplotError
20
+ from rsplot.result_builders.provenance import input_fingerprint
20
21
 
21
22
  if TYPE_CHECKING:
22
23
  from rich.console import Console
23
24
 
24
25
 
25
- def run_meteo(
26
+ def run_meteo(**kwargs: Any) -> None:
27
+ """Map ERA5 temperature, wind and an optional station hour."""
28
+ from rsplot.commands.sidecar import run_with_sidecar
29
+
30
+ run_with_sidecar(
31
+ kwargs=kwargs,
32
+ emit=lambda created: _emit_meteo(created, **kwargs),
33
+ )
34
+
35
+
36
+ def _emit_meteo(
37
+ created: list[Path],
26
38
  *,
27
39
  region: str,
28
40
  datetime_str: str,
29
41
  temp_level: str | None,
30
42
  wind_level: str | None,
31
43
  station_var: str | None,
32
- level: str | None,
33
- data_dir: str | None,
34
- station_data_dir: str | None,
35
- output: str | None,
44
+ output: str,
36
45
  dpi: int | None,
37
46
  basemap: str | None,
38
47
  cmap: str | None,
@@ -44,65 +53,114 @@ def run_meteo(
44
53
  title: str | None,
45
54
  console: Console,
46
55
  ) -> None:
47
- """Execute meteorological plotting and optional station overlay."""
56
+ """Read ERA5 (and stations) for one China-time hour and write results."""
48
57
  from rsplot.config import (
49
58
  STATION_VAR_LABELS,
50
59
  STATION_VAR_META,
51
60
  get_exceedance_threshold,
52
61
  )
53
- from rsplot.geo.boundaries import resolve_region
62
+ from rsplot.data_files import data_path, write_grid_netcdf, write_table_csv
63
+ from rsplot.geo.boundaries import resolve_regions
54
64
  from rsplot.geo.processing import buffered_extent
55
65
  from rsplot.plotting.meteo import plot_meteo
56
66
  from rsplot.plotting.styles import setup_fonts
57
67
  from rsplot.plotting.wind import wind_stride_for_shape
58
68
  from rsplot.readers.era5 import (
59
69
  mask_era5_field_to_region,
70
+ normalize_temperature_level,
60
71
  read_era5_temperature,
61
72
  )
62
73
  from rsplot.readers.era5_wind import (
63
74
  mask_wind_to_region,
75
+ normalize_wind_level,
64
76
  read_era5_wind,
65
77
  )
66
- from rsplot.readers.guokong import mask_stations_to_region, read_stations
67
- from rsplot.results import build_meteo_result, emit_result
78
+ from rsplot.readers.guokong import (
79
+ mask_stations_to_region,
80
+ read_stations,
81
+ )
82
+ from rsplot.result_builders.envelope import (
83
+ command_line,
84
+ sidecar_path,
85
+ success_envelope,
86
+ write_sidecar,
87
+ )
88
+ from rsplot.result_builders.station import build_station_display
89
+ from rsplot.result_builders.station_layer import (
90
+ TABLE_COLUMNS,
91
+ StationInputs,
92
+ build_station_layer,
93
+ )
94
+ from rsplot.temporal import adapt_hourly_time
68
95
 
96
+ # Station observations and ERA5 share one explicit China-time hour; a
97
+ # date-only input would have to pick a "latest" hour, which is forbidden.
98
+ try:
99
+ adapt_hourly_time(datetime_str, label="meteo 时次")
100
+ except ValueError as error:
101
+ raise RsplotError(
102
+ "invalid_time",
103
+ f"meteo 时次必须是 YYYYMMDDHH,不会自动选择最新小时。 ({error})",
104
+ ) from error
69
105
  if station_var is not None and wind_level is None:
70
- console.print(
71
- "[red]--station-var 必须与 --wind-level 一起使用。[/red]"
106
+ raise RsplotError(
107
+ "invalid_argument",
108
+ "--station-var 必须与 --wind-level 一起使用。",
109
+ option="--station-var",
72
110
  )
73
- raise typer.Exit(1)
74
111
  if temp_level is None and wind_level is None:
75
- console.print(
76
- "[red]请至少指定 --temp-level 或 --wind-level 中的一个。[/red]"
112
+ raise RsplotError(
113
+ "invalid_argument",
114
+ "请至少指定 --temp-level 或 --wind-level 中的一个。",
77
115
  )
78
- raise typer.Exit(1)
79
116
  if station_var is not None and station_var not in STATION_VAR_META:
80
- available = ", ".join(STATION_VAR_META)
81
- console.print(
82
- f"[red]未知站点变量 '{station_var}'[/red]。可用: {available}"
117
+ raise RsplotError(
118
+ "invalid_argument",
119
+ f"未知站点变量 '{station_var}'。可用: "
120
+ + ", ".join(STATION_VAR_META),
121
+ option="--station-var",
83
122
  )
84
- raise typer.Exit(1)
85
- if temp_level is None and any(
86
- value is not None for value in (cmap, vmin, vmax)
123
+ if temp_level is None:
124
+ for option, value in (
125
+ ("--cmap", cmap),
126
+ ("--vmin", vmin),
127
+ ("--vmax", vmax),
128
+ ):
129
+ if value is not None:
130
+ raise RsplotError(
131
+ "invalid_argument",
132
+ "--cmap/--vmin/--vmax 只用于温度底图;"
133
+ "当前命令没有指定 --temp-level。",
134
+ option=option,
135
+ )
136
+ for option, check, value in (
137
+ ("--temp-level", normalize_temperature_level, temp_level),
138
+ ("--wind-level", normalize_wind_level, wind_level),
87
139
  ):
88
- console.print(
89
- "[red]--cmap/--vmin/--vmax 只用于温度底图;"
90
- "当前命令没有指定 --temp-level。[/red]"
91
- )
92
- raise typer.Exit(1)
93
- error = _wind_option_error(
94
- stride=wind_stride,
95
- scale=wind_scale,
96
- width=wind_width,
140
+ if value is not None:
141
+ try:
142
+ check(value)
143
+ except ValueError as error:
144
+ raise RsplotError(
145
+ "invalid_argument", str(error), option=option
146
+ ) from error
147
+ error_text, error_option = _wind_option_error(
148
+ stride=wind_stride, scale=wind_scale, width=wind_width
97
149
  )
98
- if error is not None:
99
- console.print(f"[red]{error}[/red]")
100
- raise typer.Exit(1)
150
+ if error_text is not None:
151
+ raise RsplotError("invalid_argument", error_text, option=error_option)
101
152
 
102
153
  cfg = AppConfig.load()
103
154
  setup_fonts(cfg.font_dir)
104
155
  console.print(f"[bold]解析区域:[/bold] {region}")
105
- info = resolve_region(region, cfg, level_override=level)
156
+ try:
157
+ info = resolve_regions(region, cfg)
158
+ except RsplotError:
159
+ raise
160
+ except ValueError as error:
161
+ raise RsplotError(
162
+ "region_not_found", str(error), details={"region": region}
163
+ ) from error
106
164
  console.print(f" → [green]{info.name}[/green] (级别: {info.level})")
107
165
  read_extent = buffered_extent(info.extent, 0.5)
108
166
  use_dpi = dpi if dpi is not None else cfg.dpi
@@ -111,8 +169,7 @@ def run_meteo(
111
169
  validate_positive(use_dpi, "--dpi")
112
170
  validate_color_range(vmin, vmax)
113
171
  except ValueError as error:
114
- console.print(f"[red]{error}[/red]")
115
- raise typer.Exit(1) from error
172
+ raise RsplotError("invalid_argument", str(error)) from error
116
173
  warn_missing_tianditu_key(
117
174
  basemap=use_basemap,
118
175
  default_basemap=info.params.basemap,
@@ -120,30 +177,19 @@ def run_meteo(
120
177
  console=console,
121
178
  )
122
179
 
123
- station = None
180
+ read = station = None
124
181
  station_threshold = None
125
182
  station_unit = ""
126
183
  station_colorbar_label = ""
127
- resolved_datetime = datetime_str
184
+ use_station_dir = None
128
185
  if station_var is not None:
129
- use_station_dir = station_data_dir or cfg.get_data_dir("guokong")
186
+ use_station_dir = cfg.get_data_dir("guokong")
130
187
  console.print(f"\n[bold]读取站点数据:[/bold] {use_station_dir}")
131
188
  console.print(f" 时间: {datetime_str}, 变量: {station_var}")
132
- try:
133
- station, resolved_datetime = read_stations(
134
- use_station_dir,
135
- datetime_str,
136
- station_var,
137
- extent=read_extent,
138
- )
139
- station = mask_stations_to_region(station, info.geometry)
140
- except (FileNotFoundError, ValueError) as error:
141
- console.print(f"[red]{error}[/red]")
142
- raise typer.Exit(1) from error
143
- if resolved_datetime != datetime_str:
144
- console.print(
145
- f" → 自动选择最新时次: [cyan]{resolved_datetime}[/cyan]"
146
- )
189
+ read, _ = read_stations(
190
+ use_station_dir, datetime_str, station_var, extent=read_extent
191
+ )
192
+ station = mask_stations_to_region(read, info.geometry)
147
193
  console.print(
148
194
  f" → [green]{station.n_valid}[/green] 有效站点 "
149
195
  f"(共 {station.n_stations} 站)"
@@ -154,48 +200,36 @@ def run_meteo(
154
200
  station_colorbar_label = (
155
201
  f"{display_var} ({station_unit})" if station_unit else display_var
156
202
  )
157
- if station_threshold is not None:
158
- finite = station.values[np.isfinite(station.values)]
159
- n_exceed = int(np.sum(finite > station_threshold))
160
- console.print(
161
- f" → 超标阈值: {station_threshold}, "
162
- f"超标站点: [red]{n_exceed}[/red]"
163
- )
164
203
 
165
- use_data_dir = data_dir or cfg.get_data_dir("era5")
204
+ use_data_dir = str(cfg.get_data_dir("era5"))
166
205
  console.print(f"\n[bold]读取 ERA5:[/bold] {use_data_dir}")
167
- console.print(f" 输入时次: {resolved_datetime} (中国时间)")
168
- if temp_level is not None:
169
- console.print(f" 温度图层: {temp_level}")
170
- if wind_level is not None:
171
- console.print(f" 风场图层: {wind_level}")
172
-
173
- field = None
174
- wind = None
206
+ console.print(f" 输入时次: {datetime_str}")
207
+ field = wind = None
175
208
  try:
176
209
  if temp_level is not None:
177
- field = read_era5_temperature(
178
- use_data_dir,
179
- resolved_datetime,
180
- temp_level,
181
- read_extent,
210
+ field = mask_era5_field_to_region(
211
+ read_era5_temperature(
212
+ use_data_dir, datetime_str, temp_level, read_extent
213
+ ),
214
+ info.geometry,
182
215
  )
183
- field = mask_era5_field_to_region(field, info.geometry)
184
- if field.n_valid == 0:
185
- raise ValueError("目标区域内没有有效 ERA5 温度网格。")
186
216
  if wind_level is not None:
187
- wind = read_era5_wind(
188
- use_data_dir,
189
- resolved_datetime,
190
- wind_level,
191
- read_extent,
217
+ wind = mask_wind_to_region(
218
+ read_era5_wind(
219
+ use_data_dir, datetime_str, wind_level, read_extent
220
+ ),
221
+ info.geometry,
192
222
  )
193
- wind = mask_wind_to_region(wind, info.geometry)
194
- if wind is not None and wind.n_valid == 0:
195
- raise ValueError("目标区域内没有有效 ERA5 风矢量。")
196
- except (FileNotFoundError, ValueError) as error:
197
- console.print(f"[red]{error}[/red]")
198
- raise typer.Exit(1) from error
223
+ except (FileNotFoundError, RsplotError):
224
+ raise
225
+ except ValueError as error:
226
+ raise RsplotError("read_failed", str(error)) from error
227
+ if field is not None and field.n_valid == 0:
228
+ raise RsplotError(
229
+ "no_valid_data", "目标区域内没有有效 ERA5 温度网格。"
230
+ )
231
+ if wind is not None and wind.n_valid == 0:
232
+ raise RsplotError("no_valid_data", "目标区域内没有有效 ERA5 风矢量。")
199
233
 
200
234
  use_wind_stride = None
201
235
  if wind is not None:
@@ -204,55 +238,217 @@ def run_meteo(
204
238
  if wind_stride is not None
205
239
  else wind_stride_for_shape(wind.speed.shape, info.level)
206
240
  )
207
-
208
241
  use_cmap = cmap or "RdYlBu_r"
209
- use_vmin = None
210
- use_vmax = None
242
+ use_vmin = use_vmax = None
211
243
  if field is not None:
212
- try:
213
- use_vmin, use_vmax = _temperature_range(
214
- field.values,
215
- vmin=vmin,
216
- vmax=vmax,
217
- )
218
- except ValueError as error:
219
- console.print(f"[red]{error}[/red]")
220
- raise typer.Exit(1) from error
221
-
222
- datetime_utc = (
223
- field.datetime_utc if field is not None else wind.datetime_utc
224
- )
225
- console.print(f" → ERA5 UTC 时次: [cyan]{datetime_utc}[/cyan]")
226
- if field is not None:
227
- console.print(
228
- f" → 温度有效网格: [green]{field.n_valid}[/green], "
229
- f"色阶: {use_vmin:.2f} ~ {use_vmax:.2f} °C"
244
+ use_vmin, use_vmax = _temperature_range(
245
+ field.values, vmin=vmin, vmax=vmax
230
246
  )
231
- if wind is not None:
232
- console.print(
233
- f" → 风场层次: {wind.level}, "
234
- f"有效网格: [green]{wind.n_valid}[/green], "
235
- f"抽稀步长: {use_wind_stride}"
236
- )
237
-
238
247
  use_title = title or _default_title(
239
248
  region=info.name,
240
- datetime_str=resolved_datetime,
249
+ datetime_str=datetime_str,
241
250
  temp_level=field.level if field is not None else None,
242
251
  station_var=station_var,
243
252
  wind_level=wind.level if wind is not None else None,
244
253
  )
245
- if output is None:
246
- layer_suffix = _output_layer_suffix(
247
- temp_level=field.level if field is not None else None,
248
- station_var=station_var,
249
- wind_level=wind.level if wind is not None else None,
254
+ image = str(Path(output).resolve())
255
+ sidecar = sidecar_path(image)
256
+
257
+ from shapely import contains_xy
258
+
259
+ time = {
260
+ "aggregation": "hourly",
261
+ "at": datetime_str,
262
+ "basis": "era5_hour",
263
+ }
264
+ layers: list[dict[str, Any]] = []
265
+ flags: list[dict[str, Any]] = []
266
+ data_entries: list[dict[str, Any]] = []
267
+ render_layers: dict[str, Any] = {}
268
+ if field is not None:
269
+ counted = contains_xy(info.geometry.buffer(1e-9), field.lon, field.lat)
270
+ path = data_path(image, "temperature", ".nc")
271
+ created.append(path)
272
+ entry = write_grid_netcdf(
273
+ path,
274
+ field.lon,
275
+ field.lat,
276
+ field.values,
277
+ counted,
278
+ extent=info.extent,
279
+ layer="temperature",
280
+ attrs={
281
+ "quantity": f"temperature_{field.level}",
282
+ "unit": "degC",
283
+ "scale": 1.0,
284
+ "time_aggregation": "hourly",
285
+ },
286
+ )
287
+ data_entries.append(entry)
288
+ layer, layer_flags = _era5_grid_layer(
289
+ layer_id="temperature",
290
+ kind="grid",
291
+ quantity={
292
+ "name": f"temperature_{field.level}",
293
+ "unit": "degC",
294
+ "scale": 1,
295
+ "label": f"{_level_label(field.level)} temperature (°C)",
296
+ },
297
+ time=time,
298
+ data_root=use_data_dir,
299
+ files=[field.source_file],
300
+ method={
301
+ "level": field.level,
302
+ "conversion": "kelvin_minus_273.15",
303
+ "cell_selection": "center_inside_region",
304
+ "cell_weighting": "equal",
305
+ },
306
+ values=field.values,
307
+ lon=field.lon,
308
+ lat=field.lat,
309
+ counted=counted,
310
+ region=info,
311
+ data=entry["path"],
312
+ )
313
+ layers.append(layer)
314
+ flags.extend(layer_flags)
315
+ render_layers["temperature"] = {
316
+ "cmap": use_cmap,
317
+ "vmin": use_vmin,
318
+ "vmax": use_vmax,
319
+ "range_method": (
320
+ "manual"
321
+ if vmin is not None and vmax is not None
322
+ else "region_p02_p98"
323
+ ),
324
+ }
325
+ if wind is not None:
326
+ counted = contains_xy(info.geometry.buffer(1e-9), wind.lon, wind.lat)
327
+ path = data_path(image, "wind", ".nc")
328
+ created.append(path)
329
+ entry = write_grid_netcdf(
330
+ path,
331
+ wind.lon,
332
+ wind.lat,
333
+ wind.speed,
334
+ counted,
335
+ extent=info.extent,
336
+ layer="wind",
337
+ attrs={
338
+ "quantity": f"wind_{wind.level}",
339
+ "unit": "m/s",
340
+ "scale": 1.0,
341
+ "time_aggregation": "hourly",
342
+ },
343
+ extra={"u": wind.u, "v": wind.v},
344
+ content="vector_grid",
345
+ )
346
+ data_entries.append(entry)
347
+ layer, layer_flags = _era5_grid_layer(
348
+ layer_id="wind",
349
+ kind="vector_grid",
350
+ quantity={
351
+ "name": f"wind_{wind.level}",
352
+ "unit": "m/s",
353
+ "scale": 1,
354
+ "label": f"{_level_label(wind.level)} wind speed (m/s)",
355
+ },
356
+ time=time,
357
+ data_root=use_data_dir,
358
+ files=list(wind.source_files),
359
+ method={
360
+ "level": wind.level,
361
+ "speed": "hypot(u, v)",
362
+ "cell_selection": "center_inside_region",
363
+ "cell_weighting": "equal",
364
+ },
365
+ values=wind.speed,
366
+ lon=wind.lon,
367
+ lat=wind.lat,
368
+ counted=counted,
369
+ region=info,
370
+ data=entry["path"],
371
+ unit="vectors",
372
+ )
373
+ layer["vector_summary"] = _vector_summary(wind)
374
+ layers.append(layer)
375
+ flags.extend(layer_flags)
376
+ step = max(1, use_wind_stride or 1)
377
+ render_layers["wind"] = {
378
+ "color": "black",
379
+ "colorbar": False,
380
+ "stride": step,
381
+ "scale": wind_scale,
382
+ "width": wind_width,
383
+ "arrows_plotted": int(
384
+ np.isfinite(wind.speed[::step, ::step]).sum()
385
+ ),
386
+ "magnitude_encoding": "arrow_length_with_reference_arrow",
387
+ }
388
+
389
+ relations: dict[str, Any] = {}
390
+ if read is not None and station is not None:
391
+ assert station_var is not None and use_station_dir is not None
392
+ in_region = contains_xy(info.geometry.buffer(1e-9), read.lon, read.lat)
393
+ limit_key, limit_time = STATION_VAR_META[station_var][1:]
394
+ station_path = data_path(image, "station", ".csv")
395
+ admin_gdf = (
396
+ info.sub_boundary_gdf
397
+ if info.sub_boundary_gdf is not None and len(info.sub_boundary_gdf)
398
+ else load_fallback_city_boundaries(info, cfg.require_geojson_dir())
399
+ )
400
+ station_layer, station_flags, rows = build_station_layer(
401
+ StationInputs(
402
+ read=read,
403
+ in_region=in_region,
404
+ var=station_var,
405
+ unit=station_unit,
406
+ threshold=station_threshold,
407
+ standard=(
408
+ f"AQ_LIMITS_2026 {limit_key} {limit_time}"
409
+ if station_threshold is not None
410
+ else None
411
+ ),
412
+ hour=datetime_str,
413
+ data_root=str(use_station_dir),
414
+ ),
415
+ info,
416
+ admin_gdf=admin_gdf,
417
+ satellite_values=None,
418
+ data=str(station_path),
250
419
  )
251
- output = (
252
- f"/tmp/rsplot_meteo_{info.name}_{layer_suffix}_"
253
- f"{resolved_datetime}.png"
420
+ created.append(station_path)
421
+ data_entries.append(
422
+ write_table_csv(
423
+ station_path,
424
+ rows,
425
+ [
426
+ column
427
+ for column in TABLE_COLUMNS
428
+ if column not in ("satellite_value", "colocated")
429
+ ],
430
+ content="station_table",
431
+ layer="station",
432
+ )
254
433
  )
434
+ layers.append(station_layer)
435
+ flags.extend(station_flags)
436
+ relations["time_matching"] = {
437
+ "layers": ["wind", "station"],
438
+ "reference": "same_hour",
439
+ "difference_minutes": 0,
440
+ "manual_override": False,
441
+ }
442
+ render_layers["station"] = {
443
+ **(
444
+ build_station_display(station)
445
+ or {"range_method": "data_p5_p95"}
446
+ ),
447
+ "colorbar_label": station_colorbar_label,
448
+ }
449
+
255
450
  console.print("\n[bold]绘图中...[/bold]")
451
+ created.append(Path(image))
256
452
  plot_meteo(
257
453
  info,
258
454
  field=field,
@@ -270,38 +466,170 @@ def run_meteo(
270
466
  basemap=use_basemap,
271
467
  tianditu_key=cfg.tianditu_key,
272
468
  title=use_title,
273
- output=output,
469
+ output=image,
470
+ )
471
+
472
+ effective_basemap = (
473
+ use_basemap if use_basemap is not None else info.params.basemap
274
474
  )
275
- result = build_meteo_result(
475
+ payload = success_envelope(
476
+ command="meteo",
477
+ request=command_line(),
276
478
  region=info,
277
- variable="temperature" if field is not None else "wind",
278
- input_datetime=resolved_datetime,
279
- input_timezone=DEFAULT_INPUT_TIMEZONE,
280
- datetime_utc=datetime_utc,
281
- output=output,
282
- requested_datetime=datetime_str,
283
- field=field,
284
- field_cmap=use_cmap if field is not None else None,
285
- field_vmin=use_vmin,
286
- field_vmax=use_vmax,
287
- wind=wind,
288
- wind_stride=use_wind_stride,
289
- station=station,
290
- station_datetime=resolved_datetime if station is not None else None,
291
- station_threshold=station_threshold,
292
- station_unit=station_unit,
293
- cities_gdf=(
294
- load_fallback_city_boundaries(
295
- info,
296
- cfg.require_geojson_dir(),
297
- )
298
- if station is not None
299
- else None
300
- ),
479
+ layers=layers,
480
+ relations=relations,
481
+ flags=flags,
482
+ render={
483
+ "image": image,
484
+ "dpi": int(use_dpi),
485
+ "basemap": "satellite" if effective_basemap else "none",
486
+ "title": use_title,
487
+ "layers": render_layers,
488
+ },
489
+ artifacts={"image": image, "sidecar": sidecar, "data": data_entries},
301
490
  )
302
- sidecar = emit_result(result, output)
303
- console.print(f"\n[bold green]✓ 已保存:[/bold green] {output}")
304
- console.print(f"[bold green]✓ JSON:[/bold green] {sidecar}")
491
+ created.append(Path(sidecar))
492
+ write_sidecar(payload, sidecar)
493
+ console.print(f"\n[bold green]✓ 已保存:[/bold green] {image}")
494
+
495
+
496
+ def _era5_grid_layer(
497
+ *,
498
+ layer_id: str,
499
+ kind: str,
500
+ quantity: dict[str, Any],
501
+ time: dict[str, Any],
502
+ data_root: str,
503
+ files: list[str],
504
+ method: dict[str, Any],
505
+ values: np.ndarray,
506
+ lon: np.ndarray,
507
+ lat: np.ndarray,
508
+ counted: np.ndarray,
509
+ region: Any,
510
+ data: str,
511
+ unit: str = "cells",
512
+ ) -> tuple[dict[str, Any], list[dict[str, Any]]]:
513
+ """An ERA5 field as a grid layer with its coverage flags."""
514
+ from rsplot.result_builders.common import (
515
+ grid_per_admin_stats,
516
+ top_hotspots,
517
+ )
518
+ from rsplot.result_builders.envelope import (
519
+ capped,
520
+ coverage_block,
521
+ coverage_flags,
522
+ stats_block,
523
+ subdivision_level,
524
+ )
525
+
526
+ valid = np.isfinite(values) & counted
527
+ coverage = coverage_block(int(valid.sum()), int(counted.sum()), unit)
528
+ sub_gdf = region.sub_boundary_gdf
529
+ has_subdivisions = sub_gdf is not None and len(sub_gdf) > 0
530
+ by_admin = []
531
+ if has_subdivisions:
532
+ level_name = subdivision_level(region)
533
+ by_admin = [
534
+ {
535
+ "name": row["name"],
536
+ "level": level_name,
537
+ "n": int(row["n_pixels"]),
538
+ "mean": row["mean"],
539
+ "min": row["min"],
540
+ "max": row["max"],
541
+ }
542
+ for row in grid_per_admin_stats(lon, lat, values, sub_gdf)
543
+ ]
544
+ hotspots = top_hotspots(
545
+ lon, lat, values, sub_gdf if has_subdivisions else None, n=10
546
+ )
547
+ layer = {
548
+ "id": layer_id,
549
+ "kind": kind,
550
+ "quantity": quantity,
551
+ "time": time,
552
+ "source": {
553
+ "sensor": "era5",
554
+ "processing": None,
555
+ "data_root": data_root,
556
+ "files_total": len(files),
557
+ "failed_files": {},
558
+ **input_fingerprint(data_root, files),
559
+ },
560
+ "method": method,
561
+ "coverage": coverage,
562
+ "stats": stats_block(values[counted]),
563
+ "by_admin": by_admin,
564
+ "extremes": capped(
565
+ [
566
+ {
567
+ "lon": item["lon"],
568
+ "lat": item["lat"],
569
+ "value": item["value"],
570
+ "admin": item["city"],
571
+ }
572
+ for item in hotspots
573
+ ],
574
+ coverage["valid"],
575
+ "value_desc",
576
+ ),
577
+ "data": data,
578
+ }
579
+ if region.members:
580
+ layer["by_member"] = _member_rows(values, lon, lat, region)
581
+ return layer, coverage_flags(layer_id, coverage)
582
+
583
+
584
+ def _member_rows(
585
+ values: np.ndarray,
586
+ lon: np.ndarray,
587
+ lat: np.ndarray,
588
+ region: Any,
589
+ ) -> list[dict[str, Any]]:
590
+ """Select each member's cells with the layer's own counted rule."""
591
+ from shapely import contains_xy
592
+
593
+ from rsplot.result_builders.common import member_basic_stats
594
+
595
+ rows = []
596
+ for member in region.members:
597
+ selected = contains_xy(member.geometry.buffer(1e-9), lon, lat)
598
+ stats = member_basic_stats(values[selected])
599
+ rows.append(
600
+ {
601
+ "name": member.qualified_name or member.name,
602
+ "level": member.administrative_level or member.level,
603
+ "n": int(stats["n"]),
604
+ "mean": stats["mean"],
605
+ "min": stats["min"],
606
+ "max": stats["max"],
607
+ }
608
+ )
609
+ return rows
610
+
611
+
612
+ def _vector_summary(wind: Any) -> dict[str, Any]:
613
+ from rsplot.result_builders.envelope import stats_block
614
+ from rsplot.stats import round_finite
615
+
616
+ mean_u = float(np.nanmean(wind.u))
617
+ mean_v = float(np.nanmean(wind.v))
618
+ direction_to = (np.degrees(np.arctan2(mean_u, mean_v)) + 360.0) % 360.0
619
+ index = np.unravel_index(int(np.nanargmax(wind.speed)), wind.speed.shape)
620
+ return {
621
+ "mean_u": round_finite(mean_u),
622
+ "mean_v": round_finite(mean_v),
623
+ "direction_to_deg": round_finite(direction_to, 1),
624
+ "wind_from_deg": round_finite((direction_to + 180.0) % 360.0, 1),
625
+ "u_stats": stats_block(wind.u),
626
+ "v_stats": stats_block(wind.v),
627
+ "max_speed_location": {
628
+ "lon": round(float(wind.lon[index]), 3),
629
+ "lat": round(float(wind.lat[index]), 3),
630
+ "speed": round_finite(wind.speed[index]),
631
+ },
632
+ }
305
633
 
306
634
 
307
635
  def _temperature_range(
@@ -312,14 +640,20 @@ def _temperature_range(
312
640
  ) -> tuple[float, float]:
313
641
  finite = values[np.isfinite(values)]
314
642
  if len(finite) == 0:
315
- raise ValueError("目标区域内没有可用于温度色阶的有效值。")
643
+ raise RsplotError(
644
+ "no_valid_data", "目标区域内没有可用于温度色阶的有效值。"
645
+ )
316
646
  use_vmin = float(np.percentile(finite, 2)) if vmin is None else vmin
317
647
  use_vmax = float(np.percentile(finite, 98)) if vmax is None else vmax
318
648
  if use_vmax <= use_vmin:
319
649
  if vmin is None and vmax is None:
320
650
  midpoint = float(np.mean(finite))
321
651
  return midpoint - 0.5, midpoint + 0.5
322
- raise ValueError("--vmax 必须大于 --vmin 或自动计算的色阶下限。")
652
+ raise RsplotError(
653
+ "invalid_argument",
654
+ "--vmax 必须大于 --vmin 或自动计算的色阶下限。",
655
+ option="--vmax",
656
+ )
323
657
  return use_vmin, use_vmax
324
658
 
325
659
 
@@ -328,14 +662,14 @@ def _wind_option_error(
328
662
  stride: int | None,
329
663
  scale: float | None,
330
664
  width: float,
331
- ) -> str | None:
665
+ ) -> tuple[str | None, str | None]:
332
666
  if stride is not None and (not math.isfinite(stride) or stride < 1):
333
- return "--wind-stride 必须大于等于 1。"
667
+ return "--wind-stride 必须大于等于 1。", "--wind-stride"
334
668
  if scale is not None and (not math.isfinite(scale) or scale <= 0):
335
- return "--wind-scale 必须大于 0。"
669
+ return "--wind-scale 必须大于 0。", "--wind-scale"
336
670
  if not math.isfinite(width) or width <= 0:
337
- return "--wind-width 必须大于 0。"
338
- return None
671
+ return "--wind-width 必须大于 0。", "--wind-width"
672
+ return None, None
339
673
 
340
674
 
341
675
  def _default_title(
@@ -356,26 +690,5 @@ def _default_title(
356
690
  return f"{' + '.join(layers)} - {region} - {datetime_str}"
357
691
 
358
692
 
359
- def _output_layer_suffix(
360
- *,
361
- temp_level: str | None,
362
- station_var: str | None,
363
- wind_level: str | None,
364
- ) -> str:
365
- if temp_level is not None:
366
- suffix = f"temperature_{temp_level}"
367
- elif station_var is not None:
368
- suffix = f"station_{station_var}"
369
- else:
370
- suffix = f"wind_{wind_level}"
371
- if station_var is not None and temp_level is not None:
372
- suffix += f"_station_{station_var}"
373
- if wind_level is not None and (
374
- temp_level is not None or station_var is not None
375
- ):
376
- suffix += f"_wind{wind_level}"
377
- return suffix
378
-
379
-
380
693
  def _level_label(level: str) -> str:
381
694
  return level if level.endswith("m") else f"{level} hPa"