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.
rsplot/exceedance.py ADDED
@@ -0,0 +1,140 @@
1
+ """Daily station statistics judged against GB 3095 limits.
2
+
3
+ Ozone uses the daily maximum 8-hour mean (MDA8); particulate matter uses
4
+ the daily mean. Day D covers hours D 01 through D+1 00 (hour 24). An 8-hour mean ending at
5
+ hour t averages hours t-7..t and needs ``MIN_HOURS_PER_MEAN`` valid hours.
6
+ MDA8 is the largest of the 17 means ending at hours 08–24 and needs
7
+ ``MIN_VALID_MEANS`` valid means, except that a maximum above the limit is
8
+ kept with fewer. Equal maxima report the earliest window. A daily mean
9
+ needs ``MIN_HOURS_PER_DAY`` valid hours (GB 3095—2026 table 4), with no
10
+ exception above the limit.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from dataclasses import dataclass
16
+ from datetime import datetime, timedelta
17
+
18
+ import numpy as np
19
+
20
+ HOURS_PER_DAY = 24
21
+ WINDOW = 8
22
+ MIN_HOURS_PER_MEAN = 6
23
+ MIN_VALID_MEANS = 14
24
+ FIRST_MEAN_END = 8
25
+ MIN_HOURS_PER_DAY = 20
26
+
27
+
28
+ def day_hours(dates: list[str]) -> list[str]:
29
+ """``YYYYMMDDHH`` hours D 01 .. D+1 00 for each date, in order."""
30
+ hours = []
31
+ for date in dates:
32
+ start = datetime.strptime(date, "%Y%m%d")
33
+ hours.extend(
34
+ (start + timedelta(hours=offset)).strftime("%Y%m%d%H")
35
+ for offset in range(1, HOURS_PER_DAY + 1)
36
+ )
37
+ return hours
38
+
39
+
40
+ @dataclass
41
+ class DailyMda8:
42
+ """MDA8 per station and day; NaN/None where it is not determined."""
43
+
44
+ dates: list[str]
45
+ means: np.ndarray # (station, day * 24) mean ending at each hour
46
+ mda8: np.ndarray # (station, day)
47
+ first_hour: np.ndarray # (station, day) object: YYYYMMDDHH or None
48
+ last_hour: np.ndarray # (station, day) object: YYYYMMDDHH or None
49
+ valid_means: np.ndarray # (station, day) int
50
+ exceeded: np.ndarray # (station, day) object: True, False or None
51
+
52
+ @property
53
+ def daily(self) -> np.ndarray:
54
+ """The judged value of each station and day."""
55
+ return self.mda8
56
+
57
+
58
+ @dataclass
59
+ class DailyMean:
60
+ """Daily mean per station and day; NaN/None where it is not determined."""
61
+
62
+ dates: list[str]
63
+ mean: np.ndarray # (station, day)
64
+ valid_hours: np.ndarray # (station, day) int
65
+ exceeded: np.ndarray # (station, day) object: True, False or None
66
+
67
+ @property
68
+ def daily(self) -> np.ndarray:
69
+ """The judged value of each station and day."""
70
+ return self.mean
71
+
72
+
73
+ def daily_mean(
74
+ values: np.ndarray, dates: list[str], limit: float
75
+ ) -> DailyMean:
76
+ """Daily means of ``values(station, hour)`` read at ``day_hours``."""
77
+ days = values.reshape(values.shape[0], len(dates), HOURS_PER_DAY)
78
+ counts = np.isfinite(days).sum(axis=2)
79
+ enough = counts >= MIN_HOURS_PER_DAY
80
+ totals = np.nansum(days, axis=2)
81
+ mean = np.full(counts.shape, np.nan)
82
+ # Rounded so that a mean equal to the limit compares equal.
83
+ mean[enough] = np.round(totals[enough] / counts[enough], 6)
84
+ exceeded = np.full(counts.shape, None, dtype=object)
85
+ for station, day in zip(*np.nonzero(enough), strict=True):
86
+ exceeded[station, day] = bool(mean[station, day] > limit)
87
+ return DailyMean(
88
+ dates=dates, mean=mean, valid_hours=counts, exceeded=exceeded
89
+ )
90
+
91
+
92
+ def eight_hour_means(day: np.ndarray) -> np.ndarray:
93
+ """Means ending at each of a day's 24 hours; NaN before hour 08."""
94
+ stations = day.shape[0]
95
+ means = np.full((stations, HOURS_PER_DAY), np.nan)
96
+ for end in range(FIRST_MEAN_END - 1, HOURS_PER_DAY):
97
+ window = day[:, end - WINDOW + 1 : end + 1]
98
+ counts = np.isfinite(window).sum(axis=1)
99
+ totals = np.nansum(window, axis=1)
100
+ enough = counts >= MIN_HOURS_PER_MEAN
101
+ # Rounded so that equal windows compare equal for the earliest tie.
102
+ means[enough, end] = np.round(totals[enough] / counts[enough], 6)
103
+ return means
104
+
105
+
106
+ def daily_mda8(
107
+ values: np.ndarray, hours: list[str], dates: list[str], limit: float
108
+ ) -> DailyMda8:
109
+ """MDA8 for ``values(station, hour)`` read at ``day_hours(dates)``."""
110
+ stations = values.shape[0]
111
+ shape = (stations, len(dates))
112
+ result = DailyMda8(
113
+ dates=dates,
114
+ means=np.full(values.shape, np.nan),
115
+ mda8=np.full(shape, np.nan),
116
+ first_hour=np.full(shape, None, dtype=object),
117
+ last_hour=np.full(shape, None, dtype=object),
118
+ valid_means=np.zeros(shape, dtype=int),
119
+ exceeded=np.full(shape, None, dtype=object),
120
+ )
121
+ for day_index in range(len(dates)):
122
+ offset = day_index * HOURS_PER_DAY
123
+ columns = slice(offset, offset + HOURS_PER_DAY)
124
+ means = eight_hour_means(values[:, columns])
125
+ result.means[:, columns] = means
126
+ valid = np.isfinite(means)
127
+ result.valid_means[:, day_index] = valid.sum(axis=1)
128
+ for station in np.flatnonzero(valid.any(axis=1)):
129
+ end = int(np.nanargmax(means[station]))
130
+ best = float(means[station, end])
131
+ count = int(valid[station].sum())
132
+ if count < MIN_VALID_MEANS and not best > limit:
133
+ continue
134
+ result.mda8[station, day_index] = best
135
+ result.first_hour[station, day_index] = hours[
136
+ offset + end - WINDOW + 1
137
+ ]
138
+ result.last_hour[station, day_index] = hours[offset + end]
139
+ result.exceeded[station, day_index] = best > limit
140
+ return result
rsplot/fnr.py CHANGED
@@ -40,6 +40,7 @@ from rsplot.temporal import (
40
40
  WindowResult,
41
41
  compute_window_mean,
42
42
  parse_date_window,
43
+ read_scan_mean,
43
44
  )
