rsplot 0.3.2.dev37__py3-none-any.whl → 0.4.1.dev8__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.
@@ -0,0 +1,524 @@
1
+ """Hourly ``station`` and daily judged layers for the exceedance command.
2
+
3
+ The judged layer is ``mda8`` for O3 and ``daily_mean`` for every other
4
+ variable (PM2.5, PM10, NO2, SO2, CO).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Iterator
10
+ from dataclasses import dataclass
11
+ from typing import TYPE_CHECKING, Any
12
+
13
+ import numpy as np
14
+
15
+ from rsplot.exceedance import (
16
+ FIRST_MEAN_END,
17
+ MIN_HOURS_PER_DAY,
18
+ MIN_HOURS_PER_MEAN,
19
+ MIN_VALID_MEANS,
20
+ WINDOW,
21
+ DailyMda8,
22
+ DailyMean,
23
+ )
24
+ from rsplot.result_builders.envelope import (
25
+ EXTREMES_LIMIT,
26
+ capped,
27
+ coverage_block,
28
+ flag,
29
+ stats_block,
30
+ )
31
+ from rsplot.result_builders.series_layer import series_quantity
32
+ from rsplot.stats import round_finite
33
+
34
+ if TYPE_CHECKING:
35
+ from rsplot.geo.boundaries import RegionInfo
36
+ from rsplot.readers.guokong import RegionStationSeries
37
+
38
+ ALL_COLUMNS = [
39
+ "var",
40
+ "station_id",
41
+ "lon",
42
+ "lat",
43
+ "admin",
44
+ "date",
45
+ "value",
46
+ "limit",
47
+ "unit",
48
+ "valid_count",
49
+ "exceeded",
50
+ ]
51
+ TABLE_COLUMNS = [
52
+ "station_id",
53
+ "lon",
54
+ "lat",
55
+ "admin",
56
+ "date",
57
+ "mda8",
58
+ "first_hour",
59
+ "last_hour",
60
+ "valid_means",
61
+ "exceeded",
62
+ ]
63
+ DAILY_MEAN_COLUMNS = [
64
+ "station_id",
65
+ "lon",
66
+ "lat",
67
+ "admin",
68
+ "date",
69
+ "daily_mean",
70
+ "valid_hours",
71
+ "exceeded",
72
+ ]
73
+
74
+
75
+ def judged_layer_id(result: DailyMda8 | DailyMean) -> str:
76
+ """``mda8`` or ``daily_mean``: the judged layer and its CSV name."""
77
+ return "mda8" if isinstance(result, DailyMda8) else "daily_mean"
78
+
79
+
80
+ def _flag_text(exceeded: bool | None) -> str:
81
+ return "" if exceeded is None else str(bool(exceeded)).lower()
82
+
83
+
84
+ @dataclass
85
+ class StationAdmins:
86
+ """One attribution per station, with all selected subdivision names."""
87
+
88
+ names: np.ndarray
89
+ indices: np.ndarray
90
+ subdivisions: list[tuple[str, str]]
91
+
92
+ @classmethod
93
+ def from_region(
94
+ cls, region: RegionInfo, series: RegionStationSeries
95
+ ) -> StationAdmins:
96
+ from shapely import contains_xy, relate_pattern
97
+
98
+ from rsplot.result_builders.station import (
99
+ attribute_stations_to_areas,
100
+ station_admin_level,
101
+ )
102
+
103
+ indices = np.full(series.n_stations, -1)
104
+ names = np.full(series.n_stations, "", dtype=object)
105
+ subdivisions = []
106
+ lookup = {}
107
+ # Resolve overlapping selections at the most specific level first.
108
+ levels = ("county", "city", "province", "key_region", "country")
109
+ members = sorted(
110
+ region.members or (region,),
111
+ key=lambda item: levels.index(item.level),
112
+ )
113
+ for member in members:
114
+ areas = member.sub_boundary_gdf
115
+ if areas is None or areas.empty:
116
+ continue
117
+ # Region resolution may include neighbours touching its border.
118
+ areas = areas[
119
+ relate_pattern(
120
+ areas.geometry.array, member.geometry, "T********"
121
+ )
122
+ ]
123
+ level = station_admin_level(member) or "subdivision"
124
+ codes = []
125
+ for name, geometry in zip(
126
+ areas[member.sub_name_field], areas.geometry, strict=True
127
+ ):
128
+ key = (level, name, geometry.wkb)
129
+ if key not in lookup:
130
+ lookup[key] = len(subdivisions)
131
+ subdivisions.append((name, level))
132
+ codes.append(lookup[key])
133
+
134
+ pending = np.flatnonzero(
135
+ (indices < 0)
136
+ & contains_xy(
137
+ member.geometry.buffer(1e-9), series.lon, series.lat
138
+ )
139
+ )
140
+ hits = attribute_stations_to_areas(
141
+ series.lon[pending],
142
+ series.lat[pending],
143
+ areas.assign(area_index=codes),
144
+ "area_index",
145
+ )
146
+ matched = hits != ""
147
+ stations = pending[matched]
148
+ indices[stations] = hits[matched].astype(int)
149
+ names[stations] = [subdivisions[i][0] for i in indices[stations]]
150
+ return cls(names, indices, subdivisions)
151
+
152
+ def summary(
153
+ self, ids: np.ndarray, result: DailyMda8 | DailyMean, limit: float
154
+ ) -> list[dict]:
155
+ rows = []
156
+ for index, (name, level) in enumerate(self.subdivisions):
157
+ selected = self.indices == index
158
+ daily = result.daily[selected]
159
+ n = int(np.isfinite(daily).sum())
160
+ exceeded = int((daily > limit).sum())
161
+ maximum = float(np.nanmax(daily)) if n else None
162
+ top = int(np.nanargmax(daily)) // len(result.dates) if n else None
163
+ rows.append(
164
+ {
165
+ "name": name,
166
+ "level": level,
167
+ "n": n,
168
+ "stations": int(selected.sum()),
169
+ "exceeded": exceeded,
170
+ "exceedance_fraction": round(exceeded / n, 3)
171
+ if n
172
+ else None,
173
+ "max": maximum,
174
+ "max_station": str(ids[selected][top]) if n else None,
175
+ }
176
+ )
177
+ rows.sort(
178
+ key=lambda row: (
179
+ -row["exceeded"],
180
+ -row["max"] if row["max"] is not None else np.inf,
181
+ row["name"],
182
+ )
183
+ )
184
+ for row in rows:
185
+ if row["max"] is not None:
186
+ row["max"] = round_finite(row["max"])
187
+ return rows
188
+
189
+
190
+ def station_day_rows(
191
+ series: RegionStationSeries,
192
+ result: DailyMda8 | DailyMean,
193
+ admins: StationAdmins | None,
194
+ *,
195
+ combined: bool,
196
+ limit: float,
197
+ unit: str,
198
+ ) -> Iterator[dict]:
199
+ """One row for each requested station and day, including unjudged days."""
200
+ for station, station_id in enumerate(series.station_ids):
201
+ for day, date in enumerate(result.dates):
202
+ row = {
203
+ "station_id": str(station_id),
204
+ "lon": series.lon[station],
205
+ "lat": series.lat[station],
206
+ "date": date,
207
+ "admin": admins.names[station] if admins else "",
208
+ "exceeded": _flag_text(result.exceeded[station, day]),
209
+ }
210
+ value = result.daily[station, day]
211
+ if isinstance(result, DailyMda8):
212
+ count = int(result.valid_means[station, day])
213
+ row.update(
214
+ mda8=value,
215
+ valid_means=count,
216
+ first_hour=result.first_hour[station, day] or "",
217
+ last_hour=result.last_hour[station, day] or "",
218
+ )
219
+ else:
220
+ count = int(result.valid_hours[station, day])
221
+ row.update(daily_mean=value, valid_hours=count)
222
+ if combined:
223
+ row.update(
224
+ var=series.var_name,
225
+ value=value,
226
+ limit=limit,
227
+ unit=unit,
228
+ valid_count=count,
229
+ )
230
+ yield row
231
+
232
+
233
+ def day_rows(
234
+ station_ids: np.ndarray, result: DailyMda8 | DailyMean
235
+ ) -> list[dict[str, Any]]:
236
+ """Judged and exceeded stations and the highest value of each day."""
237
+ rows = []
238
+ for day, date in enumerate(result.dates):
239
+ values = result.daily[:, day]
240
+ judged = np.isfinite(values)
241
+ top = int(np.nanargmax(values)) if judged.any() else None
242
+ rows.append(
243
+ {
244
+ "date": date,
245
+ "judged": int(judged.sum()),
246
+ "exceeded": int(
247
+ sum(item is True for item in result.exceeded[:, day])
248
+ ),
249
+ "max": None if top is None else round_finite(values[top]),
250
+ "max_station": None if top is None else str(station_ids[top]),
251
+ }
252
+ )
253
+ return rows
254
+
255
+
256
+ def labelled_stations(
257
+ station_ids: np.ndarray, result: DailyMda8 | DailyMean, limit: int
258
+ ) -> list[str]:
259
+ """Stations that exceeded on any day, highest daily value first."""
260
+ exceeded = (result.exceeded == True).any(axis=1) # noqa: E712
261
+ peaks = np.where(np.isfinite(result.daily), result.daily, -np.inf).max(1)
262
+ order = sorted(np.flatnonzero(exceeded), key=lambda index: -peaks[index])
263
+ return [str(station_ids[index]) for index in order[:limit]]
264
+
265
+
266
+ def descending(values: np.ndarray) -> list[tuple[int, ...]]:
267
+ """Indices of the highest finite entries, at most ``EXTREMES_LIMIT``."""
268
+ finite = np.isfinite(values)
269
+ flat = np.where(finite, values, -np.inf).ravel()
270
+ order = np.argsort(-flat, kind="stable")[
271
+ : min(EXTREMES_LIMIT, finite.sum())
272
+ ]
273
+ return [
274
+ tuple(int(axis) for axis in np.unravel_index(index, values.shape))
275
+ for index in order
276
+ ]
277
+
278
+
279
+ def hourly_layer(
280
+ series: RegionStationSeries,
281
+ dates: list[str],
282
+ unit: str,
283
+ source: dict,
284
+ series_data: str,
285
+ admins: StationAdmins | None,
286
+ ) -> dict:
287
+ values = series.values
288
+ station_ids = series.station_ids
289
+ hours = series.timestamps
290
+ var = series.var_name
291
+ has_data = np.isfinite(values).any(axis=1)
292
+ station_coverage = coverage_block(
293
+ int(has_data.sum()), len(station_ids), "stations"
294
+ )
295
+ hour_order = descending(values)
296
+ layer = {
297
+ "id": "station",
298
+ "kind": "series",
299
+ "quantity": series_quantity(var, unit),
300
+ "time": {
301
+ "aggregation": "hourly_series",
302
+ "start": dates[0],
303
+ "end": dates[-1],
304
+ "basis": "station_hour",
305
+ },
306
+ "source": source,
307
+ "method": {
308
+ **({"region_selection": "point_inside_region"} if admins else {}),
309
+ "day_hours": "01-24",
310
+ "gaps": "kept_as_missing",
311
+ },
312
+ "coverage": station_coverage,
313
+ "stats": stats_block(values),
314
+ "extremes": capped(
315
+ [
316
+ {
317
+ "station_id": str(station_ids[station]),
318
+ **(
319
+ {"admin": admins.names[station] or None}
320
+ if admins
321
+ else {}
322
+ ),
323
+ "datetime": hours[hour],
324
+ "value": round_finite(values[station, hour]),
325
+ }
326
+ for station, hour in hour_order
327
+ ],
328
+ int(np.isfinite(values).sum()),
329
+ "value_desc",
330
+ ),
331
+ "data": series_data,
332
+ }
333
+
334
+ if admins is None:
335
+ layer["subject"] = {"station_id": str(station_ids[0])}
336
+ else:
337
+ layer["by_admin"] = []
338
+ return layer
339
+
340
+
341
+ def judged_layer(
342
+ series: RegionStationSeries,
343
+ result: DailyMda8 | DailyMean,
344
+ unit: str,
345
+ limit: float,
346
+ standard: str,
347
+ source: dict,
348
+ table_data: str,
349
+ admins: StationAdmins | None,
350
+ *,
351
+ combined: bool,
352
+ ) -> dict:
353
+ station_ids = series.station_ids
354
+ dates = result.dates
355
+ var = series.var_name
356
+ daily = result.daily
357
+ judged_count = int(np.isfinite(daily).sum())
358
+ exceeded_count = int((result.exceeded == True).sum()) # noqa: E712
359
+ if isinstance(result, DailyMda8):
360
+ judged = _mda8_head(result, source)
361
+ else:
362
+ judged = _daily_mean_head(var, unit, result, source)
363
+ judged.update(
364
+ {
365
+ "coverage": coverage_block(
366
+ judged_count, daily.size, "station_days"
367
+ ),
368
+ "stats": stats_block(daily),
369
+ "exceedance": {
370
+ "threshold": limit,
371
+ "operator": ">",
372
+ "standard": standard,
373
+ "count": exceeded_count,
374
+ "fraction": round(exceeded_count / judged_count, 3)
375
+ if judged_count
376
+ else None,
377
+ },
378
+ "days": day_rows(station_ids, result),
379
+ "extremes": capped(
380
+ [
381
+ {
382
+ "station_id": str(station_ids[station]),
383
+ **(
384
+ {"admin": admins.names[station] or None}
385
+ if admins
386
+ else {}
387
+ ),
388
+ "date": dates[day],
389
+ "value": round_finite(daily[station, day]),
390
+ **_extreme_detail(result, station, day),
391
+ }
392
+ for station, day in descending(daily)
393
+ ],
394
+ judged_count,
395
+ "value_desc",
396
+ ),
397
+ "data": table_data,
398
+ }
399
+ )
400
+
401
+ if combined:
402
+ prefix = var.lower().replace(".", "")
403
+ judged["id"] = f"{prefix}_{judged['id']}"
404
+ if admins is None:
405
+ judged["subject"] = {"station_id": str(station_ids[0])}
406
+ else:
407
+ judged["by_admin"] = admins.summary(station_ids, result, limit)
408
+ return judged
409
+
410
+
411
+ def series_flags(series: RegionStationSeries, layer_id: str) -> list[dict]:
412
+ hours = series.timestamps
413
+ missing_hours = series.missing_files
414
+ has_data = np.isfinite(series.values).any(axis=1)
415
+ station_ids = series.station_ids
416
+ flags: list[dict] = []
417
+ if missing_hours:
418
+ flags.append(
419
+ flag(
420
+ "missing_hours",
421
+ "warning",
422
+ layer=layer_id,
423
+ evidence={
424
+ **coverage_block(
425
+ len(hours) - len(missing_hours), len(hours), "hours"
426
+ ),
427
+ "missing": len(missing_hours),
428
+ },
429
+ )
430
+ )
431
+ empty = int((~has_data).sum())
432
+ if empty:
433
+ flags.append(
434
+ flag(
435
+ "missing_station_values",
436
+ "info",
437
+ layer=layer_id,
438
+ evidence={
439
+ "valid": len(station_ids) - empty,
440
+ "total": len(station_ids),
441
+ },
442
+ )
443
+ )
444
+ if series.failed_files:
445
+ flags.append(
446
+ flag(
447
+ "failed_files",
448
+ "warning",
449
+ layer=layer_id,
450
+ evidence={"count": len(series.failed_files)},
451
+ )
452
+ )
453
+ return flags
454
+
455
+
456
+ def _mda8_head(result: DailyMda8, source: dict[str, Any]) -> dict[str, Any]:
457
+ dates = result.dates
458
+ return {
459
+ "id": "mda8",
460
+ "kind": "station_days",
461
+ "quantity": {
462
+ "name": "O3_MDA8",
463
+ "unit": "ug/m3",
464
+ "scale": 1,
465
+ "label": "MDA8 O3 (ug/m3)",
466
+ },
467
+ "time": {
468
+ "aggregation": "daily_max_8h_mean",
469
+ "start": dates[0],
470
+ "end": dates[-1],
471
+ "basis": "station_hour",
472
+ },
473
+ "source": source,
474
+ "method": {
475
+ "input": "hourly_O3",
476
+ "day_hours": "01-24",
477
+ "window_hours": WINDOW,
478
+ "min_hours_per_mean": MIN_HOURS_PER_MEAN,
479
+ "mean_ends": f"{FIRST_MEAN_END:02d}-24",
480
+ "min_valid_means": MIN_VALID_MEANS,
481
+ "kept_below_min_means": "above_limit",
482
+ "ties": "earliest",
483
+ },
484
+ }
485
+
486
+
487
+ def _daily_mean_head(
488
+ var: str, unit: str, result: DailyMean, source: dict[str, Any]
489
+ ) -> dict[str, Any]:
490
+ dates = result.dates
491
+ return {
492
+ "id": "daily_mean",
493
+ "kind": "station_days",
494
+ "quantity": {
495
+ "name": f"{var}_daily_mean",
496
+ "unit": unit,
497
+ "scale": 1,
498
+ "label": f"{var} daily mean ({unit})",
499
+ },
500
+ "time": {
501
+ "aggregation": "daily",
502
+ "start": dates[0],
503
+ "end": dates[-1],
504
+ "basis": "station_hour",
505
+ },
506
+ "source": source,
507
+ "method": {
508
+ "input": f"hourly_{var}",
509
+ "day_hours": "01-24",
510
+ "statistic": "mean",
511
+ "min_valid_hours": MIN_HOURS_PER_DAY,
512
+ },
513
+ }
514
+
515
+
516
+ def _extreme_detail(
517
+ result: DailyMda8 | DailyMean, station: int, day: int
518
+ ) -> dict[str, Any]:
519
+ if isinstance(result, DailyMda8):
520
+ return {
521
+ "first_hour": result.first_hour[station, day],
522
+ "last_hour": result.last_hour[station, day],
523
+ }
524
+ return {"valid_hours": int(result.valid_hours[station, day])}
@@ -9,6 +9,7 @@ from typing import TYPE_CHECKING, Any
9
9
  import numpy as np
10
10
 
11
11
  from rsplot.result_builders.common import (
12
+ extract_plumes,
12
13
  grid_member_stats,
13
14
  grid_per_admin_stats,
14
15
  top_hotspots,
@@ -98,6 +99,7 @@ def build_satellite_layer(
98
99
  data: str | None,
99
100
  layer_id: str = "satellite",
100
101
  coverage_checks: bool = True,
102
+ include_plumes: bool = False,
101
103
  ) -> tuple[dict[str, Any], list[dict[str, Any]]]:
102
104
  """Return the satellite layer and the quality flags it raises.
103
105
 
@@ -181,6 +183,14 @@ def build_satellite_layer(
181
183
  ),
182
184
  "data": data,
183
185
  }
186
+ if include_plumes:
187
+ layer["plumes"] = extract_plumes(
188
+ inputs.lon,
189
+ inputs.lat,
190
+ inputs.grid,
191
+ inputs.counted,
192
+ sub_gdf if has_subdivisions else None,
193
+ )
184
194
  if region.members:
185
195
  layer["by_member"] = [
186
196
  {