rsplot 0.3.1.dev3__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 (71) hide show
  1. rsplot/atomic.py +36 -0
  2. rsplot/cli.py +282 -469
  3. rsplot/commands/common.py +113 -1
  4. rsplot/commands/fnr.py +389 -104
  5. rsplot/commands/forecast.py +24 -7
  6. rsplot/commands/meteo.py +499 -186
  7. rsplot/commands/overlay.py +292 -205
  8. rsplot/commands/radius.py +526 -0
  9. rsplot/commands/raster.py +479 -230
  10. rsplot/commands/reconstruct.py +27 -6
  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 +46 -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 +317 -11
  19. rsplot/geo/footprints.py +205 -0
  20. rsplot/geo/processing.py +84 -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 +203 -9
  25. rsplot/plotting/meteo.py +10 -3
  26. rsplot/plotting/overlay.py +36 -40
  27. rsplot/plotting/raster.py +15 -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 +89 -7
  33. rsplot/readers/_tropomi.py +121 -3
  34. rsplot/readers/base.py +16 -1
  35. rsplot/readers/era5.py +110 -10
  36. rsplot/readers/era5_wind.py +3 -2
  37. rsplot/readers/gems.py +429 -0
  38. rsplot/readers/guokong.py +125 -39
  39. rsplot/readers/netcdf.py +32 -0
  40. rsplot/readers/tropomi_hcho.py +1 -1
  41. rsplot/readers/tropomi_no2.py +1 -1
  42. rsplot/readers/tropomi_nrti.py +116 -0
  43. rsplot/readers/tropomi_o3.py +1 -1
  44. rsplot/readers/tropomi_o3pr.py +1 -1
  45. rsplot/result_builders/__init__.py +0 -14
  46. rsplot/result_builders/common.py +84 -0
  47. rsplot/result_builders/envelope.py +236 -0
  48. rsplot/result_builders/fnr.py +47 -131
  49. rsplot/result_builders/forecast.py +7 -0
  50. rsplot/result_builders/provenance.py +59 -0
  51. rsplot/result_builders/reconstruct.py +7 -0
  52. rsplot/result_builders/satellite.py +240 -0
  53. rsplot/result_builders/series_layer.py +289 -0
  54. rsplot/result_builders/station.py +23 -0
  55. rsplot/result_builders/station_layer.py +326 -0
  56. rsplot/results.py +0 -12
  57. rsplot/schemas/result.schema.json +566 -0
  58. rsplot/temporal.py +146 -16
  59. rsplot-0.3.2.dev37.dist-info/METADATA +996 -0
  60. rsplot-0.3.2.dev37.dist-info/RECORD +76 -0
  61. {rsplot-0.3.1.dev3.dist-info → rsplot-0.3.2.dev37.dist-info}/WHEEL +1 -1
  62. rsplot/commands/recent.py +0 -164
  63. rsplot/recent.py +0 -404
  64. rsplot/result_builders/meteo.py +0 -171
  65. rsplot/result_builders/overlay.py +0 -75
  66. rsplot/result_builders/raster.py +0 -72
  67. rsplot/result_builders/station_trend.py +0 -229
  68. rsplot-0.3.1.dev3.dist-info/METADATA +0 -477
  69. rsplot-0.3.1.dev3.dist-info/RECORD +0 -64
  70. {rsplot-0.3.1.dev3.dist-info → rsplot-0.3.2.dev37.dist-info}/entry_points.txt +0 -0
  71. {rsplot-0.3.1.dev3.dist-info → rsplot-0.3.2.dev37.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,76 @@
1
+ rsplot/__init__.py,sha256=3Ruc0uv8gybHmJAfHMssKlx4uZm11vfRK3qljZXs5WU,318
2
+ rsplot/__main__.py,sha256=8_HlBH7_zVm8ZVDcTcqTylcu2BPnU9zZ2Hnnw3sHItE,96
3
+ rsplot/atomic.py,sha256=-jd1FMIpgiqF9ZyqI1SluHEgk97EkUXn25iucuX_2gs,1197
4
+ rsplot/cli.py,sha256=BCCHdy24fISm28kNrNbF2a5n1SSMTiBsHRpRSQD_fzc,24114
5
+ rsplot/config.py,sha256=EBbkmMD72kvSA5zEteHUlPOnNFHW-BopYrs518hPJT8,14533
6
+ rsplot/data_files.py,sha256=ROcvzCaTP-qBPyFnmpNVbfWsV8GVl2RWcUmZV1fYMhg,8783
7
+ rsplot/errors.py,sha256=axY2z_D72Jzj0DQV_KpT1DKOTWbzO9_WDgF8feWw6Dk,1103
8
+ rsplot/fnr.py,sha256=j9Fmh9mai8aXXf8xohI1x9B9QYiOldlRf66VgV7AcFQ,11210
9
+ rsplot/results.py,sha256=tu8BMiBHnYpzZrKEzaiCJq7wyucRDbnaVJu4AD-G4AA,917
10
+ rsplot/stats.py,sha256=qDv8NCgS9_6Hu8Ni3dTh54JcBfzYBmW9K9JBLniNGaA,1158
11
+ rsplot/temporal.py,sha256=v3bi_VZz9X0QOvR0_YaUVvXytFpWGg1RenRCWxbHjgY,11475
12
+ rsplot/commands/__init__.py,sha256=zd-RHo-2h_6Jl_ws13RX13PgqMT5q4EWczpBd5Nd5Jk,73
13
+ rsplot/commands/common.py,sha256=mFIZAs4Mz9QCyaWX3zYwBHlk_SSOtcIZvDnyTKS4El8,7397
14
+ rsplot/commands/fnr.py,sha256=6dhxJRb5EdtV586kc-GUF6lDsBMzgaNNrdzluLQS7gQ,17493
15
+ rsplot/commands/forecast.py,sha256=yeZMOBdjaoNCD9OYu6fjUeXTD2qDKaVPUdPBVTqHC8A,11809
16
+ rsplot/commands/meteo.py,sha256=djaqvwsAwM6Bu1XQOyYbeze5Rs-Vp2fnKCXaEROUrHk,22829
17
+ rsplot/commands/overlay.py,sha256=ZbdJQzwYkj5jD29m-qVpGPwVRkKzSEuKn4nE-wrOVsg,11050
18
+ rsplot/commands/radius.py,sha256=8hZDNpqDQV2Y95Ihylq2PjS3y5ribANkIgWbC98NlKw,17505
19
+ rsplot/commands/raster.py,sha256=vlLyo-3FShmir78dixD69MmyzRUY3mYcB3uibSUhqG4,21342
20
+ rsplot/commands/reconstruct.py,sha256=a3enXXlHXNUd0GfiCb-zdrJDceD_KcHxKUquh-hl66I,7185
21
+ rsplot/commands/sidecar.py,sha256=DsJ1nznw-16f8KEsT0yj4FHQMRlaIkUSwuKKRfgE5K8,3737
22
+ rsplot/commands/station.py,sha256=n2PFBMqRaIlMUECNUx5YnHocC5-2t6GbIZessCID9LI,7541
23
+ rsplot/commands/station_trend.py,sha256=g3PJWEcCKuVdj2ohJxMJo3k3Oowr68Ka29-Me8oICQA,12416
24
+ rsplot/geo/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
25
+ rsplot/geo/boundaries.py,sha256=s-G1tml2PqYAnRjnMJHdvW2-IMggPy1ceRf0hL8eAVY,24929
26
+ rsplot/geo/footprints.py,sha256=UR6a_bEWp-uTicvrM9kFe-dZoboNPCiRwWrxvdRNwZE,7083
27
+ rsplot/geo/gridding.py,sha256=CA1imAZYz5lxYnVJx1SBBXxDf_WaEpiVe10J4EoVefY,4392
28
+ rsplot/geo/processing.py,sha256=oCBzqeC2wCFq2thblCD6vIH83yTS6zK0WrTwGouVLGE,5526
29
+ rsplot/geo/radius.py,sha256=KKTAHMLC-t0ZB3CbqtFt6oqa9KM5vhAql31Zh-sJ5I4,6669
30
+ rsplot/plotting/__init__.py,sha256=DYZUFHxzFHkgH8RvmoqjBTtEg9TYbKlv4-tyVXBR3nY,67
31
+ rsplot/plotting/colormap_22.txt,sha256=eHjRx-ytV1aafK-ulojhvoL7qzzo-1oJ7h7jFwS1k50,10496
32
+ rsplot/plotting/colormaps.py,sha256=g7L_SpC5hnOf_Djnx1Ts2WKi73loJJB6RiNWkcK9fhg,1638
33
+ rsplot/plotting/fnr.py,sha256=RLtyUTzDgLlKQ8SJz_msv4N8TmpMJerq1g8wAN50rN4,4032
34
+ rsplot/plotting/map_frame.py,sha256=cnA35GKwIwlkdcTNW7t5oB0eFLA3YbE4LI6TOBPlb6E,13204
35
+ rsplot/plotting/meteo.py,sha256=48IZfz8TbQ4LRhzNwZfNQ_0_iBpZiuml_QcqJfgIf2A,4965
36
+ rsplot/plotting/overlay.py,sha256=wEL4qrtNGECqcY0p69fHh437bQwAK1j_SNfEap8oZ9k,5373
37
+ rsplot/plotting/raster.py,sha256=wYXLfsxJo33R4j6r_XgoT2meLgFdGB-Y5DcdlVxsXME,3193
38
+ rsplot/plotting/station.py,sha256=Q3SPrNfNJqnBJh0VUuOguXI0z7au84l3SFgHyvY5cNk,6729
39
+ rsplot/plotting/station_focus.py,sha256=pk0Y7cy7-5r--iyND3BBCeCA2JRLUlmfbtxqXO3_X34,2705
40
+ rsplot/plotting/station_trend.py,sha256=_4IA5QeGIQFVRF0TJDRHGXJi-5C59aLdu5sK5urnWUs,10427
41
+ rsplot/plotting/styles.py,sha256=wdWLd3mW8Q04Ymk-jFofvK88TX3z-ZIGLJsRWF8LVxo,1177
42
+ rsplot/plotting/wind.py,sha256=1YNdEg0c19AyHt2hQjAng8-nMItPBfUVEmcy9sIBvqw,2102
43
+ rsplot/readers/__init__.py,sha256=HZgHdfLJADaOqqlH1wtEh4zEtAfcdmGPZ3o0oK8ANCI,6725
44
+ rsplot/readers/_tropomi.py,sha256=jBHmECgVcJiyVpqvzBZ9WMyktd6HGoWHbSYWi51TyPE,8951
45
+ rsplot/readers/base.py,sha256=1hOS3XDExzwHwcwBLahvgjv-3cOFydiTtlGX7ZW3AQU,5715
46
+ rsplot/readers/era5.py,sha256=d060c-PUy95DEQGdPghGymygLJPY2usXIEbDg-8vL7Q,9895
47
+ rsplot/readers/era5_wind.py,sha256=xZHpc3sOFYmjK31O6FepsKMNqimzmz1ns_MRtXN0noE,5470
48
+ rsplot/readers/forecast.py,sha256=a6JowdoxcpTMCnFVfMRlEffnZ2rM8DPhzHG9e-LliV8,9341
49
+ rsplot/readers/gems.py,sha256=1eg9b58NEgS3CqHwU1XSSK2Mw4Qq95zXmG9YENWCctc,15461
50
+ rsplot/readers/guokong.py,sha256=yRClssJ6q7O8OPgbtJ6By43yQaFnH4R3dVyqDeBajrs,18030
51
+ rsplot/readers/netcdf.py,sha256=3pKwA0SaakujdC5-KsX2idkzEnn2p0NarAwwhZS_ysQ,1023
52
+ rsplot/readers/reconstruct.py,sha256=NCPOP6aqJnWm4PnErj3haq0p6s18ozJb6B0j_fU58DY,13388
53
+ rsplot/readers/tropomi_hcho.py,sha256=UH_x8AO5Q1A0uXbBRTqK5_e8QvOYQz9k0g8MK3xBjik,1136
54
+ rsplot/readers/tropomi_no2.py,sha256=qT8HmarOFne_yAO_9tL9R3j9kOoCo2ONEGfHo309wFI,1112
55
+ rsplot/readers/tropomi_nrti.py,sha256=q3zdWKNkoPuoluD4PCMF2wQKKuFPeTdKt_ORe1Zq8N8,4472
56
+ rsplot/readers/tropomi_o3.py,sha256=lpRExteJ-tqCBj5MoSkrGGM0PAbhUWOeJz1odRgDllM,1170
57
+ rsplot/readers/tropomi_o3pr.py,sha256=F8S51gplMZVoVY9ZcEq9r-_1o19F1BbyBPLPruCb49E,1117
58
+ rsplot/result_builders/__init__.py,sha256=C1LR7SzdoH8UNOcDy-21X2ZKjE30fUlcx2XrDPIapT4,373
59
+ rsplot/result_builders/common.py,sha256=jrKsamSD5r89yXYjs_fKOjNHhrCK1QxXIAOg5A414gE,6788
60
+ rsplot/result_builders/envelope.py,sha256=IpDeialpg9LR5m01fm4dGwwKOZMPeuvZ4s0nRPqxG7w,6735
61
+ rsplot/result_builders/fnr.py,sha256=dB5Su0x6KBxice2NnZGbGDlgjl_6x8o9BVDcECK5aho,3072
62
+ rsplot/result_builders/forecast.py,sha256=6RLdFVPITXUTTy6If4yr-BA__GYNeUcNP4EMV5QSeXc,3587
63
+ rsplot/result_builders/provenance.py,sha256=3nONbzlGdV9TLtvfu-tmY8_-OMAeTMWYQJ0Pmnlp818,2093
64
+ rsplot/result_builders/reconstruct.py,sha256=Uqwzi75NhEUIX1O2MijFaL9RMxAlCiRvReK4zUmX_80,2556
65
+ rsplot/result_builders/satellite.py,sha256=C7JH_DH-dQEP_avb3fGDtI5wxVYN7d2HX8kbkqLhHL0,7429
66
+ rsplot/result_builders/series_layer.py,sha256=eeKqERZkpk5gqXxqhGLMJdme0sVs0oK54t3Dc-FNUlg,8728
67
+ rsplot/result_builders/station.py,sha256=7bdfiKl2Ds3MNSOORXL41jLqnCsUDF6FYqCEyeuF6KA,7911
68
+ rsplot/result_builders/station_layer.py,sha256=iIbaufgyEXcIqiX4x8eMnQVQlWBpHc6qAjWsE5aq57E,10244
69
+ rsplot/schemas/result.schema.json,sha256=QLk92OnmBkDP2cfdi6ZPa04a8dGnetVCo89D66Ke0pI,18634
70
+ rsplot/tiles/__init__.py,sha256=R7864cYKm4gfLX07fbBeQelGjebQXkzBLDJUFy67UcU,30
71
+ rsplot/tiles/tianditu.py,sha256=9B2SXmjF3adWcq38LtP8DCu_4C1INRNOejibpRx1bnA,859
72
+ rsplot-0.3.2.dev37.dist-info/METADATA,sha256=tWGjV1jsKM8-buSpIR29q76A6u_qqWBJChAG_mWK3hc,50927
73
+ rsplot-0.3.2.dev37.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
74
+ rsplot-0.3.2.dev37.dist-info/entry_points.txt,sha256=ZhA4Divb4fJcggbG7usMVJ-VUTkEaQ-qfPlMimSBuCM,47
75
+ rsplot-0.3.2.dev37.dist-info/licenses/LICENSE,sha256=KD6mzCmXoacNoASeCa35MXu2DKG1Enm2UZa4OmnhmWs,11323
76
+ rsplot-0.3.2.dev37.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: hatchling 1.32.0
2
+ Generator: hatchling 1.32.4
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
rsplot/commands/recent.py DELETED
@@ -1,164 +0,0 @@
1
- """Implementation service for the ``recent`` command."""
2
-
3
- from __future__ import annotations
4
-
5
- from typing import TYPE_CHECKING
6
-
7
- import typer
8
-
9
- from rsplot.commands.common import (
10
- validate_positive,
11
- validate_unit_interval,
12
- )
13
- from rsplot.config import AppConfig
14
-
15
- if TYPE_CHECKING:
16
- from rich.console import Console
17
-
18
-
19
- def run_recent(
20
- *,
21
- region: str,
22
- end_date: str,
23
- days: int,
24
- source: str,
25
- product: str,
26
- var: str,
27
- level: str | None,
28
- data_dir: str | None,
29
- output: str | None,
30
- res: float | None,
31
- qa: float | None,
32
- cf: float = 0.5,
33
- console: Console,
34
- ) -> None:
35
- """Execute recent-day summaries without owning the Typer signature."""
36
- from rsplot.config import STATION_VAR_META
37
- from rsplot.geo.boundaries import resolve_region
38
- from rsplot.readers import get_product_info
39
- from rsplot.recent import (
40
- build_recent_result,
41
- parse_recent_dates,
42
- summarize_recent_raster,
43
- summarize_recent_station,
44
- write_recent_result,
45
- )
46
-
47
- use_source = source.lower()
48
- if use_source not in ("raster", "station"):
49
- console.print("[red]--source 仅支持 raster / station[/red]")
50
- raise typer.Exit(1)
51
-
52
- try:
53
- dates = parse_recent_dates(end_date, days)
54
- except ValueError as e:
55
- console.print(f"[red]{e}[/red]")
56
- raise typer.Exit(1) from e
57
-
58
- cfg = AppConfig.load()
59
- console.print(f"[bold]解析区域:[/bold] {region}")
60
- info = resolve_region(region, cfg, level_override=level)
61
- console.print(f" → [green]{info.name}[/green] (级别: {info.level})")
62
- console.print(
63
- f"[bold]统计窗口:[/bold] {dates[0]} ~ {dates[-1]} ({len(dates)} 天)"
64
- )
65
-
66
- if output is None:
67
- if use_source == "raster":
68
- output = (
69
- f"/tmp/rsplot_recent_{info.name}_{product}_"
70
- f"{dates[0]}_{dates[-1]}.json"
71
- )
72
- else:
73
- output = (
74
- f"/tmp/rsplot_recent_{info.name}_{var}_"
75
- f"{dates[0]}_{dates[-1]}.json"
76
- )
77
-
78
- if use_source == "raster":
79
- prod_info = get_product_info(product)
80
- product_defaults = prod_info.defaults_for_level(info.level)
81
- use_res = (
82
- res
83
- if res is not None
84
- else product_defaults.res
85
- if product_defaults.res is not None
86
- else info.params.res
87
- )
88
- use_qa = qa if qa is not None else cfg.qa_threshold
89
- try:
90
- validate_positive(use_res, "--res")
91
- validate_unit_interval(use_qa, "--qa")
92
- validate_unit_interval(cf, "--cf")
93
- except ValueError as e:
94
- console.print(f"[red]{e}[/red]")
95
- raise typer.Exit(1) from e
96
- use_data_dir = (
97
- data_dir if data_dir is not None else cfg.get_data_dir(product)
98
- )
99
- console.print(
100
- f"\n[bold]统计栅格:[/bold] {use_data_dir} "
101
- f"(产品: {product}, QA > {use_qa}, "
102
- f"CF <= {cf}, res={use_res})"
103
- )
104
- daily = summarize_recent_raster(
105
- region=info,
106
- product=product,
107
- prod_info=prod_info,
108
- data_dir=use_data_dir,
109
- dates=dates,
110
- res=use_res,
111
- qa_threshold=use_qa,
112
- cloud_fraction_max=cf,
113
- console=console,
114
- )
115
- result = build_recent_result(
116
- region=info,
117
- source=use_source,
118
- dates=dates,
119
- daily=daily,
120
- params={
121
- "data_dir": use_data_dir,
122
- "qa_threshold": use_qa,
123
- "cloud_fraction_max": cf,
124
- "resolution_deg": use_res,
125
- },
126
- product=product,
127
- unit=prod_info.colorbar_label,
128
- output=output,
129
- )
130
- else:
131
- if var not in STATION_VAR_META:
132
- available = ", ".join(STATION_VAR_META)
133
- console.print(f"[red]未知变量 '{var}'[/red]。可用: {available}")
134
- raise typer.Exit(1)
135
- use_data_dir = (
136
- data_dir if data_dir is not None else cfg.get_data_dir("guokong")
137
- )
138
- unit = STATION_VAR_META[var][0]
139
- console.print(f"\n[bold]统计站点:[/bold] {use_data_dir} (变量: {var})")
140
- daily = summarize_recent_station(
141
- region=info,
142
- data_dir=use_data_dir,
143
- dates=dates,
144
- var_name=var,
145
- console=console,
146
- )
147
- result = build_recent_result(
148
- region=info,
149
- source=use_source,
150
- dates=dates,
151
- daily=daily,
152
- params={"data_dir": use_data_dir},
153
- variable=var,
154
- unit=unit or None,
155
- output=output,
156
- )
157
-
158
- write_recent_result(result, output)
159
- found = result["availability"]["days_found"]
160
- failed = result["availability"]["days_failed"]
161
- console.print(
162
- f"\n[bold green]✓ 已保存:[/bold green] {output} "
163
- f"(有效 {found}/{len(dates)} 天,失败 {failed})"
164
- )
rsplot/recent.py DELETED
@@ -1,404 +0,0 @@
1
- """Recent-day JSON summaries for raster and station data.
2
-
3
- The ``recent`` command is intentionally read/analysis only: it produces a
4
- compact JSON payload for comparing the last week/month/year without drawing
5
- maps. It reuses the existing product readers, gridding, and station filters so
6
- its daily numbers match the plotting commands' data path.
7
- """
8
-
9
- from __future__ import annotations
10
-
11
- import json
12
- from dataclasses import dataclass
13
- from datetime import datetime, timedelta
14
- from pathlib import Path
15
- from typing import TYPE_CHECKING, Any
16
-
17
- import numpy as np
18
- from rich.console import Console
19
- from rich.progress import track
20
-
21
- from rsplot.config import get_exceedance_threshold
22
- from rsplot.geo.gridding import grid_coverage_in_region
23
- from rsplot.geo.processing import buffered_extent, prepare_swath_grid
24
- from rsplot.readers import ProductInfo
25
- from rsplot.readers.guokong import (
26
- mask_stations_to_region,
27
- read_stations,
28
- )
29
- from rsplot.stats import basic_stats
30
-
31
- if TYPE_CHECKING:
32
- from rsplot.geo.boundaries import RegionInfo
33
-
34
-
35
- @dataclass
36
- class RecentDaily:
37
- """One daily summary row."""
38
-
39
- date: str
40
- ok: bool
41
- value: float | None
42
- stats: dict[str, Any]
43
- meta: dict[str, Any]
44
- error: str | None = None
45
-
46
-
47
- def parse_recent_dates(end_date: str, days: int) -> list[str]:
48
- """Return ascending YYYYMMDD dates ending on ``end_date``."""
49
- if days < 1:
50
- raise ValueError("--days 必须 >= 1")
51
- if len(end_date) != 8 or not end_date.isdigit():
52
- raise ValueError(f"日期格式错误: '{end_date}',应为 YYYYMMDD")
53
- try:
54
- end = datetime.strptime(end_date, "%Y%m%d")
55
- except ValueError as e:
56
- raise ValueError(
57
- f"日期无效: '{end_date}',请检查年月日是否真实存在 (原始错误: {e})"
58
- ) from e
59
-
60
- start = end - timedelta(days=days - 1)
61
- return [
62
- (start + timedelta(days=i)).strftime("%Y%m%d") for i in range(days)
63
- ]
64
-
65
-
66
- def summarize_recent_raster(
67
- *,
68
- region: RegionInfo,
69
- product: str,
70
- prod_info: ProductInfo,
71
- data_dir: str,
72
- dates: list[str],
73
- res: float,
74
- qa_threshold: float,
75
- cloud_fraction_max: float = 0.5,
76
- console: Console | None = None,
77
- ) -> list[RecentDaily]:
78
- """Read daily raster swaths and summarize each day over the region."""
79
- if console is None:
80
- console = Console()
81
-
82
- reader = prod_info.reader_cls()
83
- reader.cloud_fraction_max = cloud_fraction_max
84
- read_extent = buffered_extent(region.extent, 1.0)
85
- out: list[RecentDaily] = []
86
-
87
- for d in track(
88
- dates, description=f"[cyan]统计 {product.upper()} 最近数据..."
89
- ):
90
- try:
91
- swath = reader.read(data_dir, d, read_extent, qa_threshold)
92
- prepared = prepare_swath_grid(
93
- swath.lon,
94
- swath.lat,
95
- swath.values,
96
- read_extent,
97
- res,
98
- region.geometry,
99
- )
100
- stats = _grid_stats(
101
- prepared.lon,
102
- prepared.lat,
103
- prepared.values,
104
- region.geometry,
105
- )
106
- if not stats:
107
- raise ValueError(f"{d} 区域内无有效网格")
108
- out.append(
109
- RecentDaily(
110
- date=d,
111
- ok=True,
112
- value=stats.get("mean"),
113
- stats=stats,
114
- meta={
115
- "n_pixels": int(swath.n_pixels),
116
- "n_files": int(swath.n_files),
117
- "n_broken": int(swath.n_broken),
118
- },
119
- )
120
- )
121
- except (FileNotFoundError, ValueError) as e:
122
- out.append(
123
- RecentDaily(
124
- date=d,
125
- ok=False,
126
- value=None,
127
- stats={},
128
- meta={},
129
- error=str(e).splitlines()[0],
130
- )
131
- )
132
-
133
- return out
134
-
135
-
136
- def summarize_recent_station(
137
- *,
138
- region: RegionInfo,
139
- data_dir: str,
140
- dates: list[str],
141
- var_name: str,
142
- console: Console | None = None,
143
- ) -> list[RecentDaily]:
144
- """Read daily latest-hour station files and summarize each day."""
145
- if console is None:
146
- console = Console()
147
-
148
- read_extent = buffered_extent(region.extent, 0.5)
149
- threshold = get_exceedance_threshold(var_name)
150
- out: list[RecentDaily] = []
151
-
152
- for d in track(
153
- dates, description=f"[cyan]统计 {var_name} 站点最近数据..."
154
- ):
155
- try:
156
- data, resolved_dt = read_stations(
157
- data_dir, d, var_name, extent=read_extent
158
- )
159
- data = mask_stations_to_region(data, region.geometry)
160
- vals = data.values[np.isfinite(data.values)]
161
- stats = _array_stats(vals)
162
- if not stats:
163
- raise ValueError(f"{d} 区域内无有效站点")
164
- meta: dict[str, Any] = {
165
- "datetime": resolved_dt,
166
- "n_stations": int(data.n_stations),
167
- "n_valid": int(data.n_valid),
168
- }
169
- if threshold is not None:
170
- meta["threshold"] = threshold
171
- meta["n_exceed"] = int((vals > threshold).sum())
172
- meta["exceed_rate_pct"] = round(
173
- 100 * meta["n_exceed"] / len(vals), 1
174
- )
175
- out.append(
176
- RecentDaily(
177
- date=d,
178
- ok=True,
179
- value=stats.get("mean"),
180
- stats=stats,
181
- meta=meta,
182
- )
183
- )
184
- except (FileNotFoundError, ValueError, KeyError) as e:
185
- out.append(
186
- RecentDaily(
187
- date=d,
188
- ok=False,
189
- value=None,
190
- stats={},
191
- meta={},
192
- error=str(e).splitlines()[0],
193
- )
194
- )
195
-
196
- return out
197
-
198
-
199
- def build_recent_result(
200
- *,
201
- region: RegionInfo,
202
- source: str,
203
- dates: list[str],
204
- daily: list[RecentDaily],
205
- params: dict[str, Any],
206
- output: str,
207
- product: str | None = None,
208
- variable: str | None = None,
209
- unit: str | None = None,
210
- ) -> dict[str, Any]:
211
- """Build the JSON payload for a recent run."""
212
- daily_rows = [_daily_to_json(row) for row in daily]
213
- failed = {row.date: row.error for row in daily if not row.ok and row.error}
214
- found = [row for row in daily if row.ok]
215
-
216
- result: dict[str, Any] = {
217
- "command": "recent",
218
- "image": None,
219
- "sidecar": output,
220
- "source": source,
221
- "region": {
222
- "name": region.name,
223
- "level": region.level,
224
- "extent": [round(x, 3) for x in region.extent],
225
- },
226
- "period": {
227
- "start": dates[0],
228
- "end": dates[-1],
229
- "days_requested": len(dates),
230
- },
231
- "params": params,
232
- "availability": {
233
- "days_found": len(found),
234
- "days_failed": len(failed),
235
- "failed_dates": failed,
236
- },
237
- "daily": daily_rows,
238
- "windows": _window_summaries(daily),
239
- "changes": _change_summaries(daily),
240
- "trend": _trend_summary(daily),
241
- "warnings": _warnings(daily),
242
- }
243
- if product is not None:
244
- result["product"] = product
245
- if variable is not None:
246
- result["variable"] = variable
247
- if unit:
248
- result["unit"] = unit
249
- return result
250
-
251
-
252
- def write_recent_result(result: dict[str, Any], output: str) -> str:
253
- """Write a recent JSON result and return the path."""
254
- path = Path(output)
255
- path.parent.mkdir(parents=True, exist_ok=True)
256
- with open(path, "w", encoding="utf-8") as f:
257
- json.dump(result, f, ensure_ascii=False, indent=2)
258
- return str(path)
259
-
260
-
261
- def _daily_to_json(row: RecentDaily) -> dict[str, Any]:
262
- data: dict[str, Any] = {
263
- "date": row.date,
264
- "ok": row.ok,
265
- "stats": row.stats,
266
- "meta": row.meta,
267
- }
268
- if row.error:
269
- data["error"] = row.error
270
- return data
271
-
272
-
273
- def _window_summaries(daily: list[RecentDaily]) -> dict[str, dict[str, Any]]:
274
- windows: dict[str, dict[str, Any]] = {}
275
- n = len(daily)
276
- specs = [
277
- ("last_7", max(0, n - 7), n),
278
- ("prev_7", max(0, n - 14), max(0, n - 7)),
279
- ("last_30", max(0, n - 30), n),
280
- ("prev_30", max(0, n - 60), max(0, n - 30)),
281
- ("last_365", max(0, n - 365), n),
282
- ]
283
- for name, start, end in specs:
284
- if end <= start or end - start < _required_span(name):
285
- continue
286
- windows[name] = _summarize_rows(daily[start:end])
287
- return windows
288
-
289
-
290
- def _change_summaries(daily: list[RecentDaily]) -> dict[str, dict[str, Any]]:
291
- windows = _window_summaries(daily)
292
- pairs = [
293
- ("last_7_vs_prev_7", "last_7", "prev_7"),
294
- ("last_30_vs_prev_30", "last_30", "prev_30"),
295
- ]
296
- out: dict[str, dict[str, Any]] = {}
297
- for name, cur_key, prev_key in pairs:
298
- cur = windows.get(cur_key, {})
299
- prev = windows.get(prev_key, {})
300
- cur_mean = cur.get("mean")
301
- prev_mean = prev.get("mean")
302
- if cur_mean is None or prev_mean is None:
303
- continue
304
- abs_change = round(float(cur_mean) - float(prev_mean), 3)
305
- pct_change = None
306
- if prev_mean != 0:
307
- pct_change = round(100 * abs_change / float(prev_mean), 1)
308
- out[name] = {
309
- "current_mean": cur_mean,
310
- "previous_mean": prev_mean,
311
- "abs_change": abs_change,
312
- "pct_change": pct_change,
313
- "direction": _direction(abs_change),
314
- "current_valid_days": cur.get("valid_days", 0),
315
- "previous_valid_days": prev.get("valid_days", 0),
316
- }
317
- return out
318
-
319
-
320
- def _trend_summary(daily: list[RecentDaily]) -> dict[str, Any]:
321
- xs = []
322
- ys = []
323
- for i, row in enumerate(daily):
324
- if row.ok and row.value is not None and np.isfinite(row.value):
325
- xs.append(i)
326
- ys.append(float(row.value))
327
- if len(ys) < 2:
328
- return {
329
- "valid_days": len(ys),
330
- "slope_per_day": None,
331
- "direction": "flat",
332
- }
333
- slope = float(
334
- np.polyfit(np.asarray(xs, dtype=float), np.asarray(ys), 1)[0]
335
- )
336
- return {
337
- "valid_days": len(ys),
338
- "slope_per_day": round(slope, 4),
339
- "direction": _direction(slope),
340
- }
341
-
342
-
343
- def _warnings(daily: list[RecentDaily]) -> list[str]:
344
- if not daily:
345
- return []
346
- valid_days = sum(1 for row in daily if row.ok)
347
- rate = valid_days / len(daily)
348
- warnings: list[str] = []
349
- if valid_days == 0:
350
- warnings.append("请求窗口内无有效日期。")
351
- elif rate < 0.5:
352
- warnings.append("有效日期少于请求天数的一半,变化判断可信度较低。")
353
- return warnings
354
-
355
-
356
- def _summarize_rows(rows: list[RecentDaily]) -> dict[str, Any]:
357
- values = np.asarray(
358
- [row.value for row in rows if row.ok and row.value is not None],
359
- dtype=float,
360
- )
361
- stats = _array_stats(values)
362
- stats["valid_days"] = len(values)
363
- stats["requested_days"] = len(rows)
364
- return stats
365
-
366
-
367
- def _grid_stats(
368
- LON: np.ndarray,
369
- LAT: np.ndarray,
370
- grid: np.ndarray,
371
- geometry: Any,
372
- ) -> dict[str, Any]:
373
- stats = _array_stats(grid)
374
- if stats:
375
- coverage_pct, n_valid_region, total_region_pixels = (
376
- grid_coverage_in_region(LON, LAT, grid, geometry)
377
- )
378
- stats["coverage_pct"] = coverage_pct
379
- stats["valid_region_pixels"] = n_valid_region
380
- stats["total_region_pixels"] = total_region_pixels
381
- stats["grid_shape"] = list(grid.shape)
382
- return stats
383
-
384
-
385
- def _array_stats(values: np.ndarray) -> dict[str, Any]:
386
- return basic_stats(np.asarray(values, dtype=float))
387
-
388
-
389
- def _direction(delta: float) -> str:
390
- if delta > 0:
391
- return "up"
392
- if delta < 0:
393
- return "down"
394
- return "flat"
395
-
396
-
397
- def _required_span(name: str) -> int:
398
- if name.endswith("_7"):
399
- return 7
400
- if name.endswith("_30"):
401
- return 30
402
- if name.endswith("_365"):
403
- return 365
404
- return 1