44
45
 
45
46
  if TYPE_CHECKING:
@@ -127,6 +128,7 @@ class FnrResult:
127
128
  n_min: int
128
129
  no2_min_column: float
129
130
  diagnostic_masks: dict[str, np.ndarray]
131
+ sensor: str = "tropomi"
130
132
  processing: str | None = None
131
133
  daily_metadata_no2: dict[str, Any] = field(default_factory=dict)
132
134
  daily_metadata_hcho: dict[str, Any] = field(default_factory=dict)
@@ -142,20 +144,22 @@ def compute_fnr(
142
144
  res: float,
143
145
  qa_threshold: float,
144
146
  cloud_fraction_max: float = 0.5,
147
+ sensor: str = "tropomi",
145
148
  processing: str | None = None,
149
+ scan_request: str | None = None,
146
150
  n_min: int,
147
151
  raster_dir_no2: str,
148
152
  raster_dir_hcho: str,
149
153
  no2_min_column: float = NO2_MIN_COLUMN,
150
154
  console: Console | None = None,
151
155
  ) -> FnrResult:
152
- """Read NO2 + HCHO over a date window and compute per-pixel FNR.
156
+ """Read NO2 + HCHO over a date window or GEMS scan and compute FNR.
153
157
 
154
- Each daily swath/grid is first binned onto the same target grid, then
155
- the two time-stacks are averaged and divided. Pixels with fewer than
156
- ``n_min`` valid days in *either* product, or with mean NO2 below
157
- ``no2_min_column``, are masked to NaN. Nothing is filled or smoothed;
158
- smoothing is display-only (:func:`smooth_fnr_for_display`).
158
+ Each daily swath/grid (or single GEMS scan) is gridded onto the same
159
+ target grid, averaged across the window when applicable, and divided.
160
+ Pixels with fewer than ``n_min`` valid days in *either* product, or with
161
+ mean NO2 below ``no2_min_column``, are masked to NaN. Nothing is filled
162
+ or smoothed; smoothing is display-only (:func:`smooth_fnr_for_display`).
159
163
  """
160
164
  if console is None:
161
165
  console = Console()
@@ -168,71 +172,100 @@ def compute_fnr(
168
172
  region.extent[3] + buf,
169
173
  )
170
174
 
171
- if processing is None:
172
- no2_reader = get_product_info("no2").reader_cls()
173
- hcho_reader = get_product_info("hcho").reader_cls()
174
- else:
175
- no2_info = get_product_info("no2", processing=processing)
176
- hcho_info = get_product_info("hcho", processing=processing)
177
- no2_reader = no2_info.create_reader()
178
- hcho_reader = hcho_info.create_reader()
179
- processing = no2_info.processing
175
+ no2_info = get_product_info("no2", sensor=sensor, processing=processing)
176
+ hcho_info = get_product_info("hcho", sensor=sensor, processing=processing)
177
+ no2_reader = no2_info.create_reader()
178
+ hcho_reader = hcho_info.create_reader()
179
+ processing = no2_info.processing
180
180
  no2_reader.cloud_fraction_max = cloud_fraction_max
181
181
  hcho_reader.cloud_fraction_max = cloud_fraction_max
182
182
 
183
- # --- Read each product over the window via the shared helper ---
184
- no2_win = compute_window_mean(
185
- reader=no2_reader,
186
- data_dir=raster_dir_no2,
187
- dates=dates,
188
- extent=read_extent,
189
- res=res,
190
- qa_threshold=qa_threshold,
191
- label="NO2",
192
- console=console,
193
- )
194
- hcho_win = compute_window_mean(
195
- reader=hcho_reader,
196
- data_dir=raster_dir_hcho,
197
- dates=dates,
198
- extent=read_extent,
199
- res=res,
200
- qa_threshold=qa_threshold,
201
- label="HCHO",
202
- console=console,
203
- )
183
+ if scan_request is not None:
184
+ no2_batch = read_scan_mean(
185
+ reader=no2_reader,
186
+ data_dir=raster_dir_no2,
187
+ request=scan_request,
188
+ extent=read_extent,
189
+ res=res,
190
+ )
191
+ hcho_batch = read_scan_mean(
192
+ reader=hcho_reader,
193
+ data_dir=raster_dir_hcho,
194
+ request=scan_request,
195
+ extent=read_extent,
196
+ res=res,
197
+ )
198
+ LON, LAT = no2_batch.LON, no2_batch.LAT
199
+ no2_grid, hcho_grid = no2_batch.grid, hcho_batch.grid
200
+ n_valid_no2 = np.isfinite(no2_grid).astype(np.int32)
201
+ n_valid_hcho = np.isfinite(hcho_grid).astype(np.int32)
202
+ dates_found_no2 = [scan_request[:8]]
203
+ dates_found_hcho = [scan_request[:8]]
204
+ dates_failed_no2: dict[str, str] = {}
205
+ dates_failed_hcho: dict[str, str] = {}
206
+ daily_meta_no2 = {scan_request: no2_batch.metadata}
207
+ daily_meta_hcho = {scan_request: hcho_batch.metadata}
208
+ else:
209
+ no2_win = compute_window_mean(
210
+ reader=no2_reader,
211
+ data_dir=raster_dir_no2,
212
+ dates=dates,
213
+ extent=read_extent,
214
+ res=res,
215
+ qa_threshold=qa_threshold,
216
+ label="NO2",
217
+ console=console,
218
+ )
219
+ hcho_win = compute_window_mean(
220
+ reader=hcho_reader,
221
+ data_dir=raster_dir_hcho,
222
+ dates=dates,
223
+ extent=read_extent,
224
+ res=res,
225
+ qa_threshold=qa_threshold,
226
+ label="HCHO",
227
+ console=console,
228
+ )
229
+ LON, LAT = no2_win.LON, no2_win.LAT
230
+ no2_grid, hcho_grid = no2_win.grid, hcho_win.grid
231
+ n_valid_no2, n_valid_hcho = no2_win.n_valid, hcho_win.n_valid
232
+ dates_found_no2 = no2_win.dates_found
233
+ dates_found_hcho = hcho_win.dates_found
234
+ dates_failed_no2 = no2_win.dates_failed
235
+ dates_failed_hcho = hcho_win.dates_failed
236
+ daily_meta_no2 = no2_win.daily_metadata
237
+ daily_meta_hcho = hcho_win.daily_metadata
204
238
 
205
- LON, LAT = no2_win.LON, no2_win.LAT
206
239
  shape = LON.shape
207
240
 
208
241
  # --- Combined coverage mask: need n_min valid days in BOTH products ---
209
- coverage_ok = (no2_win.n_valid >= n_min) & (hcho_win.n_valid >= n_min)
242
+ coverage_ok = (n_valid_no2 >= n_min) & (n_valid_hcho >= n_min)
210
243
 
211
244
  # --- NO2-min mask: avoid dividing by tiny NO2 backgrounds ---
212
- no2_ok = np.isfinite(no2_win.grid) & (no2_win.grid >= no2_min_column)
245
+ no2_ok = np.isfinite(no2_grid) & (no2_grid >= no2_min_column)
213
246
 
214
247
  # HCHO retrieval noise can yield negative columns; do not let those
215
248
  # become negative FNR values that classify as VOC-limited.
216
- hcho_ok = np.isfinite(hcho_win.grid) & (hcho_win.grid >= 0)
249
+ hcho_ok = np.isfinite(hcho_grid) & (hcho_grid >= 0)
217
250
 
218
251
  valid = coverage_ok & no2_ok & hcho_ok
219
252
 
220
253
  fnr = np.full(shape, np.nan)
221
254
  with np.errstate(divide="ignore", invalid="ignore"):
222
- fnr[valid] = hcho_win.grid[valid] / no2_win.grid[valid]
255
+ fnr[valid] = hcho_grid[valid] / no2_grid[valid]
223
256
 
224
257
  region_mask = region_grid_mask(LON, LAT, region.geometry)
225
258
  hcho_raw = mask_to_region(
226
259
  LON,
227
260
  LAT,
228
- hcho_win.grid,
261
+ hcho_grid,
229
262
  region.geometry,
230
263
  region_mask=region_mask,
231
264
  )
232
265
  no2_raw = mask_to_region(
233
266
  LON,
234
267
  LAT,
235
- no2_win.grid,
268
+ no2_grid,
236
269
  region.geometry,
237
270
  region_mask=region_mask,
238
271
  )
@@ -242,21 +275,22 @@ def compute_fnr(
242
275
  )
243
276
 
244
277
  return FnrResult(
278
+ sensor=sensor,
245
279
  processing=processing,
246
- daily_metadata_no2=no2_win.daily_metadata,
247
- daily_metadata_hcho=hcho_win.daily_metadata,
280
+ daily_metadata_no2=daily_meta_no2,
281
+ daily_metadata_hcho=daily_meta_hcho,
248
282
  LON=LON,
249
283
  LAT=LAT,
250
284
  fnr=fnr,
251
285
  hcho_mean=hcho_raw,
252
286
  no2_mean=no2_raw,
253
- n_valid_hcho=hcho_win.n_valid,
254
- n_valid_no2=no2_win.n_valid,
287
+ n_valid_hcho=n_valid_hcho,
288
+ n_valid_no2=n_valid_no2,
255
289
  dates_requested=list(dates),
256
- dates_found_hcho=hcho_win.dates_found,
257
- dates_found_no2=no2_win.dates_found,
258
- dates_failed_hcho=hcho_win.dates_failed,
259
- dates_failed_no2=no2_win.dates_failed,
290
+ dates_found_hcho=dates_found_hcho,
291
+ dates_found_no2=dates_found_no2,
292
+ dates_failed_hcho=dates_failed_hcho,
293
+ dates_failed_no2=dates_failed_no2,
260
294
  n_min=n_min,
261
295
  no2_min_column=no2_min_column,
262
296
  diagnostic_masks={
@@ -1 +1,7 @@
1
1
  """Plotting module: raster maps, styles, annotations, basemaps."""
2
+
3
+ import matplotlib
4
+
5
+ # rsplot only writes image files. With DISPLAY set, matplotlib would pick a
6
+ # window backend, and opening its window can hang (Tk on a 1x1 Xvfb screen).
7
+ matplotlib.use("Agg")