rsplot 0.3.2.dev4__py3-none-any.whl → 0.4.0__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.4.0.dist-info}/METADATA +426 -121
- rsplot-0.4.0.dist-info/RECORD +76 -0
- {rsplot-0.3.2.dev4.dist-info → rsplot-0.4.0.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.4.0.dist-info}/entry_points.txt +0 -0
- {rsplot-0.3.2.dev4.dist-info → rsplot-0.4.0.dist-info}/licenses/LICENSE +0 -0
rsplot/recent.py
DELETED
|
@@ -1,447 +0,0 @@
|
|
|
1
|
-
"""Recent-day JSON summaries for raster and station data.
|
|
2
|
-
|
|
3
|
-
The ``recent`` command is intentionally read/analysis only: it produces a
|
|
4
|
-
compact JSON payload for comparing the last week/month/year without drawing
|
|
5
|
-
maps. It reuses the existing product readers, gridding, and station filters so
|
|
6
|
-
its daily numbers match the plotting commands' data path.
|
|
7
|
-
"""
|
|
8
|
-
|
|
9
|
-
from __future__ import annotations
|
|
10
|
-
|
|
11
|
-
import json
|
|
12
|
-
from dataclasses import dataclass
|
|
13
|
-
from datetime import datetime, timedelta
|
|
14
|
-
from pathlib import Path
|
|
15
|
-
from typing import TYPE_CHECKING, Any
|
|
16
|
-
|
|
17
|
-
import numpy as np
|
|
18
|
-
from rich.console import Console
|
|
19
|
-
from rich.progress import track
|
|
20
|
-
|
|
21
|
-
from rsplot.config import get_exceedance_threshold
|
|
22
|
-
from rsplot.geo.gridding import grid_coverage_in_region
|
|
23
|
-
from rsplot.geo.processing import (
|
|
24
|
-
buffered_extent,
|
|
25
|
-
prepare_existing_grid,
|
|
26
|
-
prepare_swath_grid,
|
|
27
|
-
)
|
|
28
|
-
from rsplot.readers import ProductInfo
|
|
29
|
-
from rsplot.readers.guokong import (
|
|
30
|
-
mask_stations_to_region,
|
|
31
|
-
read_stations,
|
|
32
|
-
)
|
|
33
|
-
from rsplot.stats import basic_stats
|
|
34
|
-
|
|
35
|
-
if TYPE_CHECKING:
|
|
36
|
-
from rsplot.geo.boundaries import RegionInfo
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
@dataclass
|
|
40
|
-
class RecentDaily:
|
|
41
|
-
"""One daily summary row."""
|
|
42
|
-
|
|
43
|
-
date: str
|
|
44
|
-
ok: bool
|
|
45
|
-
value: float | None
|
|
46
|
-
stats: dict[str, Any]
|
|
47
|
-
meta: dict[str, Any]
|
|
48
|
-
error: str | None = None
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
def parse_recent_dates(end_date: str, days: int) -> list[str]:
|
|
52
|
-
"""Return ascending YYYYMMDD dates ending on ``end_date``."""
|
|
53
|
-
if days < 1:
|
|
54
|
-
raise ValueError("--days 必须 >= 1")
|
|
55
|
-
if len(end_date) != 8 or not end_date.isdigit():
|
|
56
|
-
raise ValueError(f"日期格式错误: '{end_date}',应为 YYYYMMDD")
|
|
57
|
-
try:
|
|
58
|
-
end = datetime.strptime(end_date, "%Y%m%d")
|
|
59
|
-
except ValueError as e:
|
|
60
|
-
raise ValueError(
|
|
61
|
-
f"日期无效: '{end_date}',请检查年月日是否真实存在 (原始错误: {e})"
|
|
62
|
-
) from e
|
|
63
|
-
|
|
64
|
-
start = end - timedelta(days=days - 1)
|
|
65
|
-
return [
|
|
66
|
-
(start + timedelta(days=i)).strftime("%Y%m%d") for i in range(days)
|
|
67
|
-
]
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
def summarize_recent_raster(
|
|
71
|
-
*,
|
|
72
|
-
region: RegionInfo,
|
|
73
|
-
product: str,
|
|
74
|
-
prod_info: ProductInfo,
|
|
75
|
-
data_dir: str,
|
|
76
|
-
dates: list[str],
|
|
77
|
-
res: float,
|
|
78
|
-
qa_threshold: float,
|
|
79
|
-
cloud_fraction_max: float = 0.5,
|
|
80
|
-
console: Console | None = None,
|
|
81
|
-
) -> list[RecentDaily]:
|
|
82
|
-
"""Read daily raster swaths and summarize each day over the region."""
|
|
83
|
-
if console is None:
|
|
84
|
-
console = Console()
|
|
85
|
-
|
|
86
|
-
reader = prod_info.reader_cls()
|
|
87
|
-
reader.cloud_fraction_max = cloud_fraction_max
|
|
88
|
-
read_extent = buffered_extent(region.extent, 1.0)
|
|
89
|
-
out: list[RecentDaily] = []
|
|
90
|
-
|
|
91
|
-
for d in track(
|
|
92
|
-
dates, description=f"[cyan]统计 {product.upper()} 最近数据..."
|
|
93
|
-
):
|
|
94
|
-
meta: dict[str, Any] = {}
|
|
95
|
-
try:
|
|
96
|
-
if prod_info.sensor == "gems":
|
|
97
|
-
from rsplot.readers.gems import GEMS_ANALYSIS_RESOLUTION
|
|
98
|
-
from rsplot.temporal import read_scan_mean
|
|
99
|
-
|
|
100
|
-
batch = read_scan_mean(
|
|
101
|
-
reader=reader,
|
|
102
|
-
data_dir=data_dir,
|
|
103
|
-
request=d,
|
|
104
|
-
extent=read_extent,
|
|
105
|
-
res=GEMS_ANALYSIS_RESOLUTION,
|
|
106
|
-
)
|
|
107
|
-
prepared = prepare_existing_grid(
|
|
108
|
-
batch.LON,
|
|
109
|
-
batch.LAT,
|
|
110
|
-
batch.grid,
|
|
111
|
-
region.geometry,
|
|
112
|
-
fill_gaps=False,
|
|
113
|
-
)
|
|
114
|
-
meta = {
|
|
115
|
-
"n_pixels": batch.n_pixels,
|
|
116
|
-
"n_files": batch.n_files,
|
|
117
|
-
"n_broken": batch.n_broken,
|
|
118
|
-
**batch.metadata,
|
|
119
|
-
}
|
|
120
|
-
else:
|
|
121
|
-
swath = reader.read(data_dir, d, read_extent, qa_threshold)
|
|
122
|
-
prepared = prepare_swath_grid(
|
|
123
|
-
swath.lon,
|
|
124
|
-
swath.lat,
|
|
125
|
-
swath.values,
|
|
126
|
-
read_extent,
|
|
127
|
-
res,
|
|
128
|
-
region.geometry,
|
|
129
|
-
)
|
|
130
|
-
meta = {
|
|
131
|
-
"n_pixels": int(swath.n_pixels),
|
|
132
|
-
"n_files": int(swath.n_files),
|
|
133
|
-
"n_broken": int(swath.n_broken),
|
|
134
|
-
}
|
|
135
|
-
stats = _grid_stats(
|
|
136
|
-
prepared.lon,
|
|
137
|
-
prepared.lat,
|
|
138
|
-
prepared.values,
|
|
139
|
-
region.geometry,
|
|
140
|
-
)
|
|
141
|
-
if not stats:
|
|
142
|
-
raise ValueError(f"{d} 区域内无有效网格")
|
|
143
|
-
out.append(
|
|
144
|
-
RecentDaily(
|
|
145
|
-
date=d,
|
|
146
|
-
ok=True,
|
|
147
|
-
value=stats.get("mean"),
|
|
148
|
-
stats=stats,
|
|
149
|
-
meta=meta,
|
|
150
|
-
)
|
|
151
|
-
)
|
|
152
|
-
except (FileNotFoundError, ValueError) as e:
|
|
153
|
-
out.append(
|
|
154
|
-
RecentDaily(
|
|
155
|
-
date=d,
|
|
156
|
-
ok=False,
|
|
157
|
-
value=None,
|
|
158
|
-
stats={},
|
|
159
|
-
meta=meta,
|
|
160
|
-
error=str(e).splitlines()[0],
|
|
161
|
-
)
|
|
162
|
-
)
|
|
163
|
-
|
|
164
|
-
return out
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
def summarize_recent_station(
|
|
168
|
-
*,
|
|
169
|
-
region: RegionInfo,
|
|
170
|
-
data_dir: str,
|
|
171
|
-
dates: list[str],
|
|
172
|
-
var_name: str,
|
|
173
|
-
console: Console | None = None,
|
|
174
|
-
) -> list[RecentDaily]:
|
|
175
|
-
"""Read daily latest-hour station files and summarize each day."""
|
|
176
|
-
if console is None:
|
|
177
|
-
console = Console()
|
|
178
|
-
|
|
179
|
-
read_extent = buffered_extent(region.extent, 0.5)
|
|
180
|
-
threshold = get_exceedance_threshold(var_name)
|
|
181
|
-
out: list[RecentDaily] = []
|
|
182
|
-
|
|
183
|
-
for d in track(
|
|
184
|
-
dates, description=f"[cyan]统计 {var_name} 站点最近数据..."
|
|
185
|
-
):
|
|
186
|
-
try:
|
|
187
|
-
data, resolved_dt = read_stations(
|
|
188
|
-
data_dir, d, var_name, extent=read_extent
|
|
189
|
-
)
|
|
190
|
-
data = mask_stations_to_region(data, region.geometry)
|
|
191
|
-
vals = data.values[np.isfinite(data.values)]
|
|
192
|
-
stats = _array_stats(vals)
|
|
193
|
-
if not stats:
|
|
194
|
-
raise ValueError(f"{d} 区域内无有效站点")
|
|
195
|
-
meta: dict[str, Any] = {
|
|
196
|
-
"datetime": resolved_dt,
|
|
197
|
-
"n_stations": int(data.n_stations),
|
|
198
|
-
"n_valid": int(data.n_valid),
|
|
199
|
-
}
|
|
200
|
-
if threshold is not None:
|
|
201
|
-
meta["threshold"] = threshold
|
|
202
|
-
meta["n_exceed"] = int((vals > threshold).sum())
|
|
203
|
-
meta["exceed_rate_pct"] = round(
|
|
204
|
-
100 * meta["n_exceed"] / len(vals), 1
|
|
205
|
-
)
|
|
206
|
-
out.append(
|
|
207
|
-
RecentDaily(
|
|
208
|
-
date=d,
|
|
209
|
-
ok=True,
|
|
210
|
-
value=stats.get("mean"),
|
|
211
|
-
stats=stats,
|
|
212
|
-
meta=meta,
|
|
213
|
-
)
|
|
214
|
-
)
|
|
215
|
-
except (FileNotFoundError, ValueError, KeyError) as e:
|
|
216
|
-
out.append(
|
|
217
|
-
RecentDaily(
|
|
218
|
-
date=d,
|
|
219
|
-
ok=False,
|
|
220
|
-
value=None,
|
|
221
|
-
stats={},
|
|
222
|
-
meta={},
|
|
223
|
-
error=str(e).splitlines()[0],
|
|
224
|
-
)
|
|
225
|
-
)
|
|
226
|
-
|
|
227
|
-
return out
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
def build_recent_result(
|
|
231
|
-
*,
|
|
232
|
-
region: RegionInfo,
|
|
233
|
-
source: str,
|
|
234
|
-
dates: list[str],
|
|
235
|
-
daily: list[RecentDaily],
|
|
236
|
-
params: dict[str, Any],
|
|
237
|
-
output: str,
|
|
238
|
-
product: str | None = None,
|
|
239
|
-
variable: str | None = None,
|
|
240
|
-
unit: str | None = None,
|
|
241
|
-
sensor: str | None = None,
|
|
242
|
-
quantity: str | None = None,
|
|
243
|
-
) -> dict[str, Any]:
|
|
244
|
-
"""Build the JSON payload for a recent run."""
|
|
245
|
-
daily_rows = [_daily_to_json(row) for row in daily]
|
|
246
|
-
failed = {row.date: row.error for row in daily if not row.ok and row.error}
|
|
247
|
-
found = [row for row in daily if row.ok]
|
|
248
|
-
|
|
249
|
-
result: dict[str, Any] = {
|
|
250
|
-
"command": "recent",
|
|
251
|
-
"image": None,
|
|
252
|
-
"sidecar": output,
|
|
253
|
-
"source": source,
|
|
254
|
-
"region": {
|
|
255
|
-
"name": region.name,
|
|
256
|
-
"level": region.level,
|
|
257
|
-
"extent": [round(x, 3) for x in region.extent],
|
|
258
|
-
},
|
|
259
|
-
"period": {
|
|
260
|
-
"start": dates[0],
|
|
261
|
-
"end": dates[-1],
|
|
262
|
-
"days_requested": len(dates),
|
|
263
|
-
},
|
|
264
|
-
"params": params,
|
|
265
|
-
"availability": {
|
|
266
|
-
"days_found": len(found),
|
|
267
|
-
"days_failed": len(failed),
|
|
268
|
-
"failed_dates": failed,
|
|
269
|
-
},
|
|
270
|
-
"daily": daily_rows,
|
|
271
|
-
"windows": _window_summaries(daily),
|
|
272
|
-
"changes": _change_summaries(daily),
|
|
273
|
-
"trend": _trend_summary(daily),
|
|
274
|
-
"warnings": _warnings(daily),
|
|
275
|
-
}
|
|
276
|
-
if source == "raster" and sensor == "gems":
|
|
277
|
-
result["sensor"] = sensor
|
|
278
|
-
result["quantity"] = quantity
|
|
279
|
-
result["statistics_basis"] = "unfilled_unsmoothed_grid"
|
|
280
|
-
result["input_timezone"] = "Asia/Shanghai"
|
|
281
|
-
result["params"] = {
|
|
282
|
-
key: value
|
|
283
|
-
for key, value in params.items()
|
|
284
|
-
if key != "qa_threshold"
|
|
285
|
-
}
|
|
286
|
-
if product is not None:
|
|
287
|
-
result["product"] = product
|
|
288
|
-
if variable is not None:
|
|
289
|
-
result["variable"] = variable
|
|
290
|
-
if unit:
|
|
291
|
-
result["unit"] = unit
|
|
292
|
-
return result
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
def write_recent_result(result: dict[str, Any], output: str) -> str:
|
|
296
|
-
"""Write a recent JSON result and return the path."""
|
|
297
|
-
path = Path(output)
|
|
298
|
-
path.parent.mkdir(parents=True, exist_ok=True)
|
|
299
|
-
with open(path, "w", encoding="utf-8") as f:
|
|
300
|
-
json.dump(result, f, ensure_ascii=False, indent=2)
|
|
301
|
-
return str(path)
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
def _daily_to_json(row: RecentDaily) -> dict[str, Any]:
|
|
305
|
-
data: dict[str, Any] = {
|
|
306
|
-
"date": row.date,
|
|
307
|
-
"ok": row.ok,
|
|
308
|
-
"stats": row.stats,
|
|
309
|
-
"meta": row.meta,
|
|
310
|
-
}
|
|
311
|
-
if row.error:
|
|
312
|
-
data["error"] = row.error
|
|
313
|
-
return data
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
def _window_summaries(daily: list[RecentDaily]) -> dict[str, dict[str, Any]]:
|
|
317
|
-
windows: dict[str, dict[str, Any]] = {}
|
|
318
|
-
n = len(daily)
|
|
319
|
-
specs = [
|
|
320
|
-
("last_7", max(0, n - 7), n),
|
|
321
|
-
("prev_7", max(0, n - 14), max(0, n - 7)),
|
|
322
|
-
("last_30", max(0, n - 30), n),
|
|
323
|
-
("prev_30", max(0, n - 60), max(0, n - 30)),
|
|
324
|
-
("last_365", max(0, n - 365), n),
|
|
325
|
-
]
|
|
326
|
-
for name, start, end in specs:
|
|
327
|
-
if end <= start or end - start < _required_span(name):
|
|
328
|
-
continue
|
|
329
|
-
windows[name] = _summarize_rows(daily[start:end])
|
|
330
|
-
return windows
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
def _change_summaries(daily: list[RecentDaily]) -> dict[str, dict[str, Any]]:
|
|
334
|
-
windows = _window_summaries(daily)
|
|
335
|
-
pairs = [
|
|
336
|
-
("last_7_vs_prev_7", "last_7", "prev_7"),
|
|
337
|
-
("last_30_vs_prev_30", "last_30", "prev_30"),
|
|
338
|
-
]
|
|
339
|
-
out: dict[str, dict[str, Any]] = {}
|
|
340
|
-
for name, cur_key, prev_key in pairs:
|
|
341
|
-
cur = windows.get(cur_key, {})
|
|
342
|
-
prev = windows.get(prev_key, {})
|
|
343
|
-
cur_mean = cur.get("mean")
|
|
344
|
-
prev_mean = prev.get("mean")
|
|
345
|
-
if cur_mean is None or prev_mean is None:
|
|
346
|
-
continue
|
|
347
|
-
abs_change = round(float(cur_mean) - float(prev_mean), 3)
|
|
348
|
-
pct_change = None
|
|
349
|
-
if prev_mean != 0:
|
|
350
|
-
pct_change = round(100 * abs_change / float(prev_mean), 1)
|
|
351
|
-
out[name] = {
|
|
352
|
-
"current_mean": cur_mean,
|
|
353
|
-
"previous_mean": prev_mean,
|
|
354
|
-
"abs_change": abs_change,
|
|
355
|
-
"pct_change": pct_change,
|
|
356
|
-
"direction": _direction(abs_change),
|
|
357
|
-
"current_valid_days": cur.get("valid_days", 0),
|
|
358
|
-
"previous_valid_days": prev.get("valid_days", 0),
|
|
359
|
-
}
|
|
360
|
-
return out
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
def _trend_summary(daily: list[RecentDaily]) -> dict[str, Any]:
|
|
364
|
-
xs = []
|
|
365
|
-
ys = []
|
|
366
|
-
for i, row in enumerate(daily):
|
|
367
|
-
if row.ok and row.value is not None and np.isfinite(row.value):
|
|
368
|
-
xs.append(i)
|
|
369
|
-
ys.append(float(row.value))
|
|
370
|
-
if len(ys) < 2:
|
|
371
|
-
return {
|
|
372
|
-
"valid_days": len(ys),
|
|
373
|
-
"slope_per_day": None,
|
|
374
|
-
"direction": "flat",
|
|
375
|
-
}
|
|
376
|
-
slope = float(
|
|
377
|
-
np.polyfit(np.asarray(xs, dtype=float), np.asarray(ys), 1)[0]
|
|
378
|
-
)
|
|
379
|
-
return {
|
|
380
|
-
"valid_days": len(ys),
|
|
381
|
-
"slope_per_day": round(slope, 4),
|
|
382
|
-
"direction": _direction(slope),
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
def _warnings(daily: list[RecentDaily]) -> list[str]:
|
|
387
|
-
if not daily:
|
|
388
|
-
return []
|
|
389
|
-
valid_days = sum(1 for row in daily if row.ok)
|
|
390
|
-
rate = valid_days / len(daily)
|
|
391
|
-
warnings: list[str] = []
|
|
392
|
-
if valid_days == 0:
|
|
393
|
-
warnings.append("请求窗口内无有效日期。")
|
|
394
|
-
elif rate < 0.5:
|
|
395
|
-
warnings.append("有效日期少于请求天数的一半,变化判断可信度较低。")
|
|
396
|
-
return warnings
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
def _summarize_rows(rows: list[RecentDaily]) -> dict[str, Any]:
|
|
400
|
-
values = np.asarray(
|
|
401
|
-
[row.value for row in rows if row.ok and row.value is not None],
|
|
402
|
-
dtype=float,
|
|
403
|
-
)
|
|
404
|
-
stats = _array_stats(values)
|
|
405
|
-
stats["valid_days"] = len(values)
|
|
406
|
-
stats["requested_days"] = len(rows)
|
|
407
|
-
return stats
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
def _grid_stats(
|
|
411
|
-
LON: np.ndarray,
|
|
412
|
-
LAT: np.ndarray,
|
|
413
|
-
grid: np.ndarray,
|
|
414
|
-
geometry: Any,
|
|
415
|
-
) -> dict[str, Any]:
|
|
416
|
-
stats = _array_stats(grid)
|
|
417
|
-
if stats:
|
|
418
|
-
coverage_pct, n_valid_region, total_region_pixels = (
|
|
419
|
-
grid_coverage_in_region(LON, LAT, grid, geometry)
|
|
420
|
-
)
|
|
421
|
-
stats["coverage_pct"] = coverage_pct
|
|
422
|
-
stats["valid_region_pixels"] = n_valid_region
|
|
423
|
-
stats["total_region_pixels"] = total_region_pixels
|
|
424
|
-
stats["grid_shape"] = list(grid.shape)
|
|
425
|
-
return stats
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
def _array_stats(values: np.ndarray) -> dict[str, Any]:
|
|
429
|
-
return basic_stats(np.asarray(values, dtype=float))
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
def _direction(delta: float) -> str:
|
|
433
|
-
if delta > 0:
|
|
434
|
-
return "up"
|
|
435
|
-
if delta < 0:
|
|
436
|
-
return "down"
|
|
437
|
-
return "flat"
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
def _required_span(name: str) -> int:
|
|
441
|
-
if name.endswith("_7"):
|
|
442
|
-
return 7
|
|
443
|
-
if name.endswith("_30"):
|
|
444
|
-
return 30
|
|
445
|
-
if name.endswith("_365"):
|
|
446
|
-
return 365
|
|
447
|
-
return 1
|
rsplot/result_builders/meteo.py
DELETED
|
@@ -1,171 +0,0 @@
|
|
|
1
|
-
"""Meteorological map JSON-sidecar construction."""
|
|
2
|
-
|
|
3
|
-
from __future__ import annotations
|
|
4
|
-
|
|
5
|
-
from typing import TYPE_CHECKING, Any
|
|
6
|
-
|
|
7
|
-
import numpy as np
|
|
8
|
-
|
|
9
|
-
from rsplot.result_builders.common import serialize_region
|
|
10
|
-
from rsplot.result_builders.station import build_station_result
|
|
11
|
-
from rsplot.stats import basic_stats, round_finite
|
|
12
|
-
|
|
13
|
-
if TYPE_CHECKING:
|
|
14
|
-
import geopandas as gpd
|
|
15
|
-
|
|
16
|
-
from rsplot.geo.boundaries import RegionInfo
|
|
17
|
-
from rsplot.readers.era5 import Era5FieldData
|
|
18
|
-
from rsplot.readers.era5_wind import WindFieldData
|
|
19
|
-
from rsplot.readers.guokong import StationData
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
def build_wind_block(wind: WindFieldData, stride: int) -> dict[str, Any]:
|
|
23
|
-
"""Build machine-readable metadata for a plotted ERA5 wind layer."""
|
|
24
|
-
step = max(1, stride)
|
|
25
|
-
sample = np.s_[::step, ::step]
|
|
26
|
-
sampled_valid = np.isfinite(wind.speed[sample])
|
|
27
|
-
finite = np.isfinite(wind.speed)
|
|
28
|
-
total = wind.n_cells
|
|
29
|
-
|
|
30
|
-
mean_u = float(np.nanmean(wind.u))
|
|
31
|
-
mean_v = float(np.nanmean(wind.v))
|
|
32
|
-
direction_to = (np.degrees(np.arctan2(mean_u, mean_v)) + 360.0) % 360.0
|
|
33
|
-
direction_from = (direction_to + 180.0) % 360.0
|
|
34
|
-
|
|
35
|
-
max_flat_index = int(np.nanargmax(wind.speed))
|
|
36
|
-
max_index = np.unravel_index(max_flat_index, wind.speed.shape)
|
|
37
|
-
return {
|
|
38
|
-
"source": "ERA5",
|
|
39
|
-
"level": wind.level,
|
|
40
|
-
"station_datetime": wind.station_datetime,
|
|
41
|
-
"datetime_utc": wind.datetime_utc,
|
|
42
|
-
"unit": wind.unit,
|
|
43
|
-
"source_files": list(wind.source_files),
|
|
44
|
-
"grid_shape": list(wind.speed.shape),
|
|
45
|
-
"coverage_pct": (
|
|
46
|
-
round(100 * int(finite.sum()) / total, 1) if total else 0.0
|
|
47
|
-
),
|
|
48
|
-
"n_region_cells": int(total),
|
|
49
|
-
"stride": step,
|
|
50
|
-
"n_vectors_valid": int(finite.sum()),
|
|
51
|
-
"n_arrows_plotted": int(sampled_valid.sum()),
|
|
52
|
-
"display": {"color": "black", "colorbar": False},
|
|
53
|
-
"u_stats": basic_stats(wind.u),
|
|
54
|
-
"v_stats": basic_stats(wind.v),
|
|
55
|
-
"speed_stats": basic_stats(wind.speed),
|
|
56
|
-
"resultant": {
|
|
57
|
-
"mean_u": round_finite(mean_u),
|
|
58
|
-
"mean_v": round_finite(mean_v),
|
|
59
|
-
"direction_to_deg": round_finite(direction_to, 1),
|
|
60
|
-
"wind_from_deg": round_finite(direction_from, 1),
|
|
61
|
-
},
|
|
62
|
-
"max_speed_location": {
|
|
63
|
-
"lon": round(float(wind.lon[max_index]), 3),
|
|
64
|
-
"lat": round(float(wind.lat[max_index]), 3),
|
|
65
|
-
"speed": round_finite(wind.speed[max_index]),
|
|
66
|
-
},
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
def build_meteo_result(
|
|
71
|
-
*,
|
|
72
|
-
region: RegionInfo,
|
|
73
|
-
variable: str,
|
|
74
|
-
input_datetime: str,
|
|
75
|
-
input_timezone: str,
|
|
76
|
-
datetime_utc: str,
|
|
77
|
-
output: str,
|
|
78
|
-
requested_datetime: str | None = None,
|
|
79
|
-
field: Era5FieldData | None = None,
|
|
80
|
-
field_cmap: str | None = None,
|
|
81
|
-
field_vmin: float | None = None,
|
|
82
|
-
field_vmax: float | None = None,
|
|
83
|
-
wind: WindFieldData | None = None,
|
|
84
|
-
wind_stride: int | None = None,
|
|
85
|
-
station: StationData | None = None,
|
|
86
|
-
station_datetime: str | None = None,
|
|
87
|
-
station_threshold: float | None = None,
|
|
88
|
-
station_unit: str = "",
|
|
89
|
-
cities_gdf: gpd.GeoDataFrame | None = None,
|
|
90
|
-
) -> dict[str, Any]:
|
|
91
|
-
"""Build the stable machine-readable result for ``meteo``."""
|
|
92
|
-
mode = _meteo_mode(field=field, wind=wind, station=station)
|
|
93
|
-
primary_level = field.level if field is not None else wind.level
|
|
94
|
-
primary_unit = field.unit if field is not None else wind.unit
|
|
95
|
-
result: dict[str, Any] = {
|
|
96
|
-
"command": "meteo",
|
|
97
|
-
"mode": mode,
|
|
98
|
-
"image": output,
|
|
99
|
-
"region": serialize_region(region),
|
|
100
|
-
"datetime": input_datetime,
|
|
101
|
-
"requested_datetime": requested_datetime or input_datetime,
|
|
102
|
-
"timezone": input_timezone,
|
|
103
|
-
"datetime_utc": datetime_utc,
|
|
104
|
-
"variable": variable,
|
|
105
|
-
"level": primary_level,
|
|
106
|
-
"unit": primary_unit,
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
if field is not None:
|
|
110
|
-
total = field.n_cells
|
|
111
|
-
result["field"] = {
|
|
112
|
-
"variable": field.variable,
|
|
113
|
-
"level": field.level,
|
|
114
|
-
"unit": field.unit,
|
|
115
|
-
"source_file": field.source_file,
|
|
116
|
-
"grid_shape": list(field.values.shape),
|
|
117
|
-
"coverage_pct": (
|
|
118
|
-
round(100 * field.n_valid / total, 1) if total else 0.0
|
|
119
|
-
),
|
|
120
|
-
"n_region_cells": total,
|
|
121
|
-
"n_valid": field.n_valid,
|
|
122
|
-
"stats": basic_stats(field.values),
|
|
123
|
-
"display": {
|
|
124
|
-
"cmap": field_cmap,
|
|
125
|
-
"vmin": (
|
|
126
|
-
round_finite(field_vmin)
|
|
127
|
-
if field_vmin is not None
|
|
128
|
-
else None
|
|
129
|
-
),
|
|
130
|
-
"vmax": (
|
|
131
|
-
round_finite(field_vmax)
|
|
132
|
-
if field_vmax is not None
|
|
133
|
-
else None
|
|
134
|
-
),
|
|
135
|
-
"range_method": "manual_or_region_p02_p98",
|
|
136
|
-
},
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
if wind is not None:
|
|
140
|
-
result["wind"] = build_wind_block(wind, wind_stride or 1)
|
|
141
|
-
|
|
142
|
-
if station is not None:
|
|
143
|
-
station_block = build_station_result(
|
|
144
|
-
region=region,
|
|
145
|
-
data=station,
|
|
146
|
-
datetime_str=station_datetime or input_datetime,
|
|
147
|
-
threshold=station_threshold,
|
|
148
|
-
unit=station_unit,
|
|
149
|
-
cities_gdf=cities_gdf,
|
|
150
|
-
output=output,
|
|
151
|
-
)
|
|
152
|
-
for key in ("command", "image", "region"):
|
|
153
|
-
station_block.pop(key, None)
|
|
154
|
-
result["station"] = station_block
|
|
155
|
-
|
|
156
|
-
return result
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
def _meteo_mode(
|
|
160
|
-
*,
|
|
161
|
-
field: Era5FieldData | None,
|
|
162
|
-
wind: WindFieldData | None,
|
|
163
|
-
station: StationData | None,
|
|
164
|
-
) -> str:
|
|
165
|
-
if station is not None and field is not None:
|
|
166
|
-
return "temperature_station_wind"
|
|
167
|
-
if station is not None:
|
|
168
|
-
return "station_wind"
|
|
169
|
-
if field is not None and wind is not None:
|
|
170
|
-
return "temperature_wind"
|
|
171
|
-
return "temperature" if field is not None else "wind"
|