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,231 @@
1
+ """Daily weather layers and their comparison with exceedance days."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import numpy as np
8
+
9
+ from rsplot.exceedance import DailyMda8, DailyMean
10
+ from rsplot.result_builders.envelope import (
11
+ capped,
12
+ coverage_block,
13
+ flag,
14
+ stats_block,
15
+ )
16
+ from rsplot.result_builders.exceedance import descending, judged_layer_id
17
+ from rsplot.result_builders.station_layer import spearman
18
+ from rsplot.stats import round_finite
19
+ from rsplot.weather_days import LAYERS, DailyWeather, wind_from_deg
20
+
21
+ GROUPS = ("exceeded", "not_exceeded", "unjudged")
22
+ TABLE_COLUMNS = [
23
+ "date",
24
+ "group",
25
+ "judged",
26
+ "exceeded",
27
+ "day_max",
28
+ "hours",
29
+ *(layer.id for layer in LAYERS if layer.id != "wind_10m"),
30
+ "wind_speed",
31
+ "wind_u",
32
+ "wind_v",
33
+ "wind_from_deg",
34
+ ]
35
+
36
+
37
+ def day_groups(result: DailyMda8 | DailyMean) -> list[str]:
38
+ """Exceeded if any station exceeded; not_exceeded if any was judged."""
39
+ groups = []
40
+ for day in range(len(result.dates)):
41
+ if any(item is True for item in result.exceeded[:, day]):
42
+ groups.append("exceeded")
43
+ elif np.isfinite(result.daily[:, day]).any():
44
+ groups.append("not_exceeded")
45
+ else:
46
+ groups.append("unjudged")
47
+ return groups
48
+
49
+
50
+ def day_max(result: DailyMda8 | DailyMean) -> np.ndarray:
51
+ """The day's highest judged value; NaN for unjudged days."""
52
+ judged = np.isfinite(result.daily)
53
+ peaks = np.where(judged, result.daily, -np.inf).max(axis=0)
54
+ return np.where(judged.any(axis=0), peaks, np.nan)
55
+
56
+
57
+ def weather_rows(
58
+ result: DailyMda8 | DailyMean, weather: DailyWeather, groups: list[str]
59
+ ) -> list[dict[str, Any]]:
60
+ """One table row per day: its exceedance group and weather."""
61
+ peaks = day_max(result)
62
+ rows = []
63
+ for day, date in enumerate(weather.dates):
64
+ row: dict[str, Any] = {
65
+ "date": date,
66
+ "group": groups[day],
67
+ "judged": int(np.isfinite(result.daily[:, day]).sum()),
68
+ "exceeded": int(
69
+ sum(item is True for item in result.exceeded[:, day])
70
+ ),
71
+ "day_max": float(peaks[day]),
72
+ "hours": int(weather.complete_hours[day]),
73
+ }
74
+ for layer in LAYERS:
75
+ name = "wind_speed" if layer.id == "wind_10m" else layer.id
76
+ row[name] = float(weather.values[layer.id][day])
77
+ row["wind_u"] = float(weather.wind_u[day])
78
+ row["wind_v"] = float(weather.wind_v[day])
79
+ row["wind_from_deg"] = float(weather.wind_from_deg[day])
80
+ rows.append(row)
81
+ return rows
82
+
83
+
84
+ def weather_layers(
85
+ weather: DailyWeather,
86
+ *,
87
+ n_cells: int,
88
+ source: dict[str, Any],
89
+ data: str,
90
+ ) -> list[dict[str, Any]]:
91
+ """One ``region_days`` layer per weather quantity."""
92
+ dates = weather.dates
93
+ layers = []
94
+ for spec in LAYERS:
95
+ values = weather.values[spec.id]
96
+ valid = int(np.isfinite(values).sum())
97
+ layer: dict[str, Any] = {
98
+ "id": spec.id,
99
+ "kind": "region_days",
100
+ "quantity": {
101
+ "name": spec.id,
102
+ "unit": spec.unit,
103
+ "scale": 1,
104
+ "label": spec.label,
105
+ },
106
+ "time": {
107
+ "aggregation": "daily",
108
+ "start": dates[0],
109
+ "end": dates[-1],
110
+ "basis": "era5_hour",
111
+ },
112
+ "source": source,
113
+ "method": {
114
+ "hours": weather.hours,
115
+ "hour_statistic": spec.statistic,
116
+ "cell_selection": "center_inside_region",
117
+ "cell_weighting": "equal",
118
+ "cells": n_cells,
119
+ "order": "cell_hour_region_mean_then_hours",
120
+ "missing_hours": "day_null",
121
+ "accumulation": "hour_ending"
122
+ if spec.statistic == "sum"
123
+ else None,
124
+ },
125
+ "coverage": coverage_block(valid, len(dates), "days"),
126
+ "stats": stats_block(values),
127
+ "by_admin": [],
128
+ "extremes": capped(
129
+ [
130
+ {
131
+ "date": dates[day],
132
+ "value": round_finite(values[day]),
133
+ }
134
+ for (day,) in descending(values)
135
+ ],
136
+ valid,
137
+ "value_desc",
138
+ ),
139
+ "data": data,
140
+ }
141
+ if spec.id == "wind_10m":
142
+ layer["vector_summary"] = _resultant(
143
+ weather.wind_u, weather.wind_v
144
+ )
145
+ layers.append(layer)
146
+ return layers
147
+
148
+
149
+ def exceedance_meteo(
150
+ result: DailyMda8 | DailyMean, weather: DailyWeather, groups: list[str]
151
+ ) -> dict[str, Any]:
152
+ """Weather on exceeded versus not-exceeded days, per layer."""
153
+ labels = np.array(groups)
154
+ peaks = day_max(result)
155
+ judged = judged_layer_id(result)
156
+ exceeded = labels == "exceeded"
157
+ clean = labels == "not_exceeded"
158
+ variables = []
159
+ for spec in LAYERS:
160
+ values = weather.values[spec.id]
161
+ high = stats_block(values[exceeded])
162
+ low = stats_block(values[clean])
163
+ paired = np.isfinite(values) & np.isfinite(peaks)
164
+ row: dict[str, Any] = {
165
+ "layer": spec.id,
166
+ "exceeded": high,
167
+ "not_exceeded": low,
168
+ "mean_difference": None
169
+ if high["mean"] is None or low["mean"] is None
170
+ else round_finite(high["mean"] - low["mean"]),
171
+ "spearman_day_max": spearman(values[paired], peaks[paired]),
172
+ "pairs": int(paired.sum()),
173
+ }
174
+ if spec.id == "wind_10m":
175
+ row["resultant_wind_from_deg"] = {
176
+ "exceeded": _group_direction(weather, exceeded),
177
+ "not_exceeded": _group_direction(weather, clean),
178
+ }
179
+ variables.append(row)
180
+ return {
181
+ "layers": [judged, *(spec.id for spec in LAYERS)],
182
+ "grouping": "day_exceeded_if_any_station",
183
+ "groups": {name: int((labels == name).sum()) for name in GROUPS},
184
+ "correlate_with": f"max_{judged}_of_day",
185
+ "variables": variables,
186
+ }
187
+
188
+
189
+ def missing_weather_flag(weather: DailyWeather) -> list[dict]:
190
+ """``missing_meteo_hours`` when any day-hour lacks a field."""
191
+ total = weather.hours_per_day * len(weather.dates)
192
+ valid = int(weather.complete_hours.sum())
193
+ if valid == total:
194
+ return []
195
+ return [
196
+ flag(
197
+ "missing_meteo_hours",
198
+ "warning",
199
+ evidence={
200
+ **coverage_block(valid, total, "hours"),
201
+ "missing": total - valid,
202
+ },
203
+ )
204
+ ]
205
+
206
+
207
+ def _group_direction(weather: DailyWeather, days: np.ndarray):
208
+ usable = days & np.isfinite(weather.wind_u) & np.isfinite(weather.wind_v)
209
+ if not usable.any():
210
+ return None
211
+ return round_finite(
212
+ float(
213
+ wind_from_deg(
214
+ weather.wind_u[usable].mean(), weather.wind_v[usable].mean()
215
+ )
216
+ ),
217
+ 1,
218
+ )
219
+
220
+
221
+ def _resultant(u: np.ndarray, v: np.ndarray) -> dict[str, Any]:
222
+ usable = np.isfinite(u) & np.isfinite(v)
223
+ if not usable.any():
224
+ return {"mean_u": None, "mean_v": None, "wind_from_deg": None}
225
+ mean_u = float(u[usable].mean())
226
+ mean_v = float(v[usable].mean())
227
+ return {
228
+ "mean_u": round_finite(mean_u),
229
+ "mean_v": round_finite(mean_v),
230
+ "wind_from_deg": round_finite(float(wind_from_deg(mean_u, mean_v)), 1),
231
+ }
@@ -26,7 +26,8 @@
26
26
  "station",
