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
@@ -0,0 +1,240 @@
1
+ """The ``satellite`` grid layer of a result sidecar."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from dataclasses import dataclass, field
7
+ from typing import TYPE_CHECKING, Any
8
+
9
+ import numpy as np
10
+
11
+ from rsplot.result_builders.common import (
12
+ grid_member_stats,
13
+ grid_per_admin_stats,
14
+ top_hotspots,
15
+ )
16
+ from rsplot.result_builders.envelope import (
17
+ capped,
18
+ coverage_block,
19
+ coverage_flags,
20
+ flag,
21
+ stats_block,
22
+ subdivision_level,
23
+ )
24
+ from rsplot.result_builders.provenance import input_fingerprint
25
+
26
+ if TYPE_CHECKING:
27
+ from rsplot.geo.boundaries import RegionInfo
28
+ from rsplot.readers import ProductInfo
29
+
30
+
31
+ @dataclass
32
+ class SatelliteInputs:
33
+ """Everything prepare_raster knows about the statistical grid."""
34
+
35
+ prod_info: ProductInfo
36
+ lon: np.ndarray
37
+ lat: np.ndarray
38
+ grid: np.ndarray
39
+ counted: np.ndarray
40
+ time: dict[str, Any]
41
+ data_root: str
42
+ metadata: list[dict[str, Any]]
43
+ method: dict[str, Any]
44
+ valid_days: np.ndarray | None = None
45
+ days: dict[str, Any] | None = None
46
+ extra_flags: list[dict[str, Any]] = field(default_factory=list)
47
+
48
+
49
+ def collect_provenance(
50
+ metadata: list[dict[str, Any]], data_root: str
51
+ ) -> tuple[list[str], dict[str, str], dict[str, list[str]]]:
52
+ """Gather input files, failures and versions from reader metadata."""
53
+ files: set[str] = set()
54
+ failed: dict[str, str] = {}
55
+ versions: dict[str, set[str]] = {}
56
+
57
+ def relative(path: str) -> str:
58
+ try:
59
+ relpath = os.path.relpath(path, data_root)
60
+ except ValueError:
61
+ return path
62
+ return path if relpath.startswith("..") else relpath
63
+
64
+ def add_version(kind: str, value: Any) -> None:
65
+ if value:
66
+ versions.setdefault(kind, set()).add(str(value))
67
+
68
+ def visit(meta: dict[str, Any]) -> None:
69
+ for path in meta.get("source_files", []):
70
+ files.add(relative(path))
71
+ for path, reason in meta.get("failed_files", {}).items():
72
+ failed[relative(path)] = reason
73
+ for value in meta.get("processor_versions", []):
74
+ add_version("processor", value)
75
+ for value in meta.get("product_versions", []):
76
+ add_version("product", value)
77
+ if "file" in meta:
78
+ files.add(relative(meta["file"]))
79
+ if "error" in meta:
80
+ failed[relative(meta["file"])] = meta["error"]
81
+ add_version("product", meta.get("product_version"))
82
+ for scan in meta.get("scans", []):
83
+ visit(scan)
84
+
85
+ for meta in metadata:
86
+ visit(meta)
87
+ return (
88
+ sorted(files),
89
+ dict(sorted(failed.items())),
90
+ {kind: sorted(values) for kind, values in versions.items()},
91
+ )
92
+
93
+
94
+ def build_satellite_layer(
95
+ inputs: SatelliteInputs,
96
+ region: RegionInfo,
97
+ *,
98
+ data: str | None,
99
+ layer_id: str = "satellite",
100
+ coverage_checks: bool = True,
101
+ ) -> tuple[dict[str, Any], list[dict[str, Any]]]:
102
+ """Return the satellite layer and the quality flags it raises.
103
+
104
+ ``coverage_checks=False`` skips regional coverage flags for input layers
105
+ whose own coverage is not the result (e.g. FNR's NO2 and HCHO means).
106
+ """
107
+ prod = inputs.prod_info
108
+ files, failed, versions = collect_provenance(
109
+ inputs.metadata, inputs.data_root
110
+ )
111
+ valid = np.isfinite(inputs.grid) & inputs.counted
112
+ coverage = coverage_block(
113
+ int(valid.sum()), int(inputs.counted.sum()), "cells"
114
+ )
115
+ time = dict(inputs.time)
116
+ if inputs.days is not None:
117
+ time["days"] = inputs.days
118
+
119
+ sub_gdf = region.sub_boundary_gdf
120
+ has_subdivisions = sub_gdf is not None and len(sub_gdf) > 0
121
+ by_admin = []
122
+ if has_subdivisions:
123
+ level = subdivision_level(region)
124
+ by_admin = [
125
+ {
126
+ "name": row["name"],
127
+ "level": level,
128
+ "n": int(row["n_pixels"]),
129
+ "mean": row["mean"],
130
+ "min": row["min"],
131
+ "max": row["max"],
132
+ }
133
+ for row in grid_per_admin_stats(
134
+ inputs.lon, inputs.lat, inputs.grid, sub_gdf
135
+ )
136
+ ]
137
+ hotspots = top_hotspots(
138
+ inputs.lon,
139
+ inputs.lat,
140
+ inputs.grid,
141
+ sub_gdf if has_subdivisions else None,
142
+ n=10,
143
+ )
144
+ layer: dict[str, Any] = {
145
+ "id": layer_id,
146
+ "kind": "grid",
147
+ "quantity": {
148
+ "name": prod.quantity,
149
+ "unit": prod.unit,
150
+ "scale": prod.unit_scale,
151
+ "label": prod.colorbar_label,
152
+ },
153
+ "time": time,
154
+ "source": {
155
+ "sensor": prod.sensor,
156
+ "processing": (
157
+ prod.processing or "offl" if prod.sensor == "tropomi" else None
158
+ ),
159
+ "data_root": inputs.data_root,
160
+ "files_total": len(files),
161
+ "failed_files": failed,
162
+ "versions": versions,
163
+ **input_fingerprint(inputs.data_root, [*files, *failed]),
164
+ },
165
+ "method": inputs.method,
166
+ "coverage": coverage,
167
+ "stats": stats_block(inputs.grid[inputs.counted]),
168
+ "by_admin": by_admin,
169
+ "extremes": capped(
170
+ [
171
+ {
172
+ "lon": item["lon"],
173
+ "lat": item["lat"],
174
+ "value": item["value"],
175
+ "admin": item["city"],
176
+ }
177
+ for item in hotspots
178
+ ],
179
+ coverage["valid"],
180
+ "value_desc",
181
+ ),
182
+ "data": data,
183
+ }
184
+ if region.members:
185
+ layer["by_member"] = [
186
+ {
187
+ "name": row["region"]["name"],
188
+ "level": row["region"].get("administrative_level")
189
+ or row["region"]["level"],
190
+ "n": int(row["stats"]["n"]),
191
+ "mean": row["stats"]["mean"],
192
+ "min": row["stats"]["min"],
193
+ "max": row["stats"]["max"],
194
+ }
195
+ for row in grid_member_stats(
196
+ inputs.lon, inputs.lat, inputs.grid, region
197
+ )
198
+ ]
199
+
200
+ flags = coverage_flags(layer_id, coverage) if coverage_checks else []
201
+ days = inputs.days
202
+ if days is not None and days["found"] < days["requested"]:
203
+ flags.append(
204
+ flag(
205
+ "missing_days",
206
+ "warning",
207
+ layer=layer_id,
208
+ evidence={
209
+ "requested": days["requested"],
210
+ "found": days["found"],
211
+ "failed": days["failed"],
212
+ },
213
+ )
214
+ )
215
+ if days is not None and inputs.valid_days is not None:
216
+ observed = inputs.valid_days[inputs.counted & (inputs.valid_days > 0)]
217
+ median = float(np.median(observed)) if observed.size else 0.0
218
+ if median < days["n_min"]:
219
+ flags.append(
220
+ flag(
221
+ "few_valid_days",
222
+ "warning",
223
+ layer=layer_id,
224
+ evidence={
225
+ "median_valid_days": median,
226
+ "n_min": days["n_min"],
227
+ },
228
+ )
229
+ )
230
+ if failed:
231
+ flags.append(
232
+ flag(
233
+ "failed_files",
234
+ "warning",
235
+ layer=layer_id,
236
+ evidence={"count": len(failed)},
237
+ )
238
+ )
239
+ flags.extend(inputs.extra_flags)
240
+ return layer, flags
@@ -0,0 +1,289 @@
1
+ """Hourly ``series`` layers for station and regional trends."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import numpy as np
8
+
9
+ from rsplot.result_builders.envelope import (
10
+ capped,
11
+ coverage_block,
12
+ flag,
13
+ stats_block,
14
+ )
15
+ from rsplot.stats import round_finite
16
+
17
+ COMPLETE_HOURS = 0.90
18
+ MIN_STATIONS = 3
19
+
20
+
21
+ def series_time(dates: list[str]) -> dict[str, Any]:
22
+ return {
23
+ "aggregation": "hourly_series",
24
+ "start": dates[0],
25
+ "end": dates[-1],
26
+ "basis": "station_hour",
27
+ }
28
+
29
+
30
+ def series_quantity(var: str, unit: str) -> dict[str, Any]:
31
+ return {
32
+ "name": var,
33
+ "unit": unit or "1",
34
+ "scale": 1,
35
+ "label": f"{var} ({unit})" if unit else var,
36
+ }
37
+
38
+
39
+ def exceedance_block(
40
+ values: np.ndarray, threshold: float | None, standard: str | None
41
+ ) -> dict[str, Any] | None:
42
+ if threshold is None:
43
+ return None
44
+ finite = values[np.isfinite(values)]
45
+ count = int((finite > threshold).sum())
46
+ return {
47
+ "threshold": threshold,
48
+ "operator": ">",
49
+ "standard": standard,
50
+ "count": count,
51
+ "fraction": round(count / finite.size, 3) if finite.size else None,
52
+ }
53
+
54
+
55
+ def missing_hours_flag(layer_id: str, coverage: dict) -> list[dict]:
56
+ fraction = coverage["fraction"]
57
+ if fraction is None or fraction >= COMPLETE_HOURS:
58
+ return []
59
+ return [
60
+ flag(
61
+ "missing_hours",
62
+ "warning",
63
+ layer=layer_id,
64
+ evidence={**coverage, "threshold": COMPLETE_HOURS},
65
+ )
66
+ ]
67
+
68
+
69
+ def daily_rows(
70
+ timestamps: list[str], values: np.ndarray
71
+ ) -> list[dict[str, Any]]:
72
+ """One row per China-time day: valid hours, mean, min and max."""
73
+ days: dict[str, list[float]] = {}
74
+ for stamp, value in zip(timestamps, values, strict=True):
75
+ days.setdefault(stamp[:8], []).append(float(value))
76
+ rows = []
77
+ for date, day_values in days.items():
78
+ finite = np.asarray(day_values)[np.isfinite(day_values)]
79
+ empty = finite.size == 0
80
+ rows.append(
81
+ {
82
+ "date": date,
83
+ "hours": int(finite.size),
84
+ "mean": None if empty else round_finite(np.mean(finite)),
85
+ "min": None if empty else round_finite(np.min(finite)),
86
+ "max": None if empty else round_finite(np.max(finite)),
87
+ }
88
+ )
89
+ return rows
90
+
91
+
92
+ def diurnal_rows(
93
+ timestamps: list[str], values: np.ndarray
94
+ ) -> list[dict[str, Any]]:
95
+ """One row per China-time hour of day: valid days and their mean."""
96
+ hours = np.array([int(stamp[8:10]) for stamp in timestamps])
97
+ rows = []
98
+ for hour in range(24):
99
+ selected = values[hours == hour]
100
+ finite = selected[np.isfinite(selected)]
101
+ rows.append(
102
+ {
103
+ "hour": hour,
104
+ "days": int(finite.size),
105
+ "mean": round_finite(np.mean(finite)) if finite.size else None,
106
+ }
107
+ )
108
+ return rows
109
+
110
+
111
+ def station_series_layer(
112
+ *,
113
+ station_id: str,
114
+ var: str,
115
+ unit: str,
116
+ timestamps: list[str],
117
+ values: np.ndarray,
118
+ dates: list[str],
119
+ source: dict[str, Any],
120
+ threshold: float | None,
121
+ standard: str | None,
122
+ data: str,
123
+ ) -> tuple[dict[str, Any], list[dict]]:
124
+ """One station's hours as a ``series`` layer."""
125
+ valid = np.isfinite(values)
126
+ coverage = coverage_block(int(valid.sum()), len(values), "hours")
127
+ order = np.flatnonzero(valid)[np.argsort(values[valid])[::-1]]
128
+ layer: dict[str, Any] = {
129
+ "id": "station",
130
+ "kind": "series",
131
+ "subject": {"station_id": station_id},
132
+ "quantity": series_quantity(var, unit),
133
+ "time": series_time(dates),
134
+ "source": source,
135
+ "method": {"gaps": "kept_as_missing", "hours_per_day": 24},
136
+ "coverage": coverage,
137
+ "stats": stats_block(values),
138
+ "daily": daily_rows(timestamps, values),
139
+ "diurnal": diurnal_rows(timestamps, values),
140
+ "by_admin": [],
141
+ "extremes": capped(
142
+ [
143
+ {
144
+ "datetime": timestamps[index],
145
+ "value": round_finite(values[index]),
146
+ }
147
+ for index in order
148
+ ],
149
+ coverage["valid"],
150
+ "value_desc",
151
+ ),
152
+ "data": data,
153
+ }
154
+ exceedance = exceedance_block(values, threshold, standard)
155
+ if exceedance is not None:
156
+ layer["exceedance"] = exceedance
157
+ flags = missing_hours_flag("station", coverage)
158
+ if source["failed_files"]:
159
+ flags.append(
160
+ flag(
161
+ "failed_files",
162
+ "warning",
163
+ layer="station",
164
+ evidence={"count": len(source["failed_files"])},
165
+ )
166
+ )
167
+ return layer, flags
168
+
169
+
170
+ def region_series_layers(
171
+ *,
172
+ station_ids: np.ndarray,
173
+ lon: np.ndarray,
174
+ lat: np.ndarray,
175
+ var: str,
176
+ unit: str,
177
+ timestamps: list[str],
178
+ values: np.ndarray,
179
+ mean: np.ndarray,
180
+ counts: np.ndarray,
181
+ dates: list[str],
182
+ source: dict[str, Any],
183
+ threshold: float | None,
184
+ standard: str | None,
185
+ data: str,
186
+ ) -> tuple[list[dict[str, Any]], list[dict]]:
187
+ """The hourly regional mean and every station's hours."""
188
+ quantity = series_quantity(var, unit)
189
+ time = series_time(dates)
190
+ mean_coverage = coverage_block(
191
+ int((counts > 0).sum()), len(counts), "hours"
192
+ )
193
+ mean_valid = np.isfinite(mean)
194
+ mean_order = np.flatnonzero(mean_valid)[np.argsort(mean[mean_valid])[::-1]]
195
+ regional: dict[str, Any] = {
196
+ "id": "regional_mean",
197
+ "kind": "series",
198
+ "quantity": quantity,
199
+ "time": time,
200
+ "source": source,
201
+ "method": {
202
+ "aggregation": "mean_over_stations_with_value",
203
+ "gaps": "kept_as_missing",
204
+ },
205
+ "coverage": mean_coverage,
206
+ "stats": stats_block(mean),
207
+ "daily": daily_rows(timestamps, mean),
208
+ "diurnal": diurnal_rows(timestamps, mean),
209
+ "by_admin": [],
210
+ "extremes": capped(
211
+ [
212
+ {
213
+ "datetime": timestamps[index],
214
+ "value": round_finite(mean[index]),
215
+ "n_stations": int(counts[index]),
216
+ }
217
+ for index in mean_order
218
+ ],
219
+ mean_coverage["valid"],
220
+ "value_desc",
221
+ ),
222
+ "data": data,
223
+ }
224
+ mean_exceedance = exceedance_block(mean, threshold, standard)
225
+ if mean_exceedance is not None:
226
+ regional["exceedance"] = mean_exceedance
227
+
228
+ has_data = np.isfinite(values).any(axis=1)
229
+ station_rows = []
230
+ for index in np.flatnonzero(has_data):
231
+ row_values = values[index]
232
+ finite = row_values[np.isfinite(row_values)]
233
+ item: dict[str, Any] = {
234
+ "id": str(station_ids[index]),
235
+ "lon": round(float(lon[index]), 3),
236
+ "lat": round(float(lat[index]), 3),
237
+ "value": round_finite(np.max(finite)),
238
+ "mean": round_finite(np.mean(finite)),
239
+ "hours_valid": int(finite.size),
240
+ }
241
+ if threshold is not None:
242
+ item["n_exceed"] = int((finite > threshold).sum())
243
+ station_rows.append(item)
244
+ station_rows.sort(key=lambda row: -(row["value"] or 0))
245
+ station_coverage = coverage_block(
246
+ int(has_data.sum()), len(station_ids), "stations"
247
+ )
248
+ stations: dict[str, Any] = {
249
+ "id": "station",
250
+ "kind": "series",
251
+ "quantity": quantity,
252
+ "time": time,
253
+ "source": source,
254
+ "method": {
255
+ "region_selection": "point_inside_region",
256
+ "gaps": "kept_as_missing",
257
+ },
258
+ "coverage": station_coverage,
259
+ "stats": stats_block(values),
260
+ "by_admin": [],
261
+ "extremes": capped(
262
+ station_rows, station_coverage["valid"], "max_value_desc"
263
+ ),
264
+ "data": data,
265
+ }
266
+ station_exceedance = exceedance_block(values, threshold, standard)
267
+ if station_exceedance is not None:
268
+ stations["exceedance"] = station_exceedance
269
+
270
+ flags = missing_hours_flag("regional_mean", mean_coverage)
271
+ if station_coverage["valid"] < MIN_STATIONS:
272
+ flags.append(
273
+ flag(
274
+ "few_stations",
275
+ "warning",
276
+ layer="station",
277
+ evidence={**station_coverage, "threshold": MIN_STATIONS},
278
+ )
279
+ )
280
+ if source["failed_files"]:
281
+ flags.append(
282
+ flag(
283
+ "failed_files",
284
+ "warning",
285
+ layer="station",
286
+ evidence={"count": len(source["failed_files"])},
287
+ )
288
+ )
289
+ return [regional, stations], flags
@@ -6,6 +6,7 @@ from typing import TYPE_CHECKING, Any
6
6
 
7
7
  import numpy as np
8
8
 
9
+ from rsplot.config import get_station_color_scale
9
10
  from rsplot.result_builders.common import serialize_region
10
11
  from rsplot.stats import basic_stats, round_finite
11
12
 
@@ -97,6 +98,24 @@ def top_station_entries(
97
98
  return entries
98
99
 
99
100
 
101
+ def build_station_display(data: StationData) -> dict[str, Any] | None:
102
+ """Describe the fixed scale shared by station map renderers."""
103
+ scale = get_station_color_scale(data.var_name)
104
+ if scale is None:
105
+ return None
106
+ return {
107
+ "colorbar": bool(np.isfinite(data.values).any()),
108
+ "cmap": scale.cmap,
109
+ "range_method": "fixed_exceedance",
110
+ "vmin": scale.vmin,
111
+ "vmax": scale.vmax,
112
+ "threshold": scale.threshold,
113
+ "exceedance_operator": ">",
114
+ "exceedance_color": scale.exceedance_color,
115
+ "extend": "max",
116
+ }
117
+
118
+
100
119
  def build_station_result(
101
120
  *,
102
121
  region: RegionInfo,
@@ -133,6 +152,10 @@ def build_station_result(
133
152
  "stats": basic_stats(values),
134
153
  }
135
154
 
155
+ display = build_station_display(data)
156
+ if display is not None:
157
+ result["display"] = display
158
+
136
159
  station_areas = None
137
160
  if admin_gdf is not None and len(admin_gdf) > 0 and len(values) > 0:
138
161
  station_areas = attribute_stations_to_areas(