rsplot 0.3.1.dev3__py3-none-any.whl → 0.3.2.dev37__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- rsplot/atomic.py +36 -0
- rsplot/cli.py +282 -469
- rsplot/commands/common.py +113 -1
- rsplot/commands/fnr.py +389 -104
- rsplot/commands/forecast.py +24 -7
- rsplot/commands/meteo.py +499 -186
- rsplot/commands/overlay.py +292 -205
- rsplot/commands/radius.py +526 -0
- rsplot/commands/raster.py +479 -230
- rsplot/commands/reconstruct.py +27 -6
- rsplot/commands/sidecar.py +106 -0
- rsplot/commands/station.py +154 -42
- rsplot/commands/station_trend.py +259 -174
- rsplot/config.py +46 -16
- rsplot/data_files.py +253 -0
- rsplot/errors.py +43 -0
- rsplot/fnr.py +38 -46
- rsplot/geo/boundaries.py +317 -11
- rsplot/geo/footprints.py +205 -0
- rsplot/geo/processing.py +84 -5
- rsplot/geo/radius.py +205 -0
- rsplot/plotting/colormap_22.txt +256 -0
- rsplot/plotting/colormaps.py +24 -29
- rsplot/plotting/map_frame.py +203 -9
- rsplot/plotting/meteo.py +10 -3
- rsplot/plotting/overlay.py +36 -40
- rsplot/plotting/raster.py +15 -3
- rsplot/plotting/station.py +86 -33
- rsplot/plotting/station_focus.py +84 -0
- rsplot/plotting/station_trend.py +60 -47
- rsplot/plotting/styles.py +3 -5
- rsplot/readers/__init__.py +89 -7
- rsplot/readers/_tropomi.py +121 -3
- rsplot/readers/base.py +16 -1
- rsplot/readers/era5.py +110 -10
- rsplot/readers/era5_wind.py +3 -2
- rsplot/readers/gems.py +429 -0
- rsplot/readers/guokong.py +125 -39
- rsplot/readers/netcdf.py +32 -0
- rsplot/readers/tropomi_hcho.py +1 -1
- rsplot/readers/tropomi_no2.py +1 -1
- rsplot/readers/tropomi_nrti.py +116 -0
- rsplot/readers/tropomi_o3.py +1 -1
- rsplot/readers/tropomi_o3pr.py +1 -1
- rsplot/result_builders/__init__.py +0 -14
- rsplot/result_builders/common.py +84 -0
- rsplot/result_builders/envelope.py +236 -0
- rsplot/result_builders/fnr.py +47 -131
- rsplot/result_builders/forecast.py +7 -0
- rsplot/result_builders/provenance.py +59 -0
- rsplot/result_builders/reconstruct.py +7 -0
- rsplot/result_builders/satellite.py +240 -0
- rsplot/result_builders/series_layer.py +289 -0
- rsplot/result_builders/station.py +23 -0
- rsplot/result_builders/station_layer.py +326 -0
- rsplot/results.py +0 -12
- rsplot/schemas/result.schema.json +566 -0
- rsplot/temporal.py +146 -16
- rsplot-0.3.2.dev37.dist-info/METADATA +996 -0
- rsplot-0.3.2.dev37.dist-info/RECORD +76 -0
- {rsplot-0.3.1.dev3.dist-info → rsplot-0.3.2.dev37.dist-info}/WHEEL +1 -1
- rsplot/commands/recent.py +0 -164
- rsplot/recent.py +0 -404
- rsplot/result_builders/meteo.py +0 -171
- rsplot/result_builders/overlay.py +0 -75
- rsplot/result_builders/raster.py +0 -72
- rsplot/result_builders/station_trend.py +0 -229
- rsplot-0.3.1.dev3.dist-info/METADATA +0 -477
- rsplot-0.3.1.dev3.dist-info/RECORD +0 -64
- {rsplot-0.3.1.dev3.dist-info → rsplot-0.3.2.dev37.dist-info}/entry_points.txt +0 -0
- {rsplot-0.3.1.dev3.dist-info → rsplot-0.3.2.dev37.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,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
|
|
@@ -7,6 +7,7 @@ from typing import TYPE_CHECKING, Any
|
|
|
7
7
|
import numpy as np
|
|
8
8
|
|
|
9
9
|
from rsplot.result_builders.common import (
|
|
10
|
+
grid_boundary_policy,
|
|
10
11
|
grid_per_admin_stats,
|
|
11
12
|
serialize_region,
|
|
12
13
|
top_hotspots,
|
|
@@ -33,6 +34,7 @@ def build_forecast_result(
|
|
|
33
34
|
vmin: float,
|
|
34
35
|
vmax: float,
|
|
35
36
|
output: str,
|
|
37
|
+
display_grid: np.ndarray | None = None,
|
|
36
38
|
station_data: StationData | None = None,
|
|
37
39
|
station_datetime: str | None = None,
|
|
38
40
|
station_threshold: float | None = None,
|
|
@@ -100,6 +102,11 @@ def build_forecast_result(
|
|
|
100
102
|
station_block.pop(key, None)
|
|
101
103
|
result["station"] = station_block
|
|
102
104
|
|
|
105
|
+
if display_grid is not None:
|
|
106
|
+
result["boundary_policy"] = grid_boundary_policy(
|
|
107
|
+
LON, LAT, display_grid, region
|
|
108
|
+
)
|
|
109
|
+
|
|
103
110
|
sub_gdf = region.sub_boundary_gdf
|
|
104
111
|
if sub_gdf is not None and len(sub_gdf) > 0:
|
|
105
112
|
result["spatial_summary"] = grid_per_admin_stats(
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Fingerprint a layer's input files without listing them."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import os
|
|
7
|
+
from collections.abc import Iterable
|
|
8
|
+
from datetime import datetime
|
|
9
|
+
from typing import Any
|
|
10
|
+
from zoneinfo import ZoneInfo
|
|
11
|
+
|
|
12
|
+
from rsplot.temporal import DEFAULT_INPUT_TIMEZONE
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def input_fingerprint(data_root: str, paths: Iterable[str]) -> dict[str, Any]:
|
|
16
|
+
"""Return ``inputs_digest`` and ``data_as_of`` for a ``source`` block.
|
|
17
|
+
|
|
18
|
+
The digest hashes each input's name relative to ``data_root``, size and
|
|
19
|
+
modification time, so a later run can tell whether the same request
|
|
20
|
+
now reads different files (an NRTI day that gained granules). Paths
|
|
21
|
+
may be absolute or relative to ``data_root``; files that no longer
|
|
22
|
+
exist are skipped. ``data_as_of`` is the latest modification time.
|
|
23
|
+
"""
|
|
24
|
+
rows: list[str] = []
|
|
25
|
+
latest: int | None = None
|
|
26
|
+
for path in set(paths):
|
|
27
|
+
full = os.path.join(data_root, path)
|
|
28
|
+
try:
|
|
29
|
+
stat = os.stat(full)
|
|
30
|
+
except OSError:
|
|
31
|
+
continue
|
|
32
|
+
name = os.path.relpath(full, data_root)
|
|
33
|
+
rows.append(f"{name}\t{stat.st_size}\t{stat.st_mtime_ns}")
|
|
34
|
+
latest = max(latest or 0, stat.st_mtime_ns)
|
|
35
|
+
digest = hashlib.sha256("\n".join(sorted(rows)).encode()).hexdigest()
|
|
36
|
+
return {
|
|
37
|
+
"inputs_digest": f"sha256:{digest}",
|
|
38
|
+
"data_as_of": None if latest is None else _china_time(latest),
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def combined_fingerprint(sources: Iterable[dict[str, Any]]) -> dict[str, Any]:
|
|
43
|
+
"""Fingerprint a layer derived from other layers' ``source`` blocks."""
|
|
44
|
+
sources = list(sources)
|
|
45
|
+
digest = hashlib.sha256(
|
|
46
|
+
"\n".join(source["inputs_digest"] for source in sources).encode()
|
|
47
|
+
).hexdigest()
|
|
48
|
+
stamps = [s["data_as_of"] for s in sources if s["data_as_of"]]
|
|
49
|
+
return {
|
|
50
|
+
"inputs_digest": f"sha256:{digest}",
|
|
51
|
+
"data_as_of": max(stamps, default=None),
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _china_time(mtime_ns: int) -> str:
|
|
56
|
+
moment = datetime.fromtimestamp(
|
|
57
|
+
mtime_ns / 1e9, ZoneInfo(DEFAULT_INPUT_TIMEZONE)
|
|
58
|
+
)
|
|
59
|
+
return moment.strftime("%Y-%m-%dT%H:%M:%S")
|
|
@@ -7,6 +7,7 @@ from typing import TYPE_CHECKING, Any
|
|
|
7
7
|
import numpy as np
|
|
8
8
|
|
|
9
9
|
from rsplot.result_builders.common import (
|
|
10
|
+
grid_boundary_policy,
|
|
10
11
|
grid_per_admin_stats,
|
|
11
12
|
grid_stats,
|
|
12
13
|
serialize_region,
|
|
@@ -29,6 +30,7 @@ def build_reconstruct_result(
|
|
|
29
30
|
vmin: float,
|
|
30
31
|
vmax: float,
|
|
31
32
|
output: str,
|
|
33
|
+
display_grid: np.ndarray | None = None,
|
|
32
34
|
) -> dict[str, Any]:
|
|
33
35
|
"""Build the stable JSON sidecar payload for a reconstructed grid."""
|
|
34
36
|
stats = grid_stats(
|
|
@@ -72,6 +74,11 @@ def build_reconstruct_result(
|
|
|
72
74
|
"stats": stats,
|
|
73
75
|
}
|
|
74
76
|
|
|
77
|
+
if display_grid is not None:
|
|
78
|
+
result["boundary_policy"] = grid_boundary_policy(
|
|
79
|
+
LON, LAT, display_grid, region
|
|
80
|
+
)
|
|
81
|
+
|
|
75
82
|
sub_gdf = region.sub_boundary_gdf
|
|
76
83
|
if sub_gdf is not None and len(sub_gdf) > 0:
|
|
77
84
|
result["spatial_summary"] = grid_per_admin_stats(
|