27
27
  "trend",
28
28
  "meteo",
29
- "fnr"
29
+ "fnr",
30
+ "exceedance"
30
31
  ]
31
32
  },
32
33
  "rsplot_version": {"type": "string"},
@@ -40,7 +41,7 @@
40
41
  },
41
42
  "region": {
42
43
  "oneOf": [{"$ref": "#/$defs/region"}, {"type": "null"}],
43
- "description": "Null only when the command targets one station (trend station mode)."
44
+ "description": "Null only when the command targets one station (trend or exceedance station mode)."
44
45
  },
45
46
  "layers": {
46
47
  "type": "array",
@@ -52,6 +53,20 @@
52
53
  "render": {"$ref": "#/$defs/render"},
53
54
  "artifacts": {"$ref": "#/$defs/artifacts"}
54
55
  },
56
+ "if": {
57
+ "properties": {
58
+ "command": {"const": "exceedance"},
59
+ "region": {"type": "null"}
60
+ }
61
+ },
62
+ "then": {
63
+ "properties": {"layers": {"items": {
64
+ "required": ["subject"],
65
+ "properties": {"subject": {"required": ["station_id"]}},
66
+ "not": {"required": ["by_admin"]}
67
+ }}}
68
+ },
69
+ "else": {"properties": {"layers": {"items": {"required": ["by_admin"]}}}},
55
70
  "$defs": {
56
71
  "nullableNumber": {"type": ["number", "null"]},
57
72
  "compactDate": {"type": "string", "pattern": "^[0-9]{8}$"},
@@ -124,7 +139,7 @@
124
139
  "properties": {
125
140
  "name": {
126
141
  "type": "string",
127
- "description": "Machine name, e.g. no2_tropospheric_column, NO2, O3_8h_24h, t2m, wind_10m, fnr."
142
+ "description": "Machine name, e.g. no2_tropospheric_column, NO2, O3_MDA8, t2m, wind_10m, fnr."
128
143
  },
129
144
  "unit": {
130
145
  "type": "string",
@@ -153,7 +168,8 @@
153
168
  "daily",
154
169
  "daily_scan_mean",
155
170
  "window_mean",
156
- "hourly_series"
171
+ "hourly_series",
172
+ "daily_max_8h_mean"
157
173
  ]
158
174
  },
159
175
  "at": {
@@ -242,7 +258,16 @@
242
258
  "valid": {"type": "integer", "minimum": 0},
243
259
  "total": {"type": "integer", "minimum": 0},
244
260
  "fraction": {"type": ["number", "null"], "minimum": 0, "maximum": 1},
245
- "unit": {"enum": ["cells", "stations", "hours", "days", "vectors"]}
261
+ "unit": {
262
+ "enum": [
263
+ "cells",
264
+ "stations",
265
+ "hours",
266
+ "days",
267
+ "vectors",
268
+ "station_days"
269
+ ]
270
+ }
246
271
  }
247
272
  },
