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.
Files changed (67) hide show
  1. rsplot/atomic.py +36 -0
  2. rsplot/cli.py +272 -497
  3. rsplot/commands/common.py +52 -3
  4. rsplot/commands/fnr.py +389 -104
  5. rsplot/commands/forecast.py +0 -2
  6. rsplot/commands/meteo.py +499 -186
  7. rsplot/commands/overlay.py +284 -326
  8. rsplot/commands/radius.py +526 -0
  9. rsplot/commands/raster.py +418 -293
  10. rsplot/commands/reconstruct.py +0 -1
  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 +43 -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 +212 -9
  19. rsplot/geo/footprints.py +3 -0
  20. rsplot/geo/processing.py +2 -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 +84 -6
  25. rsplot/plotting/meteo.py +10 -3
  26. rsplot/plotting/overlay.py +31 -40
  27. rsplot/plotting/raster.py +10 -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 +52 -4
  33. rsplot/readers/_tropomi.py +121 -3
  34. rsplot/readers/era5.py +110 -10
  35. rsplot/readers/era5_wind.py +3 -2
  36. rsplot/readers/gems.py +11 -8
  37. rsplot/readers/guokong.py +125 -39
  38. rsplot/readers/netcdf.py +32 -0
  39. rsplot/readers/tropomi_hcho.py +1 -1
  40. rsplot/readers/tropomi_no2.py +1 -1
  41. rsplot/readers/tropomi_nrti.py +116 -0
  42. rsplot/readers/tropomi_o3.py +1 -1
  43. rsplot/readers/tropomi_o3pr.py +1 -1
  44. rsplot/result_builders/__init__.py +0 -14
  45. rsplot/result_builders/common.py +4 -1
  46. rsplot/result_builders/envelope.py +236 -0
  47. rsplot/result_builders/fnr.py +47 -131
  48. rsplot/result_builders/provenance.py +59 -0
  49. rsplot/result_builders/satellite.py +240 -0
  50. rsplot/result_builders/series_layer.py +289 -0
  51. rsplot/result_builders/station.py +23 -0
  52. rsplot/result_builders/station_layer.py +326 -0
  53. rsplot/results.py +0 -12
  54. rsplot/schemas/result.schema.json +566 -0
  55. rsplot/temporal.py +7 -0
  56. {rsplot-0.3.2.dev4.dist-info → rsplot-0.3.2.dev37.dist-info}/METADATA +426 -121
  57. rsplot-0.3.2.dev37.dist-info/RECORD +76 -0
  58. {rsplot-0.3.2.dev4.dist-info → rsplot-0.3.2.dev37.dist-info}/WHEEL +1 -1
  59. rsplot/commands/recent.py +0 -186
  60. rsplot/recent.py +0 -447
  61. rsplot/result_builders/meteo.py +0 -171
  62. rsplot/result_builders/overlay.py +0 -105
  63. rsplot/result_builders/raster.py +0 -104
  64. rsplot/result_builders/station_trend.py +0 -229
  65. rsplot-0.3.2.dev4.dist-info/RECORD +0 -66
  66. {rsplot-0.3.2.dev4.dist-info → rsplot-0.3.2.dev37.dist-info}/entry_points.txt +0 -0
  67. {rsplot-0.3.2.dev4.dist-info → rsplot-0.3.2.dev37.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,326 @@
1
+ """The ``station`` points layer and satellite colocation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import TYPE_CHECKING, Any
7
+
8
+ import numpy as np
9
+
10
+ from rsplot.result_builders.envelope import (
11
+ capped,
12
+ coverage_block,
13
+ flag,
14
+ stats_block,
15
+ )
16
+ from rsplot.result_builders.provenance import input_fingerprint
17
+ from rsplot.result_builders.station import (
18
+ aqi_distribution,
19
+ attribute_stations_to_areas,
20
+ station_admin_level,
21
+ )
22
+ from rsplot.stats import round_finite
23
+
24
+ if TYPE_CHECKING:
25
+ import geopandas as gpd
26
+
27
+ from rsplot.geo.boundaries import RegionInfo
28
+ from rsplot.readers.guokong import StationData
29
+
30
+ MIN_STATIONS = 3
31
+ MIN_PAIRS = 3
32
+ TABLE_COLUMNS = [
33
+ "id",
34
+ "lon",
35
+ "lat",
36
+ "admin",
37
+ "admin_level",
38
+ "value",
39
+ "valid",
40
+ "exceeds",
41
+ "in_region",
42
+ "satellite_value",
43
+ "colocated",
44
+ ]
45
+
46
+
47
+ @dataclass
48
+ class StationInputs:
49
+ """One station hour read for a region, before and after masking."""
50
+
51
+ read: StationData
52
+ in_region: np.ndarray
53
+ var: str
54
+ unit: str
55
+ threshold: float | None
56
+ standard: str | None
57
+ hour: str
58
+ data_root: str
59
+
60
+
61
+ def satellite_at_stations(
62
+ lon: np.ndarray,
63
+ lat: np.ndarray,
64
+ grid: np.ndarray,
65
+ counted: np.ndarray,
66
+ station_lon: np.ndarray,
67
+ station_lat: np.ndarray,
68
+ ) -> np.ndarray:
69
+ """Value of the valid statistics cell containing each station, else NaN."""
70
+ lons = np.asarray(lon)[0, :]
71
+ lats = np.asarray(lat)[:, 0]
72
+ out = np.full(len(station_lon), np.nan)
73
+ if lons.size < 2 or lats.size < 2:
74
+ return out
75
+ dx = float(lons[1] - lons[0])
76
+ dy = float(lats[1] - lats[0])
77
+ ix = np.rint((station_lon - lons[0]) / dx).astype(int)
78
+ iy = np.rint((station_lat - lats[0]) / dy).astype(int)
79
+ for index, (column, row) in enumerate(zip(ix, iy, strict=True)):
80
+ if not (0 <= column < lons.size and 0 <= row < lats.size):
81
+ continue
82
+ inside_cell = (
83
+ abs(lons[column] - station_lon[index]) <= abs(dx) / 2 + 1e-9
84
+ and abs(lats[row] - station_lat[index]) <= abs(dy) / 2 + 1e-9
85
+ )
86
+ value = grid[row, column]
87
+ if inside_cell and counted[row, column] and np.isfinite(value):
88
+ out[index] = value
89
+ return out
90
+
91
+
92
+ def spearman(x: np.ndarray, y: np.ndarray) -> float | None:
93
+ """Rank correlation, or None with too few or constant pairs."""
94
+ if len(x) < MIN_PAIRS or np.ptp(x) == 0 or np.ptp(y) == 0:
95
+ return None
96
+ from scipy.stats import spearmanr
97
+
98
+ return round_finite(float(spearmanr(x, y).statistic), 3)
99
+
100
+
101
+ def build_station_layer(
102
+ inputs: StationInputs,
103
+ region: RegionInfo,
104
+ *,
105
+ admin_gdf: gpd.GeoDataFrame | None,
106
+ satellite_values: np.ndarray | None,
107
+ data: str | None,
108
+ extra_columns: dict[str, np.ndarray] | None = None,
109
+ ) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]:
110
+ """Return the station layer, its quality flags and its table rows.
111
+
112
+ ``extra_columns`` adds per-station table columns, e.g. radius offsets.
113
+ """
114
+ from rsplot.readers.guokong import mask_stations_to_region
115
+
116
+ read = inputs.read
117
+ values = np.asarray(read.values, dtype=float)
118
+ valid = np.isfinite(values)
119
+ in_region = np.asarray(inputs.in_region, dtype=bool)
120
+ level = station_admin_level(region)
121
+ admins = (
122
+ attribute_stations_to_areas(
123
+ read.lon, read.lat, admin_gdf, region.sub_name_field
124
+ )
125
+ if admin_gdf is not None and len(admin_gdf) > 0
126
+ else np.full(len(values), "", dtype=object)
127
+ )
128
+ threshold = inputs.threshold
129
+ exceeds = (
130
+ valid & (values > threshold)
131
+ if threshold is not None
132
+ else np.zeros(len(values), dtype=bool)
133
+ )
134
+ paired = satellite_values is not None
135
+ if satellite_values is None:
136
+ satellite_values = np.full(len(values), np.nan)
137
+ colocated = valid & in_region & np.isfinite(satellite_values)
138
+
139
+ rows = [
140
+ {
141
+ "id": str(read.id[index]),
142
+ "lon": float(read.lon[index]),
143
+ "lat": float(read.lat[index]),
144
+ "admin": admins[index] or "",
145
+ "admin_level": (level or "") if admins[index] else "",
146
+ "value": float(values[index]),
147
+ "valid": int(valid[index]),
148
+ "exceeds": int(exceeds[index]),
149
+ "in_region": int(in_region[index]),
150
+ "satellite_value": float(satellite_values[index]),
151
+ "colocated": int(colocated[index]),
152
+ **{
153
+ name: column[index]
154
+ for name, column in (extra_columns or {}).items()
155
+ },
156
+ }
157
+ for index in range(len(values))
158
+ ]
159
+
160
+ region_valid = valid & in_region
161
+ region_values = values[region_valid]
162
+ n_stations = int(in_region.sum())
163
+ n_valid = int(region_valid.sum())
164
+
165
+ by_admin: dict[str, list[int]] = {}
166
+ for index in np.flatnonzero(region_valid):
167
+ if admins[index]:
168
+ by_admin.setdefault(admins[index], []).append(int(index))
169
+ admin_rows = []
170
+ for name, indices in by_admin.items():
171
+ area_values = values[indices]
172
+ row: dict[str, Any] = {
173
+ "name": name,
174
+ "level": level or "subdivision",
175
+ "n": len(indices),
176
+ "mean": round_finite(np.mean(area_values)),
177
+ "min": round_finite(np.min(area_values)),
178
+ "max": round_finite(np.max(area_values)),
179
+ }
180
+ if threshold is not None:
181
+ row["n_exceed"] = int(exceeds[indices].sum())
182
+ admin_rows.append(row)
183
+ admin_rows.sort(key=lambda row: -(row["mean"] or 0))
184
+
185
+ order = np.flatnonzero(region_valid)[
186
+ np.argsort(values[region_valid])[::-1]
187
+ ]
188
+ extremes = [
189
+ {
190
+ "id": str(read.id[index]),
191
+ "lon": round(float(read.lon[index]), 3),
192
+ "lat": round(float(read.lat[index]), 3),
193
+ "value": round_finite(values[index]),
194
+ "admin": admins[index] or None,
195
+ **(
196
+ {"satellite_value": round_finite(satellite_values[index])}
197
+ if paired
198
+ else {}
199
+ ),
200
+ }
201
+ for index in order
202
+ ]
203
+
204
+ unit = inputs.unit or "1"
205
+ layer: dict[str, Any] = {
206
+ "id": "station",
207
+ "kind": "points",
208
+ "quantity": {
209
+ "name": inputs.var,
210
+ "unit": unit,
211
+ "scale": 1,
212
+ "label": f"{inputs.var} ({inputs.unit})"
213
+ if inputs.unit
214
+ else inputs.var,
215
+ },
216
+ "time": {
217
+ "aggregation": "hourly",
218
+ "at": inputs.hour,
219
+ "basis": "station_hour",
220
+ },
221
+ "source": {
222
+ "sensor": "station",
223
+ "processing": None,
224
+ "data_root": inputs.data_root,
225
+ "files_total": 1,
226
+ "failed_files": {},
227
+ **input_fingerprint(inputs.data_root, [f"{inputs.hour}.nc"]),
228
+ },
229
+ "method": {
230
+ "region_selection": "point_inside_region",
231
+ "boundary_tolerance_deg": 1e-9,
232
+ "fill_values_removed": ">= 65534",
233
+ },
234
+ "coverage": coverage_block(n_valid, n_stations, "stations"),
235
+ "stats": stats_block(region_values),
236
+ "by_admin": admin_rows,
237
+ "extremes": capped(extremes, n_valid, "value_desc"),
238
+ "data": data,
239
+ }
240
+ if inputs.var == "AQI":
241
+ layer["categories"] = aqi_distribution(region_values)
242
+ if threshold is not None:
243
+ count = int((exceeds & in_region).sum())
244
+ layer["exceedance"] = {
245
+ "threshold": threshold,
246
+ "operator": ">",
247
+ "standard": inputs.standard,
248
+ "count": count,
249
+ "fraction": round(count / n_valid, 3) if n_valid else None,
250
+ }
251
+ if region.members:
252
+ from rsplot.readers.guokong import StationData
253
+
254
+ region_data = StationData(
255
+ id=np.asarray(read.id)[in_region],
256
+ lon=read.lon[in_region],
257
+ lat=read.lat[in_region],
258
+ values=values[in_region],
259
+ var_name=read.var_name,
260
+ n_stations=n_stations,
261
+ n_valid=n_valid,
262
+ )
263
+ layer["by_member"] = []
264
+ for member in region.members:
265
+ selected = mask_stations_to_region(region_data, member.geometry)
266
+ member_stats = stats_block(selected.values)
267
+ layer["by_member"].append(
268
+ {
269
+ "name": member.qualified_name or member.name,
270
+ "level": member.administrative_level or member.level,
271
+ "n": member_stats["n"],
272
+ "mean": member_stats["mean"],
273
+ "min": member_stats["min"],
274
+ "max": member_stats["max"],
275
+ }
276
+ )
277
+
278
+ flags: list[dict[str, Any]] = []
279
+ evidence = {"valid": n_valid, "total": n_stations}
280
+ if n_valid == 0:
281
+ flags.append(
282
+ flag(
283
+ "no_valid_data",
284
+ "critical",
285
+ layer="station",
286
+ evidence=evidence,
287
+ )
288
+ )
289
+ elif n_valid < MIN_STATIONS:
290
+ flags.append(
291
+ flag(
292
+ "few_stations",
293
+ "warning",
294
+ layer="station",
295
+ evidence={**evidence, "threshold": MIN_STATIONS},
296
+ )
297
+ )
298
+ if 0 < n_valid < n_stations:
299
+ flags.append(
300
+ flag(
301
+ "missing_station_values",
302
+ "info",
303
+ layer="station",
304
+ evidence=evidence,
305
+ )
306
+ )
307
+ return layer, flags, rows
308
+
309
+
310
+ def colocation_block(
311
+ rows: list[dict[str, Any]], data: str | None
312
+ ) -> dict[str, Any]:
313
+ """Summarize satellite/station pairs at in-region stations."""
314
+ pairs = [row for row in rows if row["colocated"]]
315
+ station_values = np.array([row["value"] for row in pairs])
316
+ satellite_values = np.array([row["satellite_value"] for row in pairs])
317
+ block: dict[str, Any] = {
318
+ "layers": ["satellite", "station"],
319
+ "method": "station_in_valid_statistics_cell",
320
+ "pairs": len(pairs),
321
+ "spearman": spearman(satellite_values, station_values),
322
+ "comparable_units": False,
323
+ }
324
+ if data is not None:
325
+ block["data"] = data
326
+ return block
rsplot/results.py CHANGED
@@ -11,27 +11,15 @@ from pathlib import Path
11
11
  from typing import Any
12
12
 
13
13
  from rsplot.result_builders import (
14
- build_fnr_result,
15
14
  build_forecast_result,
16
- build_meteo_result,
17
- build_overlay_result,
18
- build_raster_result,
19
15
  build_reconstruct_result,
20
- build_region_trend_result,
21
16
  build_station_result,
22
- build_station_trend_result,
23
17
  )
24
18
 
25
19
  __all__ = [
26
- "build_fnr_result",
27
20
  "build_forecast_result",
28
- "build_meteo_result",
29
- "build_overlay_result",
30
- "build_raster_result",
31
21
  "build_reconstruct_result",
32
- "build_region_trend_result",
33
22
  "build_station_result",
34
- "build_station_trend_result",
35
23
  "emit_result",
36
24
  ]
37
25