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/netcdf.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Open single NetCDF inputs with coded, one-line failures."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import xarray as xr
|
|
9
|
+
|
|
10
|
+
from rsplot.errors import RsplotError
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def open_netcdf(path: str | Path, **kwargs: Any) -> xr.Dataset:
|
|
14
|
+
"""Open ``path``; a missing or unreadable file names itself.
|
|
15
|
+
|
|
16
|
+
xarray reports a corrupt file as a ValueError with a paragraph about IO
|
|
17
|
+
backends; agents get ``read_failed`` and the path instead.
|
|
18
|
+
"""
|
|
19
|
+
try:
|
|
20
|
+
return xr.open_dataset(path, **kwargs)
|
|
21
|
+
except FileNotFoundError as error:
|
|
22
|
+
raise RsplotError(
|
|
23
|
+
"data_not_found",
|
|
24
|
+
f"未找到文件: {path}",
|
|
25
|
+
details={"path": str(path)},
|
|
26
|
+
) from error
|
|
27
|
+
except (OSError, ValueError) as error:
|
|
28
|
+
raise RsplotError(
|
|
29
|
+
"read_failed",
|
|
30
|
+
f"无法读取 NetCDF 文件 {path}:文件损坏或不是 NetCDF 格式。",
|
|
31
|
+
details={"path": str(path), "reason": type(error).__name__},
|
|
32
|
+
) from error
|
rsplot/readers/tropomi_hcho.py
CHANGED
|
@@ -21,7 +21,7 @@ _SPEC = TropomiReaderSpec(
|
|
|
21
21
|
value_name=VALUE_NAME,
|
|
22
22
|
unit_conversion=UNIT_CONVERSION,
|
|
23
23
|
progress_description="[cyan]读取 HCHO 轨道...",
|
|
24
|
-
not_found_message="未找到匹配文件: \n {patterns}\n
|
|
24
|
+
not_found_message="未找到匹配文件: \n {patterns}\n请检查配置 [paths.data_dirs] 中的数据目录和日期 {date}。",
|
|
25
25
|
no_valid_data_message="{date} 当天 HCHO 无有效数据覆盖目标区域 {extent}。\n共扫描 {n_files} 个文件,损坏 {n_broken} 个;可尝试放宽 --qa 阈值。",
|
|
26
26
|
)
|
|
27
27
|
|
rsplot/readers/tropomi_no2.py
CHANGED
|
@@ -22,7 +22,7 @@ _SPEC = TropomiReaderSpec(
|
|
|
22
22
|
value_name=VALUE_NAME,
|
|
23
23
|
unit_conversion=UNIT_CONVERSION,
|
|
24
24
|
progress_description="[cyan]读取轨道数据...",
|
|
25
|
-
not_found_message="未找到匹配文件:\n {patterns}\n
|
|
25
|
+
not_found_message="未找到匹配文件:\n {patterns}\n请检查配置 [paths.data_dirs] 中的数据目录和日期。",
|
|
26
26
|
no_valid_data_message="{date} 当天无有效数据覆盖目标区域 {extent}。\n共扫描 {n_files} 个文件,损坏 {n_broken} 个。",
|
|
27
27
|
)
|
|
28
28
|
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""Observation identity and provenance for TROPOMI NRTI granules."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
import xarray as xr
|
|
13
|
+
|
|
14
|
+
_FILENAME = re.compile(
|
|
15
|
+
r"^S5P_NRTI_L2__.{7}(\d{8}T\d{6})_(\d{8}T\d{6})_"
|
|
16
|
+
r"(\d{5})_\d{2}_\d{6}_(\d{8}T\d{6})\.nc(?:\.zip)?$"
|
|
17
|
+
)
|
|
18
|
+
IDENTITY_DTYPE = np.dtype(
|
|
19
|
+
[("orbit", "i8"), ("time_ms", "i8"), ("ground_pixel", "i8")]
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class NrtiReadError(ValueError):
|
|
24
|
+
"""A failed day whose per-file diagnostics can still reach sidecars."""
|
|
25
|
+
|
|
26
|
+
def __init__(self, message: str, metadata: dict[str, Any]):
|
|
27
|
+
super().__init__(message)
|
|
28
|
+
self.metadata = metadata
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def granule_identity(path: str) -> tuple[int, str]:
|
|
32
|
+
"""Return orbit and production timestamp from the standard filename."""
|
|
33
|
+
match = _FILENAME.fullmatch(Path(path).name)
|
|
34
|
+
if match is None:
|
|
35
|
+
raise ValueError(
|
|
36
|
+
f"NRTI 文件名无法识别轨道与生成时间: {Path(path).name}"
|
|
37
|
+
)
|
|
38
|
+
for value in (match[1], match[2], match[4]):
|
|
39
|
+
datetime.strptime(value, "%Y%m%dT%H%M%S")
|
|
40
|
+
return int(match[3]), match[4]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _utc_milliseconds(values: np.ndarray, units: str) -> np.ndarray:
|
|
44
|
+
match = re.fullmatch(r"(milliseconds|seconds) since (.+)", units)
|
|
45
|
+
if match is None:
|
|
46
|
+
raise ValueError(f"NRTI delta_time 单位不支持: {units}")
|
|
47
|
+
origin = datetime.fromisoformat(match[2].replace("Z", "+00:00"))
|
|
48
|
+
if origin.tzinfo is None:
|
|
49
|
+
origin = origin.replace(tzinfo=timezone.utc)
|
|
50
|
+
epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
|
|
51
|
+
offset_ms = round((origin - epoch).total_seconds() * 1000)
|
|
52
|
+
factor = 1 if match[1] == "milliseconds" else 1000
|
|
53
|
+
milliseconds = np.asarray(values, dtype=float) * factor + offset_ms
|
|
54
|
+
if not np.all(np.isfinite(milliseconds)):
|
|
55
|
+
raise ValueError("NRTI 观测时间包含缺失或非有限值")
|
|
56
|
+
if np.any(np.abs(milliseconds) >= np.iinfo(np.int64).max):
|
|
57
|
+
raise ValueError("NRTI 观测时间超出范围")
|
|
58
|
+
return np.rint(milliseconds).astype(np.int64)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass
|
|
62
|
+
class NrtiObservations:
|
|
63
|
+
keys: np.ndarray
|
|
64
|
+
processor_version: str | None
|
|
65
|
+
product_version: str | None
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def read_nrti_observations(
|
|
69
|
+
path: str, shape: tuple[int, ...]
|
|
70
|
+
) -> NrtiObservations:
|
|
71
|
+
"""Read real pixel IDs; never substitute file-local scanline indices.
|
|
72
|
+
|
|
73
|
+
delta_time is either per scanline (NO2/O3PR) or per pixel (HCHO/O3).
|
|
74
|
+
Its CF units already contain the UTC reference epoch, so adding the
|
|
75
|
+
separate PRODUCT/time value again would double-count that epoch.
|
|
76
|
+
"""
|
|
77
|
+
orbit, _ = granule_identity(path)
|
|
78
|
+
errors = []
|
|
79
|
+
with xr.open_dataset(path, decode_times=False) as root:
|
|
80
|
+
processor = root.attrs.get("processor_version")
|
|
81
|
+
version = root.attrs.get("product_version")
|
|
82
|
+
for group, prefix in ((None, "PRODUCT_"), ("PRODUCT", "")):
|
|
83
|
+
try:
|
|
84
|
+
kwargs = {} if group is None else {"group": group}
|
|
85
|
+
with xr.open_dataset(path, decode_times=False, **kwargs) as ds:
|
|
86
|
+
delta = ds[f"{prefix}delta_time"]
|
|
87
|
+
times = _utc_milliseconds(
|
|
88
|
+
delta.values.squeeze(), delta.attrs.get("units", "")
|
|
89
|
+
)
|
|
90
|
+
columns = ds[f"{prefix}ground_pixel"].values.squeeze()
|
|
91
|
+
if len(shape) == 2 and times.ndim == 1:
|
|
92
|
+
times = times[:, None]
|
|
93
|
+
times = np.broadcast_to(times, shape)
|
|
94
|
+
columns = np.broadcast_to(columns, shape)
|
|
95
|
+
if not np.all(np.isfinite(columns)) or np.any(
|
|
96
|
+
columns != np.floor(columns)
|
|
97
|
+
):
|
|
98
|
+
raise ValueError("NRTI ground_pixel 索引无效")
|
|
99
|
+
keys = np.empty(shape, dtype=IDENTITY_DTYPE)
|
|
100
|
+
keys["orbit"] = orbit
|
|
101
|
+
keys["time_ms"] = times
|
|
102
|
+
keys["ground_pixel"] = columns
|
|
103
|
+
return NrtiObservations(keys, processor, version)
|
|
104
|
+
except (OSError, ValueError, KeyError) as error:
|
|
105
|
+
errors.append(str(error).splitlines()[0])
|
|
106
|
+
raise ValueError("无法读取 NRTI 观测身份: " + "; ".join(errors))
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def observation_range(keys: np.ndarray) -> dict[str, str] | None:
|
|
110
|
+
if not keys.size:
|
|
111
|
+
return None
|
|
112
|
+
times = keys["time_ms"]
|
|
113
|
+
return {
|
|
114
|
+
label: str(np.datetime64(int(value), "ms")) + "Z"
|
|
115
|
+
for label, value in (("start", times.min()), ("end", times.max()))
|
|
116
|
+
}
|
rsplot/readers/tropomi_o3.py
CHANGED
|
@@ -24,7 +24,7 @@ _SPEC = TropomiReaderSpec(
|
|
|
24
24
|
value_name=VALUE_NAME,
|
|
25
25
|
unit_conversion=UNIT_CONVERSION,
|
|
26
26
|
progress_description="[cyan]读取轨道数据...",
|
|
27
|
-
not_found_message="未找到匹配文件:\n {patterns}\n
|
|
27
|
+
not_found_message="未找到匹配文件:\n {patterns}\n请检查配置 [paths.data_dirs] 中的数据目录和日期。",
|
|
28
28
|
no_valid_data_message="{date} 当天无有效数据覆盖目标区域 {extent}。\n共扫描 {n_files} 个文件,损坏 {n_broken} 个。",
|
|
29
29
|
)
|
|
30
30
|
|
rsplot/readers/tropomi_o3pr.py
CHANGED
|
@@ -22,7 +22,7 @@ _SPEC = TropomiReaderSpec(
|
|
|
22
22
|
value_name=VALUE_NAME,
|
|
23
23
|
unit_conversion=UNIT_CONVERSION,
|
|
24
24
|
progress_description="[cyan]读取 O3PR 轨道...",
|
|
25
|
-
not_found_message="未找到匹配文件:\n {patterns}\n
|
|
25
|
+
not_found_message="未找到匹配文件:\n {patterns}\n请检查配置 [paths.data_dirs] 中的数据目录和日期。",
|
|
26
26
|
no_valid_data_message="{date} 当天 O3PR 无有效数据覆盖目标区域 {extent}。\n共扫描 {n_files} 个文件,损坏 {n_broken} 个。",
|
|
27
27
|
)
|
|
28
28
|
|
|
@@ -1,25 +1,11 @@
|
|
|
1
1
|
"""Domain-specific builders for rsplot's stable JSON sidecars."""
|
|
2
2
|
|
|
3
|
-
from rsplot.result_builders.fnr import build_fnr_result
|
|
4
3
|
from rsplot.result_builders.forecast import build_forecast_result
|
|
5
|
-
from rsplot.result_builders.meteo import build_meteo_result
|
|
6
|
-
from rsplot.result_builders.overlay import build_overlay_result
|
|
7
|
-
from rsplot.result_builders.raster import build_raster_result
|
|
8
4
|
from rsplot.result_builders.reconstruct import build_reconstruct_result
|
|
9
5
|
from rsplot.result_builders.station import build_station_result
|
|
10
|
-
from rsplot.result_builders.station_trend import (
|
|
11
|
-
build_region_trend_result,
|
|
12
|
-
build_station_trend_result,
|
|
13
|
-
)
|
|
14
6
|
|
|
15
7
|
__all__ = [
|
|
16
|
-
"build_fnr_result",
|
|
17
8
|
"build_forecast_result",
|
|
18
|
-
"build_meteo_result",
|
|
19
|
-
"build_overlay_result",
|
|
20
|
-
"build_raster_result",
|
|
21
9
|
"build_reconstruct_result",
|
|
22
|
-
"build_region_trend_result",
|
|
23
10
|
"build_station_result",
|
|
24
|
-
"build_station_trend_result",
|
|
25
11
|
]
|
rsplot/result_builders/common.py
CHANGED
|
@@ -21,6 +21,9 @@ def serialize_region(region: RegionInfo) -> dict[str, Any]:
|
|
|
21
21
|
"level": region.level,
|
|
22
22
|
"extent": [round(value, 3) for value in region.extent],
|
|
23
23
|
}
|
|
24
|
+
if region.geometry_kind != "administrative":
|
|
25
|
+
result["geometry_kind"] = region.geometry_kind
|
|
26
|
+
result["level"] = None
|
|
24
27
|
if region.administrative_level not in (None, region.level):
|
|
25
28
|
result["administrative_level"] = region.administrative_level
|
|
26
29
|
if region.subdivision_level is not None:
|
|
@@ -212,7 +215,7 @@ def grid_boundary_policy(
|
|
|
212
215
|
},
|
|
213
216
|
"display": {
|
|
214
217
|
"selection": "valid_cells_intersecting_region",
|
|
215
|
-
"clip": "
|
|
218
|
+
"clip": f"{region.geometry_kind}_geometry",
|
|
216
219
|
"n_valid_intersecting_cells": int(visible.sum()),
|
|
217
220
|
"n_cells_with_centers_outside": int((visible & ~inside).sum()),
|
|
218
221
|
},
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
"""Shared result-sidecar envelope; see docs/result-schema.md."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import re
|
|
8
|
+
import shlex
|
|
9
|
+
import sys
|
|
10
|
+
from datetime import datetime
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import TYPE_CHECKING, Any
|
|
13
|
+
from zoneinfo import ZoneInfo
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
|
|
17
|
+
from rsplot.stats import basic_stats, round_finite
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from rsplot.geo.boundaries import RegionInfo
|
|
21
|
+
|
|
22
|
+
STAT_KEYS = ("mean", "std", "min", "p10", "p25", "median", "p75", "p90")
|
|
23
|
+
LOW_COVERAGE = 0.30
|
|
24
|
+
VERY_LOW_COVERAGE = 0.10
|
|
25
|
+
EXTREMES_LIMIT = 10
|
|
26
|
+
# Sidecar times are China time whatever the host clock's zone is.
|
|
27
|
+
CHINA_TIME = ZoneInfo("Asia/Shanghai")
|
|
28
|
+
# Subdivision drawn inside each region level when none is configured.
|
|
29
|
+
SUBDIVISION_LEVEL = {
|
|
30
|
+
"country": "province",
|
|
31
|
+
"key_region": "city",
|
|
32
|
+
"province": "city",
|
|
33
|
+
"city": "county",
|
|
34
|
+
"county": "township",
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def rsplot_version() -> str:
|
|
39
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
40
|
+
|
|
41
|
+
try:
|
|
42
|
+
return version("rsplot")
|
|
43
|
+
except PackageNotFoundError:
|
|
44
|
+
return "unknown"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
# Characters a POSIX shell treats specially; other text, such as Chinese
|
|
48
|
+
# region names, is written as typed.
|
|
49
|
+
SHELL_SPECIAL = re.compile(r"[\s'\"\\$`!*?;&|<>()\[\]{}#~]")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def command_line() -> str:
|
|
53
|
+
"""The command as received on one line, quoting only where needed."""
|
|
54
|
+
words = ["rsplot", *(str(arg) for arg in sys.argv[1:])]
|
|
55
|
+
return " ".join(
|
|
56
|
+
shlex.quote(word) if not word or SHELL_SPECIAL.search(word) else word
|
|
57
|
+
for word in words
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def region_block(
|
|
62
|
+
region: RegionInfo, radius: dict[str, Any] | None = None
|
|
63
|
+
) -> dict[str, Any]:
|
|
64
|
+
administrative = region.geometry_kind == "administrative"
|
|
65
|
+
block = {
|
|
66
|
+
"name": region.name,
|
|
67
|
+
"level": region.level if administrative else "station_radius",
|
|
68
|
+
"kind": "administrative" if administrative else "station_radius",
|
|
69
|
+
"bbox": [round(float(value), 3) for value in region.extent],
|
|
70
|
+
"members": [
|
|
71
|
+
{
|
|
72
|
+
"name": member.name,
|
|
73
|
+
"qualified_name": member.qualified_name,
|
|
74
|
+
"level": member.administrative_level or member.level,
|
|
75
|
+
}
|
|
76
|
+
for member in region.members
|
|
77
|
+
],
|
|
78
|
+
}
|
|
79
|
+
if radius is not None:
|
|
80
|
+
block["radius"] = radius
|
|
81
|
+
return block
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def subdivision_level(region: RegionInfo) -> str:
|
|
85
|
+
return region.subdivision_level or SUBDIVISION_LEVEL.get(
|
|
86
|
+
region.level, "subdivision"
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def stats_block(values: np.ndarray) -> dict[str, Any]:
|
|
91
|
+
"""Stable statistics over finite values; explicit nulls when empty."""
|
|
92
|
+
summary = basic_stats(values)
|
|
93
|
+
if not summary:
|
|
94
|
+
return {"n": 0, **dict.fromkeys(("max", *STAT_KEYS))}
|
|
95
|
+
finite = np.asarray(values)[np.isfinite(values)]
|
|
96
|
+
return {
|
|
97
|
+
"n": int(summary["n"]),
|
|
98
|
+
"mean": summary["mean"],
|
|
99
|
+
"std": round_finite(np.std(finite)),
|
|
100
|
+
"min": summary["min"],
|
|
101
|
+
"p10": summary["p10"],
|
|
102
|
+
"p25": summary["p25"],
|
|
103
|
+
"median": summary["median"],
|
|
104
|
+
"p75": summary["p75"],
|
|
105
|
+
"p90": summary["p90"],
|
|
106
|
+
"max": summary["max"],
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def coverage_block(valid: int, total: int, unit: str) -> dict[str, Any]:
|
|
111
|
+
return {
|
|
112
|
+
"valid": int(valid),
|
|
113
|
+
"total": int(total),
|
|
114
|
+
"fraction": round(valid / total, 3) if total else None,
|
|
115
|
+
"unit": unit,
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def capped(items: list[dict], total: int, order: str) -> dict[str, Any]:
|
|
120
|
+
kept = items[:EXTREMES_LIMIT]
|
|
121
|
+
return {
|
|
122
|
+
"items": kept,
|
|
123
|
+
"total": int(total),
|
|
124
|
+
"truncated": int(total) > len(kept),
|
|
125
|
+
"order": order,
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def flag(
|
|
130
|
+
code: str,
|
|
131
|
+
severity: str,
|
|
132
|
+
*,
|
|
133
|
+
evidence: dict[str, Any],
|
|
134
|
+
layer: str | None = None,
|
|
135
|
+
) -> dict[str, Any]:
|
|
136
|
+
"""A documented condition with the counts that triggered it, no prose."""
|
|
137
|
+
result: dict[str, Any] = {"code": code, "severity": severity}
|
|
138
|
+
if layer is not None:
|
|
139
|
+
result["layer"] = layer
|
|
140
|
+
result["evidence"] = evidence
|
|
141
|
+
return result
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def coverage_flags(layer: str, coverage: dict[str, Any]) -> list[dict]:
|
|
145
|
+
"""Flag grids whose regional statistics rest on few valid cells."""
|
|
146
|
+
fraction = coverage["fraction"]
|
|
147
|
+
evidence = {
|
|
148
|
+
"valid": coverage["valid"],
|
|
149
|
+
"total": coverage["total"],
|
|
150
|
+
"fraction": fraction,
|
|
151
|
+
}
|
|
152
|
+
if coverage["valid"] == 0:
|
|
153
|
+
return [
|
|
154
|
+
flag(
|
|
155
|
+
"no_valid_data",
|
|
156
|
+
"critical",
|
|
157
|
+
layer=layer,
|
|
158
|
+
evidence=evidence,
|
|
159
|
+
)
|
|
160
|
+
]
|
|
161
|
+
if fraction is not None and fraction < VERY_LOW_COVERAGE:
|
|
162
|
+
return [
|
|
163
|
+
flag(
|
|
164
|
+
"very_low_coverage",
|
|
165
|
+
"critical",
|
|
166
|
+
layer=layer,
|
|
167
|
+
evidence={**evidence, "threshold": VERY_LOW_COVERAGE},
|
|
168
|
+
)
|
|
169
|
+
]
|
|
170
|
+
if fraction is not None and fraction < LOW_COVERAGE:
|
|
171
|
+
return [
|
|
172
|
+
flag(
|
|
173
|
+
"low_coverage",
|
|
174
|
+
"warning",
|
|
175
|
+
layer=layer,
|
|
176
|
+
evidence={**evidence, "threshold": LOW_COVERAGE},
|
|
177
|
+
)
|
|
178
|
+
]
|
|
179
|
+
return []
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def success_envelope(
|
|
183
|
+
*,
|
|
184
|
+
command: str,
|
|
185
|
+
request: str,
|
|
186
|
+
region: RegionInfo | None,
|
|
187
|
+
layers: list[dict],
|
|
188
|
+
flags: list[dict],
|
|
189
|
+
render: dict,
|
|
190
|
+
artifacts: dict,
|
|
191
|
+
relations: dict | None = None,
|
|
192
|
+
radius: dict[str, Any] | None = None,
|
|
193
|
+
) -> dict[str, Any]:
|
|
194
|
+
return {
|
|
195
|
+
"command": command,
|
|
196
|
+
"rsplot_version": rsplot_version(),
|
|
197
|
+
"generated_at": datetime.now(CHINA_TIME).isoformat("T", "seconds"),
|
|
198
|
+
"request": request,
|
|
199
|
+
"region": None if region is None else region_block(region, radius),
|
|
200
|
+
"layers": layers,
|
|
201
|
+
"relations": relations or {},
|
|
202
|
+
"quality": {"flags": flags},
|
|
203
|
+
"render": render,
|
|
204
|
+
"artifacts": artifacts,
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def sidecar_path(output: str) -> str:
|
|
209
|
+
return str(Path(output).with_suffix(".json"))
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _jsonable(value: Any) -> Any:
|
|
213
|
+
"""Convert numpy scalars and non-finite floats; JSON has no NaN."""
|
|
214
|
+
if isinstance(value, dict):
|
|
215
|
+
return {str(key): _jsonable(item) for key, item in value.items()}
|
|
216
|
+
if isinstance(value, (list, tuple)):
|
|
217
|
+
return [_jsonable(item) for item in value]
|
|
218
|
+
if isinstance(value, np.generic):
|
|
219
|
+
value = value.item()
|
|
220
|
+
if isinstance(value, float) and not math.isfinite(value):
|
|
221
|
+
return None
|
|
222
|
+
return value
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def write_sidecar(payload: dict[str, Any], path: str) -> str:
|
|
226
|
+
from rsplot.atomic import atomic_write
|
|
227
|
+
|
|
228
|
+
with atomic_write(path) as temp, open(temp, "w", encoding="utf-8") as file:
|
|
229
|
+
json.dump(
|
|
230
|
+
_jsonable(payload),
|
|
231
|
+
file,
|
|
232
|
+
ensure_ascii=False,
|
|
233
|
+
indent=2,
|
|
234
|
+
allow_nan=False,
|
|
235
|
+
)
|
|
236
|
+
return path
|
rsplot/result_builders/fnr.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""FNR
|
|
1
|
+
"""Per-administrative-unit FNR summaries."""
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
@@ -6,17 +6,58 @@ from typing import TYPE_CHECKING, Any
|
|
|
6
6
|
|
|
7
7
|
import numpy as np
|
|
8
8
|
|
|
9
|
-
from rsplot.
|
|
10
|
-
from rsplot.result_builders.common import serialize_region
|
|
11
|
-
from rsplot.stats import basic_stats, round_finite
|
|
9
|
+
from rsplot.stats import round_finite
|
|
12
10
|
|
|
13
11
|
if TYPE_CHECKING:
|
|
14
12
|
import geopandas as gpd
|
|
15
13
|
|
|
16
|
-
from rsplot.fnr import FnrResult
|
|
17
14
|
from rsplot.geo.boundaries import RegionInfo
|
|
18
15
|
|
|
19
16
|
|
|
17
|
+
def fnr_regime(
|
|
18
|
+
mean_fnr: float, voc_threshold: float, nox_threshold: float
|
|
19
|
+
) -> str:
|
|
20
|
+
"""Classify a mean FNR with the command's regime thresholds."""
|
|
21
|
+
if mean_fnr < voc_threshold:
|
|
22
|
+
return "voc_limited"
|
|
23
|
+
if mean_fnr <= nox_threshold:
|
|
24
|
+
return "transition"
|
|
25
|
+
return "nox_limited"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def fnr_member_stats(
|
|
29
|
+
LON: np.ndarray,
|
|
30
|
+
LAT: np.ndarray,
|
|
31
|
+
fnr: np.ndarray,
|
|
32
|
+
region: RegionInfo,
|
|
33
|
+
*,
|
|
34
|
+
voc_threshold: float,
|
|
35
|
+
nox_threshold: float,
|
|
36
|
+
) -> list[dict[str, Any]]:
|
|
37
|
+
"""Summarize each comma-selected member, keeping empty members."""
|
|
38
|
+
from rsplot.geo.gridding import region_grid_mask
|
|
39
|
+
|
|
40
|
+
rows: list[dict[str, Any]] = []
|
|
41
|
+
for member in region.members:
|
|
42
|
+
finite = fnr[region_grid_mask(LON, LAT, member.geometry)]
|
|
43
|
+
finite = finite[np.isfinite(finite)]
|
|
44
|
+
mean_fnr = float(np.mean(finite)) if len(finite) else None
|
|
45
|
+
rows.append(
|
|
46
|
+
{
|
|
47
|
+
"name": member.qualified_name or member.name,
|
|
48
|
+
"level": member.administrative_level or member.level,
|
|
49
|
+
"n": len(finite),
|
|
50
|
+
"mean": None if mean_fnr is None else round_finite(mean_fnr),
|
|
51
|
+
"category": (
|
|
52
|
+
None
|
|
53
|
+
if mean_fnr is None
|
|
54
|
+
else fnr_regime(mean_fnr, voc_threshold, nox_threshold)
|
|
55
|
+
),
|
|
56
|
+
}
|
|
57
|
+
)
|
|
58
|
+
return rows
|
|
59
|
+
|
|
60
|
+
|
|
20
61
|
def fnr_per_admin_stats(
|
|
21
62
|
LON: np.ndarray,
|
|
22
63
|
LAT: np.ndarray,
|
|
@@ -37,12 +78,7 @@ def fnr_per_admin_stats(
|
|
|
37
78
|
if len(finite) == 0:
|
|
38
79
|
continue
|
|
39
80
|
mean_fnr = float(np.mean(finite))
|
|
40
|
-
|
|
41
|
-
regime = "voc_limited"
|
|
42
|
-
elif mean_fnr <= nox_threshold:
|
|
43
|
-
regime = "transition"
|
|
44
|
-
else:
|
|
45
|
-
regime = "nox_limited"
|
|
81
|
+
regime = fnr_regime(mean_fnr, voc_threshold, nox_threshold)
|
|
46
82
|
rows.append(
|
|
47
83
|
{
|
|
48
84
|
"name": row["name"],
|
|
@@ -67,123 +103,3 @@ def fnr_per_admin_stats(
|
|
|
67
103
|
)
|
|
68
104
|
)
|
|
69
105
|
return rows
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
def build_fnr_result(
|
|
73
|
-
*,
|
|
74
|
-
region: RegionInfo,
|
|
75
|
-
fnr_out: FnrResult,
|
|
76
|
-
res: float,
|
|
77
|
-
output: str,
|
|
78
|
-
qa_threshold: float | None = None,
|
|
79
|
-
cloud_fraction_max: float | None = None,
|
|
80
|
-
voc_threshold: float = FNR_VOC_LIMIT,
|
|
81
|
-
nox_threshold: float = FNR_NOX_LIMIT,
|
|
82
|
-
display_max: float = FNR_DISPLAY_MAX,
|
|
83
|
-
) -> dict[str, Any]:
|
|
84
|
-
"""Build the stable JSON sidecar for an FNR run."""
|
|
85
|
-
from shapely import contains_xy
|
|
86
|
-
|
|
87
|
-
from rsplot.fnr import regime_percentages, validate_fnr_thresholds
|
|
88
|
-
from rsplot.readers._tropomi import CLOUD_FRACTION_MAX
|
|
89
|
-
|
|
90
|
-
use_cloud_fraction_max = (
|
|
91
|
-
CLOUD_FRACTION_MAX
|
|
92
|
-
if cloud_fraction_max is None
|
|
93
|
-
else cloud_fraction_max
|
|
94
|
-
)
|
|
95
|
-
|
|
96
|
-
voc_threshold, nox_threshold, display_max = validate_fnr_thresholds(
|
|
97
|
-
voc_threshold=voc_threshold,
|
|
98
|
-
nox_threshold=nox_threshold,
|
|
99
|
-
display_max=display_max,
|
|
100
|
-
)
|
|
101
|
-
fnr = fnr_out.fnr
|
|
102
|
-
region_mask = contains_xy(region.geometry, fnr_out.LON, fnr_out.LAT)
|
|
103
|
-
total_region_pixels = int(region_mask.sum())
|
|
104
|
-
n_valid_fnr = int(np.isfinite(fnr).sum())
|
|
105
|
-
coverage_pct = (
|
|
106
|
-
round(100 * n_valid_fnr / total_region_pixels, 3)
|
|
107
|
-
if total_region_pixels
|
|
108
|
-
else 0.0
|
|
109
|
-
)
|
|
110
|
-
both_valid_days = np.minimum(
|
|
111
|
-
fnr_out.n_valid_hcho,
|
|
112
|
-
fnr_out.n_valid_no2,
|
|
113
|
-
)
|
|
114
|
-
covered = both_valid_days[(both_valid_days > 0) & region_mask]
|
|
115
|
-
coverage_days = {
|
|
116
|
-
"min": int(covered.min()) if len(covered) else 0,
|
|
117
|
-
"max": int(covered.max()) if len(covered) else 0,
|
|
118
|
-
"mean": round(float(covered.mean()), 1) if len(covered) else 0.0,
|
|
119
|
-
}
|
|
120
|
-
diagnostic_masks = {
|
|
121
|
-
name: mask & region_mask
|
|
122
|
-
for name, mask in fnr_out.diagnostic_masks.items()
|
|
123
|
-
}
|
|
124
|
-
mask_diagnostics = {
|
|
125
|
-
"total_region_pixels": total_region_pixels,
|
|
126
|
-
"coverage_ge_n_min_pixels": int(diagnostic_masks["coverage_ok"].sum()),
|
|
127
|
-
"no2_ge_threshold_pixels": int(diagnostic_masks["no2_ok"].sum()),
|
|
128
|
-
"hcho_nonnegative_pixels": int(diagnostic_masks["hcho_ok"].sum()),
|
|
129
|
-
"final_valid_pixels": n_valid_fnr,
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
result: dict[str, Any] = {
|
|
133
|
-
"command": "fnr",
|
|
134
|
-
"image": output,
|
|
135
|
-
"region": serialize_region(region),
|
|
136
|
-
"window": {
|
|
137
|
-
"start": fnr_out.dates_requested[0],
|
|
138
|
-
"end": fnr_out.dates_requested[-1],
|
|
139
|
-
"n_days_requested": len(fnr_out.dates_requested),
|
|
140
|
-
"n_days_found_no2": len(fnr_out.dates_found_no2),
|
|
141
|
-
"n_days_found_hcho": len(fnr_out.dates_found_hcho),
|
|
142
|
-
"dates_failed_no2": fnr_out.dates_failed_no2,
|
|
143
|
-
"dates_failed_hcho": fnr_out.dates_failed_hcho,
|
|
144
|
-
},
|
|
145
|
-
"params": {
|
|
146
|
-
"n_min": fnr_out.n_min,
|
|
147
|
-
"no2_min_column": fnr_out.no2_min_column,
|
|
148
|
-
"voc_threshold": voc_threshold,
|
|
149
|
-
"nox_threshold": nox_threshold,
|
|
150
|
-
"display_max": display_max,
|
|
151
|
-
"resolution_deg": res,
|
|
152
|
-
"cloud_fraction_max": use_cloud_fraction_max,
|
|
153
|
-
},
|
|
154
|
-
"stats": {
|
|
155
|
-
"grid_shape": list(fnr.shape),
|
|
156
|
-
"coverage_pct": coverage_pct,
|
|
157
|
-
"valid_pixels": n_valid_fnr,
|
|
158
|
-
"total_region_pixels": total_region_pixels,
|
|
159
|
-
"coverage_days": coverage_days,
|
|
160
|
-
"mask_diagnostics": mask_diagnostics,
|
|
161
|
-
**basic_stats(fnr),
|
|
162
|
-
},
|
|
163
|
-
"regime_pct": regime_percentages(
|
|
164
|
-
fnr,
|
|
165
|
-
voc_threshold=voc_threshold,
|
|
166
|
-
nox_threshold=nox_threshold,
|
|
167
|
-
),
|
|
168
|
-
"mean_fields": {
|
|
169
|
-
"hcho_mean_raw_stats": basic_stats(fnr_out.hcho_mean),
|
|
170
|
-
"no2_mean_raw_stats": basic_stats(fnr_out.no2_mean),
|
|
171
|
-
"hcho_mean_filled_stats": basic_stats(fnr_out.hcho_mean_filled),
|
|
172
|
-
"no2_mean_filled_stats": basic_stats(fnr_out.no2_mean_filled),
|
|
173
|
-
},
|
|
174
|
-
}
|
|
175
|
-
if qa_threshold is not None:
|
|
176
|
-
result["params"]["qa_threshold"] = qa_threshold
|
|
177
|
-
|
|
178
|
-
sub_gdf = region.sub_boundary_gdf
|
|
179
|
-
if sub_gdf is not None and len(sub_gdf) > 0:
|
|
180
|
-
result["city_ranking"] = fnr_per_admin_stats(
|
|
181
|
-
fnr_out.LON,
|
|
182
|
-
fnr_out.LAT,
|
|
183
|
-
fnr,
|
|
184
|
-
sub_gdf,
|
|
185
|
-
voc_threshold=voc_threshold,
|
|
186
|
-
nox_threshold=nox_threshold,
|
|
187
|
-
)
|
|
188
|
-
|
|
189
|
-
return result
|