248
273
 
@@ -275,6 +300,12 @@
275
300
  "mean": {"$ref": "#/$defs/nullableNumber"},
276
301
  "min": {"$ref": "#/$defs/nullableNumber"},
277
302
  "max": {"$ref": "#/$defs/nullableNumber"},
303
+ "stations": {"type": "integer", "minimum": 0},
304
+ "exceeded": {"type": "integer", "minimum": 0},
305
+ "exceedance_fraction": {
306
+ "type": ["number", "null"], "minimum": 0, "maximum": 1
307
+ },
308
+ "max_station": {"type": ["string", "null"]},
278
309
  "n_exceed": {"type": "integer", "minimum": 0},
279
310
  "category": {
280
311
  "type": ["string", "null"],
@@ -306,17 +337,48 @@
306
337
  "method",
307
338
  "coverage",
308
339
  "stats",
309
- "by_admin",
310
340
  "extremes",
311
341
  "data"
312
342
  ],
313
343
  "additionalProperties": false,
344
+ "if": {
345
+ "properties": {"kind": {"const": "station_days"}}
346
+ },
347
+ "then": {
348
+ "required": ["days", "exceedance"],
349
+ "properties": {
350
+ "id": {
351
+ "enum": [
352
+ "mda8", "daily_mean", "o3_mda8", "pm25_daily_mean",
353
+ "pm10_daily_mean", "no2_daily_mean", "so2_daily_mean",
354
+ "co_daily_mean"
355
+ ]
356
+ },
357
+ "by_admin": {
358
+ "items": {
359
+ "required": [
360
+ "stations", "exceeded", "exceedance_fraction",
361
+ "max", "max_station"
362
+ ]
363
+ }
364
+ }
365
+ }
366
+ },
314
367
  "properties": {
315
368
  "id": {
316
369
  "type": "string",
317
- "description": "Unique within the sidecar: satellite, station, temperature, wind, no2, hcho, fnr, regional_mean, ..."
370
+ "description": "Unique within the sidecar."
371
+ },
372
+ "kind": {
373
+ "enum": [
374
+ "grid",
375
+ "points",
376
+ "vector_grid",
377
+ "series",
378
+ "station_days",
379
+ "region_days"
380
+ ]
318
381
  },
319
- "kind": {"enum": ["grid", "points", "vector_grid", "series"]},
320
382
  "subject": {
321
383
  "type": "object",
322
384
  "description": "Optional per-layer subject, e.g. {\"station_id\": \"1277A\"} for trend station mode.",
@@ -379,6 +441,22 @@
379
441
  }
380
442
  }
