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
@@ -3,276 +3,353 @@
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
- from rsplot.commands.common import validate_positive
11
+ from rsplot.commands.common import (
12
+ parse_explicit_window,
13
+ require_single_region,
14
+ validate_positive,
15
+ )
12
16
  from rsplot.config import AppConfig
17
+ from rsplot.errors import RsplotError
18
+ from rsplot.result_builders.provenance import input_fingerprint
13
19
 
14
20
  if TYPE_CHECKING:
15
21
  from rich.console import Console
16
22
 
17
- from rsplot.geo.boundaries import RegionInfo
18
23
  from rsplot.readers.guokong import RegionStationSeries
19
24
 
20
25
 
21
- def run_trend(
26
+ def run_trend(**kwargs: Any) -> None:
27
+ """Plot a single-station or regional hourly trend."""
28
+ from rsplot.commands.sidecar import run_with_sidecar
29
+
30
+ run_with_sidecar(
31
+ kwargs=kwargs,
32
+ emit=lambda created: _emit_trend(created, **kwargs),
33
+ )
34
+
35
+
36
+ def _emit_trend(
37
+ created: list[Path],
22
38
  *,
23
39
  target: str,
24
40
  date_arg: str,
25
- days: int,
41
+ days: int | None,
26
42
  var: str,
27
43
  region_mode: bool,
28
44
  view: str,
29
45
  focus_station_ids: list[str] | None,
30
46
  threshold: float | None,
31
- level: str | None,
32
- data_dir: str | None,
33
- output: str | None,
47
+ output: str,
34
48
  dpi: int | None,
35
49
  title: str | None,
36
50
  console: Console,
37
51
  ) -> None:
38
- """Read and plot a single-station or regional hourly trend."""
52
+ """Read and plot the trend, then write the sidecar and series file."""
39
53
  from rsplot.config import STATION_VAR_META, get_exceedance_threshold
54
+ from rsplot.data_files import data_path, write_series_netcdf
40
55
  from rsplot.geo.boundaries import resolve_region
41
56
  from rsplot.plotting.styles import setup_fonts
42
- from rsplot.temporal import parse_date_window
57
+ from rsplot.result_builders.envelope import (
58
+ command_line,
59
+ sidecar_path,
60
+ success_envelope,
61
+ write_sidecar,
62
+ )
63
+ from rsplot.result_builders.series_layer import (
64
+ region_series_layers,
65
+ station_series_layer,
66
+ )
43
67
 
44
- if days < 1:
45
- console.print("[red]--days 必须 >= 1[/red]")
46
- raise typer.Exit(1)
47
68
  if var not in STATION_VAR_META:
48
- available = ", ".join(STATION_VAR_META)
49
- console.print(f"[red]未知变量 '{var}'[/red]。可用: {available}")
50
- raise typer.Exit(1)
69
+ raise RsplotError(
70
+ "invalid_argument",
71
+ f"未知变量 '{var}'。可用: {', '.join(STATION_VAR_META)}",
72
+ option="--var",
73
+ )
51
74
  use_view = view.lower()
52
75
  if use_view not in ("lines", "mean"):
53
- console.print("[red]--view 仅支持 lines / mean[/red]")
54
- raise typer.Exit(1)
76
+ raise RsplotError(
77
+ "invalid_argument", "--view 仅支持 lines / mean", option="--view"
78
+ )
55
79
  if not region_mode and use_view != "lines":
56
- console.print("[red]--view 仅用于 --region 区域趋势[/red]")
57
- raise typer.Exit(1)
80
+ raise RsplotError(
81
+ "invalid_argument",
82
+ "--view 仅用于 --region 区域趋势",
83
+ option="--view",
84
+ )
58
85
  if not region_mode and focus_station_ids:
59
- console.print("[red]--focus-station 仅用于 --region 区域趋势[/red]")
60
- raise typer.Exit(1)
61
- if not region_mode and level is not None:
62
- console.print("[red]--level 仅用于 --region 区域趋势[/red]")
63
- raise typer.Exit(1)
86
+ raise RsplotError(
87
+ "invalid_argument",
88
+ "--focus-station 仅用于 --region 区域趋势",
89
+ option="--focus-station",
90
+ )
64
91
  if threshold is not None and (
65
92
  not math.isfinite(threshold) or threshold < 0
66
93
  ):
67
- console.print("[red]--threshold 必须是大于等于 0 的有限数字[/red]")
68
- raise typer.Exit(1)
94
+ raise RsplotError(
95
+ "invalid_argument",
96
+ "--threshold 必须是大于等于 0 的有限数字",
97
+ option="--threshold",
98
+ )
69
99
 
70
- try:
71
- dates = parse_date_window(date_arg, default_days=days)
72
- requested_focus_ids = _normalize_focus_ids(focus_station_ids or [])
73
- except ValueError as error:
74
- console.print(f"[red]{error}[/red]")
75
- raise typer.Exit(1) from error
100
+ dates = parse_explicit_window(date_arg, days)
101
+ requested_focus_ids = _normalize_focus_ids(focus_station_ids or [])
76
102
 
77
103
  cfg = AppConfig.load()
78
104
  setup_fonts(cfg.font_dir)
79
- use_data_dir = (
80
- data_dir if data_dir is not None else cfg.get_data_dir("guokong")
81
- )
105
+ use_data_dir = cfg.get_data_dir("guokong")
106
+ unit, limit_key, limit_time = STATION_VAR_META[var]
82
107
  use_threshold = (
83
108
  threshold if threshold is not None else get_exceedance_threshold(var)
84
109
  )
110
+ standard = (
111
+ "--threshold"
112
+ if threshold is not None
113
+ else f"AQ_LIMITS_2026 {limit_key} {limit_time}"
114
+ if use_threshold is not None
115
+ else None
116
+ )
85
117
  use_dpi = dpi if dpi is not None else cfg.dpi
86
118
  try:
87
119
  validate_positive(use_dpi, "--dpi")
88
120
  except ValueError as error:
89
- console.print(f"[red]{error}[/red]")
90
- raise typer.Exit(1) from error
121
+ raise RsplotError("invalid_argument", str(error)) from error
91
122
 
123
+ info = None
92
124
  if region_mode:
125
+ require_single_region(target)
93
126
  try:
94
- info = resolve_region(target, cfg, level_override=level)
95
- except (FileNotFoundError, ValueError) as error:
96
- console.print(f"[red]{error}[/red]")
97
- raise typer.Exit(1) from error
98
- _run_region_trend(
99
- info=info,
127
+ info = resolve_region(target, cfg)
128
+ except RsplotError:
129
+ raise
130
+ except ValueError as error:
131
+ raise RsplotError(
132
+ "region_not_found", str(error), details={"region": target}
133
+ ) from error
134
+
135
+ if info is None:
136
+ trend = _read_single_trend(
137
+ station_id=target,
138
+ dates=dates,
139
+ var=var,
140
+ data_dir=use_data_dir,
141
+ console=console,
142
+ )
143
+ default_title = f"站点 {trend.station_id} · {var}"
144
+ else:
145
+ trend = _read_region_trend(
146
+ info_name=info.name,
147
+ info_level=info.level,
148
+ geometry=info.geometry,
100
149
  dates=dates,
101
150
  var=var,
102
151
  data_dir=use_data_dir,
103
152
  view=use_view,
104
- focus_station_ids=requested_focus_ids,
153
+ console=console,
154
+ )
155
+ default_title = f"{info.name} · {var} 站点趋势"
156
+ canonical_focus_ids = _resolve_focus_ids(trend, requested_focus_ids)
157
+ if canonical_focus_ids:
158
+ console.print(f" → 重点站: {', '.join(canonical_focus_ids)}")
159
+
160
+ use_title = title or default_title
161
+ image = str(Path(output).resolve())
162
+ sidecar = sidecar_path(image)
163
+
164
+ root = str(use_data_dir)
165
+ failed = {
166
+ f"{stamp}.nc": reason
167
+ for stamp, reason in sorted(trend.failed_files.items())
168
+ }
169
+ data_entries = []
170
+ source = {
171
+ "sensor": "station",
172
+ "processing": None,
173
+ "data_root": root,
174
+ "files_total": len(trend.source_files),
175
+ "failed_files": failed,
176
+ **input_fingerprint(root, [*trend.source_files, *failed]),
177
+ }
178
+
179
+ series_path = data_path(image, "series", ".nc")
180
+ created.append(series_path)
181
+ attrs = {"quantity": var, "unit": unit or "1", "scale": 1}
182
+ if info is None:
183
+ series_entry = write_series_netcdf(
184
+ series_path,
185
+ station_ids=np.array([trend.station_id]),
186
+ lon=np.array([trend.lon]),
187
+ lat=np.array([trend.lat]),
188
+ timestamps=trend.timestamps,
189
+ values=trend.values,
190
+ layer="station",
191
+ attrs=attrs,
192
+ )
193
+ layer, flags = station_series_layer(
194
+ station_id=trend.station_id,
195
+ var=var,
196
+ unit=unit,
197
+ timestamps=trend.timestamps,
198
+ values=np.asarray(trend.values, dtype=float),
199
+ dates=dates,
200
+ source=source,
201
+ threshold=use_threshold,
202
+ standard=standard,
203
+ data=str(series_path),
204
+ )
205
+ layers = [layer]
206
+ render_layer = {"threshold_line": use_threshold}
207
+ else:
208
+ series_entry = write_series_netcdf(
209
+ series_path,
210
+ station_ids=trend.station_ids,
211
+ lon=trend.lon,
212
+ lat=trend.lat,
213
+ timestamps=trend.timestamps,
214
+ values=trend.values,
215
+ layer="station",
216
+ attrs=attrs,
217
+ regional_mean=trend.hourly_mean,
218
+ hourly_counts=trend.hourly_valid_counts,
219
+ )
220
+ layers, flags = region_series_layers(
221
+ station_ids=trend.station_ids,
222
+ lon=trend.lon,
223
+ lat=trend.lat,
224
+ var=var,
225
+ unit=unit,
226
+ timestamps=trend.timestamps,
227
+ values=np.asarray(trend.values, dtype=float),
228
+ mean=trend.hourly_mean,
229
+ counts=trend.hourly_valid_counts,
230
+ dates=dates,
231
+ source=source,
232
+ threshold=use_threshold,
233
+ standard=standard,
234
+ data=str(series_path),
235
+ )
236
+ render_layer = {
237
+ "view": use_view,
238
+ "focus_station_ids": canonical_focus_ids,
239
+ "threshold_line": use_threshold,
240
+ }
241
+ data_entries.insert(0, series_entry)
242
+
243
+ console.print("\n[bold]绘图中...[/bold]")
244
+ created.append(Path(image))
245
+ if info is None:
246
+ from rsplot.plotting.station_trend import plot_station_trend
247
+
248
+ plot_station_trend(
249
+ trend,
250
+ unit=unit,
105
251
  threshold=use_threshold,
106
- unit=STATION_VAR_META[var][0],
107
252
  dpi=use_dpi,
108
- output=output,
109
- title=title,
110
- console=console,
253
+ output=image,
254
+ title=use_title,
111
255
  )
112
- return
113
-
114
- _run_single_trend(
115
- station_id=target,
116
- dates=dates,
117
- var=var,
118
- data_dir=use_data_dir,
119
- threshold=use_threshold,
120
- unit=STATION_VAR_META[var][0],
121
- dpi=use_dpi,
122
- output=output,
123
- title=title,
124
- console=console,
256
+ else:
257
+ from rsplot.plotting.station_trend import plot_region_station_trend
258
+
259
+ plot_region_station_trend(
260
+ trend,
261
+ region_name=info.name,
262
+ unit=unit,
263
+ threshold=use_threshold,
264
+ view=use_view,
265
+ focus_station_ids=canonical_focus_ids,
266
+ dpi=use_dpi,
267
+ output=image,
268
+ title=use_title,
269
+ )
270
+
271
+ payload = success_envelope(
272
+ command="trend",
273
+ request=command_line(),
274
+ region=info,
275
+ layers=layers,
276
+ flags=flags,
277
+ render={
278
+ "image": image,
279
+ "dpi": int(use_dpi),
280
+ "basemap": "none",
281
+ "title": use_title,
282
+ "layers": {"station": render_layer},
283
+ },
284
+ artifacts={"image": image, "sidecar": sidecar, "data": data_entries},
125
285
  )
286
+ created.append(Path(sidecar))
287
+ write_sidecar(payload, sidecar)
288
+ console.print(f"\n[bold green]✓ 已保存:[/bold green] {image}")
126
289
 
127
290
 
128
- def _run_single_trend(
291
+ def _read_single_trend(
129
292
  *,
130
293
  station_id: str,
131
294
  dates: list[str],
132
295
  var: str,
133
296
  data_dir: str,
134
- threshold: float | None,
135
- unit: str,
136
- dpi: int,
137
- output: str | None,
138
- title: str | None,
139
297
  console: Console,
140
- ) -> None:
141
- from rsplot.plotting.station_trend import plot_station_trend
298
+ ):
142
299
  from rsplot.readers.guokong import read_station_series
143
- from rsplot.results import build_station_trend_result, emit_result
144
300
 
145
301
  console.print(f"[bold]读取站点序列:[/bold] {data_dir}")
146
302
  console.print(
147
303
  f" 站点: {station_id}, 变量: {var}, "
148
304
  f"窗口: {dates[0]} ~ {dates[-1]} ({len(dates)} 天)"
149
305
  )
150
- try:
151
- series = read_station_series(data_dir, station_id, dates, var)
152
- except (FileNotFoundError, ValueError) as error:
153
- console.print(f"[red]{error}[/red]")
154
- raise typer.Exit(1) from error
155
-
306
+ series = read_station_series(data_dir, station_id, dates, var)
156
307
  console.print(
157
308
  f" → [green]{series.n_valid}[/green]/{series.n_hours} 小时有效,"
158
309
  f"缺少文件 {len(series.missing_files)},"
159
310
  f"读取失败 {len(series.failed_files)}"
160
311
  )
161
312
  if series.n_valid == 0:
162
- console.print("[red]指定窗口内该站点没有有效观测值。[/red]")
163
- raise typer.Exit(1)
164
-
165
- use_output = output or (
166
- f"/tmp/rsplot_trend_{series.station_id}_{var}_"
167
- f"{dates[0]}_{dates[-1]}.png"
168
- )
169
- console.print("\n[bold]绘图中...[/bold]")
170
- plot_station_trend(
171
- series,
172
- unit=unit,
173
- threshold=threshold,
174
- dpi=dpi,
175
- output=use_output,
176
- title=title,
177
- )
178
- result = build_station_trend_result(
179
- series=series,
180
- dates=dates,
181
- threshold=threshold,
182
- unit=unit,
183
- output=use_output,
184
- )
185
- emit_result(result, use_output)
186
- console.print(f"\n[bold green]✓ 已保存:[/bold green] {use_output}")
313
+ raise RsplotError("no_valid_data", "指定窗口内该站点没有有效观测值。")
314
+ return series
187
315
 
188
316
 
189
- def _run_region_trend(
317
+ def _read_region_trend(
190
318
  *,
191
- info: RegionInfo,
319
+ info_name: str,
320
+ info_level: str,
321
+ geometry: Any,
192
322
  dates: list[str],
193
323
  var: str,
194
324
  data_dir: str,
195
325
  view: str,
196
- focus_station_ids: list[str],
197
- threshold: float | None,
198
- unit: str,
199
- dpi: int,
200
- output: str | None,
201
- title: str | None,
202
326
  console: Console,
203
- ) -> None:
204
- from rsplot.plotting.station_trend import plot_region_station_trend
327
+ ) -> RegionStationSeries:
205
328
  from rsplot.readers.guokong import read_region_station_series
206
- from rsplot.results import build_region_trend_result, emit_result
207
329
 
208
- console.print(f"[bold]解析区域:[/bold] {info.name} ({info.level})")
330
+ console.print(f"[bold]解析区域:[/bold] {info_name} ({info_level})")
209
331
  console.print(f"[bold]读取区域站点序列:[/bold] {data_dir}")
210
332
  console.print(
211
333
  f" 变量: {var}, 窗口: {dates[0]} ~ {dates[-1]} "
212
334
  f"({len(dates)} 天), 视图: {view}"
213
335
  )
214
336
  try:
215
- series = read_region_station_series(
216
- data_dir,
217
- dates,
218
- var,
219
- info.geometry,
220
- )
221
- except (FileNotFoundError, ValueError) as error:
222
- console.print(f"[red]{error}[/red]")
223
- raise typer.Exit(1) from error
224
-
225
- if series.n_valid == 0:
226
- console.print("[red]指定窗口内目标区域没有有效观测值。[/red]")
227
- raise typer.Exit(1)
228
- try:
229
- canonical_focus_ids = _resolve_focus_ids(series, focus_station_ids)
337
+ series = read_region_station_series(data_dir, dates, var, geometry)
338
+ except RsplotError:
339
+ raise
230
340
  except ValueError as error:
231
- console.print(f"[red]{error}[/red]")
232
- raise typer.Exit(1) from error
341
+ raise RsplotError("read_failed", str(error)) from error
342
+ if series.n_valid == 0:
343
+ raise RsplotError(
344
+ "no_valid_data", "指定窗口内目标区域没有有效观测值。"
345
+ )
233
346
  console.print(
234
347
  f" → [green]{series.n_stations}[/green] 个站点,"
235
348
  f"[green]{series.n_valid}[/green] 个有效观测值,"
236
349
  f"缺少文件 {len(series.missing_files)},"
237
350
  f"读取失败 {len(series.failed_files)}"
238
351
  )
239
- if canonical_focus_ids:
240
- console.print(f" → 重点站: {', '.join(canonical_focus_ids)}")
241
- if threshold is not None:
242
- exceed_mask = np.isfinite(series.values) & (series.values > threshold)
243
- n_exceed_stations = int(exceed_mask.any(axis=1).sum())
244
- console.print(
245
- f" → 超标阈值: {threshold:g}, "
246
- f"窗口内超标站点: [red]{n_exceed_stations}[/red]"
247
- )
248
-
249
- use_output = output or (
250
- f"/tmp/rsplot_trend_{info.name}_{var}_{dates[0]}_{dates[-1]}.png"
251
- )
252
- console.print("\n[bold]绘图中...[/bold]")
253
- plot_region_station_trend(
254
- series,
255
- region_name=info.name,
256
- unit=unit,
257
- threshold=threshold,
258
- view=view,
259
- focus_station_ids=canonical_focus_ids,
260
- dpi=dpi,
261
- output=use_output,
262
- title=title,
263
- )
264
- result = build_region_trend_result(
265
- series=series,
266
- region=info,
267
- dates=dates,
268
- threshold=threshold,
269
- unit=unit,
270
- view=view,
271
- focus_station_ids=canonical_focus_ids,
272
- output=use_output,
273
- )
274
- emit_result(result, use_output)
275
- console.print(f"\n[bold green]✓ 已保存:[/bold green] {use_output}")
352
+ return series
276
353
 
277
354
 
278
355
  def _normalize_focus_ids(station_ids: list[str]) -> list[str]:
@@ -282,7 +359,11 @@ def _normalize_focus_ids(station_ids: list[str]) -> list[str]:
282
359
  for station_id in station_ids:
283
360
  value = station_id.strip().upper()
284
361
  if not value:
285
- raise ValueError("--focus-station 不能为空")
362
+ raise RsplotError(
363
+ "invalid_argument",
364
+ "--focus-station 不能为空",
365
+ option="--focus-station",
366
+ )
286
367
  if value not in seen:
287
368
  seen.add(value)
288
369
  normalized.append(value)
@@ -307,11 +388,15 @@ def _resolve_focus_ids(
307
388
  continue
308
389
  canonical.append(str(series.station_ids[index]))
309
390
  if missing:
310
- raise ValueError(
311
- f"--focus-station 不在目标区域内: {', '.join(missing)}"
391
+ raise RsplotError(
392
+ "invalid_argument",
393
+ f"--focus-station 不在目标区域内: {', '.join(missing)}",
394
+ option="--focus-station",
312
395
  )
313
396
  if empty:
314
- raise ValueError(
315
- f"--focus-station 在窗口内没有有效值: {', '.join(empty)}"
397
+ raise RsplotError(
398
+ "invalid_argument",
399
+ f"--focus-station 在窗口内没有有效值: {', '.join(empty)}",
400
+ option="--focus-station",
316
401
  )
317
402
  return canonical
rsplot/config.py CHANGED
@@ -13,6 +13,8 @@ from dataclasses import dataclass, field
13
13
  from pathlib import Path
14
14
  from typing import Any
15
15
 
16
+ from rsplot.errors import RsplotError
17
+
16
18
  if sys.version_info >= (3, 11):
17
19
  import tomllib
18
20
  else:
@@ -23,6 +25,13 @@ else:
23
25
  # Safe built-in path defaults
24
26
  # ---------------------------------------------------------------------------
25
27
  KNOWN_DATA_PRODUCTS = (
28
+ "tropomi_nrti_no2",
29
+ "tropomi_nrti_hcho",
30
+ "tropomi_nrti_o3",
31
+ "tropomi_nrti_o3pr",
32
+ "gems_no2",
33
+ "gems_hcho",
34
+ "gems_o3",
26
35
  "no2",
27
36
  "o3",
28
37
  "o3pr",
@@ -36,13 +45,11 @@ KNOWN_DATA_PRODUCTS = (
36
45
  DEFAULT_DATA_DIRS: dict[str, str] = {}
37
46
  DEFAULT_GEOJSON_DIR = None
38
47
  DEFAULT_FONT_DIR = None
39
- DEFAULT_HCHO_CMAP_FILE = None
40
48
  DEFAULT_TIANDITU_KEY = None
41
49
 
42
50
 
43
51
  CONFIG_PATH = Path.home() / ".config" / "rsplot" / "config.toml"
44
52
  CONFIG_ENV_VAR = "RSPLOT_CONFIG"
45
- HCHO_CMAP_FILE_ENV = "RSPLOT_HCHO_CMAP_FILE"
46
53
 
47
54
 
48
55
  # ---------------------------------------------------------------------------
@@ -172,7 +179,6 @@ class AppConfig:
172
179
  )
173
180
  geojson_dir: str | None = DEFAULT_GEOJSON_DIR
174
181
  font_dir: str | None = DEFAULT_FONT_DIR
175
- hcho_cmap_file: str | None = DEFAULT_HCHO_CMAP_FILE
176
182
  tianditu_key: str | None = DEFAULT_TIANDITU_KEY
177
183
  config_files: list[str] = field(default_factory=list)
178
184
  subdivision_overrides: dict[str, SubdivisionSource] = field(
@@ -219,8 +225,6 @@ class AppConfig:
219
225
  self.geojson_dir = _normalize_path(v)
220
226
  if v := os.environ.get("RSPLOT_FONT_DIR"):
221
227
  self.font_dir = _normalize_path(v)
222
- if v := os.environ.get(HCHO_CMAP_FILE_ENV):
223
- self.hcho_cmap_file = _normalize_path(v)
224
228
  if v := os.environ.get("TIANDITU_API_KEY"):
225
229
  self.tianditu_key = v
226
230
 
@@ -235,23 +239,27 @@ class AppConfig:
235
239
  ", ".join(sorted(k for k, v in self.data_dirs.items() if v))
236
240
  or "none"
237
241
  )
238
- raise ValueError(
242
+ raise RsplotError(
243
+ "data_not_configured",
239
244
  f"No data directory configured for product '{product}'. "
240
245
  f"Set [paths.data_dirs].{key} in {CONFIG_PATH}, set "
241
- f"RSPLOT_DATA_DIR_{key.upper()}, point {CONFIG_ENV_VAR} to a "
242
- "TOML config file, or pass the command-specific data directory "
243
- f"option. Known products: {', '.join(KNOWN_DATA_PRODUCTS)}. "
244
- f"Configured products: {configured}."
246
+ f"RSPLOT_DATA_DIR_{key.upper()}, or point {CONFIG_ENV_VAR} to a "
247
+ "TOML config file. "
248
+ f"Known products: {', '.join(KNOWN_DATA_PRODUCTS)}. "
249
+ f"Configured products: {configured}.",
250
+ details={"config_key": key},
245
251
  )
246
252
 
247
253
  def require_geojson_dir(self) -> str:
248
254
  """Return the boundary GeoJSON directory, or raise with guidance."""
249
255
  if self.geojson_dir:
250
256
  return self.geojson_dir
251
- raise ValueError(
257
+ raise RsplotError(
258
+ "data_not_configured",
252
259
  "GeoJSON boundary directory is not configured. Set "
253
260
  f"[paths].geojson_dir in {CONFIG_PATH}, set RSPLOT_GEOJSON_DIR, "
254
- f"or point {CONFIG_ENV_VAR} to a TOML config file."
261
+ f"or point {CONFIG_ENV_VAR} to a TOML config file.",
262
+ details={"config_key": "geojson_dir"},
255
263
  )
256
264
 
257
265
  def _apply_toml(self, data: dict[str, Any]) -> None:
@@ -264,8 +272,6 @@ class AppConfig:
264
272
  self.geojson_dir = _normalize_path(v)
265
273
  if v := paths.get("font_dir"):
266
274
  self.font_dir = _normalize_path(v)
267
- if v := paths.get("hcho_cmap_file"):
268
- self.hcho_cmap_file = _normalize_path(v)
269
275
 
270
276
  td = data.get("tianditu", {})
271
277
  if v := td.get("api_key"):
@@ -324,8 +330,10 @@ def _config_paths() -> list[Path]:
324
330
  if raw := os.environ.get(CONFIG_ENV_VAR):
325
331
  path = Path(_normalize_path(raw))
326
332
  if not path.exists():
327
- raise FileNotFoundError(
328
- f"{CONFIG_ENV_VAR} points to a missing config file: {path}"
333
+ raise RsplotError(
334
+ "config_invalid",
335
+ f"{CONFIG_ENV_VAR} points to a missing config file: {path}",
336
+ details={"path": str(path)},
329
337
  )
330
338
  try:
331
339
  already_loaded = path.resolve() in {p.resolve() for p in paths}
@@ -416,3 +424,25 @@ def get_exceedance_threshold(var_name: str) -> float | None:
416
424
  if limits is None:
417
425
  return None
418
426
  return limits.get(limit_time)
427
+
428
+
429
+ @dataclass(frozen=True)
430
+ class StationColorScale:
431
+ """Fixed concentration scale for O3 and NO2 station map layers."""
432
+
433
+ threshold: float
434
+ vmax: float
435
+ vmin: float = 0.0
436
+ cmap: str = "rsplot_station_threshold"
437
+ exceedance_color: str = "#ff0000"
438
+
439
+
440
+ def get_station_color_scale(var_name: str) -> StationColorScale | None:
441
+ """Use existing time-specific limits with 20 ug/m3 of red headroom."""
442
+ meta = STATION_VAR_META.get(var_name)
443
+ if meta is None or meta[1] not in ("O3", "NO2"):
444
+ return None
445
+ threshold = get_exceedance_threshold(var_name)
446
+ if threshold is None:
447
+ return None
448
+ return StationColorScale(threshold=threshold, vmax=threshold + 20.0)