rsplot 0.3.2.dev37__py3-none-any.whl → 0.4.1.dev8__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.
@@ -0,0 +1,541 @@
1
+ """Implementation service for the ``exceedance`` command."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from itertools import chain
6
+ from pathlib import Path
7
+ from typing import TYPE_CHECKING, Any
8
+
9
+ from rsplot.commands.common import validate_positive
10
+ from rsplot.config import AppConfig
11
+ from rsplot.errors import RsplotError
12
+ from rsplot.result_builders.provenance import input_fingerprint
13
+
14
+ if TYPE_CHECKING:
15
+ from rich.console import Console
16
+
17
+ from rsplot.exceedance import DailyMda8, DailyMean
18
+ from rsplot.readers.guokong import RegionStationSeries
19
+ from rsplot.weather_days import DailyWeather
20
+
21
+ # Judged variable -> (AQ_LIMITS_2026 key, limit period). O3 is judged by
22
+ # its MDA8, every other variable by its daily mean.
23
+ JUDGED_VARS = {
24
+ "O3": ("O3", "8h"),
25
+ "PM2.5": ("PM2_5", "daily"),
26
+ "PM10": ("PM10", "daily"),
27
+ "NO2": ("NO2", "daily"),
28
+ "SO2": ("SO2", "daily"),
29
+ "CO": ("CO", "daily"),
30
+ }
31
+ # Processes reading a date range's hourly files; one day reads serially.
32
+ READ_WORKERS = 8
33
+ LABEL_LIMIT = 10
34
+
35
+
36
+ def run_exceedance(**kwargs: Any) -> None:
37
+ """Judge each station's daily value against the limit and plot it."""
38
+ from rsplot.commands.sidecar import run_with_sidecar
39
+
40
+ run_with_sidecar(
41
+ kwargs=kwargs,
42
+ emit=lambda created: _emit_exceedance(created, **kwargs),
43
+ )
44
+
45
+
46
+ def _emit_exceedance(
47
+ created: list[Path],
48
+ *,
49
+ target: str,
50
+ station: bool,
51
+ date_arg: str,
52
+ var: str,
53
+ meteo_hours: str | None,
54
+ output: str,
55
+ dpi: int | None,
56
+ title: str | None,
57
+ console: Console,
58
+ ) -> None:
59
+ """Read the region's hours, judge each day, plot, write the sidecar."""
60
+ from rsplot.config import AQ_LIMITS_2026, STATION_VAR_META
61
+ from rsplot.data_files import (
62
+ data_path,
63
+ write_table_csv,
64
+ )
65
+ from rsplot.exceedance import daily_mda8, daily_mean, day_hours
66
+ from rsplot.geo.boundaries import resolve_regions
67
+ from rsplot.plotting.styles import setup_fonts
68
+ from rsplot.readers.guokong import (
69
+ NoRegionStations,
70
+ read_station_hour_variables,
71
+ )
72
+ from rsplot.result_builders.envelope import (
73
+ command_line,
74
+ sidecar_path,
75
+ success_envelope,
76
+ write_sidecar,
77
+ )
78
+ from rsplot.result_builders.exceedance import (
79
+ ALL_COLUMNS,
80
+ DAILY_MEAN_COLUMNS,
81
+ TABLE_COLUMNS,
82
+ StationAdmins,
83
+ hourly_layer,
84
+ judged_layer,
85
+ labelled_stations,
86
+ series_flags,
87
+ station_day_rows,
88
+ )
89
+ from rsplot.temporal import parse_date_window
90
+
91
+ combined = var.lower() == "all"
92
+ if not combined and var not in JUDGED_VARS:
93
+ raise RsplotError(
94
+ "invalid_argument",
95
+ "exceedance 支持 --var O3、PM2.5、PM10、NO2、SO2、CO 或 all(O3 由逐"
96
+ f"小时值计算 MDA8,其余计算日均值),不支持 '{var}'。",
97
+ option="--var",
98
+ )
99
+ try:
100
+ dates = parse_date_window(date_arg, default_days=1)
101
+ except ValueError as error:
102
+ raise RsplotError("invalid_time", str(error)) from error
103
+ if meteo_hours is not None and (combined or station):
104
+ raise RsplotError(
105
+ "invalid_argument",
106
+ "区域气象比较需要指定单一 --var 并使用区域名称(省略 --station)。",
107
+ option="--meteo-hours",
108
+ )
109
+ if station and not target.strip():
110
+ raise RsplotError("invalid_argument", "站点 ID 不能为空")
111
+ window = _meteo_window(meteo_hours, dates)
112
+
113
+ cfg = AppConfig.load()
114
+ setup_fonts(cfg.font_dir)
115
+ use_dpi = dpi if dpi is not None else cfg.dpi
116
+ try:
117
+ validate_positive(use_dpi, "--dpi")
118
+ except ValueError as error:
119
+ raise RsplotError("invalid_argument", str(error)) from error
120
+
121
+ info = None
122
+ name = target.strip().upper()
123
+ if not station:
124
+ console.print(f"[bold]解析区域:[/bold] {target}")
125
+ try:
126
+ info = resolve_regions(target, cfg)
127
+ except RsplotError:
128
+ raise
129
+ except ValueError as error:
130
+ raise RsplotError(
131
+ "region_not_found", str(error), details={"region": target}
132
+ ) from error
133
+ name = info.name
134
+
135
+ data_dir = cfg.get_data_dir("guokong")
136
+ hours = day_hours(dates)
137
+ console.print(f"\n[bold]读取逐小时 {var}:[/bold] {data_dir}")
138
+ console.print(
139
+ f" 日期: {dates[0]} ~ {dates[-1]} ({len(dates)} 天),"
140
+ f"时次 {hours[0]} ~ {hours[-1]}"
141
+ )
142
+ try:
143
+ observations = read_station_hour_variables(
144
+ data_dir,
145
+ hours,
146
+ tuple(JUDGED_VARS) if combined else (var,),
147
+ geometry=info.geometry if info else None,
148
+ station_id=name if station else None,
149
+ window=(dates[0], dates[-1]),
150
+ workers=READ_WORKERS if len(dates) > 1 else 1,
151
+ )
152
+ except RsplotError:
153
+ raise
154
+ except NoRegionStations as error:
155
+ raise RsplotError("no_valid_data", str(error)) from error
156
+ except ValueError as error:
157
+ raise RsplotError("read_failed", str(error)) from error
158
+ first = next(iter(observations.values()))
159
+ admins = StationAdmins.from_region(info, first) if info else None
160
+ span = dates[0] if len(dates) == 1 else f"{dates[0]}-{dates[-1]}"
161
+ metric = "六项污染物逐日超标站数" if combined else f"{var} 超标站点"
162
+ use_title = title or f"{name} · {metric} · {span}"
163
+ image = str(Path(output).resolve())
164
+ sidecar = sidecar_path(image)
165
+ tables = []
166
+ daily_results = {}
167
+ days_by_var = {}
168
+ layers = []
169
+ entries = []
170
+ flags = []
171
+ render = {}
172
+ relations = {}
173
+ if combined:
174
+ table_id, columns = "exceedance_all", ALL_COLUMNS
175
+ elif var == "O3":
176
+ table_id, columns = "mda8", TABLE_COLUMNS
177
+ else:
178
+ table_id, columns = "daily_mean", DAILY_MEAN_COLUMNS
179
+ table_path = data_path(image, table_id, ".csv")
180
+ root = str(data_dir)
181
+ fingerprint = input_fingerprint(
182
+ root, [*first.source_files, *(f"{h}.nc" for h in first.failed_files)]
183
+ )
184
+ for pollutant, series in observations.items():
185
+ limit_key, period = JUDGED_VARS[pollutant]
186
+ limit = float(AQ_LIMITS_2026[limit_key][period])
187
+ unit = STATION_VAR_META[pollutant][0]
188
+ result = (
189
+ daily_mda8(series.values, hours, dates, limit)
190
+ if pollutant == "O3"
191
+ else daily_mean(series.values, dates, limit)
192
+ )
193
+ daily_results[pollutant] = result
194
+ source = _station_source(root, series, fingerprint)
195
+ judged = judged_layer(
196
+ series,
197
+ result,
198
+ unit,
199
+ limit,
200
+ f"AQ_LIMITS_2026 {limit_key} {period}",
201
+ source,
202
+ str(table_path),
203
+ admins,
204
+ combined=combined,
205
+ )
206
+ layers.append(judged)
207
+ days_by_var[pollutant] = judged["days"]
208
+ tables.append(
209
+ station_day_rows(
210
+ series,
211
+ result,
212
+ admins,
213
+ combined=combined,
214
+ limit=limit,
215
+ unit=unit,
216
+ )
217
+ )
218
+ console.print(
219
+ f" {pollutant} > {limit:g} 的站日: "
220
+ f"{judged['exceedance']['count']}/{judged['coverage']['valid']}"
221
+ )
222
+ flags.extend(
223
+ series_flags(series, judged["id"] if combined else "station")
224
+ )
225
+ if combined:
226
+ render[judged["id"]] = {"view": "daily_exceeded_station_count"}
227
+
228
+ created.append(table_path)
229
+ entries.append(
230
+ write_table_csv(
231
+ table_path,
232
+ chain.from_iterable(tables),
233
+ columns,
234
+ content="station_days",
235
+ layer=layers[0]["id"],
236
+ )
237
+ )
238
+ if combined:
239
+ from rsplot.plotting.exceedance import plot_screening
240
+
241
+ created.append(Path(image))
242
+ plot_screening(dates, days_by_var, use_title, image, use_dpi)
243
+ else:
244
+ series = observations[var]
245
+ result = daily_results[var]
246
+ judged = layers[0]
247
+ limit = judged["exceedance"]["threshold"]
248
+ unit = judged["quantity"]["unit"]
249
+ series_path = data_path(image, "series", ".nc")
250
+ created.append(series_path)
251
+ entries.insert(0, _write_series(series_path, series, result, unit))
252
+ layers.insert(
253
+ 0,
254
+ hourly_layer(
255
+ series,
256
+ dates,
257
+ unit,
258
+ judged["source"],
259
+ str(series_path),
260
+ admins,
261
+ ),
262
+ )
263
+ weather = None
264
+ if window is not None:
265
+ meteo, relation, extra_flags, weather, entry = _weather(
266
+ created,
267
+ cfg=cfg,
268
+ info=info,
269
+ dates=dates,
270
+ window=window,
271
+ result=result,
272
+ image=image,
273
+ console=console,
274
+ )
275
+ entries.append(entry)
276
+ layers.extend(meteo)
277
+ flags.extend(extra_flags)
278
+ relations["exceedance_meteo"] = relation
279
+ render["meteo"] = {
280
+ "panels": [item["id"] for item in meteo],
281
+ "shaded_days": "exceeded",
282
+ }
283
+
284
+ view = "hourly" if len(dates) == 1 else "heatmap"
285
+ labelled = labelled_stations(series.station_ids, result, LABEL_LIMIT)
286
+ hourly_limit = AQ_LIMITS_2026[JUDGED_VARS[var][0]].get("hourly")
287
+ render["station"] = {
288
+ "view": view,
289
+ "labelled_station_ids": labelled,
290
+ "label_limit": LABEL_LIMIT,
291
+ "threshold_line": limit,
292
+ "hourly_threshold_line": hourly_limit
293
+ if view == "hourly"
294
+ else None,
295
+ }
296
+ created.append(Path(image))
297
+ _plot_single(
298
+ series,
299
+ result,
300
+ labelled,
301
+ limit,
302
+ hourly_limit,
303
+ view,
304
+ unit,
305
+ use_dpi,
306
+ image,
307
+ use_title,
308
+ weather,
309
+ )
310
+
311
+ payload = success_envelope(
312
+ command="exceedance",
313
+ request=command_line(),
314
+ region=info,
315
+ layers=layers,
316
+ flags=flags,
317
+ relations=relations,
318
+ render={
319
+ "image": image,
320
+ "dpi": int(use_dpi),
321
+ "basemap": "none",
322
+ "title": use_title,
323
+ "layers": render,
324
+ },
325
+ artifacts={
326
+ "image": image,
327
+ "sidecar": sidecar,
328
+ "data": entries,
329
+ },
330
+ )
331
+ created.append(Path(sidecar))
332
+ write_sidecar(payload, sidecar)
333
+ console.print(f"\n[bold green]✓ 已保存:[/bold green] {image}")
334
+
335
+
336
+ def _station_source(
337
+ root: str,
338
+ series: RegionStationSeries,
339
+ fingerprint: dict,
340
+ ) -> dict:
341
+ failed = {
342
+ f"{stamp}.nc": reason
343
+ for stamp, reason in sorted(series.failed_files.items())
344
+ }
345
+ return {
346
+ "sensor": "station",
347
+ "processing": None,
348
+ "versions": {},
349
+ "data_root": root,
350
+ "files_total": len(series.source_files),
351
+ "failed_files": failed,
352
+ **fingerprint,
353
+ }
354
+
355
+
356
+ def _write_series(
357
+ series_path: Path,
358
+ series: RegionStationSeries,
359
+ result: DailyMda8 | DailyMean,
360
+ unit: str,
361
+ ) -> dict:
362
+ from rsplot.data_files import write_series_netcdf
363
+ from rsplot.exceedance import DailyMda8
364
+
365
+ return write_series_netcdf(
366
+ series_path,
367
+ station_ids=series.station_ids,
368
+ lon=series.lon,
369
+ lat=series.lat,
370
+ timestamps=series.timestamps,
371
+ values=series.values,
372
+ layer="station",
373
+ attrs={"quantity": series.var_name, "unit": unit, "scale": 1},
374
+ extra={
375
+ "o3_8h": (
376
+ result.means,
377
+ "8-hour mean ending at each hour (hours 08-24 of each "
378
+ "day, at least 6 valid hours); NaN = not determined.",
379
+ )
380
+ }
381
+ if isinstance(result, DailyMda8)
382
+ else None,
383
+ )
384
+
385
+
386
+ def _plot_single(
387
+ series: RegionStationSeries,
388
+ result: DailyMda8 | DailyMean,
389
+ labelled: list[str],
390
+ limit: float,
391
+ hourly_limit: float | None,
392
+ view: str,
393
+ unit: str,
394
+ dpi: int,
395
+ image: str,
396
+ title: str,
397
+ weather: DailyWeather | None,
398
+ ) -> None:
399
+ var = series.var_name
400
+ if view == "hourly" and var != "O3":
401
+ from rsplot.plotting.exceedance import plot_daily_mean_day
402
+
403
+ plot_daily_mean_day(
404
+ station_ids=series.station_ids,
405
+ hours=series.timestamps,
406
+ values=series.values,
407
+ result=result,
408
+ labelled=labelled,
409
+ limit=limit,
410
+ hourly_limit=hourly_limit,
411
+ var=var,
412
+ unit=unit,
413
+ dpi=dpi,
414
+ output=image,
415
+ title=title,
416
+ )
417
+ elif view == "hourly":
418
+ from rsplot.plotting.exceedance import plot_exceedance_day
419
+
420
+ plot_exceedance_day(
421
+ station_ids=series.station_ids,
422
+ hours=series.timestamps,
423
+ values=series.values,
424
+ result=result,
425
+ labelled=labelled,
426
+ limit=limit,
427
+ hourly_limit=hourly_limit,
428
+ dpi=dpi,
429
+ output=image,
430
+ title=title,
431
+ )
432
+ else:
433
+ from rsplot.plotting.exceedance import plot_exceedance_range
434
+
435
+ plot_exceedance_range(
436
+ station_ids=series.station_ids,
437
+ result=result,
438
+ limit=limit,
439
+ quantity_label="MDA8 O3" if var == "O3" else f"{var} 日均",
440
+ statistic="MDA8" if var == "O3" else "日均",
441
+ unit=unit,
442
+ dpi=dpi,
443
+ output=image,
444
+ title=title,
445
+ weather=weather,
446
+ )
447
+
448
+
449
+ def _meteo_window(
450
+ meteo_hours: str | None, dates: list[str]
451
+ ) -> tuple[int, int] | None:
452
+ """The weather hours, checked before any data is read."""
453
+ from rsplot.weather_days import parse_meteo_hours
454
+
455
+ if meteo_hours is None:
456
+ return None
457
+ if len(dates) < 2:
458
+ raise RsplotError(
459
+ "invalid_argument",
460
+ "--meteo-hours 用于比较多日的气象,需要日期区间 "
461
+ "YYYYMMDD-YYYYMMDD。",
462
+ option="--meteo-hours",
463
+ )
464
+ try:
465
+ return parse_meteo_hours(meteo_hours)
466
+ except ValueError as error:
467
+ raise RsplotError(
468
+ "invalid_argument", str(error), option="--meteo-hours"
469
+ ) from error
470
+
471
+
472
+ def _weather(
473
+ created: list[Path],
474
+ *,
475
+ cfg: AppConfig,
476
+ info: Any,
477
+ dates: list[str],
478
+ window: tuple[int, int],
479
+ result: Any,
480
+ image: str,
481
+ console: Console,
482
+ ) -> tuple[list[dict], dict, list[dict], Any, dict]:
483
+ """Read ERA5 for the window hours.
484
+
485
+ Returns the weather layers, the ``exceedance_meteo`` relation, flags,
486
+ the daily weather drawn under the heat map and the CSV's artifact entry.
487
+ """
488
+ from rsplot.data_files import data_path, write_table_csv
489
+ from rsplot.geo.processing import buffered_extent
490
+ from rsplot.readers.era5_days import read_region_weather_hours
491
+ from rsplot.result_builders.weather_days import (
492
+ TABLE_COLUMNS,
493
+ day_groups,
494
+ exceedance_meteo,
495
+ missing_weather_flag,
496
+ weather_layers,
497
+ weather_rows,
498
+ )
499
+ from rsplot.weather_days import daily_weather, window_hours
500
+
501
+ data_dir = cfg.get_data_dir("era5")
502
+ first, last = window
503
+ hours = window_hours(dates, first, last)
504
+ console.print(f"\n[bold]读取 ERA5 逐日气象:[/bold] {data_dir}")
505
+ console.print(f" 每天 {first}–{last} 时,共 {len(hours)} 个时次")
506
+ read = read_region_weather_hours(
507
+ data_dir,
508
+ hours,
509
+ info.geometry,
510
+ buffered_extent(info.extent, 0.5),
511
+ workers=READ_WORKERS,
512
+ )
513
+ weather = daily_weather(read, dates, first, last)
514
+ console.print(
515
+ f" → 区域格点 {read.n_cells} 个,完整时次 "
516
+ f"{int(weather.complete_hours.sum())}/{len(hours)}"
517
+ )
518
+ groups = day_groups(result)
519
+ root = str(data_dir)
520
+ source = {
521
+ "sensor": "era5",
522
+ "processing": None,
523
+ "data_root": root,
524
+ "files_total": len(read.source_files),
525
+ "failed_files": dict(sorted(read.failed_files.items())),
526
+ **input_fingerprint(root, [*read.source_files, *read.failed_files]),
527
+ }
528
+ table_path = data_path(image, "meteo", ".csv")
529
+ created.append(table_path)
530
+ entry = write_table_csv(
531
+ table_path,
532
+ weather_rows(result, weather, groups),
533
+ TABLE_COLUMNS,
534
+ content="region_days",
535
+ layer="t2m_max",
536
+ )
537
+ layers = weather_layers(
538
+ weather, n_cells=read.n_cells, source=source, data=str(table_path)
539
+ )
540
+ relation = exceedance_meteo(result, weather, groups)
541
+ return layers, relation, missing_weather_flag(weather), weather, entry