381
443
  },
444
+ "days": {
445
+ "type": "array",
446
+ "description": "Station-day layers: one row per China-time day with the judged and exceeding stations and the day's highest value.",
447
+ "items": {
448
+ "type": "object",
449
+ "required": ["date", "judged", "exceeded", "max", "max_station"],
450
+ "additionalProperties": false,
451
+ "properties": {
452
+ "date": {"$ref": "#/$defs/compactDate"},
453
+ "judged": {"type": "integer", "minimum": 0},
454
+ "exceeded": {"type": "integer", "minimum": 0},
455
+ "max": {"$ref": "#/$defs/nullableNumber"},
456
+ "max_station": {"type": ["string", "null"]}
457
+ }
458
+ }
459
+ },
382
460
  "categories": {
383
461
  "type": "object",
384
462
  "description": "Counts per category band, e.g. AQI levels for AQI station layers.",
@@ -398,6 +476,10 @@
398
476
  "description": "Top values: hotspot cells for grids, highest stations for points. Capped; the full set is in the data file.",
399
477
  "$ref": "#/$defs/cappedList"
400
478
  },
479
+ "plumes": {
480
+ "description": "Connected high-value plumes on raster/overlay satellite grids (8-connected components above the 90th percentile).",
481
+ "$ref": "#/$defs/plumes"
482
+ },
401
483
  "data": {
402
484
  "oneOf": [{"type": "string"}, {"type": "null"}],
403
485
  "description": "Absolute path of this layer's data file listed in artifacts.data."
@@ -405,12 +487,128 @@
405
487
  }
406
488
  },
407
489
 
