rsplot 0.3.2.dev4__py3-none-any.whl → 0.4.0__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.4.0.dist-info}/METADATA +426 -121
  57. rsplot-0.4.0.dist-info/RECORD +76 -0
  58. {rsplot-0.3.2.dev4.dist-info → rsplot-0.4.0.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.4.0.dist-info}/entry_points.txt +0 -0
  67. {rsplot-0.3.2.dev4.dist-info → rsplot-0.4.0.dist-info}/licenses/LICENSE +0 -0
rsplot/commands/raster.py CHANGED
@@ -2,16 +2,15 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- import math
5
+ from dataclasses import dataclass, field
6
+ from pathlib import Path
6
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
  parse_basemap,
13
13
  resolve_satellite,
14
- satellite_errors,
15
14
  satellite_filter_label,
16
15
  validate_color_range,
17
16
  validate_non_negative,
@@ -20,20 +19,105 @@ from rsplot.commands.common import (
20
19
  warn_missing_tianditu_key,
21
20
  )
22
21
  from rsplot.config import AppConfig
22
+ from rsplot.errors import RsplotError
23
23
 
24
24
  if TYPE_CHECKING:
25
25
  from rich.console import Console
26
26
 
27
+ from rsplot.geo.boundaries import RegionInfo
28
+ from rsplot.result_builders.satellite import SatelliteInputs
27
29
 
