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,559 @@
1
+ """Exceedance figures: one day's hours, or a station × day heat map.
2
+
3
+ The judged daily value is MDA8 for O3 and the daily mean for PM.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from datetime import datetime, timedelta
9
+
10
+ import matplotlib.dates as mdates
11
+ import matplotlib.pyplot as plt
12
+ import numpy as np
13
+ from matplotlib.collections import LineCollection
14
+ from matplotlib.colors import TwoSlopeNorm
15
+ from matplotlib.ticker import MaxNLocator
16
+
17
+ from rsplot.atomic import atomic_write
18
+ from rsplot.exceedance import DailyMda8, DailyMean
19
+ from rsplot.plotting.station_trend import (
20
+ _background_segments,
21
+ _china_hours,
22
+ _configure_time_axis,
23
+ )
24
+ from rsplot.weather_days import LAYERS as WEATHER_LAYERS
25
+ from rsplot.weather_days import DailyWeather
26
+
27
+ EXCEEDED = "#c8102e"
28
+ CONTEXT = "#8c8c8c"
29
+ # Station rows get tick labels only while they stay readable.
30
+ MAX_LABELLED_ROWS = 60
31
+ WEATHER_LINE = "#2f5d8a"
32
+ EXCEEDED_DAY = "#f6d5d9"
33
+ # Weather panels drawn as bars; the others are lines.
34
+ WEATHER_BARS = ("ssrd_sum", "tp_sum")
35
+ # Bars get count labels, and every day a wind arrow, up to these lengths.
36
+ MAX_COUNT_LABEL_DAYS = 45
37
+ MAX_WIND_ARROWS = 60
38
+ DISPLAY_UNITS = {"ug/m3": "μg/m³", "mg/m3": "mg/m³"}
39
+
40
+
41
+ def plot_exceedance_day(
42
+ *,
43
+ station_ids: np.ndarray,
44
+ hours: list[str],
45
+ values: np.ndarray,
46
+ result: DailyMda8,
47
+ labelled: list[str],
48
+ limit: float,
49
+ hourly_limit: float | None,
50
+ dpi: int,
51
+ output: str,
52
+ title: str,
53
+ ) -> None:
54
+ """Hourly O3 above, 8-hour means below; exceeding stations in red."""
55
+ times = _china_hours(hours)
56
+ time_values = mdates.date2num(times)
57
+ ids = [str(item) for item in station_ids]
58
+ exceeded = {
59
+ index
60
+ for index in range(len(ids))
61
+ if any(item is True for item in result.exceeded[index])
62
+ }
63
+ fig, (top, bottom) = plt.subplots(
64
+ 2, 1, figsize=(11, 7.6), dpi=dpi, sharex=True
65
+ )
66
+ try:
67
+ for ax, data, line, name in (
68
+ (top, values, hourly_limit, "小时 O3"),
69
+ (bottom, result.means, limit, "8 小时滑动均值"),
70
+ ):
71
+ segments = _background_segments(
72
+ time_values, data, excluded_indices=exceeded
73
+ )
74
+ if segments:
75
+ ax.add_collection(
76
+ LineCollection(
77
+ segments,
78
+ colors=CONTEXT,
79
+ linewidths=0.7,
80
+ alpha=0.45,
81
+ zorder=1,
82
+ )
83
+ )
84
+ for index in sorted(exceeded):
85
+ ax.plot(
86
+ times,
87
+ data[index],
88
+ color=EXCEEDED,
89
+ linewidth=1.6,
90
+ zorder=3,
91
+ )
92
+ if line is not None:
93
+ ax.axhline(
94
+ line,
95
+ color="#333333",
96
+ linestyle="--",
97
+ linewidth=1.0,
98
+ zorder=2,
99
+ )
100
+ ax.annotate(
101
+ f"限值 {line:g}",
102
+ xy=(0, line),
103
+ xycoords=("axes fraction", "data"),
104
+ xytext=(4, 3),
105
+ textcoords="offset points",
106
+ va="bottom",
107
+ fontsize=8,
108
+ color="#333333",
109
+ )
110
+ ax.set_ylabel(f"{name} (μg/m³)", fontsize=10)
111
+ ax.grid(True, color="#e0e0e0", linewidth=0.6)
112
+ ax.set_axisbelow(True)
113
+ ax.tick_params(axis="both", labelsize=9)
114
+ top_value = np.nanmax(data) if np.isfinite(data).any() else 0
115
+ ax.set_ylim(0, max(top_value, line or 0) * 1.15 or 1)
116
+
117
+ _label_peaks(bottom, times, hours, ids, labelled, result)
118
+
119
+ _configure_time_axis(bottom, times)
120
+ padding = timedelta(minutes=30)
121
+ bottom.set_xlim(times[0] - padding, times[-1] + padding)
122
+ bottom.set_xlabel("时间", fontsize=10)
123
+ fig.suptitle(title, fontsize=14, y=0.975)
124
+ fig.text(
125
+ 0.5,
126
+ 0.925,
127
+ f"{_summary(ids, result, limit, 'MDA8', 'μg/m³')} · "
128
+ "红线超标,灰线未超标",
129
+ ha="center",
130
+ fontsize=9,
131
+ color="#555555",
132
+ )
133
+ fig.subplots_adjust(left=0.08, right=0.88, top=0.89, hspace=0.08)
134
+ with atomic_write(output) as temp:
135
+ fig.savefig(temp, dpi=dpi, bbox_inches="tight")
136
+ finally:
137
+ plt.close(fig)
138
+
139
+
140
+ def plot_daily_mean_day(
141
+ *,
142
+ station_ids: np.ndarray,
143
+ hours: list[str],
144
+ values: np.ndarray,
145
+ result: DailyMean,
146
+ labelled: list[str],
147
+ limit: float,
148
+ hourly_limit: float | None,
149
+ var: str,
150
+ unit: str,
151
+ dpi: int,
152
+ output: str,
153
+ title: str,
154
+ ) -> None:
155
+ """Hourly values above, each station's daily mean below.
156
+
157
+ Stations are judged by the daily mean, whose limit is drawn on the
158
+ bars. A 1-hour limit (NO2, SO2, CO; none for PM) is drawn on the
159
+ hourly values as a reference only.
160
+ """
161
+ shown = DISPLAY_UNITS[unit]
162
+ times = _china_hours(hours)
163
+ time_values = mdates.date2num(times)
164
+ ids = [str(item) for item in station_ids]
165
+ means = result.mean[:, 0]
166
+ exceeded = {
167
+ index for index in range(len(ids)) if result.exceeded[index, 0]
168
+ }
169
+ fig, (top, bottom) = plt.subplots(
170
+ 2, 1, figsize=(11, 7.6), dpi=dpi, gridspec_kw={"hspace": 0.32}
171
+ )
172
+ try:
173
+ segments = _background_segments(
174
+ time_values, values, excluded_indices=exceeded
175
+ )
176
+ if segments:
177
+ top.add_collection(
178
+ LineCollection(
179
+ segments,
180
+ colors=CONTEXT,
181
+ linewidths=0.7,
182
+ alpha=0.45,
183
+ zorder=1,
184
+ )
185
+ )
186
+ for index in sorted(exceeded):
187
+ top.plot(
188
+ times, values[index], color=EXCEEDED, linewidth=1.6, zorder=3
189
+ )
190
+ if hourly_limit is not None:
191
+ _limit_line(top, hourly_limit, "小时限值", side=0)
192
+ peak = np.nanmax(values) if np.isfinite(values).any() else 0
193
+ top.set_ylim(0, max(peak, hourly_limit or 0) * 1.15 or 1)
194
+ top.set_ylabel(f"小时 {var} ({shown})", fontsize=10)
195
+ _configure_time_axis(top, times)
196
+ padding = timedelta(minutes=30)
197
+ top.set_xlim(times[0] - padding, times[-1] + padding)
198
+
199
+ finite = np.isfinite(means)
200
+ order = sorted(
201
+ range(len(ids)),
202
+ key=lambda index: -means[index] if finite[index] else np.inf,
203
+ )
204
+ heights = np.where(finite, means, 0)[order]
205
+ bottom.bar(
206
+ range(len(order)),
207
+ heights,
208
+ width=0.7,
209
+ color=[
210
+ EXCEEDED if index in exceeded else CONTEXT for index in order
211
+ ],
212
+ )
213
+ for position, index in enumerate(order):
214
+ if ids[index] in labelled:
215
+ bottom.annotate(
216
+ f"{means[index]:.3g}",
217
+ xy=(position, means[index]),
218
+ xytext=(0, 2),
219
+ textcoords="offset points",
220
+ ha="center",
221
+ fontsize=8,
222
+ )
223
+ _limit_line(bottom, limit, "日均限值", side=1)
224
+ top_mean = float(np.nanmax(means)) if finite.any() else 0.0
225
+ bottom.set_ylim(0, max(top_mean, limit) * 1.15)
226
+ bottom.set_xlim(-0.6, len(order) - 0.4)
227
+ if len(order) <= MAX_LABELLED_ROWS:
228
+ bottom.set_xticks(range(len(order)))
229
+ bottom.set_xticklabels(
230
+ [ids[index] for index in order], rotation=90, fontsize=7
231
+ )
232
+ else:
233
+ bottom.set_xticks([])
234
+ bottom.set_xlabel(f"{len(order)} 个站点(按日均排序)")
235
+ bottom.set_ylabel(f"{var} 日均 ({shown})", fontsize=10)
236
+ for ax in (top, bottom):
237
+ ax.grid(True, axis="y", color="#e0e0e0", linewidth=0.6)
238
+ ax.set_axisbelow(True)
239
+ ax.tick_params(axis="y", labelsize=9)
240
+ fig.suptitle(title, fontsize=14, y=0.975)
241
+ fig.text(
242
+ 0.5,
243
+ 0.925,
244
+ f"{_summary(ids, result, limit, '日均', shown)} · "
245
+ "红色超标,灰色未超标(日均需 ≥20 个有效小时)",
246
+ ha="center",
247
+ fontsize=9,
248
+ color="#555555",
249
+ )
250
+ fig.subplots_adjust(left=0.08, right=0.92, top=0.89)
251
+ with atomic_write(output) as temp:
252
+ fig.savefig(temp, dpi=dpi, bbox_inches="tight")
253
+ finally:
254
+ plt.close(fig)
255
+
256
+
257
+ def plot_exceedance_range(
258
+ *,
259
+ station_ids: np.ndarray,
260
+ result: DailyMda8 | DailyMean,
261
+ limit: float,
262
+ quantity_label: str,
263
+ statistic: str,
264
+ unit: str,
265
+ dpi: int,
266
+ output: str,
267
+ title: str,
268
+ weather: DailyWeather | None = None,
269
+ ) -> None:
270
+ """Daily values per station and day, with each day's exceeding count.
271
+
272
+ ``quantity_label`` names the colour bar (``MDA8 O3``) and ``statistic``
273
+ the judged value in text (``MDA8``, ``日均``).
274
+
275
+ With ``weather``, one panel per weather layer follows on the same day
276
+ axis, with the days on which any station exceeded shaded.
277
+ """
278
+ ids = [str(item) for item in station_ids]
279
+ daily = result.daily
280
+ peaks = np.where(np.isfinite(daily), daily, -np.inf).max(1)
281
+ order = sorted(range(len(ids)), key=lambda index: -peaks[index])
282
+ grid = daily[order]
283
+ days = len(result.dates)
284
+ rows = len(order)
285
+ panels = WEATHER_LAYERS if weather is not None else ()
286
+ height = min(14.0, 3.6 + 0.18 * rows) + 1.1 * len(panels)
287
+ width = min(16.0, max(8.0, 4.0 + 0.32 * days))
288
+ fig, axes = plt.subplots(
289
+ 2 + len(panels),
290
+ 1,
291
+ figsize=(width, height),
292
+ dpi=dpi,
293
+ sharex=True,
294
+ gridspec_kw={
295
+ "height_ratios": [1, max(2.0, rows / 8), *[0.9] * len(panels)]
296
+ },
297
+ )
298
+ counts, heat = axes[0], axes[1]
299
+ try:
300
+ exceeded = [
301
+ sum(item is True for item in result.exceeded[:, day])
302
+ for day in range(days)
303
+ ]
304
+ counts.bar(range(days), exceeded, color=EXCEEDED, width=0.7)
305
+ counts.set_ylabel("超标站数", fontsize=10)
306
+ counts.set_ylim(0, max(1, max(exceeded)) * 1.2)
307
+ counts.grid(True, axis="y", color="#e0e0e0", linewidth=0.6)
308
+ counts.set_axisbelow(True)
309
+ for day, count in enumerate(exceeded):
310
+ if count and days <= MAX_COUNT_LABEL_DAYS:
311
+ counts.annotate(
312
+ str(count),
313
+ xy=(day, count),
314
+ xytext=(0, 2),
315
+ textcoords="offset points",
316
+ ha="center",
317
+ fontsize=8,
318
+ )
319
+
320
+ finite = grid[np.isfinite(grid)]
321
+ high = max(limit * 1.5, float(finite.max()) if finite.size else 0)
322
+ low = min(limit * 0.5, float(finite.min()) if finite.size else limit)
323
+ cmap = plt.get_cmap("RdBu_r").copy()
324
+ cmap.set_bad("#eeeeee")
325
+ image = heat.imshow(
326
+ np.ma.masked_invalid(grid),
327
+ aspect="auto",
328
+ cmap=cmap,
329
+ norm=TwoSlopeNorm(vcenter=limit, vmin=low, vmax=high),
330
+ interpolation="nearest",
331
+ )
332
+ # An inset colorbar keeps every panel on the same day axis width.
333
+ colorbar = fig.colorbar(
334
+ image, cax=heat.inset_axes((1.01, 0.0, 0.015, 1.0))
335
+ )
336
+ colorbar.set_label(
337
+ f"{quantity_label} ({DISPLAY_UNITS[unit]})", fontsize=9
338
+ )
339
+ colorbar.ax.axhline(limit, color="#333333", linewidth=1.0)
340
+ if rows <= MAX_LABELLED_ROWS:
341
+ heat.set_yticks(range(rows))
342
+ heat.set_yticklabels([ids[index] for index in order], fontsize=7)
343
+ else:
344
+ heat.set_yticks([])
345
+ heat.set_ylabel(
346
+ f"{rows} 个站点(按最高 {statistic} 排序)", fontsize=9
347
+ )
348
+ exceeded_days = [day for day, count in enumerate(exceeded) if count]
349
+ for ax, spec in zip(axes[2:], panels, strict=True):
350
+ _weather_panel(ax, weather, spec, exceeded_days)
351
+ bottom = axes[-1]
352
+ dates = [datetime.strptime(date, "%Y%m%d") for date in result.dates]
353
+ step = max(1, round(days / 12))
354
+ bottom.set_xticks(range(0, days, step))
355
+ bottom.set_xticklabels(
356
+ [dates[day].strftime("%m-%d") for day in range(0, days, step)],
357
+ fontsize=8,
358
+ )
359
+ bottom.set_xlabel("日期", fontsize=10)
360
+ # A fixed margin in inches keeps the title close on tall figures.
361
+ fig.subplots_adjust(top=1 - 0.95 / height)
362
+ fig.suptitle(title, fontsize=14, y=1 - 0.3 / height)
363
+ counts.set_title(
364
+ _summary(ids, result, limit, statistic, DISPLAY_UNITS[unit]),
365
+ fontsize=9,
366
+ color="#555555",
367
+ pad=10,
368
+ )
369
+ with atomic_write(output) as temp:
370
+ fig.savefig(temp, dpi=dpi, bbox_inches="tight")
371
+ finally:
372
+ plt.close(fig)
373
+
374
+
375
+ def _limit_line(ax, value: float, name: str, *, side: int) -> None:
376
+ """A dashed limit, labelled inside the left (0) or right (1) edge."""
377
+ ax.axhline(value, color="#333333", linestyle="--", linewidth=1.0, zorder=2)
378
+ ax.annotate(
379
+ f"{name} {value:g}",
380
+ xy=(side, value),
381
+ xycoords=("axes fraction", "data"),
382
+ xytext=(4 if side == 0 else -4, 3),
383
+ textcoords="offset points",
384
+ ha="left" if side == 0 else "right",
385
+ va="bottom",
386
+ fontsize=8,
387
+ color="#333333",
388
+ )
389
+
390
+
391
+ def _weather_panel(ax, weather, spec, exceeded_days: list[int]) -> None:
392
+ """One weather layer per day; days with an exceeding station shaded."""
393
+ days = np.arange(len(weather.dates))
394
+ values = weather.values[spec.id]
395
+ for day in exceeded_days:
396
+ ax.axvspan(day - 0.5, day + 0.5, color=EXCEEDED_DAY, zorder=0)
397
+ if spec.id in WEATHER_BARS:
398
+ ax.bar(days, values, width=0.7, color=WEATHER_LINE, zorder=2)
399
+ else:
400
+ ax.plot(
401
+ days,
402
+ values,
403
+ color=WEATHER_LINE,
404
+ linewidth=1.2,
405
+ marker="o",
406
+ markersize=2.5,
407
+ zorder=2,
408
+ )
409
+ if spec.id == "wind_10m":
410
+ speed = np.hypot(weather.wind_u, weather.wind_v)
411
+ step = int(np.ceil(len(days) / MAX_WIND_ARROWS))
412
+ usable = np.isfinite(values) & (speed > 0) & (days % step == 0)
413
+ ax.quiver(
414
+ days[usable],
415
+ values[usable],
416
+ weather.wind_u[usable] / speed[usable],
417
+ weather.wind_v[usable] / speed[usable],
418
+ angles="uv",
419
+ pivot="middle",
420
+ color="#333333",
421
+ width=0.0015,
422
+ headwidth=4,
423
+ scale=70,
424
+ zorder=3,
425
+ )
426
+ finite = values[np.isfinite(values)]
427
+ top = float(finite.max()) if finite.size else 1.0
428
+ low = min(0.0, float(finite.min())) if finite.size else 0.0
429
+ ax.set_ylim(low, top * 1.15 if top > 0 else 1.0)
430
+ ax.set_ylabel(spec.label, fontsize=8)
431
+ ax.grid(True, axis="y", color="#e0e0e0", linewidth=0.6)
432
+ ax.set_axisbelow(True)
433
+ ax.tick_params(axis="both", labelsize=8)
434
+
435
+
436
+ def _label_peaks(
437
+ ax,
438
+ times: list[datetime],
439
+ hours: list[str],
440
+ ids: list[str],
441
+ labelled: list[str],
442
+ result: DailyMda8,
443
+ ) -> None:
444
+ """Mark each labelled station's MDA8 window end; name it at the right.
445
+
446
+ Names are stacked highest first in the right margin, at least one text
447
+ height apart, with a thin leader line to the marked point.
448
+ """
449
+ if not labelled:
450
+ return
451
+ low, high = ax.get_ylim()
452
+ gap = (high - low) * 0.055
453
+ position = high
454
+ for station_id in labelled:
455
+ index = ids.index(station_id)
456
+ day = int(np.nanargmax(np.nan_to_num(result.mda8[index], nan=-1)))
457
+ end = hours.index(result.last_hour[index, day])
458
+ value = float(result.mda8[index, day])
459
+ position = min(position - gap, value) if position < high else value
460
+ ax.plot(
461
+ times[end],
462
+ value,
463
+ marker="o",
464
+ markersize=4,
465
+ color=EXCEEDED,
466
+ markeredgecolor="white",
467
+ markeredgewidth=0.8,
468
+ zorder=5,
469
+ )
470
+ ax.annotate(
471
+ f"{station_id} {value:.0f}",
472
+ xy=(times[end], value),
473
+ xytext=(1.01, position),
474
+ textcoords=("axes fraction", "data"),
475
+ va="center",
476
+ fontsize=8,
477
+ color="#222222",
478
+ arrowprops={
479
+ "arrowstyle": "-",
480
+ "color": "#9a9a9a",
481
+ "linewidth": 0.6,
482
+ "shrinkA": 0,
483
+ "shrinkB": 3,
484
+ },
485
+ annotation_clip=False,
486
+ )
487
+
488
+
489
+ def _summary(
490
+ ids: list[str],
491
+ result: DailyMda8 | DailyMean,
492
+ limit: float,
493
+ statistic: str,
494
+ shown: str,
495
+ ) -> str:
496
+ judged = int(np.isfinite(result.daily).sum())
497
+ exceeded = int((result.exceeded == True).sum()) # noqa: E712
498
+ return (
499
+ f"{statistic} > {limit:g} {shown} 的站日 {exceeded}/{judged} · "
500
+ f"站点 {len(ids)} 个"
501
+ )
502
+
503
+
504
+ def plot_screening(
505
+ dates: list[str],
506
+ days_by_var: dict[str, list[dict]],
507
+ title: str,
508
+ output: str,
509
+ dpi: int,
510
+ ) -> None:
511
+ """Daily exceeding-station counts, with unjudged days shown in grey."""
512
+ grid = np.array(
513
+ [
514
+ [day["exceeded"] if day["judged"] else np.nan for day in days]
515
+ for days in days_by_var.values()
516
+ ]
517
+ )
518
+ finite = grid[np.isfinite(grid)]
519
+ high = max(1, int(finite.max()) if finite.size else 0)
520
+ width = min(16, max(7, len(dates) * 0.42))
521
+ fig, ax = plt.subplots(figsize=(width, 4), layout="constrained")
522
+ try:
523
+ cmap = plt.get_cmap("YlOrRd").copy()
524
+ cmap.set_bad("#dddddd")
525
+ heat = ax.imshow(
526
+ grid,
527
+ cmap=cmap,
528
+ vmin=0,
529
+ vmax=high,
530
+ aspect="auto",
531
+ interpolation="nearest",
532
+ )
533
+ colorbar = fig.colorbar(heat, ax=ax)
534
+ colorbar.locator = MaxNLocator(integer=True)
535
+ colorbar.update_ticks()
536
+ colorbar.set_label("超标站数")
537
+ ax.set_yticks(range(len(grid)), list(days_by_var))
538
+ step = max(1, (len(dates) + 11) // 12)
539
+ ticks = range(0, len(dates), step)
540
+ ax.set_xticks(
541
+ ticks, [dates[i][4:6] + "-" + dates[i][6:] for i in ticks]
542
+ )
543
+ ax.set_xlabel("日期(灰色表示无可判断站点)")
544
+ ax.set_title(title)
545
+ if len(dates) <= 20:
546
+ for (row, day), count in np.ndenumerate(grid):
547
+ if np.isfinite(count):
548
+ ax.text(
549
+ day,
550
+ row,
551
+ str(int(count)),
552
+ ha="center",
553
+ va="center",
554
+ color="white" if count > high * 0.6 else "#282828",
555
+ )
556
+ with atomic_write(output) as temp:
557
+ fig.savefig(temp, dpi=dpi, bbox_inches="tight")
558
+ finally:
559
+ plt.close(fig)