490
+ "plumes": {
491
+ "type": "object",
492
+ "required": [
493
+ "threshold_percentile",
494
+ "threshold",
495
+ "items",
496
+ "total",
497
+ "truncated"
498
+ ],
499
+ "additionalProperties": false,
500
+ "properties": {
501
+ "threshold_percentile": {
502
+ "type": "integer",
503
+ "minimum": 1,
504
+ "maximum": 99
505
+ },
506
+ "threshold": {"$ref": "#/$defs/nullableNumber"},
507
+ "total": {"type": "integer", "minimum": 0},
508
+ "truncated": {"type": "boolean"},
509
+ "items": {
510
+ "type": "array",
511
+ "maxItems": 3,
512
+ "items": {
513
+ "type": "object",
514
+ "required": [
515
+ "cells",
516
+ "area_km2",
517
+ "centroid_lon",
518
+ "centroid_lat",
519
+ "peak_lon",
520
+ "peak_lat",
521
+ "mean",
522
+ "max",
523
+ "admins",
524
+ "cross_border"
525
+ ],
526
+ "additionalProperties": false,
527
+ "properties": {
528
+ "cells": {"type": "integer", "minimum": 2},
529
+ "area_km2": {"type": "number", "minimum": 0},
530
+ "centroid_lon": {"type": "number"},
531
+ "centroid_lat": {"type": "number"},
532
+ "peak_lon": {"type": "number"},
533
+ "peak_lat": {"type": "number"},
534
+ "mean": {"$ref": "#/$defs/nullableNumber"},
535
+ "max": {"$ref": "#/$defs/nullableNumber"},
536
+ "admins": {"type": "array", "items": {"type": "string"}},
537
+ "cross_border": {"type": "boolean"}
538
+ }
539
+ }
540
+ }
541
+ }
542
+ },
543
+
408
544
  "relations": {
409
545
  "type": "object",
410
546
  "additionalProperties": false,
411
547
  "properties": {
412
548
  "time_matching": {"$ref": "#/$defs/timeMatching"},
413
- "colocation": {"$ref": "#/$defs/colocation"}
549
+ "colocation": {"$ref": "#/$defs/colocation"},
550
+ "exceedance_meteo": {"$ref": "#/$defs/exceedanceMeteo"}
551
+ }
552
+ },
553
+ "exceedanceMeteo": {
554
+ "type": "object",
555
+ "description": "exceedance --meteo-hours: each weather layer on days when any station exceeded versus days when stations were judged and none exceeded.",
556
+ "required": [
557
+ "layers",
558
+ "grouping",
559
+ "groups",
560
+ "correlate_with",
561
+ "variables"
562
+ ],
563
+ "additionalProperties": false,
564
+ "properties": {
565
+ "layers": {"type": "array", "items": {"type": "string"}},
566
+ "grouping": {"const": "day_exceeded_if_any_station"},
567
+ "groups": {
568
+ "type": "object",
569
+ "required": ["exceeded", "not_exceeded", "unjudged"],
570
+ "additionalProperties": false,
571
+ "properties": {
572
+ "exceeded": {"type": "integer", "minimum": 0},
573
+ "not_exceeded": {"type": "integer", "minimum": 0},
574
+ "unjudged": {"type": "integer", "minimum": 0}
575
+ }
576
+ },
577
+ "correlate_with": {
578
+ "enum": ["max_mda8_of_day", "max_daily_mean_of_day"]
579
+ },
580
+ "variables": {
581
+ "type": "array",
582
+ "items": {
583
+ "type": "object",
584
+ "required": [
585
+ "layer",
586
+ "exceeded",
587
+ "not_exceeded",
588
+ "mean_difference",
589
+ "spearman_day_max",
590
+ "pairs"
591
+ ],
592
+ "additionalProperties": false,
593
+ "properties": {
594
+ "layer": {"type": "string"},
595
+ "exceeded": {"$ref": "#/$defs/stats"},
596
+ "not_exceeded": {"$ref": "#/$defs/stats"},
597
+ "mean_difference": {"$ref": "#/$defs/nullableNumber"},
598
+ "spearman_day_max": {"$ref": "#/$defs/nullableNumber"},
599
+ "pairs": {"type": "integer", "minimum": 0},
600
+ "resultant_wind_from_deg": {
601
+ "type": "object",
602
+ "required": ["exceeded", "not_exceeded"],
603
+ "additionalProperties": false,
604
+ "properties": {
605
+ "exceeded": {"$ref": "#/$defs/nullableNumber"},
606
+ "not_exceeded": {"$ref": "#/$defs/nullableNumber"}
607
+ }
608
+ }
609
+ }
610
+ }
611
+ }
414
612
  }
415
613
  },
416
614
  "timeMatching": {
@@ -496,7 +694,8 @@
496
694
  "failed_files",
497
695
  "few_stations",
498
696
  "missing_station_values",
499
- "missing_hours"
697
+ "missing_hours",
698
+ "missing_meteo_hours"
500
699
  ]
501
700
  },
502
701
  "severity": {"enum": ["info", "warning", "critical"]},
