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.
rsplot/commands/fnr.py CHANGED
@@ -12,6 +12,7 @@ from rsplot.commands.common import (
12
12
  parse_explicit_window,
13
13
  print_failed_dates,
14
14
  resolve_satellite,
15
+ satellite_filter_label,
15
16
  validate_non_negative,
16
17
  validate_positive,
17
18
  validate_unit_interval,
@@ -55,6 +56,7 @@ def _emit_fnr(
55
56
  smooth: float | None,
56
57
  qa: float | None,
57
58
  cf: float = 0.5,
59
+ sensor: str = "tropomi",
58
60
  processing: str | None = None,
59
61
  title: str | None,
60
62
  console: Console,
@@ -93,31 +95,55 @@ def _emit_fnr(
93
95
  )
94
96
 
95
97
  cfg = AppConfig.load()
96
- no2_info, _ = resolve_satellite(
97
- "no2", "tropomi", qa, cfg, console, processing
98
+ no2_info, use_qa = resolve_satellite(
99
+ "no2", sensor, qa, cfg, console, processing
98
100
  )
99
101
  hcho_info, _ = resolve_satellite(
100
- "hcho", "tropomi", qa, cfg, console, processing
102
+ "hcho", sensor, qa, cfg, console, processing
101
103
  )
104
+ sensor = no2_info.sensor
102
105
  processing = no2_info.processing
103
106
  setup_fonts(cfg.font_dir)
104
107
 
105
- dates = parse_explicit_window(date_arg, days)
108
+ scan_mode = sensor == "gems" and len(date_arg) == 12
109
+ if scan_mode:
110
+ from rsplot.readers.gems import parse_gems_time
106
111
 
107
- window_n = len(dates)
108
- if n_min is not None and n_min < 1:
109
- raise RsplotError(
110
- "invalid_argument", "--n-min 必须 >= 1。", option="--n-min"
111
- )
112
- use_n_min = (
113
- n_min if n_min is not None else min(window_n, max(3, window_n // 2))
114
- )
115
- if use_n_min > window_n:
116
- raise RsplotError(
117
- "invalid_argument",
118
- f"--n-min ({use_n_min}) 大于窗口天数 ({window_n})",
119
- option="--n-min",
112
+ try:
113
+ parse_gems_time(date_arg)
114
+ except ValueError as error:
115
+ raise RsplotError("invalid_time", str(error)) from error
116
+ if days is not None:
117
+ raise RsplotError(
118
+ "invalid_argument",
119
+ "GEMS 单次扫描不能同时使用 --days。",
120
+ option="--days",
121
+ )
122
+ if n_min is not None and n_min != 1:
123
+ raise RsplotError(
124
+ "invalid_argument",
125
+ "GEMS 单次扫描的 --n-min 只能为 1。",
126
+ option="--n-min",
127
+ )
128
+ dates = [date_arg[:8]]
129
+ window_n = 1
130
+ use_n_min = 1
131
+ else:
132
+ dates = parse_explicit_window(date_arg, days)
133
+ window_n = len(dates)
134
+ if n_min is not None and n_min < 1:
135
+ raise RsplotError(
136
+ "invalid_argument", "--n-min 必须 >= 1。", option="--n-min"
137
+ )
138
+ use_n_min = (
139
+ n_min if n_min is not None else min(window_n, max(3, window_n // 2))
120
140
  )
141
+ if use_n_min > window_n:
142
+ raise RsplotError(
143
+ "invalid_argument",
144
+ f"--n-min ({use_n_min}) 大于窗口天数 ({window_n})",
145
+ option="--n-min",
146
+ )
121
147
  try:
122
148
  use_voc_threshold, use_nox_threshold, use_display_max = (
123
149
  validate_fnr_thresholds(
@@ -153,10 +179,22 @@ def _emit_fnr(
153
179
  console.print(f" → [green]{info.name}[/green] (级别: {info.level})")
154
180
 
155
181
  params = info.params
156
- use_res = res if res is not None else params.res
182
+ prod_defaults = no2_info.defaults_for_level(info.level)
183
+ use_res = (
184
+ res
185
+ if res is not None
186
+ else prod_defaults.res
187
+ if prod_defaults.res is not None
188
+ else params.res
189
+ )
157
190
  use_dpi = dpi if dpi is not None else cfg.dpi
158
- use_qa = qa if qa is not None else cfg.qa_threshold
159
- use_smooth = smooth if smooth is not None else params.smooth_sigma
191
+ use_smooth = (
192
+ smooth
193
+ if smooth is not None
194
+ else prod_defaults.smooth_sigma
195
+ if prod_defaults.smooth_sigma is not None
196
+ else params.smooth_sigma
197
+ )
160
198
 
161
199
  try:
162
200
  use_basemap = parse_basemap(basemap)
@@ -183,7 +221,7 @@ def _emit_fnr(
183
221
  console.print("\n[bold]读取数据:[/bold]")
184
222
  console.print(f" NO2 : {use_no2_dir}")
185
223
  console.print(f" HCHO: {use_hcho_dir}")
186
- console.print(f" QA > {use_qa}, CF <= {cf}")
224
+ console.print(f" {satellite_filter_label(sensor, use_qa, cf)}")
187
225
 
188
226
  try:
189
227
  fnr_out = compute_fnr(
@@ -192,10 +230,12 @@ def _emit_fnr(
192
230
  res=use_res,
193
231
  qa_threshold=use_qa,
194
232
  cloud_fraction_max=cf,
233
+ sensor=sensor,
234
+ processing=processing,
235
+ scan_request=date_arg if scan_mode else None,
195
236
  n_min=use_n_min,
196
237
  raster_dir_no2=use_no2_dir,
197
238
  raster_dir_hcho=use_hcho_dir,
198
- processing=processing,
199
239
  no2_min_column=no2_min,
200
240
  console=console,
201
241
  )
@@ -246,33 +286,57 @@ def _emit_fnr(
246
286
  f"[blue]NOx-limited {percentages['nox_limited']}%[/blue]"
247
287
  )
248
288
 
249
- if title is None and processing == "nrti":
250
- title = f"TROPOMI NRTI FNR - {info.name}"
289
+ if title is None:
290
+ if sensor == "gems":
291
+ title = f"GEMS FNR regime — {info.name}"
292
+ elif processing == "nrti":
293
+ title = f"TROPOMI NRTI FNR - {info.name}"
251
294
  # The renderer's default title, recorded so the sidecar states it.
252
295
  use_title = title or f"FNR regime — {info.name}"
253
296
  image = str(Path(output).resolve())
254
297
  sidecar = sidecar_path(image)
255
- subtitle = (
256
- f"{dates[0]}~{dates[-1]} · N_days={window_n} "
257
- f"(n_min={use_n_min}) · NO2≥{no2_min:g}×10¹⁵ molec/cm²"
258
- )
298
+ if scan_mode:
299
+ subtitle = (
300
+ f"GEMS {date_arg} · NO2≥{no2_min:g}×10¹⁵ molec/cm²"
301
+ )
302
+ else:
303
+ subtitle = (
304
+ f"{dates[0]}~{dates[-1]} · N_days={window_n} "
305
+ f"(n_min={use_n_min}) · NO2≥{no2_min:g}×10¹⁵ molec/cm²"
306
+ )
259
307
 
260
308
  lon, lat = fnr_out.LON, fnr_out.LAT
261
309
  counted = region_grid_mask(lon, lat, info.geometry)
262
- time = {
263
- "aggregation": "window_mean",
264
- "start": dates[0],
265
- "end": dates[-1],
266
- "basis": "calendar_day",
267
- }
268
- product_method = {
269
- "qa_min_exclusive": use_qa,
310
+ if scan_mode:
311
+ time: dict[str, Any] = {
312
+ "aggregation": "scan",
313
+ "at": date_arg,
314
+ "basis": "nominal_scan_time",
315
+ }
316
+ else:
317
+ time = {
318
+ "aggregation": "window_mean",
319
+ "start": dates[0],
320
+ "end": dates[-1],
321
+ "basis": "calendar_day",
322
+ }
323
+ product_method: dict[str, Any] = {
270
324
  "cloud_fraction_max": cf,
271
325
  "grid_deg": use_res,
272
- "day_weighting": "equal_days",
273
326
  "cell_selection": "center_strictly_inside",
274
327
  "cell_weighting": "equal",
275
328
  }
329
+ if sensor == "gems":
330
+ product_method.update(
331
+ quality_filter="final_algorithm_flag_0_sza_vza_below_70",
332
+ spatial_aggregation="footprint_overlap_area_mean",
333
+ area_crs="EPSG:6933",
334
+ scan_weighting="equal_scans",
335
+ )
336
+ else:
337
+ product_method["qa_min_exclusive"] = use_qa
338
+ if not scan_mode:
339
+ product_method["day_weighting"] = "equal_days"
276
340
 
277
341
  def days_block(found, failed, valid_days):
278
342
  return {
@@ -325,9 +389,9 @@ def _emit_fnr(
325
389
  "quantity": prod.quantity,
326
390
  "unit": prod.unit,
327
391
  "scale": prod.unit_scale,
328
- "time_aggregation": "window_mean",
392
+ "time_aggregation": time["aggregation"],
329
393
  },
330
- valid_days=valid_days,
394
+ valid_days=None if scan_mode else valid_days,
331
395
  )
332
396
  data_entries.append(entry)
333
397
  product_layer, product_flags = build_satellite_layer(
@@ -341,8 +405,8 @@ def _emit_fnr(
341
405
  data_root=str(root),
342
406
  metadata=list(daily.values()),
343
407
  method=dict(product_method),
344
- valid_days=valid_days,
345
- days=days_block(found, failed, valid_days),
408
+ valid_days=None if scan_mode else valid_days,
409
+ days=None if scan_mode else days_block(found, failed, valid_days),
346
410
  ),
347
411
  info,
348
412
  data=entry["path"],
@@ -367,9 +431,9 @@ def _emit_fnr(
367
431
  "quantity": "fnr",
368
432
  "unit": "1",
369
433
  "scale": 1.0,
370
- "time_aggregation": "window_mean",
434
+ "time_aggregation": time["aggregation"],
371
435
  },
372
- valid_days=both_valid,
436
+ valid_days=None if scan_mode else both_valid,
373
437
  )
374
438
  data_entries.append(fnr_entry)
375
439
 
@@ -424,6 +488,11 @@ def _emit_fnr(
424
488
  **{d: f"NO2: {m}" for d, m in fnr_out.dates_failed_no2.items()},
425
489
  **{d: f"HCHO: {m}" for d, m in fnr_out.dates_failed_hcho.items()},
426
490
  }
491
+ fnr_time = (
492
+ dict(time)
493
+ if scan_mode
494
+ else {**time, "days": days_block(found_both, failed_either, both_valid)}
495
+ )
427
496
  fnr_layer: dict[str, Any] = {
428
497
  "id": "fnr",
429
498
  "kind": "grid",
@@ -433,13 +502,12 @@ def _emit_fnr(
433
502
  "scale": 1,
434
503
  "label": "FNR (HCHO / NO2)",
435
504
  },
436
- "time": {
437
- **time,
438
- "days": days_block(found_both, failed_either, both_valid),
439
- },
505
+ "time": fnr_time,
440
506
  "source": {
441
- "sensor": "tropomi",
442
- "processing": processing or "offl",
507
+ "sensor": sensor,
508
+ "processing": (
509
+ processing or "offl" if sensor == "tropomi" else None
510
+ ),
443
511
  "data_root": str(use_no2_dir),
444
512
  "files_total": sum(
445
513
  item["source"]["files_total"] for item in layers
@@ -448,7 +516,11 @@ def _emit_fnr(
448
516
  **combined_fingerprint(item["source"] for item in layers),
449
517
  },
450
518
  "method": {
451
- "ratio": "hcho_window_mean / no2_window_mean",
519
+ "ratio": (
520
+ "hcho_scan / no2_scan"
521
+ if scan_mode
522
+ else "hcho_window_mean / no2_window_mean"
523
+ ),
452
524
  "n_min_each_product": use_n_min,
453
525
  "no2_min_column": no2_min,
454
526
  "no2_min_unit": "1e15 molec/cm2",
rsplot/commands/meteo.py CHANGED
@@ -11,6 +11,7 @@ import numpy as np
11
11
  from rsplot.commands.common import (
12
12
  load_fallback_city_boundaries,
13
13
  parse_basemap,
14
+ require_station_var,
14
15
  validate_color_range,
15
16
  validate_positive,
16
17
  warn_missing_tianditu_key,
@@ -55,7 +56,6 @@ def _emit_meteo(
55
56
  ) -> None:
56
57
  """Read ERA5 (and stations) for one China-time hour and write results."""
57
58
  from rsplot.config import (
58
- STATION_VAR_LABELS,
59
59
  STATION_VAR_META,
60
60
  get_exceedance_threshold,
61
61
  )
@@ -113,13 +113,8 @@ def _emit_meteo(
113
113
  "invalid_argument",
114
114
  "请至少指定 --temp-level 或 --wind-level 中的一个。",
115
115
  )
116
- if station_var is not None and station_var not in STATION_VAR_META:
117
- raise RsplotError(
118
- "invalid_argument",
119
- f"未知站点变量 '{station_var}'。可用: "
120
- + ", ".join(STATION_VAR_META),
121
- option="--station-var",
122
- )
116
+ if station_var is not None:
117
+ require_station_var(station_var, "--station-var")
123
118
  if temp_level is None:
124
119
  for option, value in (
125
120
  ("--cmap", cmap),
@@ -196,9 +191,8 @@ def _emit_meteo(
196
191
  )
197
192
  station_threshold = get_exceedance_threshold(station_var)
198
193
  station_unit = STATION_VAR_META[station_var][0]
199
- display_var = STATION_VAR_LABELS.get(station_var, station_var)
200
194
  station_colorbar_label = (
201
- f"{display_var} ({station_unit})" if station_unit else display_var
195
+ f"{station_var} ({station_unit})" if station_unit else station_var
202
196
  )
203
197
 
204
198
  use_data_dir = str(cfg.get_data_dir("era5"))
@@ -9,6 +9,7 @@ import numpy as np
9
9
 
10
10
  from rsplot.commands.common import (
11
11
  load_fallback_city_boundaries,
12
+ require_station_var,
12
13
  resolve_satellite,
13
14
  )
14
15
  from rsplot.commands.raster import parse_raster_dates, prepare_raster
@@ -147,13 +148,7 @@ def _emit_overlay(
147
148
  date_arg, sensor, days, station_datetime
148
149
  )
149
150
 
150
- if station_var not in STATION_VAR_META:
151
- raise RsplotError(
152
- "invalid_argument",
153
- f"未知站点变量 '{station_var}'。"
154
- f"可用: {', '.join(STATION_VAR_META)}",
155
- option="--station-var",
156
- )
151
+ require_station_var(station_var, "--station-var")
157
152
 
158
153
  try:
159
154
  info = resolve_regions(region, cfg)
@@ -304,7 +299,7 @@ def _emit_overlay(
304
299
  )
305
300
 
306
301
  satellite_layer, satellite_flags = build_satellite_layer(
307
- satellite_inputs, info, data=grid_entry["path"]
302
+ satellite_inputs, info, data=grid_entry["path"], include_plumes=True
308
303
  )
309
304
  station_display = build_station_display(region_stations) or {
310
305
  "range_method": "data_p5_p95"
rsplot/commands/radius.py CHANGED
@@ -8,6 +8,7 @@ from typing import TYPE_CHECKING, Any
8
8
 
9
9
  import numpy as np
10
10
 
11
+ from rsplot.commands.common import require_station_var
11
12
  from rsplot.commands.raster import parse_raster_dates, prepare_raster
12
13
  from rsplot.config import STATION_VAR_META, AppConfig
13
14
  from rsplot.errors import RsplotError
@@ -203,13 +204,7 @@ def _emit_radius(
203
204
  raise RsplotError("invalid_argument", "站点 ID 不能为空。")
204
205
  if station_var is not None:
205
206
  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
- )
207
+ require_station_var(station_var, "--station-var")
213
208
  options = {
214
209
  "sensor": "tropomi",
215
210
  "processing": None,
rsplot/commands/raster.py CHANGED
@@ -105,6 +105,7 @@ def _emit_raster(kwargs: dict[str, Any], created: list[Path]) -> None:
105
105
  inputs,
106
106
  run.region,
107
107
  data=grid_entry["path"],
108
+ include_plumes=True,
108
109
  )
109
110
  payload = success_envelope(
110
111
  command="raster",
@@ -11,6 +11,7 @@ import numpy as np
11
11
  from rsplot.commands.common import (
12
12
  load_fallback_city_boundaries,
13
13
  parse_basemap,
14
+ require_station_var,
14
15
  validate_positive,
15
16
  warn_missing_tianditu_key,
16
17
  )
@@ -62,11 +63,7 @@ def _emit_station(
62
63
  "不支持仅日期 YYYYMMDD,也不会自动选择最新小时。",
63
64
  ) from error
64
65
 
65
- from rsplot.config import (
66
- STATION_VAR_LABELS,
67
- STATION_VAR_META,
68
- get_exceedance_threshold,
69
- )
66
+ from rsplot.config import STATION_VAR_META, get_exceedance_threshold
70
67
  from rsplot.data_files import data_path, write_table_csv
71
68
  from rsplot.geo.boundaries import resolve_regions
72
69
  from rsplot.geo.processing import buffered_extent
@@ -92,12 +89,7 @@ def _emit_station(
92
89
  cfg = AppConfig.load()
93
90
  setup_fonts(cfg.font_dir)
94
91
 
95
- if var not in STATION_VAR_META:
96
- raise RsplotError(
97
- "invalid_argument",
98
- f"未知变量 '{var}'。可用: {', '.join(STATION_VAR_META)}",
99
- option="--var",
100
- )
92
+ require_station_var(var, "--var")
101
93
 
102
94
  console.print(f"[bold]解析区域:[/bold] {region}")
103
95
  try:
@@ -146,8 +138,7 @@ def _emit_station(
146
138
  )
147
139
 
148
140
  unit, limit_key, limit_time = STATION_VAR_META[var]
149
- display_var = STATION_VAR_LABELS.get(var, var)
150
- colorbar_label = f"{display_var} ({unit})" if unit else display_var
141
+ colorbar_label = f"{var} ({unit})" if unit else var
151
142
  use_title = title
152
143
  if use_title is None:
153
144
  hour_label = f"{resolved_dt[:8]} {resolved_dt[8:]}:00"
@@ -11,6 +11,7 @@ import numpy as np
11
11
  from rsplot.commands.common import (
12
12
  parse_explicit_window,
13
13
  require_single_region,
14
+ require_station_var,
14
15
  validate_positive,
15
16
  )
16
17
  from rsplot.config import AppConfig
@@ -65,12 +66,7 @@ def _emit_trend(
65
66
  station_series_layer,
66
67
  )
67
68
 
68
- if var not in STATION_VAR_META:
69
- raise RsplotError(
70
- "invalid_argument",
71
- f"未知变量 '{var}'。可用: {', '.join(STATION_VAR_META)}",
72
- option="--var",
73
- )
69
+ require_station_var(var, "--var")
74
70
  use_view = view.lower()
75
71
  if use_view not in ("lines", "mean"):
76
72
  raise RsplotError(
rsplot/config.py CHANGED
@@ -397,17 +397,13 @@ STATION_VAR_META: dict[str, tuple[str, str | None, str | None]] = {
397
397
  "NO2": ("ug/m3", "NO2", "hourly"),
398
398
  "NO2_24h": ("ug/m3", "NO2", "daily"),
399
399
  "O3": ("ug/m3", "O3", "hourly"),
400
- "O3_24h": ("ug/m3", "O3", "hourly"),
401
- "O3_8h": ("ug/m3", "O3", "8h"),
402
- "O3_8h_24h": ("ug/m3", "O3", "8h"),
403
400
  "CO": ("mg/m3", "CO", "hourly"),
404
401
  "CO_24h": ("mg/m3", "CO", "daily"),
405
402
  }
406
403
 
407
- STATION_VAR_LABELS: dict[str, str] = {
408
- "O3_8h": "8h O3",
409
- "O3_8h_24h": "MDA8 O3",
410
- }
404
+ # Display labels by station variable; empty since the ozone summary columns
405
+ # were removed. Kept for the disabled forecast command.
406
+ STATION_VAR_LABELS: dict[str, str] = {}
411
407
 
412
408
 
413
409
  def get_exceedance_threshold(var_name: str) -> float | None:
rsplot/data_files.py CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ from collections.abc import Iterable
5
6
  from pathlib import Path
6
7
  from typing import Any
7
8
 
@@ -129,7 +130,7 @@ def format_number(value: float | None) -> str:
129
130
 
130
131
  def write_table_csv(
131
132
  path: Path,
132
- rows: list[dict[str, Any]],
133
+ rows: Iterable[dict[str, Any]],
133
134
  columns: list[str],
134
135
  *,
135
136
  content: str,
@@ -144,6 +145,7 @@ def write_table_csv(
144
145
  ):
145
146
  writer = csv.writer(handle)
146
147
  writer.writerow(columns)
148
+ count = 0
147
149
  for row in rows:
148
150
  writer.writerow(
149
151
  [
@@ -153,12 +155,13 @@ def write_table_csv(
153
155
  for column in columns
154
156
  ]
155
157
  )
158
+ count += 1
156
159
  return {
157
160
  "path": str(path),
158
161
  "format": "csv",
159
162
  "content": content,
160
163
  "layer": layer,
161
- "rows": len(rows),
164
+ "rows": count,
162
165
  "bytes": path.stat().st_size,
163
166
  }
164
167
 
@@ -175,9 +178,13 @@ def write_series_netcdf(
175
178
  attrs: dict[str, Any],
176
179
  regional_mean: np.ndarray | None = None,
177
180
  hourly_counts: np.ndarray | None = None,
181
+ extra: dict[str, tuple[np.ndarray, str]] | None = None,
178
182
  ) -> dict[str, Any]:
179
183
  """Write hourly station values as ``value(station, time)``.
180
184
 
185
+ ``extra`` adds further ``(station, time)`` variables by name, each with
186
+ its description.
187
+
181
188
  ``time`` counts China clock hours, like every rsplot time, so readers
182
189
  decode it to the CLI's ``YYYYMMDDHH`` hours without a UTC shift.
183
190
  """
@@ -227,6 +234,17 @@ def write_series_netcdf(
227
234
  value.setncattr("units", attrs.get("unit", ""))
228
235
  value.setncattr("description", "Hourly value; NaN = missing.")
229
236
  value[:] = matrix
237
+ for name, (data, description) in (extra or {}).items():
238
+ variable = dataset.createVariable(
239
+ name,
240
+ "f4",
241
+ ("station", "time"),
242
+ fill_value=np.float32(np.nan),
243
+ **compression,
244
+ )
245
+ variable.setncattr("units", attrs.get("unit", ""))
246
+ variable.setncattr("description", description)
247
+ variable[:] = np.atleast_2d(np.asarray(data, dtype=np.float32))
230
248
  if regional_mean is not None:
231
249
  mean = dataset.createVariable(
232
250
  "regional_mean",