28
- def default_raster_n_min(product: str, window_n: int) -> int:
29
- """Return a product-aware threshold that fits the requested window."""
30
- if window_n < 1:
31
- raise ValueError("窗口至少需要 1 天。")
32
- if product.lower() == "hcho":
33
- preferred = max(3, math.ceil(window_n * 0.25))
34
- else:
35
- preferred = max(3, window_n // 2)
36
- return min(window_n, preferred)
30
+ # How the colour range was chosen, recorded with the display settings.
31
+ RANGE_METHOD = {
32
+ "cli": "manual",
33
+ "product_default": "product_default",
34
+ "built_in": "region_p02_p98",
35
+ }
36
+
37
+
38
+ @dataclass
39
+ class RasterRun:
40
+ """Prepared satellite layer and sidecar, independent of rendering."""
41
+
42
+ lon: np.ndarray
43
+ lat: np.ndarray
44
+ grid: np.ndarray
45
+ region: RegionInfo
46
+ plot_options: dict[str, Any]
47
+ # Inputs for the sidecar satellite layer.
48
+ satellite: SatelliteInputs | None = None
49
+ render: dict[str, Any] = field(default_factory=dict)
50
+
51
+
52
+ def run_raster(**kwargs: Any) -> None:
53
+ """Prepare, render, and emit the administrative raster command."""
54
+ from rsplot.commands.sidecar import run_with_sidecar
55
+
56
+ run_with_sidecar(
57
+ kwargs=kwargs,
58
+ emit=lambda created: _emit_raster(kwargs, created),
59
+ )
60
+
61
+
62
+ def _emit_raster(kwargs: dict[str, Any], created: list[Path]) -> None:
63
+ from rsplot.data_files import (
64
+ data_path,
65
+ write_grid_netcdf,
66
+ )
67
+ from rsplot.plotting.raster import plot_raster
68
+ from rsplot.result_builders.envelope import (
69
+ command_line,
70
+ sidecar_path,
71
+ success_envelope,
72
+ write_sidecar,
73
+ )
74
+ from rsplot.result_builders.satellite import build_satellite_layer
75
+
76
+ run = prepare_raster(**kwargs)
77
+ inputs = run.satellite
78
+ assert inputs is not None
79
+ image = str(Path(run.plot_options["output"]).resolve())
80
+ sidecar = str(Path(sidecar_path(image)))
81
+
82
+ grid_path = data_path(image, "satellite", ".nc")
83
+ created.append(grid_path)
84
+ grid_entry = write_grid_netcdf(
85
+ grid_path,
86
+ inputs.lon,
87
+ inputs.lat,
88
+ inputs.grid,
89
+ inputs.counted,
90
+ extent=run.region.extent,
91
+ layer="satellite",
92
+ attrs={
93
+ "quantity": inputs.prod_info.quantity,
94
+ "unit": inputs.prod_info.unit,
95
+ "scale": inputs.prod_info.unit_scale,
96
+ "time_aggregation": inputs.time["aggregation"],
97
+ },
98
+ valid_days=inputs.valid_days,
99
+ )
100
+ data_entries = [grid_entry]
101
+
102
+ created.append(Path(image))
103
+ plot_raster(run.lon, run.lat, run.grid, run.region, **run.plot_options)
104
+ layer, flags = build_satellite_layer(
105
+ inputs,
106
+ run.region,
107
+ data=grid_entry["path"],
108
+ )
109
+ payload = success_envelope(
110
+ command="raster",
111
+ request=command_line(),
112
+ region=run.region,
113
+ layers=[layer],
114
+ flags=flags,
115
+ render={"image": image, **run.render},
116
+ artifacts={"image": image, "sidecar": sidecar, "data": data_entries},
117
+ )
118
+ created.append(Path(sidecar))
119
+ write_sidecar(payload, sidecar)
120
+ kwargs["console"].print(f"[bold green]✓ 已保存:[/bold green] {image}")
37
121
 
38
122
 
39
123
  def parse_raster_dates(
@@ -44,37 +128,48 @@ def parse_raster_dates(
44
128
  from rsplot.temporal import parse_date_window, parse_yyyymmdd
45
129
 
46
130
  if days is not None and days < 1:
47
- raise ValueError("--days 必须 >= 1。")
48
- if "-" in date_arg:
49
- dates = parse_date_window(date_arg, default_days=0)
50
- window_mode = True
51
- elif days is not None:
52
- dates = parse_date_window(date_arg, default_days=days)
53
- window_mode = True
54
- else:
55
- if len(date_arg) != 8 or not date_arg.isdigit():
56
- raise ValueError(
57
- f"日期格式错误: '{date_arg}',"
58
- "应为 YYYYMMDD 或 YYYYMMDD-YYYYMMDD"
59
- )
60
- parse_yyyymmdd(date_arg)
61
- dates = [date_arg]
62
- window_mode = False
131
+ raise RsplotError(
132
+ "invalid_argument", "--days 必须 >= 1。", option="--days"
133
+ )
134
+ if days is not None and "-" in date_arg:
135
+ raise RsplotError(
136
+ "invalid_argument",
137
+ "日期区间不能与 --days 同时使用;"
138
+ "请选择 YYYYMMDD-YYYYMMDD 或结束日期 YYYYMMDD 配合 --days N。",
139
+ option="--days",
140
+ )
141
+ try:
142
+ if "-" in date_arg:
143
+ dates = parse_date_window(date_arg, default_days=0)
144
+ window_mode = True
145
+ elif days is not None:
146
+ dates = parse_date_window(date_arg, default_days=days)
147
+ window_mode = True
148
+ else:
149
+ if len(date_arg) != 8 or not date_arg.isdigit():
150
+ raise ValueError(
151
+ f"日期格式错误: '{date_arg}',"
152
+ "应为 YYYYMMDD 或 YYYYMMDD-YYYYMMDD"
153
+ )
154
+ parse_yyyymmdd(date_arg)
155
+ dates = [date_arg]
156
+ window_mode = False
157
+ except RsplotError:
158
+ raise
159
+ except ValueError as error:
160
+ raise RsplotError("invalid_time", str(error)) from error
63
161
  return dates, window_mode
64
162
 
65
163
 
66
- @satellite_errors
67
- def run_raster(
164
+ def prepare_raster(
68
165
  *,
69
- region: str,
166
+ region: str | RegionInfo,
70
167
  date_arg: str,
71
168
  product: str,
72
169
  sensor: str = "tropomi",
170
+ processing: str | None = None,
73
171
  days: int | None,
74
- n_min: int | None,
75
- level: str | None,
76
- data_dir: str | None,
77
- output: str | None,
172
+ output: str,
78
173
  dpi: int | None,
79
174
  res: float | None,
80
175
  basemap: str | None,
@@ -86,63 +181,63 @@ def run_raster(
86
181
  qa: float | None,
87
182
  cf: float = 0.5,
88
183
  console: Console,
89
- ) -> None:
90
- """Execute raster orchestration without owning the Typer signature."""
91
- from rsplot.geo.boundaries import resolve_regions
184
+ ) -> RasterRun:
185
+ """Prepare a satellite layer for an administrative or supplied geometry."""
186
+ from rsplot.geo.boundaries import RegionInfo, resolve_regions
187
+ from rsplot.geo.gridding import fill_nan_gaps, region_grid_mask
92
188
  from rsplot.geo.processing import (
93
189
  buffered_extent,
94
190
  prepare_display_grid,
95
191
  prepare_existing_grid,
96
192
  prepare_swath_grid,
97
193
  )
98
- from rsplot.plotting.raster import plot_raster
99
194
  from rsplot.plotting.styles import setup_fonts
100
195
  from rsplot.readers import auto_vrange
101
- from rsplot.results import build_raster_result, emit_result
196
+ from rsplot.result_builders.common import grid_boundary_policy
197
+ from rsplot.result_builders.envelope import stats_block
198
+ from rsplot.result_builders.satellite import SatelliteInputs
102
199
  from rsplot.temporal import compute_window_mean, read_scan_mean
103
200
 
104
201
  cfg = AppConfig.load()
105
- prod_info, use_qa = resolve_satellite(product, sensor, qa, cfg, console)
202
+ prod_info, use_qa = resolve_satellite(
203
+ product, sensor, qa, cfg, console, processing
204
+ )
106
205
  sensor = prod_info.sensor
206
+ processing = prod_info.processing
107
207
  scan_mode = sensor == "gems" and len(date_arg) == 12
108
208
  if scan_mode:
109
209
  from rsplot.readers.gems import parse_gems_time
110
210
 
111
- parse_gems_time(date_arg)
112
- if days is not None or n_min is not None:
113
- raise ValueError("GEMS 单次扫描不能同时使用 --days 或 --n-min。")
114
- try:
115
- dates, window_mode = parse_raster_dates(
116
- date_arg[:8] if scan_mode else date_arg, days
117
- )
118
- except ValueError as e:
119
- console.print(f"[red]{e}[/red]")
120
- raise typer.Exit(1) from e
211
+ try:
212
+ parse_gems_time(date_arg)
213
+ except ValueError as error:
214
+ raise RsplotError("invalid_time", str(error)) from error
215
+ if days is not None:
216
+ raise RsplotError(
217
+ "invalid_argument",
218
+ "GEMS 单次扫描不能同时使用 --days。",
219
+ option="--days",
220
+ )
221
+ dates, window_mode = parse_raster_dates(
222
+ date_arg[:8] if scan_mode else date_arg, days
223
+ )
121
224
 
122
225
  window_n = len(dates)
123
- use_n_min: int | None = None
124
- if n_min is not None and n_min < 1:
125
- console.print("[red]--n-min 必须 >= 1。[/red]")
126
- raise typer.Exit(1)
127
- if not window_mode and n_min is not None:
128
- console.print("[red]--n-min 仅用于日期范围或 --days 窗口。[/red]")
129
- raise typer.Exit(1)
130
- if window_mode:
131
- use_n_min = (
132
- n_min
133
- if n_min is not None
134
- else default_raster_n_min(product, window_n)
135
- )
136
- if use_n_min > window_n:
137
- console.print(
138
- f"[red]--n-min ({use_n_min}) 大于窗口天数 ({window_n})[/red]"
139
- )
140
- raise typer.Exit(1)
141
226
 
142
227
  setup_fonts(cfg.font_dir)
143
228
 
144
- console.print(f"[bold]解析区域:[/bold] {region}")
145
- info = resolve_regions(region, cfg, level_override=level)
229
+ if isinstance(region, RegionInfo):
230
+ info = region
231
+ else:
232
+ try:
233
+ info = resolve_regions(region, cfg)
234
+ except RsplotError:
235
+ raise
236
+ except ValueError as error:
237
+ raise RsplotError(
238
+ "region_not_found", str(error), details={"region": region}
239
+ ) from error
240
+ console.print(f"[bold]分析范围:[/bold] {info.name}")
146
241
  console.print(f" → [green]{info.name}[/green] (级别: {info.level})")
147
242
  if info.members:
148
243
  console.print(
@@ -184,8 +279,7 @@ def run_raster(
184
279
  if use_smooth is not None:
185
280
  validate_non_negative(use_smooth, "--smooth")
186
281
  except ValueError as e:
187
- console.print(f"[red]{e}[/red]")
188
- raise typer.Exit(1) from e
282
+ raise RsplotError("invalid_argument", str(e)) from e
189
283
  if use_smooth == 0:
190
284
  use_smooth = None
191
285
  warn_missing_tianditu_key(
@@ -196,163 +290,116 @@ def run_raster(
196
290
  )
197
291
 
198
292
  read_extent = buffered_extent(info.extent, 1.0)
199
- use_data_dir = (
200
- data_dir
201
- if data_dir is not None
202
- else cfg.get_data_dir(prod_info.data_key or product)
203
- )
204
- reader = prod_info.reader_cls()
293
+ use_data_dir = cfg.get_data_dir(prod_info.data_key or product)
294
+ reader = prod_info.create_reader()
205
295
  reader.cloud_fraction_max = cf
206
- analysis_res = use_res
207
296
  if sensor == "gems":
208
- from rsplot.readers.gems import GEMS_ANALYSIS_RESOLUTION
297
+ console.print(f" → GEMS 目标网格 {use_res}°(分析与显示)")
298
+ provenance: list[dict[str, Any]] = []
299
+ pixels_used = 0
300
+ valid_days: np.ndarray | None = None
209
301
 
210
- analysis_res = GEMS_ANALYSIS_RESOLUTION
211
- console.print(
212
- f" → GEMS 分析网格 {analysis_res}°,显示网格 {use_res}°"
213
- )
214
- swath_meta: dict[str, Any]
215
- window_meta: dict[str, Any] | None = None
216
- scientific_valid_mask: np.ndarray | None = None
217
-
218
- if not window_mode:
219
- console.print(
220
- f"\n[bold]读取数据:[/bold] {use_data_dir} (产品: {product})"
221
- )
222
- console.print(
223
- f" 时间: {date_arg}, {satellite_filter_label(sensor, use_qa, cf)}"
224
- )
225
- if sensor == "gems":
226
- batch = read_scan_mean(
227
- reader=reader,
228
- data_dir=use_data_dir,
229
- request=date_arg,
230
- extent=read_extent,
231
- res=analysis_res,
302
+ try:
303
+ if not window_mode:
304
+ console.print(
305
+ f"\n[bold]读取数据:[/bold] {use_data_dir} (产品: {product})"
232
306
  )
233
- prepared = prepare_existing_grid(
234
- batch.LON,
235
- batch.LAT,
236
- batch.grid,
237
- info.geometry,
238
- fill_gaps=False,
307
+ console.print(
308
+ f" 时间: {date_arg}, "
309
+ f"{satellite_filter_label(sensor, use_qa, cf)}"
239
310
  )
240
- swath_meta = {
241
- "n_pixels": batch.n_pixels,
242
- "n_files": batch.n_files,
243
- "n_broken": batch.n_broken,
244
- "resolution_deg": use_res,
245
- "cloud_fraction_max": cf,
246
- **batch.metadata,
247
- }
248
- scientific_valid_mask = np.isfinite(prepared.values)
311
+ if sensor == "gems":
312
+ batch = read_scan_mean(
313
+ reader=reader,
314
+ data_dir=use_data_dir,
315
+ request=date_arg,
316
+ extent=read_extent,
317
+ res=use_res,
318
+ )
319
+ prepared = prepare_existing_grid(
320
+ batch.LON,
321
+ batch.LAT,
322
+ batch.grid,
323
+ info.geometry,
324
+ fill_gaps=False,
325
+ )
326
+ provenance = [batch.metadata]
327
+ pixels_used = int(batch.n_pixels)
328
+ else:
329
+ swath = reader.read(
330
+ use_data_dir,
331
+ dates[0],
332
+ read_extent,
333
+ qa_threshold=use_qa,
334
+ )
335
+ console.print(
336
+ f" → [green]{swath.n_pixels}[/green] 有效像元 "
337
+ f"({swath.n_files} 文件, {swath.n_broken} 损坏)"
338
+ )
339
+ console.print(f"\n[bold]网格化:[/bold] {use_res}° 分辨率")
340
+ prepared = prepare_swath_grid(
341
+ swath.lon,
342
+ swath.lat,
343
+ swath.values,
344
+ read_extent,
345
+ use_res,
346
+ info.geometry,
347
+ )
348
+ provenance = [swath.metadata]
349
+ pixels_used = int(swath.n_pixels)
249
350
  else:
250
- swath = reader.read(
251
- use_data_dir,
252
- dates[0],
253
- read_extent,
351
+ console.print(
352
+ f"\n[bold]时间窗口:[/bold] {dates[0]} ~ {dates[-1]} "
353
+ f"({window_n} 天,每像元取有效天等权均值)"
354
+ )
355
+ console.print(
356
+ f"\n[bold]读取数据:[/bold] {use_data_dir} (产品: {product})"
357
+ )
358
+ console.print(f" {satellite_filter_label(sensor, use_qa, cf)}")
359
+ window = compute_window_mean(
360
+ reader=reader,
361
+ data_dir=use_data_dir,
362
+ dates=dates,
363
+ extent=read_extent,
364
+ res=use_res,
254
365
  qa_threshold=use_qa,
366
+ label=product.upper(),
367
+ console=console,
255
368
  )
256
369
  console.print(
257
- f" → [green]{swath.n_pixels}[/green] 有效像元 "
258
- f"({swath.n_files} 文件, {swath.n_broken} 损坏)"
370
+ f" → 有效天数 [green]{len(window.dates_found)}[/green] / "
371
+ f"{window_n} (失败 {len(window.dates_failed)}),累计 "
372
+ f"[green]{window.n_pixels_total}[/green] 像元 "
373
+ f"({window.n_files_total} 文件, "
374
+ f"{window.n_broken_total} 损坏)"
259
375
  )
260
- console.print(f"\n[bold]网格化:[/bold] {use_res}° 分辨率")
261
- prepared = prepare_swath_grid(
262
- swath.lon,
263
- swath.lat,
264
- swath.values,
265
- read_extent,
266
- use_res,
376
+ # Each cell averages its valid days; cells with none stay NaN.
377
+ prepared = prepare_existing_grid(
378
+ window.LON,
379
+ window.LAT,
380
+ window.grid,
267
381
  info.geometry,
382
+ fill_gaps=False,
268
383
  )
269
- swath_meta = {
270
- "n_pixels": int(swath.n_pixels),
271
- "n_files": int(swath.n_files),
272
- "n_broken": int(swath.n_broken),
273
- "qa_threshold": use_qa,
274
- "cloud_fraction_max": cf,
275
- "resolution_deg": use_res,
276
- }
277
- else:
278
- assert use_n_min is not None
279
- console.print(
280
- f"\n[bold]时间窗口:[/bold] {dates[0]} ~ {dates[-1]} "
281
- f"({window_n} 天,每像元至少 {use_n_min} 天有效)"
282
- )
283
- console.print(
284
- f"\n[bold]读取数据:[/bold] {use_data_dir} (产品: {product})"
285
- )
286
- console.print(f" {satellite_filter_label(sensor, use_qa, cf)}")
287
- window = compute_window_mean(
288
- reader=reader,
289
- data_dir=use_data_dir,
290
- dates=dates,
291
- extent=read_extent,
292
- res=analysis_res,
293
- qa_threshold=use_qa,
294
- label=product.upper(),
295
- console=console,
296
- )
297
- console.print(
298
- f" → 有效天数 [green]{len(window.dates_found)}[/green] / "
299
- f"{window_n} (失败 {len(window.dates_failed)}),累计 "
300
- f"[green]{window.n_pixels_total}[/green] 像元 "
301
- f"({window.n_files_total} 文件, {window.n_broken_total} 损坏)"
302
- )
303
- mean_grid = window.grid.copy()
304
- mean_grid[window.n_valid < use_n_min] = np.nan
305
- prepared = prepare_existing_grid(
306
- window.LON,
307
- window.LAT,
308
- mean_grid,
309
- info.geometry,
310
- fill_gaps=False,
311
- )
312
- scientific_valid_mask = np.isfinite(prepared.values)
313
-
314
- covered = window.n_valid[window.n_valid > 0]
315
- coverage_days: dict[str, Any] = {
316
- "min": int(covered.min()) if len(covered) else 0,
317
- "max": int(covered.max()) if len(covered) else 0,
318
- "mean": round(float(covered.mean()), 1) if len(covered) else 0.0,
319
- }
320
- if len(covered):
321
- coverage_days.update(
322
- {
323
- "p10": int(np.percentile(covered, 10)),
324
- "p25": int(np.percentile(covered, 25)),
325
- "median": int(np.percentile(covered, 50)),
326
- "p75": int(np.percentile(covered, 75)),
327
- "p90": int(np.percentile(covered, 90)),
328
- }
329
- )
330
- swath_meta = {
331
- "n_pixels_total": int(window.n_pixels_total),
332
- "n_files_total": int(window.n_files_total),
333
- "n_broken_total": int(window.n_broken_total),
334
- "qa_threshold": use_qa,
335
- "cloud_fraction_max": cf,
336
- "resolution_deg": use_res,
337
- }
338
- window_meta = {
339
- "start": dates[0],
340
- "end": dates[-1],
341
- "n_days_requested": window_n,
342
- "n_days_found": len(window.dates_found),
343
- "n_min": use_n_min,
344
- "n_min_default": n_min is None,
345
- "dates_failed": window.dates_failed,
346
- "coverage_days": coverage_days,
347
- }
384
+ provenance = list(window.daily_metadata.values())
385
+ pixels_used = int(window.n_pixels_total)
386
+ valid_days = window.n_valid
348
387
 
349
- if sensor == "gems":
350
- swath_meta.pop("qa_threshold", None)
351
- window_meta["aggregation"] = "equal_day_mean_of_equal_scan_means"
352
- window_meta["daily"] = window.daily_metadata
388
+ except (RsplotError, OSError):
389
+ raise
390
+ except ValueError as error:
391
+ # Readers raise ValueError when nothing valid survives filtering.
392
+ raise RsplotError("no_valid_data", str(error)) from error
353
393
 
394
+ # Statistics keep observed cells only. A TROPOMI day fills small gaps
395
+ # for the image alone; windows and GEMS draw observed cells.
354
396
  display_source = prepared.unmasked_values
355
- statistics_grid = prepared.values.copy() if sensor == "gems" else None
397
+ display_gap_fill = "none"
398
+ if sensor != "gems" and not window_mode:
399
+ display_source = fill_nan_gaps(
400
+ prepared.lon, prepared.lat, display_source
401
+ )
402
+ display_gap_fill = "nearest_within_3_cells"
356
403
  display_lon, display_lat = prepared.lon, prepared.lat
357
404
  display_support = None
358
405
  if sensor == "gems":
@@ -363,16 +410,12 @@ def run_raster(
363
410
  prepared.lat,
364
411
  display_source,
365
412
  info.geometry,
366
- analysis_res=analysis_res,
413
+ analysis_res=use_res,
367
414
  display_res=use_res,
368
415
  smooth_sigma=use_smooth,
369
416
  )
370
417
  display_lon, display_lat = display.lon, display.lat
371
418
  display_grid, display_support = display.values, display.support
372
- swath_meta["resolution_deg"] = analysis_res
373
- swath_meta["analysis_resolution_deg"] = analysis_res
374
- swath_meta["display_resolution_deg"] = use_res
375
- swath_meta["display_support"] = "fixed_analysis_valid_cells"
376
419
  else:
377
420
  display_grid = prepare_display_grid(
378
421
  prepared.lon,
@@ -383,39 +426,20 @@ def run_raster(
383
426
  )
384
427
 
385
428
  if not np.isfinite(display_grid).any():
386
- console.print(
387
- "[red]窗口均值全区无有效像元,可能原因:窗口内覆盖不足,"
388
- "或 --n-min 太严。可放宽 --n-min / 扩大窗口。[/red]"
389
- )
390
- raise typer.Exit(1)
391
-
392
- if (
393
- sensor != "gems"
394
- and use_smooth is not None
395
- and np.isfinite(prepared.values).any()
396
- ):
397
- console.print(f" → 高斯平滑 sigma={use_smooth}")
398
- prepared = prepare_existing_grid(
399
- prepared.lon,
400
- prepared.lat,
401
- prepared.values,
402
- info.geometry,
403
- fill_gaps=False,
404
- smooth_sigma=use_smooth,
405
- )
406
- if scientific_valid_mask is not None:
407
- restored = np.where(
408
- scientific_valid_mask,
409
- prepared.values,
410
- np.nan,
429
+ if window_mode:
430
+ message = (
431
+ f"{dates[0]}~{dates[-1]} 窗口内目标区域 {info.name} "
432
+ "无任何有效观测。请扩大窗口或检查区域及质量/云量筛选条件。"
411
433
  )
412
- prepared = prepare_existing_grid(
413
- prepared.lon,
414
- prepared.lat,
415
- restored,
416
- info.geometry,
417
- fill_gaps=False,
434
+ else:
435
+ message = (
436
+ f"{date_arg} 在目标区域 {info.name} 内无有效像元。"
437
+ "请检查所选日期、区域及质量/云量筛选条件。"
418
438
  )
439
+ raise RsplotError("no_valid_data", message)
440
+
441
+ if use_smooth is not None:
442
+ console.print(f" → 显示高斯平滑 sigma={use_smooth}")
419
443
  console.print(
420
444
  f" → 网格 {prepared.values.shape}, "
421
445
  f"区域内覆盖率 {prepared.coverage_pct:.1f}% "
@@ -424,9 +448,11 @@ def run_raster(
424
448
 
425
449
  if vmin is not None and vmax is not None:
426
450
  use_vmin, use_vmax = vmin, vmax
451
+ vrange_source = "cli"
427
452
  elif prod_info.vmin is not None and prod_info.vmax is not None:
428
453
  use_vmin = vmin if vmin is not None else prod_info.vmin
429
454
  use_vmax = vmax if vmax is not None else prod_info.vmax
455
+ vrange_source = "product_default"
430
456
  else:
431
457
  auto_min, auto_max = auto_vrange(
432
458
  prepared.values
@@ -436,75 +462,174 @@ def run_raster(
436
462
  )
437
463
  use_vmin = vmin if vmin is not None else auto_min
438
464
  use_vmax = vmax if vmax is not None else auto_max
465
+ vrange_source = "built_in"
439
466
  try:
440
467
  validate_color_range(use_vmin, use_vmax)
441
468
  except ValueError as e:
442
- console.print(f"[red]色标范围无效:{e}[/red]")
443
- raise typer.Exit(1) from e
469
+ raise RsplotError("invalid_argument", f"色标范围无效:{e}") from e
444
470
  console.print(f" → 色标范围: {use_vmin:.1f} ~ {use_vmax:.1f}")
445
471
 
446
- if output is None and sensor == "gems":
447
- suffix = f"{dates[0]}_{dates[-1]}" if window_mode else date_arg
448
- output = f"/tmp/rsplot_gems_{product}_{info.name}_{suffix}.png"
449
- if output is None:
450
- if window_mode:
451
- output = f"/tmp/rsplot_{info.name}_{dates[0]}_{dates[-1]}.png"
452
- else:
453
- output = f"/tmp/rsplot_{info.name}_{dates[0]}.png"
472
+ if processing == "nrti":
473
+ period = f"{dates[0]}_{dates[-1]}" if window_mode else date_arg
474
+ if title is None:
475
+ label = " mean" if window_mode else ""
476
+ title = (
477
+ f"TROPOMI NRTI {product.upper()} "
478
+ f"{period}{label} - {info.name}"
479
+ )
480
+
454
481
  if title is None and sensor == "gems":
455
482
  period = (
456
483
  f"{dates[0]}~{dates[-1]} mean"
457
484
  if window_mode
458
485
  else (
459
- f"{date_arg} CST scan"
460
- if scan_mode
461
- else f"{date_arg} daily mean (CST)"
486
+ f"{date_arg} scan" if scan_mode else f"{date_arg} daily mean"
462
487
  )
463
488
  )
464
- title = f"GEMS {product.upper()} - {info.name} ({period})"
489
+ title = f"GEMS {product.upper()} {period} - {info.name}"
465
490
  if title is None and window_mode:
466
491
  title = (
467
- f"TROPOMI {product.upper()} - {info.name} "
468
- f"({dates[0]}~{dates[-1]}, {window_n}d mean)"
492
+ f"TROPOMI {product.upper()} "
493
+ f"{dates[0]}~{dates[-1]}, {window_n}d mean - {info.name}"
469
494
  )
495
+ if title is None:
496
+ title = f"TROPOMI {product.upper()} {dates[0]} - {info.name}"
470
497
 
471
- console.print("\n[bold]绘图中...[/bold]")
472
- plot_raster(
473
- display_lon,
474
- display_lat,
475
- display_grid,
476
- info,
498
+ plot_options = dict(
477
499
  dpi=use_dpi,
478
500
  cmap=use_cmap,
479
501
  vmin=use_vmin,
480
502
  vmax=use_vmax,
481
503
  basemap=use_basemap,
482
504
  tianditu_key=cfg.tianditu_key,
483
- hcho_cmap_file=cfg.hcho_cmap_file,
484
505
  title=title,
485
506
  output=output,
486
507
  **({"coverage_geometry": display_support} if sensor == "gems" else {}),
487
508
  colorbar_label=prod_info.colorbar_label,
488
509
  )
489
- console.print(f"\n[bold green]✓ 已保存:[/bold green] {output}")
490
510
 
491
- result = build_raster_result(
492
- region=info,
493
- product=product,
494
- date=dates[0] if not window_mode else dates[-1],
511
+ # --- sidecar inputs ---------------------------------------------------
512
+ counted = region_grid_mask(prepared.lon, prepared.lat, info.geometry)
513
+ china = sensor == "gems"
514
+ if scan_mode:
515
+ time = {
516
+ "aggregation": "scan",
517
+ "at": date_arg,
518
+ "basis": "nominal_scan_time",
519
+ }
520
+ else:
521
+ time = {
522
+ "aggregation": (
523
+ "window_mean"
524
+ if window_mode
525
+ else "daily_scan_mean"
526
+ if china
527
+ else "daily"
528
+ ),
529
+ "start": dates[0],
530
+ "end": dates[-1],
531
+ "basis": "calendar_day",
532
+ }
533
+ days_block = None
534
+ if window_mode:
535
+ assert valid_days is not None
536
+ days_block = {
537
+ "requested": window_n,
538
+ "found": len(window.dates_found),
539
+ "failed": dict(window.dates_failed),
540
+ # One valid day keeps a cell; there is no stricter threshold.
541
+ "n_min": 1,
542
+ "valid_days_per_cell": stats_block(
543
+ valid_days[counted & (valid_days > 0)].astype(float)
544
+ ),
545
+ }
546
+
547
+ method: dict[str, Any] = {
548
+ "cloud_fraction_max": cf,
549
+ "grid_deg": use_res,
550
+ "pixels_used": pixels_used,
551
+ "cell_selection": "center_strictly_inside",
552
+ "cell_weighting": "equal",
553
+ }
554
+ if china:
555
+ scans = [scan for meta in provenance for scan in meta.get("scans", [])]
556
+ method.update(
557
+ quality_filter="final_algorithm_flag_0_sza_vza_below_70",
558
+ spatial_aggregation="footprint_overlap_area_mean",
559
+ area_crs="EPSG:6933",
560
+ scan_weighting="equal_scans",
561
+ scans_found=len(scans),
562
+ scans_valid=sum(scan.get("n_pixels", 0) > 0 for scan in scans),
563
+ footprint_source=sorted(
564
+ {
565
+ scan["footprint_source"]
566
+ for scan in scans
567
+ if "footprint_source" in scan
568
+ }
569
+ ),
570
+ )
571
+ else:
572
+ method.update(qa_min_exclusive=use_qa)
573
+ if processing == "nrti":
574
+ dedup = [m for m in provenance if "deduplication" in m]
575
+ method["deduplication"] = (
576
+ dedup[0]["deduplication"] if dedup else None
577
+ )
578
+ method["duplicates_removed"] = sum(
579
+ int(m.get("n_duplicates_removed", 0)) for m in dedup
580
+ )
581
+ if window_mode:
582
+ method["day_weighting"] = "equal_days"
583
+
584
+ satellite = SatelliteInputs(
495
585
  prod_info=prod_info,
496
- LON=prepared.lon,
497
- LAT=prepared.lat,
498
- grid=statistics_grid
499
- if statistics_grid is not None
500
- else prepared.values,
501
- swath_meta=swath_meta,
502
- vmin=use_vmin,
503
- vmax=use_vmax,
504
- output=output,
505
- window=window_meta,
506
- display_grid=display_grid,
507
- display_lon=display_lon,
508
- display_lat=display_lat,
586
+ lon=prepared.lon,
587
+ lat=prepared.lat,
588
+ grid=prepared.values,
589
+ counted=counted,
590
+ time=time,
591
+ data_root=str(use_data_dir),
592
+ metadata=provenance,
593
+ method=method,
594
+ valid_days=valid_days,
595
+ days=days_block,
596
+ )
597
+
598
+ effective_basemap = (
599
+ use_basemap if use_basemap is not None else params.basemap
600
+ )
601
+ display_policy = grid_boundary_policy(
602
+ display_lon, display_lat, display_grid, info
603
+ )["display"]
604
+ if sensor == "gems":
605
+ display_policy["clip"] += "_and_analysis_valid_cells"
606
+ render = {
607
+ "dpi": int(use_dpi),
608
+ "basemap": "satellite" if effective_basemap else "none",
609
+ "title": title,
610
+ "layers": {
611
+ "satellite": {
612
+ "cmap": use_cmap,
613
+ "vmin": use_vmin,
614
+ "vmax": use_vmax,
615
+ "range_method": RANGE_METHOD[vrange_source],
616
+ "display_gap_fill": display_gap_fill,
617
+ "display_smoothing_sigma": use_smooth or 0,
618
+ "display_grid_shape": list(display_grid.shape),
619
+ "display_selection": display_policy["selection"],
620
+ "display_clip": display_policy["clip"],
621
+ "display_valid_cells": display_policy[
622
+ "n_valid_intersecting_cells"
623
+ ],
624
+ }
625
+ },
626
+ }
627
+ return RasterRun(
628
+ display_lon,
629
+ display_lat,
630
+ display_grid,
631
+ info,
632
+ plot_options,
633
+ satellite=satellite,
634
+ render=render,
509
635
  )
510
- emit_result(result, output)