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
@@ -221,7 +221,6 @@ def run_reconstruct(
221
221
  vmax=use_vmax,
222
222
  basemap=use_basemap,
223
223
  tianditu_key=cfg.tianditu_key,
224
- hcho_cmap_file=cfg.hcho_cmap_file,
225
224
  title=title,
226
225
  output=output,
227
226
  colorbar_label=f"{data.label} reconstructed ({data.unit})",
@@ -0,0 +1,106 @@
1
+ """Run a command that writes a result sidecar only when it succeeds.
2
+
3
+ Successful runs write the data files, image and, last, the sidecar; each
4
+ file appears whole, through a temporary name. A run first removes any
5
+ sidecar an earlier run left at the same path, so a sidecar on disk always
6
+ describes the image beside it. A failure removes what the run already wrote,
7
+ prints one ``rsplot error <code>[ <option>]: <message>[ <details>]``
8
+ line on stderr and exits 1.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import sys
15
+ from collections.abc import Callable
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ import typer
20
+
21
+ from rsplot.errors import RsplotError
22
+
23
+
24
+ def coded_error(error: Exception) -> RsplotError:
25
+ """Map an exception to an rsplot error code.
26
+
27
+ Readers, config and boundary loading and output writing raise their
28
+ own codes. What is left is an uncoded file failure (``read_failed``,
29
+ naming the file), an uncoded ValueError or an internal error.
30
+ """
31
+ if isinstance(error, RsplotError):
32
+ return error
33
+ if isinstance(error, OSError):
34
+ return RsplotError(
35
+ "read_failed",
36
+ error.strerror or str(error),
37
+ details={"path": str(error.filename)} if error.filename else None,
38
+ )
39
+ if isinstance(error, ValueError):
40
+ return RsplotError("invalid_argument", str(error))
41
+ return RsplotError(
42
+ "internal_error",
43
+ str(error) or type(error).__name__,
44
+ details={"exception": type(error).__name__},
45
+ )
46
+
47
+
48
+ def error_line(error: RsplotError) -> str:
49
+ """Format the single stderr line that reports a failure."""
50
+ option = f" {error.option}" if error.option else ""
51
+ message = " ".join(str(error).split())
52
+ details = (
53
+ " " + json.dumps(error.details, ensure_ascii=False, default=str)
54
+ if error.details
55
+ else ""
56
+ )
57
+ return f"rsplot error {error.code}{option}: {message}{details}"
58
+
59
+
60
+ def run_with_sidecar(
61
+ *,
62
+ kwargs: dict[str, Any],
63
+ emit: Callable[[list[Path]], None],
64
+ ) -> None:
65
+ """Call ``emit(created)``; on failure clean up and report one error line.
66
+
67
+ ``emit`` appends every file it writes to ``created`` before writing it,
68
+ writes each through ``atomic.atomic_write`` and writes the sidecar last.
69
+ """
70
+ from rsplot.result_builders.envelope import sidecar_path
71
+
72
+ output = kwargs.get("output")
73
+ created: list[Path] = []
74
+ cleanup_sidecar: Path | None = None
75
+ try:
76
+ if output is None or Path(output).suffix.lower() != ".png":
77
+ raise RsplotError(
78
+ "invalid_argument",
79
+ "输出文件必须使用 .png 后缀。",
80
+ option="--output",
81
+ )
82
+ image = Path(output).resolve()
83
+ if image.is_dir() or image.suffix.lower() != ".png":
84
+ raise RsplotError(
85
+ "invalid_argument",
86
+ "输出路径必须指向 .png 文件,不能是目录。",
87
+ option="--output",
88
+ )
89
+ # Only a validated image path can own a sidecar to clean up. Remove
90
+ # an earlier run's sidecar first: if this run is killed, no sidecar
91
+ # is left to vouch for a new image.
92
+ cleanup_sidecar = Path(sidecar_path(str(image)))
93
+ cleanup_sidecar.unlink(missing_ok=True)
94
+ emit(created)
95
+ except typer.Exit:
96
+ raise
97
+ except Exception as error:
98
+ coded = coded_error(error)
99
+ for path in created:
100
+ path.unlink(missing_ok=True)
101
+ if cleanup_sidecar is not None:
102
+ cleanup_sidecar.unlink(missing_ok=True)
103
+ print(error_line(coded), file=sys.stderr, flush=True)
104
+ if coded.code == "internal_error":
105
+ raise
106
+ raise typer.Exit(1) from error
@@ -2,10 +2,11 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from typing import TYPE_CHECKING
5
+ from datetime import datetime
6
+ from pathlib import Path
7
+ from typing import TYPE_CHECKING, Any
6
8
 
7
9
  import numpy as np
8
- import typer
9
10
 
10
11
  from rsplot.commands.common import (
11
12
  load_fallback_city_boundaries,
@@ -14,55 +15,106 @@ from rsplot.commands.common import (
14
15
  warn_missing_tianditu_key,
15
16
  )
16
17
  from rsplot.config import AppConfig
18
+ from rsplot.errors import RsplotError
17
19
 
18
20
  if TYPE_CHECKING:
19
21
  from rich.console import Console
20
22
 
21
23
 
22
- def run_station(
24
+ def run_station(**kwargs: Any) -> None:
25
+ """Map one station hour for a region."""
26
+ from rsplot.commands.sidecar import run_with_sidecar
27
+
28
+ run_with_sidecar(
29
+ kwargs=kwargs,
30
+ emit=lambda created: _emit_station(created, **kwargs),
31
+ )
32
+
33
+
34
+ def _emit_station(
35
+ created: list[Path],
23
36
  *,
24
37
  region: str,
25
38
  datetime_str: str,
26
39
  var: str,
27
- level: str | None,
28
- data_dir: str | None,
29
- output: str | None,
40
+ output: str,
30
41
  dpi: int | None,
31
42
  basemap: str | None,
32
43
  title: str | None,
33
44
  console: Console,
34
45
  ) -> None:
35
- """Execute station plotting without owning the Typer signature."""
46
+ """Read one station hour, plot it, and write the sidecar."""
47
+ # Validate before configuration, boundary lookup, or any source reads.
48
+ # The shared reader still supports date-only selection for other commands.
49
+ try:
50
+ if (
51
+ len(datetime_str) != 10
52
+ or not datetime_str.isascii()
53
+ or not datetime_str.isdigit()
54
+ ):
55
+ raise ValueError("Expected ten ASCII digits")
56
+ datetime.strptime(datetime_str, "%Y%m%d%H")
57
+ except ValueError as error:
58
+ raise RsplotError(
59
+ "invalid_time",
60
+ "station 时间必须是有效的 YYYYMMDDHH"
61
+ "(10 位数字,小时 00–23),如 2026041415;"
62
+ "不支持仅日期 YYYYMMDD,也不会自动选择最新小时。",
63
+ ) from error
64
+
36
65
  from rsplot.config import (
37
66
  STATION_VAR_LABELS,
38
67
  STATION_VAR_META,
39
68
  get_exceedance_threshold,
40
69
  )
41
- from rsplot.geo.boundaries import resolve_region
70
+ from rsplot.data_files import data_path, write_table_csv
71
+ from rsplot.geo.boundaries import resolve_regions
42
72
  from rsplot.geo.processing import buffered_extent
43
73
  from rsplot.plotting.station import plot_station
44
74
  from rsplot.plotting.styles import setup_fonts
45
- from rsplot.readers.guokong import mask_stations_to_region, read_stations
46
- from rsplot.results import build_station_result, emit_result
75
+ from rsplot.readers.guokong import (
76
+ mask_stations_to_region,
77
+ read_stations,
78
+ )
79
+ from rsplot.result_builders.envelope import (
80
+ command_line,
81
+ sidecar_path,
82
+ success_envelope,
83
+ write_sidecar,
84
+ )
85
+ from rsplot.result_builders.station import build_station_display
86
+ from rsplot.result_builders.station_layer import (
87
+ TABLE_COLUMNS,
88
+ StationInputs,
89
+ build_station_layer,
90
+ )
47
91
 
48
92
  cfg = AppConfig.load()
49
93
  setup_fonts(cfg.font_dir)
50
94
 
51
95
  if var not in STATION_VAR_META:
52
- available = ", ".join(STATION_VAR_META)
53
- console.print(f"[red]未知变量 '{var}'[/red]。可用: {available}")
54
- raise typer.Exit(1)
96
+ raise RsplotError(
97
+ "invalid_argument",
98
+ f"未知变量 '{var}'。可用: {', '.join(STATION_VAR_META)}",
99
+ option="--var",
100
+ )
55
101
 
56
102
  console.print(f"[bold]解析区域:[/bold] {region}")
57
- info = resolve_region(region, cfg, level_override=level)
103
+ try:
104
+ info = resolve_regions(region, cfg)
105
+ except RsplotError:
106
+ raise
107
+ except ValueError as error:
108
+ raise RsplotError(
109
+ "region_not_found", str(error), details={"region": region}
110
+ ) from error
58
111
  console.print(f" → [green]{info.name}[/green] (级别: {info.level})")
59
112
  use_dpi = dpi if dpi is not None else cfg.dpi
60
113
  try:
61
114
  use_basemap = parse_basemap(basemap)
62
115
  validate_positive(use_dpi, "--dpi")
63
- except ValueError as e:
64
- console.print(f"[red]{e}[/red]")
65
- raise typer.Exit(1) from e
116
+ except ValueError as error:
117
+ raise RsplotError("invalid_argument", str(error)) from error
66
118
  warn_missing_tianditu_key(
67
119
  basemap=use_basemap,
68
120
  default_basemap=info.params.basemap,
@@ -70,19 +122,16 @@ def run_station(
70
122
  console=console,
71
123
  )
72
124
 
73
- use_data_dir = data_dir or cfg.get_data_dir("guokong")
125
+ use_data_dir = cfg.get_data_dir("guokong")
74
126
  console.print(f"\n[bold]读取站点数据:[/bold] {use_data_dir}")
75
127
  console.print(f" 时间: {datetime_str}, 变量: {var}")
76
- read_extent = buffered_extent(info.extent, 0.5)
77
- data, resolved_dt = read_stations(
128
+ read, resolved_dt = read_stations(
78
129
  use_data_dir,
79
130
  datetime_str,
80
131
  var,
81
- extent=read_extent,
132
+ extent=buffered_extent(info.extent, 0.5),
82
133
  )
83
- data = mask_stations_to_region(data, info.geometry)
84
- if resolved_dt != datetime_str:
85
- console.print(f" → 自动选择最新时次: [cyan]{resolved_dt}[/cyan]")
134
+ data = mask_stations_to_region(read, info.geometry)
86
135
  console.print(
87
136
  f" → [green]{data.n_valid}[/green] 有效站点 (共 {data.n_stations} 站)"
88
137
  )
@@ -96,17 +145,61 @@ def run_station(
96
145
  f" → 超标阈值: {threshold}, 超标站点: [red]{n_exceed}[/red]"
97
146
  )
98
147
 
99
- unit = STATION_VAR_META[var][0]
148
+ unit, limit_key, limit_time = STATION_VAR_META[var]
100
149
  display_var = STATION_VAR_LABELS.get(var, var)
101
150
  colorbar_label = f"{display_var} ({unit})" if unit else display_var
102
151
  use_title = title
103
- if use_title is None and display_var != var:
104
- use_title = f"{display_var} - {info.name}"
152
+ if use_title is None:
153
+ hour_label = f"{resolved_dt[:8]} {resolved_dt[8:]}:00"
154
+ use_title = f"站点 {var} {hour_label} - {info.name}"
105
155
 
106
- if output is None:
107
- output = f"/tmp/rsplot_station_{info.name}_{var}_{resolved_dt}.png"
156
+ image = str(Path(output).resolve())
157
+ sidecar = sidecar_path(image)
158
+
159
+ from shapely import contains_xy
160
+
161
+ in_region = contains_xy(info.geometry.buffer(1e-9), read.lon, read.lat)
162
+ admin_gdf = (
163
+ info.sub_boundary_gdf
164
+ if info.sub_boundary_gdf is not None and len(info.sub_boundary_gdf)
165
+ else load_fallback_city_boundaries(info, cfg.require_geojson_dir())
166
+ )
167
+ station_path = data_path(image, "station", ".csv")
168
+ layer, flags, rows = build_station_layer(
169
+ StationInputs(
170
+ read=read,
171
+ in_region=in_region,
172
+ var=var,
173
+ unit=unit,
174
+ threshold=threshold,
175
+ standard=(
176
+ f"AQ_LIMITS_2026 {limit_key} {limit_time}"
177
+ if threshold is not None
178
+ else None
179
+ ),
180
+ hour=resolved_dt,
181
+ data_root=str(use_data_dir),
182
+ ),
183
+ info,
184
+ admin_gdf=admin_gdf,
185
+ satellite_values=None,
186
+ data=str(station_path),
187
+ )
188
+ created.append(station_path)
189
+ station_entry = write_table_csv(
190
+ station_path,
191
+ rows,
192
+ [
193
+ column
194
+ for column in TABLE_COLUMNS
195
+ if column not in ("satellite_value", "colocated")
196
+ ],
197
+ content="station_table",
198
+ layer="station",
199
+ )
108
200
 
109
201
  console.print("\n[bold]绘图中...[/bold]")
202
+ created.append(Path(image))
110
203
  plot_station(
111
204
  data,
112
205
  info,
@@ -115,21 +208,40 @@ def run_station(
115
208
  basemap=use_basemap,
116
209
  tianditu_key=cfg.tianditu_key,
117
210
  title=use_title,
118
- output=output,
211
+ output=image,
119
212
  colorbar_label=colorbar_label,
120
213
  )
121
- console.print(f"\n[bold green]✓ 已保存:[/bold green] {output}")
122
214
 
123
- result = build_station_result(
215
+ effective_basemap = (
216
+ use_basemap if use_basemap is not None else info.params.basemap
217
+ )
218
+ payload = success_envelope(
219
+ command="station",
220
+ request=command_line(),
124
221
  region=info,
125
- data=data,
126
- datetime_str=resolved_dt,
127
- threshold=threshold,
128
- unit=unit,
129
- cities_gdf=load_fallback_city_boundaries(
130
- info,
131
- cfg.require_geojson_dir(),
132
- ),
133
- output=output,
222
+ layers=[layer],
223
+ flags=flags,
224
+ render={
225
+ "image": image,
226
+ "dpi": int(use_dpi),
227
+ "basemap": "satellite" if effective_basemap else "none",
228
+ "title": use_title,
229
+ "layers": {
230
+ "station": {
231
+ **(
232
+ build_station_display(data)
233
+ or {"range_method": "data_p5_p95"}
234
+ ),
235
+ "colorbar_label": colorbar_label,
236
+ }
237
+ },
238
+ },
239
+ artifacts={
240
+ "image": image,
241
+ "sidecar": sidecar,
242
+ "data": [station_entry],
243
+ },
134
244
  )
135
- emit_result(result, output)
245
+ created.append(Path(sidecar))
246
+ write_sidecar(payload, sidecar)
247
+ console.print(f"\n[bold green]✓ 已保存:[/bold green] {image}")