rsplot 0.3.2.dev4__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 +272 -497
- rsplot/commands/common.py +52 -3
- rsplot/commands/fnr.py +389 -104
- rsplot/commands/forecast.py +0 -2
- rsplot/commands/meteo.py +499 -186
- rsplot/commands/overlay.py +284 -326
- rsplot/commands/radius.py +526 -0
- rsplot/commands/raster.py +418 -293
- rsplot/commands/reconstruct.py +0 -1
- rsplot/commands/sidecar.py +106 -0
- rsplot/commands/station.py +154 -42
- rsplot/commands/station_trend.py +259 -174
- rsplot/config.py +43 -16
- rsplot/data_files.py +253 -0
- rsplot/errors.py +43 -0
- rsplot/fnr.py +38 -46
- rsplot/geo/boundaries.py +212 -9
- rsplot/geo/footprints.py +3 -0
- rsplot/geo/processing.py +2 -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 +84 -6
- rsplot/plotting/meteo.py +10 -3
- rsplot/plotting/overlay.py +31 -40
- rsplot/plotting/raster.py +10 -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 +52 -4
- rsplot/readers/_tropomi.py +121 -3
- rsplot/readers/era5.py +110 -10
- rsplot/readers/era5_wind.py +3 -2
- rsplot/readers/gems.py +11 -8
- 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 +4 -1
- rsplot/result_builders/envelope.py +236 -0
- rsplot/result_builders/fnr.py +47 -131
- rsplot/result_builders/provenance.py +59 -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 +7 -0
- {rsplot-0.3.2.dev4.dist-info → rsplot-0.3.2.dev37.dist-info}/METADATA +426 -121
- rsplot-0.3.2.dev37.dist-info/RECORD +76 -0
- {rsplot-0.3.2.dev4.dist-info → rsplot-0.3.2.dev37.dist-info}/WHEEL +1 -1
- rsplot/commands/recent.py +0 -186
- rsplot/recent.py +0 -447
- rsplot/result_builders/meteo.py +0 -171
- rsplot/result_builders/overlay.py +0 -105
- rsplot/result_builders/raster.py +0 -104
- rsplot/result_builders/station_trend.py +0 -229
- rsplot-0.3.2.dev4.dist-info/RECORD +0 -66
- {rsplot-0.3.2.dev4.dist-info → rsplot-0.3.2.dev37.dist-info}/entry_points.txt +0 -0
- {rsplot-0.3.2.dev4.dist-info → rsplot-0.3.2.dev37.dist-info}/licenses/LICENSE +0 -0
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/era5.py
CHANGED
|
@@ -8,8 +8,9 @@ from pathlib import Path
|
|
|
8
8
|
from typing import TYPE_CHECKING
|
|
9
9
|
|
|
10
10
|
import numpy as np
|
|
11
|
-
import xarray as xr
|
|
12
11
|
|
|
12
|
+
from rsplot.errors import RsplotError
|
|
13
|
+
from rsplot.readers.netcdf import open_netcdf
|
|
13
14
|
from rsplot.temporal import DEFAULT_INPUT_TIMEZONE, adapt_hourly_time
|
|
14
15
|
|
|
15
16
|
if TYPE_CHECKING:
|
|
@@ -18,6 +19,8 @@ if TYPE_CHECKING:
|
|
|
18
19
|
|
|
19
20
|
PRESSURE_LEVELS = ("1000", "925", "850", "700", "500")
|
|
20
21
|
TEMPERATURE_LEVELS = ("2m", *PRESSURE_LEVELS)
|
|
22
|
+
# CDS files written since the 2024 backend change use `valid_time`.
|
|
23
|
+
TIME_NAMES = ("valid_time", "time")
|
|
21
24
|
|
|
22
25
|
|
|
23
26
|
@dataclass(frozen=True)
|
|
@@ -126,23 +129,48 @@ def read_era5_grid(
|
|
|
126
129
|
) -> tuple[np.ndarray, np.ndarray, np.ndarray, str]:
|
|
127
130
|
"""Read one exact UTC hour from a standard ERA5 lat/lon grid."""
|
|
128
131
|
if not path.exists():
|
|
129
|
-
|
|
132
|
+
before, after = nearest_era5_hours(path, data_datetime)
|
|
133
|
+
raise RsplotError(
|
|
134
|
+
"data_not_found",
|
|
135
|
+
f"未找到 {field_label}文件: {path};{_nearest_label(before, after)}",
|
|
136
|
+
details={
|
|
137
|
+
"path": str(path),
|
|
138
|
+
"nearest_before": before,
|
|
139
|
+
"nearest_after": after,
|
|
140
|
+
"search_hours": NEAREST_HOURS,
|
|
141
|
+
},
|
|
142
|
+
)
|
|
130
143
|
|
|
131
|
-
with
|
|
132
|
-
|
|
144
|
+
with open_netcdf(path) as ds:
|
|
145
|
+
time_name = next(
|
|
146
|
+
(name for name in TIME_NAMES if name in ds.variables), None
|
|
147
|
+
)
|
|
148
|
+
required = {"latitude", "longitude", variable}
|
|
133
149
|
missing = sorted(required - set(ds.variables))
|
|
150
|
+
if time_name is None:
|
|
151
|
+
missing.insert(0, " / ".join(TIME_NAMES))
|
|
134
152
|
if missing:
|
|
135
153
|
raise ValueError(
|
|
136
154
|
f"{field_label}文件 {path} 缺少变量: {', '.join(missing)}"
|
|
137
155
|
)
|
|
138
156
|
|
|
139
157
|
target = np.datetime64(data_datetime.replace(tzinfo=None), "ns")
|
|
140
|
-
times = np.asarray(ds[
|
|
158
|
+
times = np.asarray(ds[time_name].values).astype("datetime64[ns]")
|
|
141
159
|
time_indices = np.flatnonzero(times == target)
|
|
142
160
|
if len(time_indices) == 0:
|
|
143
161
|
target_label = data_datetime.strftime("%Y-%m-%d %H:%M UTC")
|
|
144
|
-
|
|
145
|
-
|
|
162
|
+
before, after = nearest_era5_hours(path, data_datetime)
|
|
163
|
+
raise RsplotError(
|
|
164
|
+
"data_not_found",
|
|
165
|
+
f"{field_label}文件 {path} 中没有时次 {target_label};"
|
|
166
|
+
+ _nearest_label(before, after),
|
|
167
|
+
details={
|
|
168
|
+
"path": str(path),
|
|
169
|
+
"time_utc": target_label,
|
|
170
|
+
"nearest_before": before,
|
|
171
|
+
"nearest_after": after,
|
|
172
|
+
"search_hours": NEAREST_HOURS,
|
|
173
|
+
},
|
|
146
174
|
)
|
|
147
175
|
|
|
148
176
|
lon_raw = np.asarray(ds["longitude"].values, dtype=float)
|
|
@@ -166,9 +194,11 @@ def read_era5_grid(
|
|
|
166
194
|
values = np.asarray(
|
|
167
195
|
ds[variable]
|
|
168
196
|
.isel(
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
197
|
+
{
|
|
198
|
+
time_name: int(time_indices[0]),
|
|
199
|
+
"latitude": lat_indices,
|
|
200
|
+
"longitude": lon_indices,
|
|
201
|
+
}
|
|
172
202
|
)
|
|
173
203
|
.values,
|
|
174
204
|
dtype=float,
|
|
@@ -187,6 +217,76 @@ def read_era5_grid(
|
|
|
187
217
|
return lon, lat, values, unit
|
|
188
218
|
|
|
189
219
|
|
|
220
|
+
# How far either side of a missing hour to look for available ERA5 hours.
|
|
221
|
+
# ERA5 normally arrives about five days late, so a 48-hour window would
|
|
222
|
+
# find nothing for a recent request.
|
|
223
|
+
NEAREST_HOURS = 240
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def nearest_era5_hours(
|
|
227
|
+
path: Path, data_datetime: datetime
|
|
228
|
+
) -> tuple[str | None, str | None]:
|
|
229
|
+
"""Nearest available hours, as CLI ``YYYYMMDDHH``, around a missing one.
|
|
230
|
+
|
|
231
|
+
ERA5 keeps one file per UTC day, so this probes the same layout day by
|
|
232
|
+
day outward and reads the time axis of the nearest existing file in
|
|
233
|
+
each direction only. Reports only; never selects.
|
|
234
|
+
"""
|
|
235
|
+
from datetime import timedelta
|
|
236
|
+
|
|
237
|
+
day = data_datetime.strftime("%Y%m%d")
|
|
238
|
+
parts = path.parts
|
|
239
|
+
if day not in parts:
|
|
240
|
+
return None, None
|
|
241
|
+
index = len(parts) - 1 - parts[::-1].index(day)
|
|
242
|
+
target = np.datetime64(data_datetime.replace(tzinfo=None), "ns")
|
|
243
|
+
window = np.timedelta64(NEAREST_HOURS, "h")
|
|
244
|
+
|
|
245
|
+
def day_times(offset: int) -> np.ndarray | None:
|
|
246
|
+
stamp = (data_datetime + timedelta(days=offset)).strftime("%Y%m%d")
|
|
247
|
+
candidate = Path(*parts[:index], stamp, *parts[index + 1 :])
|
|
248
|
+
if not candidate.exists():
|
|
249
|
+
return None
|
|
250
|
+
try:
|
|
251
|
+
with open_netcdf(candidate) as ds:
|
|
252
|
+
name = next((n for n in TIME_NAMES if n in ds.variables), None)
|
|
253
|
+
if name is None:
|
|
254
|
+
return None
|
|
255
|
+
times = np.asarray(ds[name].values).astype("datetime64[ns]")
|
|
256
|
+
except RsplotError:
|
|
257
|
+
return None
|
|
258
|
+
return times[(times != target) & (abs(times - target) <= window)]
|
|
259
|
+
|
|
260
|
+
def nearest(step: int) -> str | None:
|
|
261
|
+
for distance in range(NEAREST_HOURS // 24 + 1):
|
|
262
|
+
times = day_times(step * distance)
|
|
263
|
+
if times is None:
|
|
264
|
+
continue
|
|
265
|
+
side = times[times < target] if step < 0 else times[times > target]
|
|
266
|
+
if len(side):
|
|
267
|
+
return _cli_hour(side.max() if step < 0 else side.min())
|
|
268
|
+
return None
|
|
269
|
+
|
|
270
|
+
return nearest(-1), nearest(1)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _cli_hour(utc: np.datetime64) -> str:
|
|
274
|
+
"""Format a UTC archive time as the China-time CLI ``YYYYMMDDHH``."""
|
|
275
|
+
from zoneinfo import ZoneInfo
|
|
276
|
+
|
|
277
|
+
moment = utc.astype("datetime64[s]").item().replace(tzinfo=ZoneInfo("UTC"))
|
|
278
|
+
return moment.astimezone(ZoneInfo(DEFAULT_INPUT_TIMEZONE)).strftime(
|
|
279
|
+
"%Y%m%d%H"
|
|
280
|
+
)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _nearest_label(before: str | None, after: str | None) -> str:
|
|
284
|
+
return (
|
|
285
|
+
f"{NEAREST_HOURS // 24} 天内最近可用 DATETIME: 之前 {before or '无'},"
|
|
286
|
+
f"之后 {after or '无'}。"
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
|
|
190
290
|
def _temperature_path(
|
|
191
291
|
root: Path,
|
|
192
292
|
dt_utc: datetime,
|
rsplot/readers/era5_wind.py
CHANGED
|
@@ -54,7 +54,7 @@ def read_era5_wind(
|
|
|
54
54
|
station_timezone: str = "Asia/Shanghai",
|
|
55
55
|
) -> WindFieldData:
|
|
56
56
|
"""Read one ERA5 wind field matching a station observation hour."""
|
|
57
|
-
normalized_level =
|
|
57
|
+
normalized_level = normalize_wind_level(level)
|
|
58
58
|
dt_utc = _to_utc(station_datetime, station_timezone)
|
|
59
59
|
u_path, v_path, u_name, v_name = _component_paths(
|
|
60
60
|
Path(data_dir), dt_utc, normalized_level
|
|
@@ -118,7 +118,8 @@ def _display_unit(unit: str) -> str:
|
|
|
118
118
|
return unit or "m/s"
|
|
119
119
|
|
|
120
120
|
|
|
121
|
-
def
|
|
121
|
+
def normalize_wind_level(level: str) -> str:
|
|
122
|
+
"""Normalize and validate a supported ERA5 wind level."""
|
|
122
123
|
value = level.strip().lower().removesuffix("hpa")
|
|
123
124
|
if value in ("10", "10m"):
|
|
124
125
|
return "10m"
|
rsplot/readers/gems.py
CHANGED
|
@@ -17,10 +17,13 @@ from zoneinfo import ZoneInfo
|
|
|
17
17
|
import numpy as np
|
|
18
18
|
from netCDF4 import Dataset
|
|
19
19
|
|
|
20
|
+
from rsplot.errors import RsplotError
|
|
20
21
|
from rsplot.readers.base import BaseReader, SwathData
|
|
21
22
|
|
|
22
|
-
#
|
|
23
|
-
|
|
23
|
+
# Default target-grid spacing, overridable with --res; not native resolution.
|
|
24
|
+
GEMS_DEFAULT_RESOLUTION = 0.05
|
|
25
|
+
# Compatibility alias for existing imports; no longer a forced spacing.
|
|
26
|
+
GEMS_ANALYSIS_RESOLUTION = GEMS_DEFAULT_RESOLUTION
|
|
24
27
|
|
|
25
28
|
CHINA_TIME = ZoneInfo("Asia/Shanghai")
|
|
26
29
|
EPOCH = datetime(2000, 1, 1, 12, tzinfo=timezone.utc)
|
|
@@ -30,7 +33,7 @@ FILE_RE = re.compile(r"^GK2_GEMS_L2_(\d{8})_(\d{4})_(NO2|HCHO|O3P)_.+\.nc$")
|
|
|
30
33
|
def parse_gems_time(value: str) -> datetime:
|
|
31
34
|
"""Parse an exact nominal scan time in Asia/Shanghai."""
|
|
32
35
|
if not value.isdigit() or len(value) != 12:
|
|
33
|
-
raise ValueError("GEMS
|
|
36
|
+
raise ValueError("GEMS 扫描时间应为 YYYYMMDDHHMM。")
|
|
34
37
|
try:
|
|
35
38
|
return datetime.strptime(value, "%Y%m%d%H%M").replace(
|
|
36
39
|
tzinfo=CHINA_TIME
|
|
@@ -57,7 +60,6 @@ def match_station_hour(
|
|
|
57
60
|
"satellite_date": scan,
|
|
58
61
|
"satellite_aggregation": "daily_mean",
|
|
59
62
|
"station_datetime": hour,
|
|
60
|
-
"timezone": "Asia/Shanghai",
|
|
61
63
|
"difference_minutes": None,
|
|
62
64
|
"manual_override": True,
|
|
63
65
|
"reference": "daily_mean_with_explicit_station_hour",
|
|
@@ -72,7 +74,6 @@ def match_station_hour(
|
|
|
72
74
|
return hour, {
|
|
73
75
|
"scan_datetime": scan,
|
|
74
76
|
"station_datetime": hour,
|
|
75
|
-
"timezone": "Asia/Shanghai",
|
|
76
77
|
"difference_minutes": (station - time).total_seconds() / 60,
|
|
77
78
|
"manual_override": override is not None,
|
|
78
79
|
"reference": "nominal_scan_time",
|
|
@@ -140,9 +141,11 @@ class GemsReader(BaseReader):
|
|
|
140
141
|
for _, time in files
|
|
141
142
|
}
|
|
142
143
|
)
|
|
143
|
-
raise
|
|
144
|
-
|
|
145
|
-
|
|
144
|
+
raise RsplotError(
|
|
145
|
+
"data_not_found",
|
|
146
|
+
f"未找到 GEMS {request};当日可用扫描: "
|
|
147
|
+
+ (", ".join(available) or "无"),
|
|
148
|
+
details={"available": available},
|
|
146
149
|
)
|
|
147
150
|
times = [time for _, time in selected]
|
|
148
151
|
if len(set(times)) != len(times):
|
rsplot/readers/guokong.py
CHANGED
|
@@ -13,7 +13,9 @@ from pathlib import Path
|
|
|
13
13
|
from typing import TYPE_CHECKING
|
|
14
14
|
|
|
15
15
|
import numpy as np
|
|
16
|
-
|
|
16
|
+
|
|
17
|
+
from rsplot.errors import RsplotError
|
|
18
|
+
from rsplot.readers.netcdf import open_netcdf
|
|
17
19
|
|
|
18
20
|
if TYPE_CHECKING:
|
|
19
21
|
from shapely.geometry.base import BaseGeometry
|
|
@@ -102,25 +104,8 @@ class RegionStationSeries:
|
|
|
102
104
|
return int(matches[0]) if len(matches) else None
|
|
103
105
|
|
|
104
106
|
|
|
105
|
-
def
|
|
106
|
-
|
|
107
|
-
datetime_str: str,
|
|
108
|
-
var_name: str,
|
|
109
|
-
extent: tuple[float, float, float, float] | None = None,
|
|
110
|
-
) -> tuple[StationData, str]:
|
|
111
|
-
"""Read station data for a given hour and variable.
|
|
112
|
-
|
|
113
|
-
Parameters
|
|
114
|
-
----------
|
|
115
|
-
data_dir : directory containing {YYYYMMDDHH}.nc files.
|
|
116
|
-
datetime_str : YYYYMMDDHH (exact hour) or YYYYMMDD (latest hour).
|
|
117
|
-
var_name : variable name in the NC file (e.g. "AQI", "PM2.5", "O3").
|
|
118
|
-
extent : optional (lon_min, lon_max, lat_min, lat_max) for spatial filter.
|
|
119
|
-
|
|
120
|
-
Returns
|
|
121
|
-
-------
|
|
122
|
-
tuple of (StationData, resolved_datetime_str).
|
|
123
|
-
"""
|
|
107
|
+
def resolve_station_file(data_dir: str, datetime_str: str) -> Path:
|
|
108
|
+
"""Resolve an exact local hour or the latest file on a local date."""
|
|
124
109
|
if not datetime_str.isdigit() or len(datetime_str) not in (8, 10):
|
|
125
110
|
raise ValueError(
|
|
126
111
|
f"datetime 参数 '{datetime_str}' 格式不正确,"
|
|
@@ -143,21 +128,113 @@ def read_stations(
|
|
|
143
128
|
None,
|
|
144
129
|
)
|
|
145
130
|
if path is None:
|
|
146
|
-
raise
|
|
131
|
+
raise RsplotError(
|
|
132
|
+
"data_not_found",
|
|
147
133
|
f"未找到 {datetime_str} 当天的站点数据文件: {pattern}\n"
|
|
148
|
-
|
|
134
|
+
"请检查日期和配置 [paths.data_dirs].guokong 路径。",
|
|
135
|
+
details={"path": pattern},
|
|
149
136
|
)
|
|
150
137
|
datetime_str = path.stem
|
|
151
138
|
else:
|
|
152
139
|
path = root / f"{datetime_str}.nc"
|
|
140
|
+
if not path.exists():
|
|
141
|
+
before, after = nearest_station_hours(root, datetime_str)
|
|
142
|
+
raise RsplotError(
|
|
143
|
+
"data_not_found",
|
|
144
|
+
f"未找到站点数据文件: {path};"
|
|
145
|
+
f"{NEAREST_HOURS} 小时内最近可用: 之前 {before or '无'},"
|
|
146
|
+
f"之后 {after or '无'}。",
|
|
147
|
+
details={
|
|
148
|
+
"path": str(path),
|
|
149
|
+
"nearest_before": before,
|
|
150
|
+
"nearest_after": after,
|
|
151
|
+
"search_hours": NEAREST_HOURS,
|
|
152
|
+
},
|
|
153
|
+
)
|
|
153
154
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
155
|
+
return path
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
# How far either side of a missing hour to look for available files.
|
|
159
|
+
NEAREST_HOURS = 48
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def nearest_station_hours(
|
|
163
|
+
root: Path, datetime_str: str
|
|
164
|
+
) -> tuple[str | None, str | None]:
|
|
165
|
+
"""Nearest existing hourly files before and after a missing hour.
|
|
166
|
+
|
|
167
|
+
Probes exact ``YYYYMMDDHH.nc`` paths hour by hour rather than listing
|
|
168
|
+
the archive, which holds ~100k files. Reports only; never selects.
|
|
169
|
+
"""
|
|
170
|
+
from datetime import datetime, timedelta
|
|
171
|
+
|
|
172
|
+
hour = datetime.strptime(datetime_str, "%Y%m%d%H")
|
|
173
|
+
|
|
174
|
+
def nearest(step: int) -> str | None:
|
|
175
|
+
for offset in range(1, NEAREST_HOURS + 1):
|
|
176
|
+
stamp = (hour + timedelta(hours=step * offset)).strftime(
|
|
177
|
+
"%Y%m%d%H"
|
|
178
|
+
)
|
|
179
|
+
if (root / f"{stamp}.nc").exists():
|
|
180
|
+
return stamp
|
|
181
|
+
return None
|
|
182
|
+
|
|
183
|
+
return nearest(-1), nearest(1)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
@dataclass(frozen=True)
|
|
187
|
+
class StationLocations:
|
|
188
|
+
"""Station coordinates from one hourly snapshot, without observations."""
|
|
189
|
+
|
|
190
|
+
id: np.ndarray
|
|
191
|
+
lon: np.ndarray
|
|
192
|
+
lat: np.ndarray
|
|
193
|
+
source_file: str
|
|
194
|
+
datetime: str
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def read_station_locations(
|
|
198
|
+
data_dir: str,
|
|
199
|
+
datetime_str: str,
|
|
200
|
+
) -> StationLocations:
|
|
201
|
+
"""Read locations even when pollutant variables are absent or missing."""
|
|
202
|
+
path = resolve_station_file(data_dir, datetime_str)
|
|
203
|
+
with open_netcdf(path) as ds:
|
|
204
|
+
for name in ("id", "lon", "lat"):
|
|
205
|
+
if name not in ds:
|
|
206
|
+
raise ValueError(f"站点文件缺少 {name}: {path}")
|
|
207
|
+
ids = np.char.upper(_normalize_station_ids(ds["id"].values))
|
|
208
|
+
lon = ds["lon"].values.astype(float).ravel()
|
|
209
|
+
lat = ds["lat"].values.astype(float).ravel()
|
|
210
|
+
if not (len(ids) == len(lon) == len(lat)):
|
|
211
|
+
raise ValueError(f"站点 ID 与坐标数量不一致: {path}")
|
|
212
|
+
return StationLocations(ids, lon, lat, str(path), path.stem)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def read_stations(
|
|
216
|
+
data_dir: str,
|
|
217
|
+
datetime_str: str,
|
|
218
|
+
var_name: str,
|
|
219
|
+
extent: tuple[float, float, float, float] | None = None,
|
|
220
|
+
) -> tuple[StationData, str]:
|
|
221
|
+
"""Read station data for a given hour and variable.
|
|
222
|
+
|
|
223
|
+
Parameters
|
|
224
|
+
----------
|
|
225
|
+
data_dir : directory containing {YYYYMMDDHH}.nc files.
|
|
226
|
+
datetime_str : YYYYMMDDHH (exact hour) or YYYYMMDD (latest hour).
|
|
227
|
+
var_name : variable name in the NC file (e.g. "AQI", "PM2.5", "O3").
|
|
228
|
+
extent : optional (lon_min, lon_max, lat_min, lat_max) for spatial filter.
|
|
229
|
+
|
|
230
|
+
Returns
|
|
231
|
+
-------
|
|
232
|
+
tuple of (StationData, resolved_datetime_str).
|
|
233
|
+
"""
|
|
234
|
+
path = resolve_station_file(data_dir, datetime_str)
|
|
235
|
+
datetime_str = path.stem
|
|
236
|
+
|
|
237
|
+
ds = open_netcdf(path)
|
|
161
238
|
|
|
162
239
|
try:
|
|
163
240
|
lon = ds["lon"].values.astype(float)
|
|
@@ -165,6 +242,8 @@ def read_stations(
|
|
|
165
242
|
station_id = ds["id"].values
|
|
166
243
|
|
|
167
244
|
# Read variable — xarray auto-applies scale_factor/add_offset for CO
|
|
245
|
+
if var_name not in ds:
|
|
246
|
+
raise ValueError(f"站点文件缺少变量 {var_name}: {path}")
|
|
168
247
|
raw = ds[var_name].values.astype(float)
|
|
169
248
|
finally:
|
|
170
249
|
ds.close()
|
|
@@ -235,7 +314,7 @@ def read_station_series(
|
|
|
235
314
|
continue
|
|
236
315
|
|
|
237
316
|
try:
|
|
238
|
-
with
|
|
317
|
+
with open_netcdf(path) as ds:
|
|
239
318
|
opened_files += 1
|
|
240
319
|
required = ("id", "lon", "lat", var_name)
|
|
241
320
|
missing_vars = [name for name in required if name not in ds]
|
|
@@ -268,9 +347,11 @@ def read_station_series(
|
|
|
268
347
|
failed_files[timestamp] = str(error).splitlines()[0]
|
|
269
348
|
|
|
270
349
|
if opened_files == 0:
|
|
271
|
-
raise
|
|
350
|
+
raise RsplotError(
|
|
351
|
+
"data_not_found",
|
|
272
352
|
f"窗口 {dates[0]}~{dates[-1]} 内未找到可读取的站点文件: "
|
|
273
|
-
f"{root}/YYYYMMDDHH.nc"
|
|
353
|
+
f"{root}/YYYYMMDDHH.nc",
|
|
354
|
+
details={"path": f"{root}/YYYYMMDDHH.nc"},
|
|
274
355
|
)
|
|
275
356
|
if canonical_id is None or station_lon is None or station_lat is None:
|
|
276
357
|
if failed_files and not station_missing_hours:
|
|
@@ -278,12 +359,15 @@ def read_station_series(
|
|
|
278
359
|
f"{timestamp}: {message}"
|
|
279
360
|
for timestamp, message in list(failed_files.items())[:3]
|
|
280
361
|
)
|
|
281
|
-
raise
|
|
362
|
+
raise RsplotError(
|
|
363
|
+
"read_failed",
|
|
282
364
|
f"窗口 {dates[0]}~{dates[-1]} 内无法读取变量 "
|
|
283
|
-
f"'{var_name}': {examples}"
|
|
365
|
+
f"'{var_name}': {examples}",
|
|
284
366
|
)
|
|
285
|
-
raise
|
|
286
|
-
|
|
367
|
+
raise RsplotError(
|
|
368
|
+
"region_not_found",
|
|
369
|
+
f"窗口 {dates[0]}~{dates[-1]} 内未找到站点 '{station_id}'",
|
|
370
|
+
details={"station_id": station_id},
|
|
287
371
|
)
|
|
288
372
|
|
|
289
373
|
return StationSeries(
|
|
@@ -336,7 +420,7 @@ def read_region_station_series(
|
|
|
336
420
|
|
|
337
421
|
existing_files += 1
|
|
338
422
|
try:
|
|
339
|
-
with
|
|
423
|
+
with open_netcdf(path) as ds:
|
|
340
424
|
required = ("id", "lon", "lat", var_name)
|
|
341
425
|
missing_vars = [name for name in required if name not in ds]
|
|
342
426
|
if missing_vars:
|
|
@@ -376,9 +460,11 @@ def read_region_station_series(
|
|
|
376
460
|
hourly_values.append({})
|
|
377
461
|
|
|
378
462
|
if existing_files == 0:
|
|
379
|
-
raise
|
|
463
|
+
raise RsplotError(
|
|
464
|
+
"data_not_found",
|
|
380
465
|
f"窗口 {dates[0]}~{dates[-1]} 内未找到可读取的站点文件: "
|
|
381
|
-
f"{root}/YYYYMMDDHH.nc"
|
|
466
|
+
f"{root}/YYYYMMDDHH.nc",
|
|
467
|
+
details={"path": f"{root}/YYYYMMDDHH.nc"},
|
|
382
468
|
)
|
|
383
469
|
if not source_files:
|
|
384
470
|
examples = "; ".join(
|