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.
Files changed (71) hide show
  1. rsplot/atomic.py +36 -0
  2. rsplot/cli.py +282 -469
  3. rsplot/commands/common.py +113 -1
  4. rsplot/commands/fnr.py +389 -104
  5. rsplot/commands/forecast.py +24 -7
  6. rsplot/commands/meteo.py +499 -186
  7. rsplot/commands/overlay.py +292 -205
  8. rsplot/commands/radius.py +526 -0
  9. rsplot/commands/raster.py +479 -230
  10. rsplot/commands/reconstruct.py +27 -6
  11. rsplot/commands/sidecar.py +106 -0
  12. rsplot/commands/station.py +154 -42
  13. rsplot/commands/station_trend.py +259 -174
  14. rsplot/config.py +46 -16
  15. rsplot/data_files.py +253 -0
  16. rsplot/errors.py +43 -0
  17. rsplot/fnr.py +38 -46
  18. rsplot/geo/boundaries.py +317 -11
  19. rsplot/geo/footprints.py +205 -0
  20. rsplot/geo/processing.py +84 -5
  21. rsplot/geo/radius.py +205 -0
  22. rsplot/plotting/colormap_22.txt +256 -0
  23. rsplot/plotting/colormaps.py +24 -29
  24. rsplot/plotting/map_frame.py +203 -9
  25. rsplot/plotting/meteo.py +10 -3
  26. rsplot/plotting/overlay.py +36 -40
  27. rsplot/plotting/raster.py +15 -3
  28. rsplot/plotting/station.py +86 -33
  29. rsplot/plotting/station_focus.py +84 -0
  30. rsplot/plotting/station_trend.py +60 -47
  31. rsplot/plotting/styles.py +3 -5
  32. rsplot/readers/__init__.py +89 -7
  33. rsplot/readers/_tropomi.py +121 -3
  34. rsplot/readers/base.py +16 -1
  35. rsplot/readers/era5.py +110 -10
  36. rsplot/readers/era5_wind.py +3 -2
  37. rsplot/readers/gems.py +429 -0
  38. rsplot/readers/guokong.py +125 -39
  39. rsplot/readers/netcdf.py +32 -0
  40. rsplot/readers/tropomi_hcho.py +1 -1
  41. rsplot/readers/tropomi_no2.py +1 -1
  42. rsplot/readers/tropomi_nrti.py +116 -0
  43. rsplot/readers/tropomi_o3.py +1 -1
  44. rsplot/readers/tropomi_o3pr.py +1 -1
  45. rsplot/result_builders/__init__.py +0 -14
  46. rsplot/result_builders/common.py +84 -0
  47. rsplot/result_builders/envelope.py +236 -0
  48. rsplot/result_builders/fnr.py +47 -131
  49. rsplot/result_builders/forecast.py +7 -0
  50. rsplot/result_builders/provenance.py +59 -0
  51. rsplot/result_builders/reconstruct.py +7 -0
  52. rsplot/result_builders/satellite.py +240 -0
  53. rsplot/result_builders/series_layer.py +289 -0
  54. rsplot/result_builders/station.py +23 -0
  55. rsplot/result_builders/station_layer.py +326 -0
  56. rsplot/results.py +0 -12
  57. rsplot/schemas/result.schema.json +566 -0
  58. rsplot/temporal.py +146 -16
  59. rsplot-0.3.2.dev37.dist-info/METADATA +996 -0
  60. rsplot-0.3.2.dev37.dist-info/RECORD +76 -0
  61. {rsplot-0.3.1.dev3.dist-info → rsplot-0.3.2.dev37.dist-info}/WHEEL +1 -1
  62. rsplot/commands/recent.py +0 -164
  63. rsplot/recent.py +0 -404
  64. rsplot/result_builders/meteo.py +0 -171
  65. rsplot/result_builders/overlay.py +0 -75
  66. rsplot/result_builders/raster.py +0 -72
  67. rsplot/result_builders/station_trend.py +0 -229
  68. rsplot-0.3.1.dev3.dist-info/METADATA +0 -477
  69. rsplot-0.3.1.dev3.dist-info/RECORD +0 -64
  70. {rsplot-0.3.1.dev3.dist-info → rsplot-0.3.2.dev37.dist-info}/entry_points.txt +0 -0
  71. {rsplot-0.3.1.dev3.dist-info → rsplot-0.3.2.dev37.dist-info}/licenses/LICENSE +0 -0
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
- raise FileNotFoundError(f"未找到 {field_label}文件: {path}")
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 xr.open_dataset(path) as ds:
132
- required = {"time", "latitude", "longitude", variable}
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["time"].values).astype("datetime64[ns]")
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
- raise ValueError(
145
- f"{field_label}文件 {path} 中没有时次 {target_label}。"
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
- time=int(time_indices[0]),
170
- latitude=lat_indices,
171
- longitude=lon_indices,
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,
@@ -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 = _normalize_level(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 _normalize_level(level: str) -> str:
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 ADDED
@@ -0,0 +1,429 @@
1
+ """GEMS L2 scan readers; UTC archive names and China-time requests.
2
+
3
+ Daily ``read`` returns concatenated samples for BaseReader compatibility.
4
+ Scientific daily means use ``iter_scans`` and equal-scan grid averaging.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from collections.abc import Iterator
11
+ from dataclasses import dataclass
12
+ from datetime import datetime, timedelta, timezone
13
+ from pathlib import Path
14
+ from typing import Any, ClassVar
15
+ from zoneinfo import ZoneInfo
16
+
17
+ import numpy as np
18
+ from netCDF4 import Dataset
19
+
20
+ from rsplot.errors import RsplotError
21
+ from rsplot.readers.base import BaseReader, SwathData
22
+
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
27
+
28
+ CHINA_TIME = ZoneInfo("Asia/Shanghai")
29
+ EPOCH = datetime(2000, 1, 1, 12, tzinfo=timezone.utc)
30
+ FILE_RE = re.compile(r"^GK2_GEMS_L2_(\d{8})_(\d{4})_(NO2|HCHO|O3P)_.+\.nc$")
31
+
32
+
33
+ def parse_gems_time(value: str) -> datetime:
34
+ """Parse an exact nominal scan time in Asia/Shanghai."""
35
+ if not value.isdigit() or len(value) != 12:
36
+ raise ValueError("GEMS 扫描时间应为 YYYYMMDDHHMM。")
37
+ try:
38
+ return datetime.strptime(value, "%Y%m%d%H%M").replace(
39
+ tzinfo=CHINA_TIME
40
+ )
41
+ except ValueError as error:
42
+ raise ValueError(f"无效 GEMS 扫描时间: {value}") from error
43
+
44
+
45
+ def match_station_hour(
46
+ scan: str, override: str | None = None
47
+ ) -> tuple[str, dict[str, Any]]:
48
+ """Match a scan to an hour, or pair a daily mean with an explicit hour."""
49
+ from rsplot.temporal import adapt_hourly_time, parse_yyyymmdd
50
+
51
+ if len(scan) == 8:
52
+ parse_yyyymmdd(scan, "GEMS 日均日期")
53
+ if override is None:
54
+ raise ValueError(
55
+ "GEMS 日均叠加需通过 --station-datetime YYYYMMDDHH "
56
+ "显式指定站点时次。"
57
+ )
58
+ hour = adapt_hourly_time(override).input_time.strftime("%Y%m%d%H")
59
+ return hour, {
60
+ "satellite_date": scan,
61
+ "satellite_aggregation": "daily_mean",
62
+ "station_datetime": hour,
63
+ "difference_minutes": None,
64
+ "manual_override": True,
65
+ "reference": "daily_mean_with_explicit_station_hour",
66
+ }
67
+
68
+ time = parse_gems_time(scan)
69
+ if override is None:
70
+ station = (time + timedelta(minutes=30)).replace(minute=0)
71
+ else:
72
+ station = adapt_hourly_time(override).input_time
73
+ hour = station.strftime("%Y%m%d%H")
74
+ return hour, {
75
+ "scan_datetime": scan,
76
+ "station_datetime": hour,
77
+ "difference_minutes": (station - time).total_seconds() / 60,
78
+ "manual_override": override is not None,
79
+ "reference": "nominal_scan_time",
80
+ }
81
+
82
+
83
+ @dataclass(frozen=True)
84
+ class GemsSpec:
85
+ file_product: str
86
+ value: str
87
+ cloud: str
88
+ scale: float = 1e-15
89
+ profile: bool = False
90
+
91
+
92
+ class GemsReader(BaseReader):
93
+ """Read required fields, filter each scan, and retain provenance."""
94
+
95
+ spec: ClassVar[GemsSpec]
96
+ uses_footprints = True
97
+ cloud_fraction_max: float = 0.5
98
+
99
+ def discover(
100
+ self, data_dir: str, request: str
101
+ ) -> list[tuple[Path, datetime]]:
102
+ exact = len(request) == 12
103
+ if exact:
104
+ start = parse_gems_time(request).replace(hour=0, minute=0)
105
+ else:
106
+ if len(request) != 8 or not request.isdigit():
107
+ raise ValueError("GEMS 日期应为 YYYYMMDD 或 YYYYMMDDHHMM。")
108
+ try:
109
+ start = datetime.strptime(request, "%Y%m%d").replace(
110
+ tzinfo=CHINA_TIME
111
+ )
112
+ except ValueError as error:
113
+ raise ValueError(f"无效 GEMS 日期: {request}") from error
114
+ end = start + timedelta(days=1)
115
+ utc_days = {
116
+ start.astimezone(timezone.utc).date(),
117
+ (end - timedelta(microseconds=1)).astimezone(timezone.utc).date(),
118
+ }
119
+ files = []
120
+ for day in sorted(utc_days):
121
+ folder = Path(data_dir) / day.strftime("%Y%m") / day.strftime("%d")
122
+ for path in sorted(folder.glob("GK2_GEMS_L2_*.nc")):
123
+ match = FILE_RE.match(path.name)
124
+ if not match or match[3] != self.spec.file_product:
125
+ continue
126
+ nominal = datetime.strptime(
127
+ match[1] + match[2], "%Y%m%d%H%M"
128
+ ).replace(tzinfo=timezone.utc)
129
+ if start <= nominal < end:
130
+ files.append((path, nominal))
131
+ files.sort(key=lambda item: (item[1], str(item[0])))
132
+ selected = (
133
+ [item for item in files if item[1] == parse_gems_time(request)]
134
+ if exact
135
+ else files
136
+ )
137
+ if not selected:
138
+ available = sorted(
139
+ {
140
+ time.astimezone(CHINA_TIME).strftime("%Y%m%d%H%M")
141
+ for _, time in files
142
+ }
143
+ )
144
+ raise RsplotError(
145
+ "data_not_found",
146
+ f"未找到 GEMS {request};当日可用扫描: "
147
+ + (", ".join(available) or "无"),
148
+ details={"available": available},
149
+ )
150
+ times = [time for _, time in selected]
151
+ if len(set(times)) != len(times):
152
+ raise ValueError(
153
+ "GEMS 同一标称时次存在多个文件,请使用仅含一个版本的数据目录。"
154
+ )
155
+ return selected
156
+
157
+ def iter_scans(
158
+ self,
159
+ data_dir: str,
160
+ date: str,
161
+ extent: tuple[float, float, float, float],
162
+ qa_threshold: float = 0.5,
163
+ ) -> Iterator[SwathData]:
164
+ """Yield empty diagnostic batches for unreadable files as well."""
165
+ for path, nominal in self.discover(data_dir, date):
166
+ try:
167
+ yield self.read_file(path, nominal, extent)
168
+ except (
169
+ OSError,
170
+ ValueError,
171
+ KeyError,
172
+ IndexError,
173
+ AttributeError,
174
+ RuntimeError,
175
+ ) as error:
176
+ empty = np.empty(0, dtype=float)
177
+ yield SwathData(
178
+ empty,
179
+ empty,
180
+ empty,
181
+ 0,
182
+ 1,
183
+ 1,
184
+ {
185
+ "file": str(path),
186
+ "nominal_utc": nominal.isoformat(),
187
+ "nominal_local": nominal.astimezone(
188
+ CHINA_TIME
189
+ ).isoformat(),
190
+ "error": str(error).splitlines()[0],
191
+ },
192
+ )
193
+
194
+ def read(
195
+ self,
196
+ data_dir: str,
197
+ date: str,
198
+ extent: tuple[float, float, float, float],
199
+ qa_threshold: float = 0.5,
200
+ ) -> SwathData:
201
+ scans = list(self.iter_scans(data_dir, date, extent, qa_threshold))
202
+ valid = [scan for scan in scans if scan.n_pixels]
203
+ if not valid:
204
+ raise ValueError(
205
+ f"GEMS {date} 区域内无有效像元: "
206
+ + str([scan.metadata for scan in scans])
207
+ )
208
+ return SwathData(
209
+ np.concatenate([scan.lon for scan in valid]),
210
+ np.concatenate([scan.lat for scan in valid]),
211
+ np.concatenate([scan.values for scan in valid]),
212
+ sum(scan.n_pixels for scan in scans),
213
+ len(scans),
214
+ sum(scan.n_broken for scan in scans),
215
+ {"scans": [scan.metadata for scan in scans]},
216
+ np.concatenate([scan.corner_lon for scan in valid]),
217
+ np.concatenate([scan.corner_lat for scan in valid]),
218
+ )
219
+
220
+ def read_file(
221
+ self,
222
+ path: Path,
223
+ nominal: datetime,
224
+ extent: tuple[float, float, float, float],
225
+ ) -> SwathData:
226
+ spec = self.spec
227
+ geo = "geolocation" if spec.profile else "Geolocation Fields"
228
+ data = "product" if spec.profile else "Data Fields"
229
+ names = (
230
+ (
231
+ "longitude",
232
+ "latitude",
233
+ "solar_zenith_angle",
234
+ "viewing_zenith_angle",
235
+ )
236
+ if spec.profile
237
+ else (
238
+ "Longitude",
239
+ "Latitude",
240
+ "SolarZenithAngle",
241
+ "ViewingZenithAngle",
242
+ )
243
+ )
244
+ flag_path = data + (
245
+ "/final_algorithm_flags"
246
+ if spec.profile
247
+ else "/FinalAlgorithmFlags"
248
+ )
249
+ with Dataset(path) as ds:
250
+
251
+ def array(name: str) -> np.ndarray:
252
+ return np.ma.asarray(ds[name][:], dtype=float).filled(np.nan)
253
+
254
+ lon, lat, sza, vza = [array(f"{geo}/{name}") for name in names]
255
+ value_var = ds[f"{data}/{spec.value}"]
256
+ units = value_var.getncattr("units")
257
+ expected = "DU" if spec.profile else "molecules cm-2"
258
+ if units != expected:
259
+ raise ValueError(
260
+ f"{spec.value} 单位不匹配: {units!r},预期 {expected}"
261
+ )
262
+ value = array(f"{data}/{spec.value}")
263
+ flags = array(flag_path)
264
+ cloud = array(spec.cloud)
265
+ if value.ndim != 2 or any(
266
+ a.shape != value.shape
267
+ for a in (lon, lat, sza, vza, flags, cloud)
268
+ ):
269
+ raise ValueError(
270
+ "GEMS 经纬度、数值和质量变量必须为同形状二维数组。"
271
+ )
272
+ from rsplot.geo.footprints import (
273
+ inferred_corner_grid,
274
+ pixel_corners,
275
+ )
276
+
277
+ valid_geo = (
278
+ np.isfinite(lon)
279
+ & np.isfinite(lat)
280
+ & (np.abs(lon) <= 180)
281
+ & (np.abs(lat) <= 90)
282
+ )
283
+ lon = np.where(valid_geo, lon, np.nan)
284
+ lat = np.where(valid_geo, lat, np.nan)
285
+ if (
286
+ "CornerLongitude" in ds[geo].variables
287
+ and "CornerLatitude" in ds[geo].variables
288
+ ):
289
+ corner_lon = array(f"{geo}/CornerLongitude")
290
+ corner_lat = array(f"{geo}/CornerLatitude")
291
+ footprint_source = "file_corner_coordinates"
292
+ else:
293
+ corner_lon = inferred_corner_grid(lon)
294
+ corner_lat = inferred_corner_grid(lat)
295
+ footprint_source = "estimated_from_unfiltered_native_centers"
296
+ expected_shape = (value.shape[0] + 1, value.shape[1] + 1)
297
+ if (
298
+ corner_lon.shape != expected_shape
299
+ or corner_lat.shape != expected_shape
300
+ ):
301
+ raise ValueError("GEMS 像元角点网格形状不匹配。")
302
+ corner_lon, corner_lat = (
303
+ pixel_corners(corner_lon),
304
+ pixel_corners(corner_lat),
305
+ )
306
+ footprint_valid = (
307
+ np.isfinite(corner_lon).all(axis=-1)
308
+ & np.isfinite(corner_lat).all(axis=-1)
309
+ & (np.abs(corner_lon) <= 180).all(axis=-1)
310
+ & (np.abs(corner_lat) <= 90).all(axis=-1)
311
+ )
312
+ west, east, south, north = extent
313
+ mask = (
314
+ np.isfinite(value)
315
+ & (np.abs(value) < 1e29)
316
+ & np.isfinite(lon)
317
+ & np.isfinite(lat)
318
+ & footprint_valid
319
+ & (corner_lon.max(axis=-1) > west)
320
+ & (corner_lon.min(axis=-1) < east)
321
+ & (corner_lat.max(axis=-1) > south)
322
+ & (corner_lat.min(axis=-1) < north)
323
+ & (np.abs(lon) <= 180)
324
+ & (np.abs(lat) <= 90)
325
+ & (flags == 0)
326
+ & np.isfinite(sza)
327
+ & (sza >= 0)
328
+ & (sza < 70)
329
+ & np.isfinite(vza)
330
+ & (vza >= 0)
331
+ & (vza < 70)
332
+ & np.isfinite(cloud)
333
+ & (cloud >= 0)
334
+ & (cloud <= self.cloud_fraction_max)
335
+ )
336
+ settings = (
337
+ ds if spec.profile else ds["METADATA/ALGORITHM_SETTINGS"]
338
+ )
339
+ version = (
340
+ str(settings.getncattr("product_version"))
341
+ if "product_version" in settings.ncattrs()
342
+ else None
343
+ )
344
+ time_name = f"{geo}/" + ("time" if spec.profile else "Time")
345
+ time = array(time_name)
346
+ time_units = ds[time_name].getncattr("units")
347
+ # NO2 v4 omits the epoch; it uses the GEMS mission epoch.
348
+ known_units = (
349
+ "second",
350
+ "Seconds since 2000-01-01 12 UTC",
351
+ "seconds since 2000-01-01 12:00:00 UTC",
352
+ )
353
+ if time_units not in known_units:
354
+ raise ValueError(f"未知 GEMS 时间单位: {time_units!r}")
355
+ time = time[np.isfinite(time) & (np.abs(time) < 1e12)]
356
+ meta = {
357
+ "file": str(path),
358
+ "product_version": version,
359
+ "variable": f"{data}/{spec.value}",
360
+ "source_unit": units,
361
+ "unit_scale": spec.scale,
362
+ "nominal_utc": nominal.isoformat(),
363
+ "nominal_local": nominal.astimezone(CHINA_TIME).isoformat(),
364
+ "observation_start_utc": (
365
+ (EPOCH + timedelta(seconds=float(time.min()))).isoformat()
366
+ if time.size
367
+ else None
368
+ ),
369
+ "observation_end_utc": (
370
+ (EPOCH + timedelta(seconds=float(time.max()))).isoformat()
371
+ if time.size
372
+ else None
373
+ ),
374
+ "time_epoch": EPOCH.isoformat(),
375
+ "quality": {
376
+ "flag_variable": flag_path,
377
+ "accepted_values": [0],
378
+ "solar_zenith_max_exclusive": 70,
379
+ "viewing_zenith_max_exclusive": 70,
380
+ "cloud_variable": spec.cloud,
381
+ "cloud_fraction_max": self.cloud_fraction_max,
382
+ },
383
+ "n_pixels": int(mask.sum()),
384
+ "footprint_source": footprint_source,
385
+ "footprint_geometry": "native_quadrilateral",
386
+ }
387
+ if not mask.any():
388
+ meta["empty_reason"] = "区域内无通过质量筛选的像元"
389
+ return SwathData(
390
+ lon[mask],
391
+ lat[mask],
392
+ value[mask] * spec.scale,
393
+ int(mask.sum()),
394
+ 1,
395
+ 0,
396
+ meta,
397
+ corner_lon[mask],
398
+ corner_lat[mask],
399
+ )
400
+
401
+
402
+ class GemsNO2Reader(GemsReader):
403
+ spec = GemsSpec("NO2", "ColumnAmountNO2Trop", "Data Fields/CloudFraction")
404
+
405
+
406
+ class GemsHCHOReader(GemsReader):
407
+ spec = GemsSpec(
408
+ "HCHO", "ColumnAmount", "Data Fields/CloudRadianceFraction"
409
+ )
410
+
411
+
412
+ class GemsO3Reader(GemsReader):
413
+ spec = GemsSpec(
414
+ "O3P",
415
+ "total_ozone_column",
416
+ "support_data/effective_cloud_fraction",
417
+ scale=1.0,
418
+ profile=True,
419
+ )
420
+
421
+
422
+ class GemsO3PRReader(GemsReader):
423
+ spec = GemsSpec(
424
+ "O3P",
425
+ "troposphere_ozone_column",
426
+ "support_data/effective_cloud_fraction",
427
+ scale=1.0,
428
+ profile=True,
429
+ )