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
@@ -0,0 +1,526 @@
1
+ """Station-centered satellite maps with optional single-hour observations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from pathlib import Path
7
+ from typing import TYPE_CHECKING, Any
8
+
9
+ import numpy as np
10
+
11
+ from rsplot.commands.raster import parse_raster_dates, prepare_raster
12
+ from rsplot.config import STATION_VAR_META, AppConfig
13
+ from rsplot.errors import RsplotError
14
+ from rsplot.result_builders.provenance import input_fingerprint
15
+
16
+ if TYPE_CHECKING:
17
+ from rich.console import Console
18
+
19
+ LOCATION_COLUMNS = [
20
+ "id",
21
+ "lon",
22
+ "lat",
23
+ "admin",
24
+ "in_region",
25
+ "is_center",
26
+ "distance_km",
27
+ "dx_km",
28
+ "dy_km",
29
+ ]
30
+ RADIUS_COLUMNS = ["is_center", "distance_km", "dx_km", "dy_km"]
31
+
32
+
33
+ def location_snapshot_hour(
34
+ date_arg: str,
35
+ sensor: str,
36
+ days: int | None,
37
+ station_datetime: str | None,
38
+ ) -> str:
39
+ """Explicit hour whose station coordinates are drawn without values."""
40
+ from rsplot.readers.gems import parse_gems_time
41
+ from rsplot.temporal import adapt_hourly_time
42
+
43
+ scan_mode = sensor == "gems" and len(date_arg) == 12
44
+ if scan_mode:
45
+ try:
46
+ parse_gems_time(date_arg)
47
+ except ValueError as error:
48
+ raise RsplotError("invalid_time", str(error)) from error
49
+ if days is not None:
50
+ raise RsplotError(
51
+ "invalid_argument",
52
+ "GEMS 单次扫描不能同时使用 --days。",
53
+ option="--days",
54
+ )
55
+ parse_raster_dates(date_arg[:8] if scan_mode else date_arg, days)
56
+ if station_datetime is None:
57
+ raise RsplotError(
58
+ "invalid_argument",
59
+ "只标站点位置时,必须通过 --station-datetime YYYYMMDDHH "
60
+ "指定站点坐标所用的小时;不会自动选择。",
61
+ option="--station-datetime",
62
+ )
63
+ try:
64
+ adapt_hourly_time(station_datetime, label="--station-datetime ")
65
+ except ValueError as error:
66
+ raise RsplotError(
67
+ "invalid_time", str(error), option="--station-datetime"
68
+ ) from error
69
+ return station_datetime
70
+
71
+
72
+ def _day(stamp: str, *, year: bool = True) -> str:
73
+ """Format ``YYYYMMDD...`` as ``YYYY-MM-DD``, or ``MM-DD`` without year."""
74
+ day = f"{stamp[4:6]}-{stamp[6:8]}"
75
+ return f"{stamp[:4]}-{day}" if year else day
76
+
77
+
78
+ def center_place(context: dict[str, Any]) -> str:
79
+ """The centre's city and the subdivision containing it, e.g. 北京市西城区."""
80
+ unit = next(
81
+ (u for u in context["subdivisions"] if u["contains_center"]), None
82
+ )
83
+ if unit is not None:
84
+ return f"{unit['city']}{unit['name']}"
85
+ return "".join(context["center_cities"][:1])
86
+
87
+
88
+ def radius_titles(
89
+ *,
90
+ station_id: str,
91
+ km: float,
92
+ place: str,
93
+ source: str,
94
+ date_arg: str,
95
+ dates: list[str],
96
+ window_mode: bool,
97
+ gems: bool,
98
+ station_var: str | None,
99
+ station_hour: str,
100
+ ) -> tuple[str, str]:
101
+ """Title (where and when) and grey subtitle (each layer's time).
102
+
103
+ The satellite date appears once, in the title; the subtitle repeats a
104
+ date only where the station hour falls on another day.
105
+ """
106
+ first, last = dates[0], dates[-1]
107
+ if not window_mode:
108
+ period = _day(first)
109
+ else:
110
+ period = f"{_day(first)} ~ {_day(last, year=first[:4] != last[:4])}"
111
+ side = f"{2 * km:g}"
112
+ title = " · ".join(
113
+ part
114
+ for part in (f"{station_id} 周边 {side} × {side} km", place, period)
115
+ if part
116
+ )
117
+
118
+ if window_mode:
119
+ aggregation = f"{len(dates)} 天均值"
120
+ elif len(date_arg) == 12:
121
+ aggregation = f"{date_arg[8:10]}:{date_arg[10:]} 扫描"
122
+ else:
123
+ aggregation = "有效扫描均值" if gems else "日均"
124
+ day, hour = station_hour[:8], f"{station_hour[8:]}:00"
125
+ if not window_mode and day == first:
126
+ when = hour
127
+ else:
128
+ when = f"{_day(day, year=day[:4] != last[:4])} {hour}"
129
+ station = f"站点 {station_var}" if station_var else "站点位置"
130
+ return title, f"{source} {aggregation} | {station} {when}"
131
+
132
+
133
+ def run_radius(**kwargs: Any) -> None:
134
+ """Map a station-centred square with an optional station hour."""
135
+ from rsplot.commands.sidecar import run_with_sidecar
136
+
137
+ run_with_sidecar(
138
+ kwargs=kwargs,
139
+ emit=lambda created: _emit_radius(created, **kwargs),
140
+ )
141
+
142
+
143
+ def _emit_radius(
144
+ created: list[Path],
145
+ *,
146
+ station_id: str,
147
+ date_arg: str,
148
+ km: float,
149
+ station_var: str | None = None,
150
+ station_datetime: str | None = None,
151
+ console: Console,
152
+ **raster_options: Any,
153
+ ) -> None:
154
+ """Resolve stations and a square, reuse satellite preparation, emit."""
155
+ from rsplot.commands.overlay import resolve_station_hour
156
+ from rsplot.config import get_exceedance_threshold
157
+ from rsplot.data_files import data_path, write_grid_netcdf, write_table_csv
158
+ from rsplot.geo.radius import (
159
+ administrative_context,
160
+ resolve_radius_region,
161
+ station_distances,
162
+ station_offsets_km,
163
+ station_square_mask,
164
+ )
165
+ from rsplot.plotting.overlay import plot_overlay
166
+ from rsplot.plotting.raster import plot_raster
167
+ from rsplot.plotting.station_focus import StationFocus
168
+ from rsplot.readers import get_product_info
169
+ from rsplot.readers.guokong import (
170
+ StationData,
171
+ read_station_locations,
172
+ read_stations,
173
+ )
174
+ from rsplot.result_builders.envelope import (
175
+ command_line,
176
+ coverage_block,
177
+ sidecar_path,
178
+ stats_block,
179
+ success_envelope,
180
+ write_sidecar,
181
+ )
182
+ from rsplot.result_builders.satellite import build_satellite_layer
183
+ from rsplot.result_builders.station import (
184
+ attribute_stations_to_areas,
185
+ build_station_display,
186
+ )
187
+ from rsplot.result_builders.station_layer import (
188
+ TABLE_COLUMNS,
189
+ StationInputs,
190
+ build_station_layer,
191
+ colocation_block,
192
+ satellite_at_stations,
193
+ )
194
+
195
+ if not math.isfinite(km) or km <= 0:
196
+ raise RsplotError(
197
+ "invalid_argument",
198
+ "--km 必须是大于 0 的有限数字。",
199
+ option="--km",
200
+ )
201
+ station_id = station_id.strip().upper()
202
+ if not station_id:
203
+ raise RsplotError("invalid_argument", "站点 ID 不能为空。")
204
+ if station_var is not None:
205
+ station_var = station_var.strip()
206
+ if station_var not in STATION_VAR_META:
207
+ raise RsplotError(
208
+ "invalid_argument",
209
+ f"未知站点变量 '{station_var}'。可用: "
210
+ + ", ".join(STATION_VAR_META),
211
+ option="--station-var",
212
+ )
213
+ options = {
214
+ "sensor": "tropomi",
215
+ "processing": None,
216
+ "days": None,
217
+ "dpi": 300,
218
+ "res": None,
219
+ "basemap": "none",
220
+ "vmin": None,
221
+ "vmax": None,
222
+ "cmap": None,
223
+ "smooth": None,
224
+ "title": None,
225
+ "qa": None,
226
+ "cf": 0.5,
227
+ **raster_options,
228
+ }
229
+ prod = get_product_info(
230
+ options["product"],
231
+ sensor=options["sensor"],
232
+ processing=options["processing"],
233
+ )
234
+ options["processing"] = prod.processing
235
+ options["sensor"] = prod.sensor
236
+ matching = None
237
+ if station_var is not None:
238
+ request, matching, dates, window_mode = resolve_station_hour(
239
+ date_arg,
240
+ prod.sensor,
241
+ options["days"],
242
+ station_datetime,
243
+ )
244
+ else:
245
+ request = location_snapshot_hour(
246
+ date_arg, prod.sensor, options["days"], station_datetime
247
+ )
248
+ scan_mode = prod.sensor == "gems" and len(date_arg) == 12
249
+ dates, window_mode = parse_raster_dates(
250
+ date_arg[:8] if scan_mode else date_arg, options["days"]
251
+ )
252
+ cfg = AppConfig.load()
253
+ directory = cfg.get_data_dir("guokong")
254
+ locations = read_station_locations(directory, request)
255
+ values = np.full(len(locations.id), np.nan)
256
+ if station_var is not None:
257
+ observations, _ = read_stations(
258
+ directory, locations.datetime, station_var
259
+ )
260
+ values = observations.values
261
+ indices = np.flatnonzero(locations.id == station_id)
262
+ if not len(indices):
263
+ raise RsplotError(
264
+ "region_not_found",
265
+ f"站点文件 {locations.source_file} 中未找到 '{station_id}'。",
266
+ details={"station_id": station_id},
267
+ )
268
+ center = int(indices[0])
269
+ lon, lat = float(locations.lon[center]), float(locations.lat[center])
270
+ info = resolve_radius_region(station_id, lon, lat, km, cfg)
271
+ distances = station_distances(lon, lat, locations.lon, locations.lat)
272
+ dx_km, dy_km = station_offsets_km(lon, lat, locations.lon, locations.lat)
273
+ selected = np.flatnonzero(
274
+ station_square_mask(lon, lat, km, locations.lon, locations.lat)
275
+ )
276
+ unique = {}
277
+ for index in np.concatenate((indices, selected)):
278
+ key = str(locations.id[index])
279
+ if not key:
280
+ continue
281
+ if key in unique:
282
+ previous = unique[key]
283
+ if not (
284
+ locations.lon[index] == locations.lon[previous]
285
+ and locations.lat[index] == locations.lat[previous]
286
+ and (
287
+ values[index] == values[previous]
288
+ or (np.isnan(values[index]) and np.isnan(values[previous]))
289
+ )
290
+ ):
291
+ raise RsplotError(
292
+ "read_failed", f"站点 '{key}' 重复且坐标或观测值冲突。"
293
+ )
294
+ else:
295
+ unique[key] = int(index)
296
+ selected = np.asarray(list(unique.values()), dtype=int)
297
+ data = StationData(
298
+ id=locations.id[selected],
299
+ lon=locations.lon[selected],
300
+ lat=locations.lat[selected],
301
+ values=values[selected],
302
+ var_name=station_var or "",
303
+ n_stations=len(selected),
304
+ n_valid=int(np.isfinite(values[selected]).sum()),
305
+ )
306
+ source_label = prod.sensor.upper() + (" NRTI" if prod.processing else "")
307
+ context = administrative_context(info, lon, lat)
308
+ subtitle = None
309
+ if options["title"] is None:
310
+ options["title"], subtitle = radius_titles(
311
+ station_id=station_id,
312
+ km=km,
313
+ place=center_place(context),
314
+ source=f"{source_label} {options['product'].upper()}",
315
+ date_arg=date_arg,
316
+ dates=dates,
317
+ window_mode=window_mode,
318
+ gems=prod.sensor == "gems",
319
+ station_var=station_var,
320
+ station_hour=locations.datetime,
321
+ )
322
+ console.print(
323
+ f"[bold]站点快照:[/bold] {locations.datetime},"
324
+ f"正方形范围内 {data.n_stations} 站"
325
+ )
326
+ run = prepare_raster(
327
+ region=info,
328
+ date_arg=date_arg,
329
+ console=console,
330
+ **options,
331
+ )
332
+ satellite_inputs = run.satellite
333
+ assert satellite_inputs is not None
334
+ image = str(Path(options["output"]).resolve())
335
+ sidecar = sidecar_path(image)
336
+
337
+ grid_path = data_path(image, "satellite", ".nc")
338
+ created.append(grid_path)
339
+ grid_entry = write_grid_netcdf(
340
+ grid_path,
341
+ satellite_inputs.lon,
342
+ satellite_inputs.lat,
343
+ satellite_inputs.grid,
344
+ satellite_inputs.counted,
345
+ extent=info.extent,
346
+ layer="satellite",
347
+ attrs={
348
+ "quantity": prod.quantity,
349
+ "unit": prod.unit,
350
+ "scale": prod.unit_scale,
351
+ "time_aggregation": satellite_inputs.time["aggregation"],
352
+ },
353
+ valid_days=satellite_inputs.valid_days,
354
+ )
355
+
356
+ offsets = {
357
+ "is_center": (data.id == station_id).astype(int),
358
+ "distance_km": distances[selected],
359
+ "dx_km": dx_km[selected],
360
+ "dy_km": dy_km[selected],
361
+ }
362
+ station_path = data_path(image, "station", ".csv")
363
+ admin_gdf = info.sub_boundary_gdf
364
+ relations: dict[str, Any] = {}
365
+ station_flags: list[dict[str, Any]] = []
366
+ if station_var is not None:
367
+ unit, limit_key, limit_time = STATION_VAR_META[station_var]
368
+ threshold = get_exceedance_threshold(station_var)
369
+ station_layer, station_flags, rows = build_station_layer(
370
+ StationInputs(
371
+ read=data,
372
+ in_region=np.ones(data.n_stations, dtype=bool),
373
+ var=station_var,
374
+ unit=unit,
375
+ threshold=threshold,
376
+ standard=(
377
+ f"AQ_LIMITS_2026 {limit_key} {limit_time}"
378
+ if threshold is not None
379
+ else None
380
+ ),
381
+ hour=locations.datetime,
382
+ data_root=str(directory),
383
+ ),
384
+ info,
385
+ admin_gdf=admin_gdf,
386
+ satellite_values=satellite_at_stations(
387
+ satellite_inputs.lon,
388
+ satellite_inputs.lat,
389
+ satellite_inputs.grid,
390
+ satellite_inputs.counted,
391
+ data.lon,
392
+ data.lat,
393
+ ),
394
+ data=str(station_path),
395
+ extra_columns=offsets,
396
+ )
397
+ columns = TABLE_COLUMNS + list(offsets)
398
+ else:
399
+ admins = (
400
+ attribute_stations_to_areas(
401
+ data.lon, data.lat, admin_gdf, info.sub_name_field
402
+ )
403
+ if admin_gdf is not None and len(admin_gdf) > 0
404
+ else np.full(data.n_stations, "", dtype=object)
405
+ )
406
+ rows = [
407
+ {
408
+ "id": str(data.id[index]),
409
+ "lon": float(data.lon[index]),
410
+ "lat": float(data.lat[index]),
411
+ "admin": admins[index] or "",
412
+ "in_region": 1,
413
+ **{name: column[index] for name, column in offsets.items()},
414
+ }
415
+ for index in range(data.n_stations)
416
+ ]
417
+ columns = LOCATION_COLUMNS
418
+ station_layer = {
419
+ "id": "station",
420
+ "kind": "points",
421
+ "quantity": {"name": "location", "unit": "1", "scale": 1},
422
+ "time": {
423
+ "aggregation": "hourly",
424
+ "at": locations.datetime,
425
+ "basis": "station_hour",
426
+ },
427
+ "source": {
428
+ "sensor": "station",
429
+ "processing": None,
430
+ "data_root": str(directory),
431
+ "files_total": 1,
432
+ "failed_files": {},
433
+ **input_fingerprint(str(directory), [locations.source_file]),
434
+ },
435
+ "method": {
436
+ "region_selection": "square_east_north_offsets",
437
+ "values": "locations_only",
438
+ },
439
+ "coverage": coverage_block(
440
+ data.n_stations, data.n_stations, "stations"
441
+ ),
442
+ "stats": stats_block(np.array([])),
443
+ "by_admin": [],
444
+ "extremes": {
445
+ "items": [],
446
+ "total": 0,
447
+ "truncated": False,
448
+ "order": "value_desc",
449
+ },
450
+ "data": str(station_path),
451
+ }
452
+ station_layer["method"]["region_selection"] = "square_east_north_offsets"
453
+ created.append(station_path)
454
+ station_entry = write_table_csv(
455
+ station_path,
456
+ rows,
457
+ columns,
458
+ content="station_table",
459
+ layer="station",
460
+ )
461
+
462
+ created.append(Path(image))
463
+ focus = StationFocus(data, station_id, km, station_var is None)
464
+ plot_options = {
465
+ **run.plot_options,
466
+ "subtitle": subtitle,
467
+ "station_focus": focus,
468
+ }
469
+ if station_var is None:
470
+ plot_raster(run.lon, run.lat, run.grid, info, **plot_options)
471
+ else:
472
+ for key in ("cmap", "vmin", "vmax"):
473
+ plot_options[f"raster_{key}"] = plot_options.pop(key)
474
+ plot_options["raster_label"] = plot_options.pop("colorbar_label")
475
+ unit = STATION_VAR_META[station_var][0]
476
+ plot_options["station_label"] = (
477
+ f"{station_var} ({unit})" if unit else station_var
478
+ )
479
+ plot_overlay(run.lon, run.lat, run.grid, data, info, **plot_options)
480
+
481
+ satellite_layer, satellite_flags = build_satellite_layer(
482
+ satellite_inputs, info, data=grid_entry["path"]
483
+ )
484
+ if matching is not None:
485
+ relations = {
486
+ "time_matching": matching,
487
+ "colocation": colocation_block(rows, str(station_path)),
488
+ }
489
+
490
+ render_layers = dict(run.render["layers"])
491
+ if station_var is not None:
492
+ render_layers["station"] = build_station_display(data) or {
493
+ "range_method": "data_p5_p95"
494
+ }
495
+ payload = success_envelope(
496
+ command="radius",
497
+ request=command_line(),
498
+ region=info,
499
+ layers=[satellite_layer, station_layer],
500
+ relations=relations,
501
+ flags=satellite_flags + station_flags,
502
+ render={
503
+ "image": image,
504
+ **run.render,
505
+ "subtitle": subtitle,
506
+ "layers": render_layers,
507
+ },
508
+ artifacts={
509
+ "image": image,
510
+ "sidecar": sidecar,
511
+ "data": [grid_entry, station_entry],
512
+ },
513
+ radius={
514
+ "center_station": station_id,
515
+ "km": km,
516
+ "side_length_km": 2 * km,
517
+ "shape": "square",
518
+ "projection": "station_centered_WGS84_AEQD",
519
+ "center_lon": lon,
520
+ "center_lat": lat,
521
+ "administrative_context": context,
522
+ },
523
+ )
524
+ created.append(Path(sidecar))
525
+ write_sidecar(payload, sidecar)
526
+ console.print(f"[bold green]✓ 已保存:[/bold green] {image}")