rsplot/weather_days.py ADDED
@@ -0,0 +1,121 @@
1
+ """Daily regional weather over China hours A..B of each MDA8 day.
2
+
3
+ Hour h of day D is D 00 + h hours, so hour 24 is D+1 00, as in the MDA8
4
+ day. A day's value takes its statistic over the hours A..B of the hourly
5
+ regional means and is NaN unless every one of those hours was read.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from dataclasses import dataclass
12
+ from datetime import datetime, timedelta
13
+
14
+ import numpy as np
15
+
16
+ from rsplot.readers.era5_days import QUANTITIES, RegionWeatherHours
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class WeatherLayer:
21
+ id: str
22
+ quantity: str # key of RegionWeatherHours.values
23
+ statistic: str # max, mean or sum over the hours
24
+ unit: str
25
+ label: str
26
+
27
+
28
+ LAYERS = (
29
+ WeatherLayer("t2m_max", "t2m", "max", "degC", "最高气温 (°C)"),
30
+ WeatherLayer("rh_mean", "rh", "mean", "%", "相对湿度 (%)"),
31
+ WeatherLayer("ssrd_sum", "ssrd", "sum", "MJ/m2", "短波辐射 (MJ/m²)"),
32
+ WeatherLayer("blh_max", "blh", "max", "m", "边界层高度 (m)"),
33
+ WeatherLayer("tp_sum", "tp", "sum", "mm", "降水 (mm)"),
34
+ WeatherLayer("wind_10m", "wind_speed", "mean", "m/s", "10 m 风速 (m/s)"),
35
+ )
36
+ STATISTICS = {"max": np.max, "mean": np.mean, "sum": np.sum}
37
+
38
+
39
+ @dataclass
40
+ class DailyWeather:
41
+ """One value per day and layer; NaN where an hour is missing."""
42
+
43
+ dates: list[str]
44
+ hours: str # "A-B" as given
45
+ hours_per_day: int
46
+ complete_hours: np.ndarray # (day,) hours with every field read
47
+ values: dict[str, np.ndarray] # layer id -> (day,)
48
+ wind_u: np.ndarray
49
+ wind_v: np.ndarray
50
+ wind_from_deg: np.ndarray
51
+
52
+
53
+ def parse_meteo_hours(text: str) -> tuple[int, int]:
54
+ """``A-B`` with 1 <= A <= B <= 24, or ValueError."""
55
+ match = re.fullmatch(r"\s*(\d{1,2})\s*-\s*(\d{1,2})\s*", text)
56
+ if not match:
57
+ raise ValueError(
58
+ f"--meteo-hours 应为 A-B(如 12-20),得到 '{text}'。"
59
+ )
60
+ first, last = int(match.group(1)), int(match.group(2))
61
+ if not 1 <= first <= last <= 24:
62
+ raise ValueError(
63
+ "--meteo-hours 的小时应满足 1 ≤ A ≤ B ≤ 24(与 MDA8 日一致,"
64
+ f"24 时为次日 00 时),得到 '{text}'。"
65
+ )
66
+ return first, last
67
+
68
+
69
+ def window_hours(dates: list[str], first: int, last: int) -> list[str]:
70
+ """``YYYYMMDDHH`` of hours ``first..last`` of each date, day-major."""
71
+ stamps = []
72
+ for date in dates:
73
+ start = datetime.strptime(date, "%Y%m%d")
74
+ stamps.extend(
75
+ (start + timedelta(hours=hour)).strftime("%Y%m%d%H")
76
+ for hour in range(first, last + 1)
77
+ )
78
+ return stamps
79
+
80
+
81
+ def wind_from_deg(u: np.ndarray, v: np.ndarray) -> np.ndarray:
82
+ """Direction the wind blows from, in degrees; NaN for calm or missing."""
83
+ u = np.asarray(u, dtype=float)
84
+ v = np.asarray(v, dtype=float)
85
+ direction = (270.0 - np.degrees(np.arctan2(v, u))) % 360.0
86
+ return np.where(np.hypot(u, v) > 0, direction, np.nan)
87
+
88
+
89
+ def daily_weather(
90
+ read: RegionWeatherHours, dates: list[str], first: int, last: int
91
+ ) -> DailyWeather:
92
+ """Each day's statistic over its window hours."""
93
+ per_day = last - first + 1
94
+
95
+ def by_day(name: str) -> np.ndarray:
96
+ return read.values[name].reshape(len(dates), per_day)
97
+
98
+ def reduce(name: str, statistic: str) -> np.ndarray:
99
+ hourly = by_day(name)
100
+ complete = np.isfinite(hourly).all(axis=1)
101
+ out = np.full(len(dates), np.nan)
102
+ if complete.any():
103
+ out[complete] = STATISTICS[statistic](hourly[complete], axis=1)
104
+ return out
105
+
106
+ every = np.all([np.isfinite(by_day(name)) for name in QUANTITIES], axis=0)
107
+ wind_u = reduce("wind_u", "mean")
108
+ wind_v = reduce("wind_v", "mean")
109
+ return DailyWeather(
110
+ dates=dates,
111
+ hours=f"{first}-{last}",
112
+ hours_per_day=per_day,
113
+ complete_hours=every.sum(axis=1),
114
+ values={
115
+ layer.id: reduce(layer.quantity, layer.statistic)
116
+ for layer in LAYERS
117
+ },
118
+ wind_u=wind_u,
119
+ wind_v=wind_v,
120
+ wind_from_deg=wind_from_deg(wind_u, wind_v),
121
+ )