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.
- rsplot/atomic.py +36 -0
- rsplot/cli.py +282 -469
- rsplot/commands/common.py +113 -1
- rsplot/commands/fnr.py +389 -104
- rsplot/commands/forecast.py +24 -7
- rsplot/commands/meteo.py +499 -186
- rsplot/commands/overlay.py +292 -205
- rsplot/commands/radius.py +526 -0
- rsplot/commands/raster.py +479 -230
- rsplot/commands/reconstruct.py +27 -6
- rsplot/commands/sidecar.py +106 -0
- rsplot/commands/station.py +154 -42
- rsplot/commands/station_trend.py +259 -174
- rsplot/config.py +46 -16
- rsplot/data_files.py +253 -0
- rsplot/errors.py +43 -0
- rsplot/fnr.py +38 -46
- rsplot/geo/boundaries.py +317 -11
- rsplot/geo/footprints.py +205 -0
- rsplot/geo/processing.py +84 -5
- rsplot/geo/radius.py +205 -0
- rsplot/plotting/colormap_22.txt +256 -0
- rsplot/plotting/colormaps.py +24 -29
- rsplot/plotting/map_frame.py +203 -9
- rsplot/plotting/meteo.py +10 -3
- rsplot/plotting/overlay.py +36 -40
- rsplot/plotting/raster.py +15 -3
- rsplot/plotting/station.py +86 -33
- rsplot/plotting/station_focus.py +84 -0
- rsplot/plotting/station_trend.py +60 -47
- rsplot/plotting/styles.py +3 -5
- rsplot/readers/__init__.py +89 -7
- rsplot/readers/_tropomi.py +121 -3
- rsplot/readers/base.py +16 -1
- rsplot/readers/era5.py +110 -10
- rsplot/readers/era5_wind.py +3 -2
- rsplot/readers/gems.py +429 -0
- rsplot/readers/guokong.py +125 -39
- rsplot/readers/netcdf.py +32 -0
- rsplot/readers/tropomi_hcho.py +1 -1
- rsplot/readers/tropomi_no2.py +1 -1
- rsplot/readers/tropomi_nrti.py +116 -0
- rsplot/readers/tropomi_o3.py +1 -1
- rsplot/readers/tropomi_o3pr.py +1 -1
- rsplot/result_builders/__init__.py +0 -14
- rsplot/result_builders/common.py +84 -0
- rsplot/result_builders/envelope.py +236 -0
- rsplot/result_builders/fnr.py +47 -131
- rsplot/result_builders/forecast.py +7 -0
- rsplot/result_builders/provenance.py +59 -0
- rsplot/result_builders/reconstruct.py +7 -0
- rsplot/result_builders/satellite.py +240 -0
- rsplot/result_builders/series_layer.py +289 -0
- rsplot/result_builders/station.py +23 -0
- rsplot/result_builders/station_layer.py +326 -0
- rsplot/results.py +0 -12
- rsplot/schemas/result.schema.json +566 -0
- rsplot/temporal.py +146 -16
- rsplot-0.3.2.dev37.dist-info/METADATA +996 -0
- rsplot-0.3.2.dev37.dist-info/RECORD +76 -0
- {rsplot-0.3.1.dev3.dist-info → rsplot-0.3.2.dev37.dist-info}/WHEEL +1 -1
- rsplot/commands/recent.py +0 -164
- rsplot/recent.py +0 -404
- rsplot/result_builders/meteo.py +0 -171
- rsplot/result_builders/overlay.py +0 -75
- rsplot/result_builders/raster.py +0 -72
- rsplot/result_builders/station_trend.py +0 -229
- rsplot-0.3.1.dev3.dist-info/METADATA +0 -477
- rsplot-0.3.1.dev3.dist-info/RECORD +0 -64
- {rsplot-0.3.1.dev3.dist-info → rsplot-0.3.2.dev37.dist-info}/entry_points.txt +0 -0
- {rsplot-0.3.1.dev3.dist-info → rsplot-0.3.2.dev37.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Station labels and radius decorations shared by raster and overlay maps."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import TYPE_CHECKING
|
|
7
|
+
|
|
8
|
+
import cartopy.crs as ccrs
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
from rsplot.plotting.station import station_marker_size
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from cartopy.mpl.geoaxes import GeoAxes
|
|
15
|
+
|
|
16
|
+
from rsplot.geo.boundaries import RegionInfo
|
|
17
|
+
from rsplot.readers.guokong import StationData
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class StationFocus:
|
|
22
|
+
data: StationData
|
|
23
|
+
center_id: str
|
|
24
|
+
radius_km: float
|
|
25
|
+
locations_only: bool = False
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def add_station_focus(
|
|
29
|
+
ax: GeoAxes,
|
|
30
|
+
region: RegionInfo,
|
|
31
|
+
focus: StationFocus,
|
|
32
|
+
) -> None:
|
|
33
|
+
"""Add station IDs and missing sites inside the map frame."""
|
|
34
|
+
data = focus.data
|
|
35
|
+
marker_size = station_marker_size(region.level)
|
|
36
|
+
missing = ~np.isfinite(data.values)
|
|
37
|
+
visible = (
|
|
38
|
+
np.ones(data.n_stations, dtype=bool)
|
|
39
|
+
if focus.locations_only
|
|
40
|
+
else missing
|
|
41
|
+
)
|
|
42
|
+
if visible.any():
|
|
43
|
+
ax.scatter(
|
|
44
|
+
data.lon[visible],
|
|
45
|
+
data.lat[visible],
|
|
46
|
+
s=marker_size,
|
|
47
|
+
facecolors="#2374ab" if focus.locations_only else "none",
|
|
48
|
+
edgecolors="white" if focus.locations_only else "#666",
|
|
49
|
+
linewidths=1.2,
|
|
50
|
+
transform=ccrs.PlateCarree(),
|
|
51
|
+
zorder=7,
|
|
52
|
+
label="国控站点" if focus.locations_only else "站点缺测",
|
|
53
|
+
)
|
|
54
|
+
west, east, south, north = region.extent
|
|
55
|
+
for index, station_id in enumerate(data.id):
|
|
56
|
+
right_edge = data.lon[index] > west + (east - west) * 0.8
|
|
57
|
+
y_offset = 10 if index % 2 == 0 else -15
|
|
58
|
+
if data.lat[index] < south + (north - south) * 0.15:
|
|
59
|
+
y_offset = 10
|
|
60
|
+
elif data.lat[index] > south + (north - south) * 0.85:
|
|
61
|
+
y_offset = -15
|
|
62
|
+
ax.annotate(
|
|
63
|
+
str(station_id),
|
|
64
|
+
(data.lon[index], data.lat[index]),
|
|
65
|
+
xycoords=ccrs.PlateCarree()._as_mpl_transform(ax),
|
|
66
|
+
xytext=(-8 if right_edge else 8, y_offset),
|
|
67
|
+
ha="right" if right_edge else "left",
|
|
68
|
+
textcoords="offset points",
|
|
69
|
+
fontsize=8,
|
|
70
|
+
bbox={"facecolor": "white", "alpha": 0.8, "edgecolor": "none"},
|
|
71
|
+
arrowprops={"arrowstyle": "-", "color": "#555", "lw": 0.5},
|
|
72
|
+
zorder=9,
|
|
73
|
+
)
|
|
74
|
+
if not focus.locations_only and not np.isfinite(data.values).any():
|
|
75
|
+
ax.text(
|
|
76
|
+
0.02,
|
|
77
|
+
0.98,
|
|
78
|
+
"该小时站点观测全部缺测",
|
|
79
|
+
transform=ax.transAxes,
|
|
80
|
+
va="top",
|
|
81
|
+
fontsize=9,
|
|
82
|
+
zorder=10,
|
|
83
|
+
bbox={"facecolor": "white", "alpha": 0.8, "edgecolor": "none"},
|
|
84
|
+
)
|
rsplot/plotting/station_trend.py
CHANGED
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
from datetime import datetime, timedelta
|
|
6
|
-
from pathlib import Path
|
|
7
6
|
from typing import TYPE_CHECKING
|
|
7
|
+
from zoneinfo import ZoneInfo
|
|
8
8
|
|
|
9
9
|
import matplotlib.dates as mdates
|
|
10
10
|
import matplotlib.pyplot as plt
|
|
@@ -12,10 +12,12 @@ import numpy as np
|
|
|
12
12
|
from matplotlib.collections import LineCollection
|
|
13
13
|
from matplotlib.ticker import FuncFormatter
|
|
14
14
|
|
|
15
|
+
from rsplot.atomic import atomic_write
|
|
15
16
|
from rsplot.readers.guokong import RegionStationSeries, StationSeries
|
|
16
17
|
|
|
17
18
|
if TYPE_CHECKING:
|
|
18
19
|
from matplotlib.axes import Axes
|
|
20
|
+
from matplotlib.figure import Figure
|
|
19
21
|
|
|
20
22
|
|
|
21
23
|
_DISPLAY_UNITS = {
|
|
@@ -23,6 +25,10 @@ _DISPLAY_UNITS = {
|
|
|
23
25
|
"mg/m3": "mg/m³",
|
|
24
26
|
}
|
|
25
27
|
|
|
28
|
+
# Station hours are China time. Every date locator and formatter gets this
|
|
29
|
+
# zone explicitly so a matplotlibrc ``timezone`` cannot shift the axis.
|
|
30
|
+
CHINA_TIME = ZoneInfo("Asia/Shanghai")
|
|
31
|
+
|
|
26
32
|
_FOCUS_COLORS = (
|
|
27
33
|
"#e6550d",
|
|
28
34
|
"#31a354",
|
|
@@ -43,12 +49,9 @@ def plot_station_trend(
|
|
|
43
49
|
title: str | None = None,
|
|
44
50
|
) -> None:
|
|
45
51
|
"""Plot an hourly station series, preserving NaN gaps."""
|
|
46
|
-
times =
|
|
47
|
-
datetime.strptime(timestamp, "%Y%m%d%H")
|
|
48
|
-
for timestamp in series.timestamps
|
|
49
|
-
]
|
|
52
|
+
times = _china_hours(series.timestamps)
|
|
50
53
|
width = min(16.0, max(10.0, 8.0 + series.n_hours / 96))
|
|
51
|
-
fig, ax = plt.subplots(figsize=(width, 5.
|
|
54
|
+
fig, ax = plt.subplots(figsize=(width, 5.8), dpi=dpi)
|
|
52
55
|
try:
|
|
53
56
|
show_markers = series.n_hours <= 72
|
|
54
57
|
ax.plot(
|
|
@@ -102,17 +105,10 @@ def plot_station_trend(
|
|
|
102
105
|
fontsize=9,
|
|
103
106
|
color="#555555",
|
|
104
107
|
)
|
|
105
|
-
|
|
106
|
-
fig.subplots_adjust(
|
|
107
|
-
left=0.09,
|
|
108
|
-
right=0.98,
|
|
109
|
-
bottom=0.17,
|
|
110
|
-
top=0.84,
|
|
111
|
-
)
|
|
108
|
+
_place_trend_legend(fig, ax)
|
|
112
109
|
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
fig.savefig(path, dpi=dpi, bbox_inches="tight")
|
|
110
|
+
with atomic_write(output) as temp:
|
|
111
|
+
fig.savefig(temp, dpi=dpi, bbox_inches="tight")
|
|
116
112
|
finally:
|
|
117
113
|
plt.close(fig)
|
|
118
114
|
|
|
@@ -130,10 +126,7 @@ def plot_region_station_trend(
|
|
|
130
126
|
title: str | None = None,
|
|
131
127
|
) -> None:
|
|
132
128
|
"""Plot regional station context, mean, and explicit focus stations."""
|
|
133
|
-
times =
|
|
134
|
-
datetime.strptime(timestamp, "%Y%m%d%H")
|
|
135
|
-
for timestamp in series.timestamps
|
|
136
|
-
]
|
|
129
|
+
times = _china_hours(series.timestamps)
|
|
137
130
|
time_values = mdates.date2num(times)
|
|
138
131
|
width = min(16.0, max(10.0, 8.0 + series.n_hours / 96))
|
|
139
132
|
fig, ax = plt.subplots(figsize=(width, 5.8), dpi=dpi)
|
|
@@ -243,32 +236,36 @@ def plot_region_station_trend(
|
|
|
243
236
|
fontsize=9,
|
|
244
237
|
color="#555555",
|
|
245
238
|
)
|
|
246
|
-
|
|
247
|
-
fig.legend(
|
|
248
|
-
handles,
|
|
249
|
-
labels,
|
|
250
|
-
loc="upper center",
|
|
251
|
-
bbox_to_anchor=(0.5, 0.855),
|
|
252
|
-
ncol=min(6, len(labels)),
|
|
253
|
-
frameon=False,
|
|
254
|
-
fontsize=9,
|
|
255
|
-
columnspacing=1.4,
|
|
256
|
-
handlelength=2.4,
|
|
257
|
-
)
|
|
258
|
-
fig.subplots_adjust(
|
|
259
|
-
left=0.09,
|
|
260
|
-
right=0.98,
|
|
261
|
-
bottom=0.17,
|
|
262
|
-
top=0.78,
|
|
263
|
-
)
|
|
239
|
+
_place_trend_legend(fig, ax)
|
|
264
240
|
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
fig.savefig(path, dpi=dpi, bbox_inches="tight")
|
|
241
|
+
with atomic_write(output) as temp:
|
|
242
|
+
fig.savefig(temp, dpi=dpi, bbox_inches="tight")
|
|
268
243
|
finally:
|
|
269
244
|
plt.close(fig)
|
|
270
245
|
|
|
271
246
|
|
|
247
|
+
def _place_trend_legend(fig: Figure, ax: Axes) -> None:
|
|
248
|
+
"""Keep station and regional legends between the subtitle and axes."""
|
|
249
|
+
handles, labels = ax.get_legend_handles_labels()
|
|
250
|
+
fig.legend(
|
|
251
|
+
handles,
|
|
252
|
+
labels,
|
|
253
|
+
loc="upper center",
|
|
254
|
+
bbox_to_anchor=(0.5, 0.855),
|
|
255
|
+
ncol=min(6, len(labels)),
|
|
256
|
+
frameon=False,
|
|
257
|
+
fontsize=9,
|
|
258
|
+
columnspacing=1.4,
|
|
259
|
+
handlelength=2.4,
|
|
260
|
+
)
|
|
261
|
+
fig.subplots_adjust(
|
|
262
|
+
left=0.09,
|
|
263
|
+
right=0.98,
|
|
264
|
+
bottom=0.17,
|
|
265
|
+
top=0.78,
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
|
|
272
269
|
def _background_segments(
|
|
273
270
|
times: np.ndarray,
|
|
274
271
|
values: np.ndarray,
|
|
@@ -293,28 +290,44 @@ def _background_segments(
|
|
|
293
290
|
return segments
|
|
294
291
|
|
|
295
292
|
|
|
293
|
+
def _china_hours(timestamps: list[str]) -> list[datetime]:
|
|
294
|
+
"""Parse ``YYYYMMDDHH`` station labels as China-time instants."""
|
|
295
|
+
return [
|
|
296
|
+
datetime.strptime(timestamp, "%Y%m%d%H").replace(tzinfo=CHINA_TIME)
|
|
297
|
+
for timestamp in timestamps
|
|
298
|
+
]
|
|
299
|
+
|
|
300
|
+
|
|
296
301
|
def _configure_time_axis(ax: Axes, times: list[datetime]) -> None:
|
|
297
302
|
"""Choose readable ticks without Matplotlib's overlapping offset label."""
|
|
298
303
|
span_hours = (times[-1] - times[0]).total_seconds() / 3600
|
|
299
304
|
if span_hours <= 72:
|
|
300
|
-
ax.xaxis.set_major_locator(
|
|
305
|
+
ax.xaxis.set_major_locator(
|
|
306
|
+
mdates.HourLocator(byhour=(0, 6, 12, 18), tz=CHINA_TIME)
|
|
307
|
+
)
|
|
301
308
|
ax.xaxis.set_major_formatter(FuncFormatter(_format_hour_tick))
|
|
302
309
|
return
|
|
303
310
|
|
|
304
311
|
if span_hours <= 24 * 14:
|
|
305
312
|
days = max(1, round(span_hours / 24))
|
|
306
313
|
interval = max(1, round(days / 7))
|
|
307
|
-
ax.xaxis.set_major_locator(
|
|
308
|
-
|
|
314
|
+
ax.xaxis.set_major_locator(
|
|
315
|
+
mdates.DayLocator(interval=interval, tz=CHINA_TIME)
|
|
316
|
+
)
|
|
317
|
+
ax.xaxis.set_major_formatter(
|
|
318
|
+
mdates.DateFormatter("%m-%d", tz=CHINA_TIME)
|
|
319
|
+
)
|
|
309
320
|
return
|
|
310
321
|
|
|
311
|
-
locator = mdates.AutoDateLocator(minticks=5, maxticks=10)
|
|
322
|
+
locator = mdates.AutoDateLocator(minticks=5, maxticks=10, tz=CHINA_TIME)
|
|
312
323
|
ax.xaxis.set_major_locator(locator)
|
|
313
|
-
ax.xaxis.set_major_formatter(
|
|
324
|
+
ax.xaxis.set_major_formatter(
|
|
325
|
+
mdates.DateFormatter("%Y-%m-%d", tz=CHINA_TIME)
|
|
326
|
+
)
|
|
314
327
|
|
|
315
328
|
|
|
316
329
|
def _format_hour_tick(value: float, _position: int | None = None) -> str:
|
|
317
|
-
timestamp = mdates.num2date(value)
|
|
330
|
+
timestamp = mdates.num2date(value, tz=CHINA_TIME)
|
|
318
331
|
if timestamp.hour == 0:
|
|
319
332
|
return timestamp.strftime("%m-%d\n%H:%M")
|
|
320
333
|
return timestamp.strftime("%H:%M")
|
rsplot/plotting/styles.py
CHANGED
|
@@ -10,9 +10,7 @@ from matplotlib import font_manager
|
|
|
10
10
|
from rsplot.plotting.colormaps import register_rsplot_colormaps
|
|
11
11
|
|
|
12
12
|
|
|
13
|
-
def setup_fonts(
|
|
14
|
-
font_dir: str | None, hcho_cmap_file: str | None = None
|
|
15
|
-
) -> None:
|
|
13
|
+
def setup_fonts(font_dir: str | None) -> None:
|
|
16
14
|
"""Register Chinese fonts and set matplotlib defaults.
|
|
17
15
|
|
|
18
16
|
Looks for Microsoft YaHei in font_dir. Falls back gracefully
|
|
@@ -20,7 +18,7 @@ def setup_fonts(
|
|
|
20
18
|
"""
|
|
21
19
|
if not font_dir:
|
|
22
20
|
mpl.rcParams["axes.unicode_minus"] = False
|
|
23
|
-
register_rsplot_colormaps(
|
|
21
|
+
register_rsplot_colormaps()
|
|
24
22
|
return
|
|
25
23
|
|
|
26
24
|
font_root = Path(font_dir)
|
|
@@ -40,4 +38,4 @@ def setup_fonts(
|
|
|
40
38
|
mpl.rcParams["font.sans-serif"] = ["Microsoft YaHei"]
|
|
41
39
|
|
|
42
40
|
mpl.rcParams["axes.unicode_minus"] = False
|
|
43
|
-
register_rsplot_colormaps(
|
|
41
|
+
register_rsplot_colormaps()
|
rsplot/readers/__init__.py
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
import math
|
|
6
|
-
from dataclasses import dataclass, field
|
|
6
|
+
from dataclasses import dataclass, field, replace
|
|
7
7
|
|
|
8
8
|
import numpy as np
|
|
9
9
|
|
|
@@ -14,6 +14,8 @@ from rsplot.readers.tropomi_o3 import TropomiO3Reader
|
|
|
14
14
|
from rsplot.readers.tropomi_o3pr import TropomiO3PRReader
|
|
15
15
|
|
|
16
16
|
HCHO_CMAP = "rsplot_hcho"
|
|
17
|
+
NO2_CMAP = "rsplot_no2"
|
|
18
|
+
COLORMAP_22 = "rsplot_colormap_22"
|
|
17
19
|
|
|
18
20
|
|
|
19
21
|
@dataclass
|
|
@@ -40,6 +42,20 @@ class ProductInfo:
|
|
|
40
42
|
default_factory=dict
|
|
41
43
|
)
|
|
42
44
|
|
|
45
|
+
sensor: str = "tropomi"
|
|
46
|
+
data_key: str | None = None
|
|
47
|
+
quantity: str | None = None
|
|
48
|
+
processing: str | None = None
|
|
49
|
+
# Machine-readable unit: stored value * unit_scale = value in unit.
|
|
50
|
+
unit: str = ""
|
|
51
|
+
unit_scale: float = 1.0
|
|
52
|
+
|
|
53
|
+
def create_reader(self) -> BaseReader:
|
|
54
|
+
"""Construct the configured reader without changing legacy callers."""
|
|
55
|
+
if self.processing is not None:
|
|
56
|
+
return self.reader_cls(processing=self.processing)
|
|
57
|
+
return self.reader_cls()
|
|
58
|
+
|
|
43
59
|
def defaults_for_level(self, level: str) -> ProductPlotDefaults:
|
|
44
60
|
"""Return product-specific defaults for an administrative level."""
|
|
45
61
|
return self.level_defaults.get(level, ProductPlotDefaults())
|
|
@@ -49,26 +65,33 @@ PRODUCT_REGISTRY: dict[str, ProductInfo] = {
|
|
|
49
65
|
"no2": ProductInfo(
|
|
50
66
|
reader_cls=TropomiNO2Reader,
|
|
51
67
|
colorbar_label="NO2 VCD (x10^15 molec/cm2)",
|
|
52
|
-
cmap=
|
|
68
|
+
cmap=NO2_CMAP,
|
|
53
69
|
vmin=0.0,
|
|
54
70
|
vmax=20.0,
|
|
55
71
|
min_range=5.0,
|
|
72
|
+
quantity="tropospheric_no2_column",
|
|
73
|
+
unit="molec/cm2",
|
|
74
|
+
unit_scale=1e15,
|
|
56
75
|
),
|
|
57
76
|
"o3": ProductInfo(
|
|
58
77
|
reader_cls=TropomiO3Reader,
|
|
59
78
|
colorbar_label="O3 Total Column (DU)",
|
|
60
|
-
cmap=
|
|
79
|
+
cmap=COLORMAP_22,
|
|
61
80
|
vmin=None,
|
|
62
81
|
vmax=None,
|
|
63
82
|
min_range=30.0,
|
|
83
|
+
quantity="total_ozone_column",
|
|
84
|
+
unit="DU",
|
|
64
85
|
),
|
|
65
86
|
"o3pr": ProductInfo(
|
|
66
87
|
reader_cls=TropomiO3PRReader,
|
|
67
88
|
colorbar_label="O3 Tropospheric Column from Profile (DU)",
|
|
68
|
-
cmap=
|
|
89
|
+
cmap=COLORMAP_22,
|
|
69
90
|
vmin=None,
|
|
70
91
|
vmax=None,
|
|
71
92
|
min_range=5.0,
|
|
93
|
+
quantity="tropospheric_ozone_column",
|
|
94
|
+
unit="DU",
|
|
72
95
|
level_defaults={
|
|
73
96
|
# O3__PR is a coarse 30x30 km profile product. These defaults
|
|
74
97
|
# keep map pixels close to the native sampling while still using
|
|
@@ -87,19 +110,78 @@ PRODUCT_REGISTRY: dict[str, ProductInfo] = {
|
|
|
87
110
|
vmin=None, # unit not yet confirmed — let auto-range pick
|
|
88
111
|
vmax=None,
|
|
89
112
|
min_range=5.0,
|
|
113
|
+
quantity="tropospheric_hcho_column",
|
|
114
|
+
unit="molec/cm2",
|
|
115
|
+
unit_scale=1e15,
|
|
90
116
|
),
|
|
91
117
|
}
|
|
92
118
|
|
|
93
119
|
|
|
94
|
-
def get_product_info(
|
|
95
|
-
|
|
120
|
+
def get_product_info(
|
|
121
|
+
product: str,
|
|
122
|
+
*,
|
|
123
|
+
sensor: str = "tropomi",
|
|
124
|
+
processing: str | None = None,
|
|
125
|
+
) -> ProductInfo:
|
|
126
|
+
"""Resolve a product within a sensor, preserving legacy registry keys."""
|
|
127
|
+
if processing is not None:
|
|
128
|
+
processing = processing.lower()
|
|
129
|
+
if processing != "nrti":
|
|
130
|
+
raise ValueError("--processing 仅支持 nrti;省略时保持原有行为。")
|
|
131
|
+
if sensor.lower() != "tropomi":
|
|
132
|
+
raise ValueError("--processing nrti 仅用于 --sensor tropomi。")
|
|
96
133
|
key = product.lower()
|
|
134
|
+
sensor = sensor.lower()
|
|
135
|
+
if sensor not in ("tropomi", "gems"):
|
|
136
|
+
raise ValueError(f"未知卫星来源 '{sensor}',可用: tropomi / gems")
|
|
97
137
|
if key not in PRODUCT_REGISTRY:
|
|
98
138
|
available = ", ".join(PRODUCT_REGISTRY)
|
|
99
139
|
raise ValueError(
|
|
100
140
|
f"Unsupported product '{product}'. Available: {available}"
|
|
101
141
|
)
|
|
102
|
-
|
|
142
|
+
if sensor == "tropomi":
|
|
143
|
+
if processing == "nrti":
|
|
144
|
+
return replace(
|
|
145
|
+
PRODUCT_REGISTRY[key],
|
|
146
|
+
processing=processing,
|
|
147
|
+
data_key=f"tropomi_nrti_{key}",
|
|
148
|
+
)
|
|
149
|
+
return PRODUCT_REGISTRY[key]
|
|
150
|
+
from rsplot.config import LEVEL_DEFAULTS
|
|
151
|
+
from rsplot.readers.gems import (
|
|
152
|
+
GEMS_DEFAULT_RESOLUTION,
|
|
153
|
+
GemsHCHOReader,
|
|
154
|
+
GemsNO2Reader,
|
|
155
|
+
GemsO3PRReader,
|
|
156
|
+
GemsO3Reader,
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
readers = {
|
|
160
|
+
"no2": GemsNO2Reader,
|
|
161
|
+
"hcho": GemsHCHOReader,
|
|
162
|
+
"o3": GemsO3Reader,
|
|
163
|
+
"o3pr": GemsO3PRReader,
|
|
164
|
+
}
|
|
165
|
+
quantities = {
|
|
166
|
+
"no2": "tropospheric_no2_column",
|
|
167
|
+
"hcho": "hcho_column",
|
|
168
|
+
"o3": "total_ozone_column",
|
|
169
|
+
"o3pr": "tropospheric_ozone_column",
|
|
170
|
+
}
|
|
171
|
+
return replace(
|
|
172
|
+
PRODUCT_REGISTRY[key],
|
|
173
|
+
reader_cls=readers[key],
|
|
174
|
+
sensor="gems",
|
|
175
|
+
level_defaults={
|
|
176
|
+
level: replace(
|
|
177
|
+
PRODUCT_REGISTRY[key].defaults_for_level(level),
|
|
178
|
+
res=GEMS_DEFAULT_RESOLUTION,
|
|
179
|
+
)
|
|
180
|
+
for level in LEVEL_DEFAULTS
|
|
181
|
+
},
|
|
182
|
+
data_key="gems_o3" if key == "o3pr" else f"gems_{key}",
|
|
183
|
+
quantity=quantities[key],
|
|
184
|
+
)
|
|
103
185
|
|
|
104
186
|
|
|
105
187
|
def auto_vrange(
|
rsplot/readers/_tropomi.py
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
from collections.abc import Iterator
|
|
5
6
|
from dataclasses import dataclass
|
|
6
7
|
from pathlib import Path
|
|
7
8
|
from typing import ClassVar
|
|
@@ -9,6 +10,7 @@ from typing import ClassVar
|
|
|
9
10
|
import numpy as np
|
|
10
11
|
from rich.progress import track
|
|
11
12
|
|
|
13
|
+
from rsplot.errors import RsplotError
|
|
12
14
|
from rsplot.readers.base import (
|
|
13
15
|
BaseReader,
|
|
14
16
|
SwathData,
|
|
@@ -36,6 +38,38 @@ class TropomiReader(BaseReader):
|
|
|
36
38
|
spec: ClassVar[TropomiReaderSpec]
|
|
37
39
|
cloud_fraction_max: float = CLOUD_FRACTION_MAX
|
|
38
40
|
|
|
41
|
+
def __init__(self, *, processing: str | None = None) -> None:
|
|
42
|
+
if processing not in (None, "nrti"):
|
|
43
|
+
raise ValueError("TROPOMI processing 仅支持 nrti 或 None")
|
|
44
|
+
self.processing = processing
|
|
45
|
+
|
|
46
|
+
def iter_scans(
|
|
47
|
+
self,
|
|
48
|
+
data_dir: str,
|
|
49
|
+
date: str,
|
|
50
|
+
extent: tuple[float, float, float, float],
|
|
51
|
+
qa_threshold: float = 0.5,
|
|
52
|
+
) -> Iterator[SwathData]:
|
|
53
|
+
"""Keep failed NRTI days diagnosable in window results."""
|
|
54
|
+
if self.processing is None:
|
|
55
|
+
yield self.read(data_dir, date, extent, qa_threshold)
|
|
56
|
+
return
|
|
57
|
+
|
|
58
|
+
from rsplot.readers.tropomi_nrti import NrtiReadError
|
|
59
|
+
|
|
60
|
+
try:
|
|
61
|
+
yield self.read(data_dir, date, extent, qa_threshold)
|
|
62
|
+
except NrtiReadError as error:
|
|
63
|
+
yield SwathData(
|
|
64
|
+
lon=np.array([]),
|
|
65
|
+
lat=np.array([]),
|
|
66
|
+
values=np.array([]),
|
|
67
|
+
n_pixels=0,
|
|
68
|
+
n_files=error.metadata["n_files"],
|
|
69
|
+
n_broken=error.metadata["n_broken"],
|
|
70
|
+
metadata=error.metadata,
|
|
71
|
+
)
|
|
72
|
+
|
|
39
73
|
def read(
|
|
40
74
|
self,
|
|
41
75
|
data_dir: str,
|
|
@@ -49,6 +83,11 @@ class TropomiReader(BaseReader):
|
|
|
49
83
|
relative_patterns = [
|
|
50
84
|
pattern.format(date=date) for pattern in spec.filename_patterns
|
|
51
85
|
]
|
|
86
|
+
if self.processing == "nrti":
|
|
87
|
+
relative_patterns = [
|
|
88
|
+
pattern.replace("S5P_*_", "S5P_NRTI_")
|
|
89
|
+
for pattern in relative_patterns
|
|
90
|
+
]
|
|
52
91
|
patterns = [str(root / pattern) for pattern in relative_patterns]
|
|
53
92
|
files = sorted(
|
|
54
93
|
{
|
|
@@ -58,11 +97,21 @@ class TropomiReader(BaseReader):
|
|
|
58
97
|
}
|
|
59
98
|
)
|
|
60
99
|
if not files:
|
|
61
|
-
raise
|
|
100
|
+
raise RsplotError(
|
|
101
|
+
"data_not_found",
|
|
62
102
|
spec.not_found_message.format(
|
|
63
103
|
date=date,
|
|
64
104
|
patterns="\n ".join(patterns),
|
|
65
|
-
)
|
|
105
|
+
),
|
|
106
|
+
details={"path": patterns[0]},
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
if self.processing == "nrti":
|
|
110
|
+
from rsplot.readers.tropomi_nrti import (
|
|
111
|
+
NrtiReadError,
|
|
112
|
+
granule_identity,
|
|
113
|
+
observation_range,
|
|
114
|
+
read_nrti_observations,
|
|
66
115
|
)
|
|
67
116
|
|
|
68
117
|
lon_min, lon_max, lat_min, lat_max = extent
|
|
@@ -71,6 +120,11 @@ class TropomiReader(BaseReader):
|
|
|
71
120
|
all_values: list[np.ndarray] = []
|
|
72
121
|
broken = 0
|
|
73
122
|
broken_examples: list[str] = []
|
|
123
|
+
failed_files: dict[str, str] = {}
|
|
124
|
+
all_keys: list[np.ndarray] = []
|
|
125
|
+
priorities: list[tuple[str, str, int]] = []
|
|
126
|
+
processor_versions: set[str] = set()
|
|
127
|
+
product_versions: set[str] = set()
|
|
74
128
|
|
|
75
129
|
for path in track(files, description=spec.progress_description):
|
|
76
130
|
try:
|
|
@@ -80,8 +134,16 @@ class TropomiReader(BaseReader):
|
|
|
80
134
|
spec.value_name,
|
|
81
135
|
)
|
|
82
136
|
)
|
|
137
|
+
if self.processing == "nrti":
|
|
138
|
+
observations = read_nrti_observations(path, values.shape)
|
|
139
|
+
_, production = granule_identity(path)
|
|
140
|
+
if observations.processor_version:
|
|
141
|
+
processor_versions.add(observations.processor_version)
|
|
142
|
+
if observations.product_version:
|
|
143
|
+
product_versions.add(observations.product_version)
|
|
83
144
|
except (OSError, ValueError, KeyError) as error:
|
|
84
145
|
broken += 1
|
|
146
|
+
failed_files[path] = str(error).splitlines()[0]
|
|
85
147
|
if len(broken_examples) < 3:
|
|
86
148
|
broken_examples.append(
|
|
87
149
|
f"{Path(path).name}: {str(error).splitlines()[0]}"
|
|
@@ -100,17 +162,47 @@ class TropomiReader(BaseReader):
|
|
|
100
162
|
& (values < 1e30)
|
|
101
163
|
)
|
|
102
164
|
if mask.sum() > 0:
|
|
165
|
+
if self.processing == "nrti":
|
|
166
|
+
priorities.append((production, path, len(all_keys)))
|
|
167
|
+
all_keys.append(observations.keys[mask])
|
|
103
168
|
all_lon.append(lon[mask])
|
|
104
169
|
all_lat.append(lat[mask])
|
|
105
170
|
all_values.append(values[mask] * spec.unit_conversion)
|
|
106
171
|
|
|
172
|
+
# Every stream records its inputs; NRTI adds deduplication details.
|
|
173
|
+
metadata: dict = {
|
|
174
|
+
"source_files": files,
|
|
175
|
+
"failed_files": failed_files,
|
|
176
|
+
}
|
|
177
|
+
if self.processing == "nrti":
|
|
178
|
+
metadata = {
|
|
179
|
+
"sensor": "tropomi",
|
|
180
|
+
"processing": "nrti",
|
|
181
|
+
"date_basis": "filename_start_date_utc",
|
|
182
|
+
"aggregation": "deduplicated_pixel_mean",
|
|
183
|
+
"source_files": files,
|
|
184
|
+
"failed_files": failed_files,
|
|
185
|
+
"processor_versions": sorted(processor_versions),
|
|
186
|
+
"product_versions": sorted(product_versions),
|
|
187
|
+
"deduplication": {
|
|
188
|
+
"key": ["orbit", "time_utc_ms", "ground_pixel"],
|
|
189
|
+
"selection": "latest_valid_production_then_filename",
|
|
190
|
+
},
|
|
191
|
+
"n_files": len(files),
|
|
192
|
+
"n_broken": broken,
|
|
193
|
+
"n_pixels": 0,
|
|
194
|
+
"n_pixels_before_dedup": 0,
|
|
195
|
+
"n_duplicates_removed": 0,
|
|
196
|
+
"observation_time_range_utc": None,
|
|
197
|
+
}
|
|
198
|
+
|
|
107
199
|
if not all_lon:
|
|
108
200
|
broken_message = (
|
|
109
201
|
"\n损坏/不可读示例:\n " + "\n ".join(broken_examples)
|
|
110
202
|
if broken_examples
|
|
111
203
|
else ""
|
|
112
204
|
)
|
|
113
|
-
|
|
205
|
+
message = (
|
|
114
206
|
spec.no_valid_data_message.format(
|
|
115
207
|
date=date,
|
|
116
208
|
extent=extent,
|
|
@@ -119,6 +211,31 @@ class TropomiReader(BaseReader):
|
|
|
119
211
|
)
|
|
120
212
|
+ broken_message
|
|
121
213
|
)
|
|
214
|
+
if self.processing == "nrti":
|
|
215
|
+
raise NrtiReadError(message, metadata)
|
|
216
|
+
raise ValueError(message)
|
|
217
|
+
|
|
218
|
+
if self.processing == "nrti":
|
|
219
|
+
# Stable sorts give newest production first, filename ascending
|
|
220
|
+
# for ties. np.unique's first index then selects the valid winner.
|
|
221
|
+
priorities.sort(key=lambda item: item[1])
|
|
222
|
+
priorities.sort(key=lambda item: item[0], reverse=True)
|
|
223
|
+
order = [item[2] for item in priorities]
|
|
224
|
+
keys = np.concatenate([all_keys[index] for index in order])
|
|
225
|
+
_, selected = np.unique(keys, return_index=True)
|
|
226
|
+
selected.sort()
|
|
227
|
+
before = len(keys)
|
|
228
|
+
all_lon = [np.concatenate([all_lon[i] for i in order])[selected]]
|
|
229
|
+
all_lat = [np.concatenate([all_lat[i] for i in order])[selected]]
|
|
230
|
+
all_values = [
|
|
231
|
+
np.concatenate([all_values[i] for i in order])[selected]
|
|
232
|
+
]
|
|
233
|
+
metadata.update(
|
|
234
|
+
n_pixels=len(selected),
|
|
235
|
+
n_pixels_before_dedup=before,
|
|
236
|
+
n_duplicates_removed=before - len(selected),
|
|
237
|
+
observation_time_range_utc=observation_range(keys[selected]),
|
|
238
|
+
)
|
|
122
239
|
|
|
123
240
|
return SwathData(
|
|
124
241
|
lon=np.concatenate(all_lon),
|
|
@@ -127,4 +244,5 @@ class TropomiReader(BaseReader):
|
|
|
127
244
|
n_pixels=sum(len(values) for values in all_lon),
|
|
128
245
|
n_files=len(files),
|
|
129
246
|
n_broken=broken,
|
|
247
|
+
metadata=metadata,
|
|
130
248
|
)
|
rsplot/readers/base.py
CHANGED
|
@@ -3,7 +3,9 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
from abc import ABC, abstractmethod
|
|
6
|
-
from
|
|
6
|
+
from collections.abc import Iterator
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from typing import Any
|
|
7
9
|
|
|
8
10
|
import numpy as np
|
|
9
11
|
import xarray as xr
|
|
@@ -19,11 +21,24 @@ class SwathData:
|
|
|
19
21
|
n_pixels: int
|
|
20
22
|
n_files: int
|
|
21
23
|
n_broken: int
|
|
24
|
+
metadata: dict[str, Any] = field(default_factory=dict)
|
|
25
|
+
corner_lon: np.ndarray | None = None # (n_pixels, 4)
|
|
26
|
+
corner_lat: np.ndarray | None = None # (n_pixels, 4)
|
|
22
27
|
|
|
23
28
|
|
|
24
29
|
class BaseReader(ABC):
|
|
25
30
|
"""Interface for reading a single-day satellite product."""
|
|
26
31
|
|
|
32
|
+
def iter_scans(
|
|
33
|
+
self,
|
|
34
|
+
data_dir: str,
|
|
35
|
+
date: str,
|
|
36
|
+
extent: tuple[float, float, float, float],
|
|
37
|
+
qa_threshold: float = 0.5,
|
|
38
|
+
) -> Iterator[SwathData]:
|
|
39
|
+
"""Yield temporal batches; legacy readers supply one daily batch."""
|
|
40
|
+
yield self.read(data_dir, date, extent, qa_threshold)
|
|
41
|
+
|
|
27
42
|
@abstractmethod
|
|
28
43
|
def read(
|
|
29
44
|
self,
|