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
rsplot/geo/boundaries.py CHANGED
@@ -9,6 +9,7 @@ from __future__ import annotations
9
9
  import re
10
10
  from dataclasses import dataclass
11
11
  from functools import lru_cache
12
+ from pathlib import Path
12
13
  from typing import TYPE_CHECKING
13
14
 
14
15
  import geopandas as gpd
@@ -21,8 +22,11 @@ from rsplot.config import (
21
22
  LevelParams,
22
23
  SubdivisionSource,
23
24
  )
25
+ from rsplot.errors import RsplotError
24
26
 
25
27
  if TYPE_CHECKING:
28
+ from collections.abc import Iterable
29
+
26
30
  from shapely.geometry.base import BaseGeometry
27
31
 
28
32
 
@@ -35,6 +39,11 @@ NAME_FIELD = "name"
35
39
 
36
40
  # 直辖市 — resolved as province but displayed with county-level sub-boundaries
37
41
  MUNICIPALITIES = {"北京市", "天津市", "上海市", "重庆市"}
42
+ # Municipalities present in both the province and city files resolve as
43
+ # cities; 重庆市 (and same-name entries such as 香港) stay provinces.
44
+ CITY_MUNICIPALITIES = {"北京市", "天津市", "上海市"}
45
+ # Placeholder features in the boundary files, never a region.
46
+ PLACEHOLDER_NAMES = {"境界线"}
38
47
 
39
48
 
40
49
  @dataclass
@@ -58,10 +67,87 @@ class RegionInfo:
58
67
  sub_name_field: str = NAME_FIELD
59
68
  administrative_level: str | None = None
60
69
  subdivision_level: str | None = None
70
+ qualified_name: str | None = None
71
+ members: tuple[RegionInfo, ...] = ()
72
+ geometry_kind: str = "administrative"
73
+ projection_center: tuple[float, float] | None = None
74
+
75
+
76
+ # China's 56 ethnic groups, as written in autonomous-area names.
77
+ _ETHNIC_GROUPS = [
78
+ "汉",
79
+ "蒙古",
80
+ "回",
81
+ "藏",
82
+ "维吾尔",
83
+ "苗",
84
+ "彝",
85
+ "壮",
86
+ "布依",
87
+ "朝鲜",
88
+ "满",
89
+ "侗",
90
+ "瑶",
91
+ "白",
92
+ "土家",
93
+ "哈尼",
94
+ "哈萨克",
95
+ "傣",
96
+ "黎",
97
+ "傈僳",
98
+ "佤",
99
+ "畲",
100
+ "高山",
101
+ "拉祜",
102
+ "水",
103
+ "东乡",
104
+ "纳西",
105
+ "景颇",
106
+ "柯尔克孜",
107
+ "土",
108
+ "达斡尔",
109
+ "仫佬",
110
+ "羌",
111
+ "布朗",
112
+ "撒拉",
113
+ "毛南",
114
+ "仡佬",
115
+ "锡伯",
116
+ "阿昌",
117
+ "普米",
118
+ "塔吉克",
119
+ "怒",
120
+ "乌孜别克",
121
+ "俄罗斯",
122
+ "鄂温克",
123
+ "德昂",
124
+ "保安",
125
+ "裕固",
126
+ "京",
127
+ "塔塔尔",
128
+ "独龙",
129
+ "鄂伦春",
130
+ "赫哲",
131
+ "门巴",
132
+ "珞巴",
133
+ "基诺",
134
+ ]
135
+ # One or more groups right before the autonomous suffix: 广西壮族自治区 ->
136
+ # 广西自治区, 黔东南苗族侗族自治州 -> 黔东南自治州. Groups carry 族, except
137
+ # 维吾尔 in 新疆维吾尔自治区; 内蒙古 and 西藏 are place names, not groups.
138
+ _ETHNIC_DESIGNATION = re.compile(
139
+ r"(?:(?:"
140
+ + "|".join(sorted(_ETHNIC_GROUPS, key=len, reverse=True))
141
+ + r")族|维吾尔)+(?=自治[区州县旗]$)"
142
+ )
61
143
 
62
144
 
63
145
  def _strip_suffix(name: str) -> str:
64
- return _SUFFIXES.sub("", name)
146
+ stripped = _ETHNIC_DESIGNATION.sub("", name)
147
+ if stripped.startswith("自治"):
148
+ # The whole name is the ethnic designation (鄂伦春自治旗).
149
+ stripped = name
150
+ return _SUFFIXES.sub("", stripped)
65
151
 
66
152
 
67
153
  def _fuzzy_match(
@@ -91,19 +177,30 @@ def _fuzzy_match(
91
177
  # ---------------------------------------------------------------------------
92
178
  # GeoJSON loaders (cached)
93
179
  # ---------------------------------------------------------------------------
180
+ def _read_boundary_file(path: str) -> gpd.GeoDataFrame:
181
+ """Read a configured boundary file; a missing one is a config error."""
182
+ if not Path(path).is_file():
183
+ raise RsplotError(
184
+ "config_invalid",
185
+ f"边界文件不存在: {path};请检查配置 [paths].geojson_dir。",
186
+ details={"path": path},
187
+ )
188
+ return gpd.read_file(path)
189
+
190
+
94
191
  @lru_cache(maxsize=1)
95
192
  def _load_province(geojson_dir: str) -> gpd.GeoDataFrame:
96
- return gpd.read_file(f"{geojson_dir}/中国_省.geojson")
193
+ return _read_boundary_file(f"{geojson_dir}/中国_省.geojson")
97
194
 
98
195
 
99
196
  @lru_cache(maxsize=1)
100
197
  def _load_city(geojson_dir: str) -> gpd.GeoDataFrame:
101
- return gpd.read_file(f"{geojson_dir}/中国_市.geojson")
198
+ return _read_boundary_file(f"{geojson_dir}/中国_市.geojson")
102
199
 
103
200
 
104
201
  @lru_cache(maxsize=1)
105
202
  def _load_county(geojson_dir: str) -> gpd.GeoDataFrame:
106
- return gpd.read_file(f"{geojson_dir}/中国_县.geojson")
203
+ return _read_boundary_file(f"{geojson_dir}/中国_县.geojson")
107
204
 
108
205
 
109
206
  @lru_cache(maxsize=16)
@@ -116,7 +213,9 @@ def _load_subdivision_source(
116
213
  try:
117
214
  source = gpd.read_file(path)
118
215
  except Exception as exc:
119
- raise ValueError(f"无法读取下级行政区边界文件 '{path}': {exc}") from exc
216
+ raise ValueError(
217
+ f"无法读取下级行政区边界文件 '{path}': {exc}"
218
+ ) from exc
120
219
 
121
220
  if name_field not in source.columns:
122
221
  available = ", ".join(str(column) for column in source.columns)
@@ -137,7 +236,9 @@ def _load_subdivision_source(
137
236
  normalized = source[[name_field, "geometry"]].rename(
138
237
  columns={name_field: NAME_FIELD}
139
238
  )
140
- normalized[NAME_FIELD] = normalized[NAME_FIELD].astype("string").str.strip()
239
+ normalized[NAME_FIELD] = (
240
+ normalized[NAME_FIELD].astype("string").str.strip()
241
+ )
141
242
  normalized = normalized[
142
243
  normalized[NAME_FIELD].notna()
143
244
  & normalized[NAME_FIELD].ne("")
@@ -250,7 +351,12 @@ def _resolve_qualified_county(
250
351
  city_name, county_name = name.split("/", 1)
251
352
  city_match = _fuzzy_match(city_name, cities)
252
353
  if city_match is None:
253
- raise ValueError(f"无法识别城市 '{city_name}'。")
354
+ suggestions = suggest_region_names(city_name, [cities])
355
+ raise RsplotError(
356
+ "region_not_found",
357
+ f"无法识别城市 '{city_name}'。{_did_you_mean(suggestions)}",
358
+ details={"region": name, "suggestions": suggestions},
359
+ )
254
360
  canonical_city_name = city_match.iloc[0][NAME_FIELD]
255
361
  city_geometry = unary_union(city_match.geometry)
256
362
  configured = _city_subdivisions(
@@ -280,6 +386,7 @@ def _resolve_qualified_county(
280
386
  main_gdf=county_match,
281
387
  sub_gdf=None,
282
388
  administrative_level=administrative_level,
389
+ qualified_name=f"{canonical_city_name}/{county_match.iloc[0][NAME_FIELD]}",
283
390
  )
284
391
 
285
392
 
@@ -380,6 +487,84 @@ def _resolve_city(
380
487
  )
381
488
 
382
489
 
490
+ def _matched_name(query: str, candidates: gpd.GeoDataFrame) -> str | None:
491
+ match = _fuzzy_match(query, candidates)
492
+ if match is None:
493
+ return None
494
+ name = match.iloc[0][NAME_FIELD]
495
+ return None if name in PLACEHOLDER_NAMES else name
496
+
497
+
498
+ def _resolve_named_place(
499
+ name: str,
500
+ cfg: AppConfig,
501
+ provinces: gpd.GeoDataFrame,
502
+ cities: gpd.GeoDataFrame,
503
+ counties: gpd.GeoDataFrame,
504
+ ) -> RegionInfo | None:
505
+ """Resolve a province or city name without guessing between them.
506
+
507
+ A full name selects its own level; a short name matching different
508
+ places at both levels is rejected with the candidates.
509
+ """
510
+ province = _matched_name(name, provinces)
511
+ city = _matched_name(name, cities)
512
+ if province is not None and province == city:
513
+ use_city = province in CITY_MUNICIPALITIES
514
+ elif province is not None and city is not None:
515
+ if (province == name) == (city == name):
516
+ raise RsplotError(
517
+ "region_ambiguous",
518
+ f"区域名 '{name}' 同时匹配 {province}(省级)和 "
519
+ f"{city}(市级),请写全称。",
520
+ details={"region": name, "candidates": [province, city]},
521
+ )
522
+ use_city = city == name
523
+ elif province is not None or city is not None:
524
+ use_city = city is not None
525
+ else:
526
+ return None
527
+ if use_city:
528
+ return _resolve_city(city, cfg, cities, counties)
529
+ return _resolve_province(province, provinces, cities, counties)
530
+
531
+
532
+ def suggest_region_names(
533
+ query: str,
534
+ frames: list[gpd.GeoDataFrame],
535
+ extra: Iterable[str] = (),
536
+ *,
537
+ limit: int = 5,
538
+ ) -> list[str]:
539
+ """Close full names for a misspelled region, most similar first.
540
+
541
+ Compares both the full and the suffix-stripped names, so 安微 finds
542
+ 安徽省. Ties keep the order of ``frames`` (provinces before cities),
543
+ then the extra names (key regions).
544
+ """
545
+ from difflib import SequenceMatcher
546
+
547
+ stripped = _strip_suffix(query)
548
+ groups = [frame[NAME_FIELD].tolist() for frame in frames] + [list(extra)]
549
+ scored: dict[str, tuple[float, int]] = {}
550
+ for rank, names in enumerate(groups):
551
+ for full in names:
552
+ if full in PLACEHOLDER_NAMES or full in scored:
553
+ continue
554
+ score = max(
555
+ SequenceMatcher(None, query, full).ratio(),
556
+ SequenceMatcher(None, stripped, _strip_suffix(full)).ratio(),
557
+ )
558
+ if score >= 0.5:
559
+ scored[full] = (-score, rank)
560
+ ranked = sorted(scored, key=lambda full: (*scored[full], full))
561
+ return ranked[:limit]
562
+
563
+
564
+ def _did_you_mean(suggestions: list[str]) -> str:
565
+ return f"是否指: {'、'.join(suggestions)}?" if suggestions else ""
566
+
567
+
383
568
  def resolve_region(
384
569
  name: str,
385
570
  cfg: AppConfig,
@@ -415,7 +600,32 @@ def resolve_region(
415
600
  if key_region is not None:
416
601
  return key_region
417
602
 
418
- if level_override is None or level_override == "province":
603
+ if level_override is None:
604
+ assert provinces is not None
605
+ named = _resolve_named_place(
606
+ name,
607
+ cfg,
608
+ provinces,
609
+ load_city_boundaries(geojson_dir),
610
+ load_county_boundaries(geojson_dir),
611
+ )
612
+ if named is not None:
613
+ return named
614
+ suggestions = suggest_region_names(
615
+ name,
616
+ [provinces, load_city_boundaries(geojson_dir)],
617
+ cfg.key_regions,
618
+ )
619
+ raise RsplotError(
620
+ "region_not_found",
621
+ f"无法识别区域 '{name}'。{_did_you_mean(suggestions)}"
622
+ "请使用中文全称或简称,县区写成 城市/区县,如 合肥/蜀山。",
623
+ details={"region": name, "suggestions": suggestions},
624
+ )
625
+
626
+ # The level filter below serves only the disabled forecast and
627
+ # reconstruct commands; enabled commands resolve by name alone.
628
+ if level_override == "province":
419
629
  assert provinces is not None
420
630
  cities = load_city_boundaries(geojson_dir)
421
631
  counties = load_county_boundaries(geojson_dir)
@@ -423,7 +633,7 @@ def resolve_region(
423
633
  if province is not None:
424
634
  return province
425
635
 
426
- if level_override is None or level_override == "city":
636
+ if level_override == "city":
427
637
  cities = load_city_boundaries(geojson_dir)
428
638
  counties = load_county_boundaries(geojson_dir)
429
639
  city = _resolve_city(name, cfg, cities, counties)
@@ -437,8 +647,8 @@ def resolve_region(
437
647
  )
438
648
 
439
649
  raise ValueError(
440
- f"无法识别区域 '{name}'。请检查名称是否正确,"
441
- "或使用 --level 指定级别 (key_region/province/city/county)。"
650
+ f"无法识别区域 '{name}'。请使用中文行政区名称或重点区域名,"
651
+ "区县写作 城市/区县,如 合肥/蜀山。"
442
652
  )
443
653
 
444
654
 
@@ -451,6 +661,7 @@ def _build_info(
451
661
  detail_gdf: gpd.GeoDataFrame | None = None,
452
662
  administrative_level: str | None = None,
453
663
  subdivision_level: str | None = None,
664
+ qualified_name: str | None = None,
454
665
  ) -> RegionInfo:
455
666
  bounds = geometry.bounds # (minx, miny, maxx, maxy)
456
667
  params = LEVEL_DEFAULTS[level]
@@ -471,4 +682,99 @@ def _build_info(
471
682
  detail_boundary_gdf=detail_gdf,
472
683
  administrative_level=administrative_level,
473
684
  subdivision_level=subdivision_level,
685
+ qualified_name=qualified_name,
686
+ )
687
+
688
+
689
+ def resolve_regions(
690
+ expression: str,
691
+ cfg: AppConfig,
692
+ level_override: str | None = None,
693
+ ) -> RegionInfo:
694
+ """Resolve a comma-separated selection without changing single-region APIs."""
695
+ if "," not in expression and "," not in expression:
696
+ return resolve_region(expression, cfg, level_override)
697
+ names = [
698
+ part.replace("\r", "").replace("\n", "").strip()
699
+ for part in re.split("[,,]", expression)
700
+ ]
701
+ if any(not name for name in names):
702
+ raise ValueError("多区域列表包含空项,请检查连续逗号或首尾逗号。")
703
+ members = []
704
+ seen = set()
705
+ for index, name in enumerate(names, 1):
706
+ try:
707
+ member = resolve_region(name, cfg, level_override)
708
+ except ValueError as error:
709
+ raise ValueError(
710
+ f"第 {index} 个区域 '{name}' 无法解析:{error}"
711
+ ) from error
712
+ key = (member.level, member.qualified_name or member.name)
713
+ if key not in seen:
714
+ members.append(member)
715
+ seen.add(key)
716
+
717
+ levels = ("country", "key_region", "province", "city", "county")
718
+ level = min((member.level for member in members), key=levels.index)
719
+ geometry = unary_union([member.geometry for member in members])
720
+ crs = next(
721
+ (
722
+ m.main_boundary_gdf.crs
723
+ for m in members
724
+ if m.main_boundary_gdf is not None
725
+ and m.main_boundary_gdf.crs is not None
726
+ ),
727
+ "EPSG:4326",
728
+ )
729
+ main = gpd.GeoDataFrame(
730
+ {NAME_FIELD: [m.qualified_name or m.name for m in members]},
731
+ geometry=[m.geometry for m in members],
732
+ crs=crs,
733
+ )
734
+ sub = _merge_member_layers(members, "sub_boundary_gdf", crs)
735
+ detail = _merge_member_layers(members, "detail_boundary_gdf", crs)
736
+ if detail is not None and sub is not None:
737
+ sub_keys = {g.normalize().wkb for g in sub.geometry}
738
+ detail = detail[
739
+ ~detail.geometry.map(lambda g: g.normalize().wkb in sub_keys)
740
+ ].copy()
741
+ info = _build_info(
742
+ name=f"联合区域({len(members)}个)",
743
+ level=level,
744
+ geometry=geometry,
745
+ main_gdf=main,
746
+ sub_gdf=sub,
747
+ detail_gdf=detail,
474
748
  )
749
+ info.members = tuple(members)
750
+ return info
751
+
752
+
753
+ def _merge_member_layers(
754
+ members: list[RegionInfo],
755
+ attribute: str,
756
+ crs: object,
757
+ ) -> gpd.GeoDataFrame | None:
758
+ """Keep only each member's own subdivisions and deduplicate shared features."""
759
+ rows = []
760
+ seen = set()
761
+ for member in members:
762
+ frame = getattr(member, attribute)
763
+ if frame is None or len(frame) == 0:
764
+ continue
765
+ if frame.crs is not None and frame.crs != crs:
766
+ frame = frame.to_crs(crs)
767
+ for _, row in frame.iterrows():
768
+ geometry = row.geometry.intersection(member.geometry)
769
+ if geometry.is_empty or geometry.area == 0:
770
+ continue
771
+ key = geometry.normalize().wkb
772
+ if key in seen:
773
+ continue
774
+ seen.add(key)
775
+ rows.append(
776
+ {NAME_FIELD: row[member.sub_name_field], "geometry": geometry}
777
+ )
778
+ if not rows:
779
+ return None
780
+ return gpd.GeoDataFrame(rows, geometry="geometry", crs=crs)
@@ -0,0 +1,205 @@
1
+ """Area-overlap remapping and stable display support for gridded fields."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import TYPE_CHECKING
7
+
8
+ import numpy as np
9
+
10
+ if TYPE_CHECKING:
11
+ from shapely.geometry.base import BaseGeometry
12
+
13
+
14
+ def inferred_corner_grid(centers: np.ndarray) -> np.ndarray:
15
+ """Estimate shared corners from the unfiltered 2-D native center lattice.
16
+
17
+ Midpoints use adjacent native rows/columns, never adjacent QA survivors.
18
+ Outer edges are linearly extrapolated. Missing geolocation stays missing.
19
+ """
20
+ if centers.ndim != 2 or min(centers.shape) < 2:
21
+ raise ValueError("估算像元边界需要至少 2×2 的原始定位网格。")
22
+ padded = np.pad(centers.astype(float), 1, mode="edge")
23
+ padded[0, 1:-1] = 2 * centers[0] - centers[1]
24
+ padded[-1, 1:-1] = 2 * centers[-1] - centers[-2]
25
+ padded[:, 0] = 2 * padded[:, 1] - padded[:, 2]
26
+ padded[:, -1] = 2 * padded[:, -2] - padded[:, -3]
27
+ return (
28
+ padded[:-1, :-1] + padded[1:, :-1] + padded[1:, 1:] + padded[:-1, 1:]
29
+ ) / 4
30
+
31
+
32
+ def pixel_corners(corners: np.ndarray) -> np.ndarray:
33
+ """Convert a shared (ny+1, nx+1) corner grid to (ny, nx, 4)."""
34
+ return np.stack(
35
+ [
36
+ corners[:-1, :-1],
37
+ corners[:-1, 1:],
38
+ corners[1:, 1:],
39
+ corners[1:, :-1],
40
+ ],
41
+ axis=-1,
42
+ )
43
+
44
+
45
+ def regular_grid(
46
+ extent: tuple[float, float, float, float],
47
+ res: float,
48
+ ) -> tuple[np.ndarray, np.ndarray]:
49
+ """Build globally aligned cell centers covering an extent."""
50
+ west, east, south, north = extent
51
+ x = (np.arange(np.floor(west / res), np.ceil(east / res)) + 0.5) * res
52
+ y = (np.arange(np.floor(south / res), np.ceil(north / res)) + 0.5) * res
53
+ return np.meshgrid(x, y)
54
+
55
+
56
+ def grid_edges(centers: np.ndarray, res: float) -> np.ndarray:
57
+ return np.concatenate((centers - res / 2, centers[-1:] + res / 2))
58
+
59
+
60
+ def rectangle_corners(
61
+ lon: np.ndarray,
62
+ lat: np.ndarray,
63
+ res: float,
64
+ ) -> tuple[np.ndarray, np.ndarray]:
65
+ x = grid_edges(lon[0], res)
66
+ y = grid_edges(lat[:, 0], res)
67
+ xx, yy = np.meshgrid(x, y)
68
+ return pixel_corners(xx).reshape(-1, 4), pixel_corners(yy).reshape(-1, 4)
69
+
70
+
71
+ def overlap_mean(
72
+ corner_lon: np.ndarray,
73
+ corner_lat: np.ndarray,
74
+ values: np.ndarray,
75
+ lon: np.ndarray,
76
+ lat: np.ndarray,
77
+ res: float,
78
+ ) -> np.ndarray:
79
+ """Remap valid source polygons with overlap-area weights in EPSG:6933.
80
+
81
+ No extrapolation: a target needs positive-area overlap with a valid source.
82
+ Chunked queries bound temporary target/intersection geometry allocations.
83
+ """
84
+ from pyproj import Transformer
85
+ from shapely import STRtree, area, intersection, is_valid, polygons
86
+
87
+ result = np.full(lon.size, np.nan)
88
+ if not len(values):
89
+ return result.reshape(lon.shape)
90
+ transform = Transformer.from_crs(4326, 6933, always_xy=True)
91
+ x, y = transform.transform(corner_lon, corner_lat)
92
+ finite = (
93
+ np.isfinite(values)
94
+ & np.isfinite(x).all(axis=1)
95
+ & np.isfinite(y).all(axis=1)
96
+ )
97
+ source = polygons(np.stack([x[finite], y[finite]], axis=-1))
98
+ source_values = values[finite]
99
+ valid = is_valid(source) & (area(source) > 0)
100
+ source, source_values = source[valid], source_values[valid]
101
+ if not len(source):
102
+ return result.reshape(lon.shape)
103
+ tree = STRtree(source)
104
+ xcorners, ycorners = rectangle_corners(lon, lat, res)
105
+ for start in range(0, lon.size, 8192):
106
+ stop = min(start + 8192, lon.size)
107
+ x, y = transform.transform(xcorners[start:stop], ycorners[start:stop])
108
+ target = polygons(np.stack([x, y], axis=-1))
109
+ ti, si = tree.query(target, predicate="intersects")
110
+ if not len(ti):
111
+ continue
112
+ weights = area(intersection(target[ti], source[si]))
113
+ # Shared edges can differ by a few floating-point ulps after projection.
114
+ # Exclude numerical slivers, without extending support to empty cells.
115
+ threshold = 1e-10 * np.minimum(area(target[ti]), area(source[si]))
116
+ weights = np.where(weights > threshold, weights, 0.0)
117
+ # Boundary-only touches do not supply an observation.
118
+ sums = np.bincount(
119
+ ti, weights=weights * source_values[si], minlength=len(target)
120
+ )
121
+ weight_sum = np.bincount(ti, weights=weights, minlength=len(target))
122
+ np.divide(
123
+ sums, weight_sum, out=result[start:stop], where=weight_sum > 0
124
+ )
125
+ return result.reshape(lon.shape)
126
+
127
+
128
+ def valid_grid_geometry(
129
+ lon: np.ndarray,
130
+ lat: np.ndarray,
131
+ valid: np.ndarray,
132
+ res: float,
133
+ ) -> BaseGeometry:
134
+ """Union valid analysis cells using row runs, preserving missing cells."""
135
+ from shapely import box, union_all
136
+
137
+ x = grid_edges(lon[0], res)
138
+ y = grid_edges(lat[:, 0], res)
139
+ rectangles = []
140
+ for row, mask in enumerate(valid):
141
+ changes = np.diff(np.r_[False, mask, False].astype(np.int8))
142
+ starts, stops = (
143
+ np.flatnonzero(changes == 1),
144
+ np.flatnonzero(changes == -1),
145
+ )
146
+ rectangles.extend(box(x[starts], y[row], x[stops], y[row + 1]))
147
+ return union_all(rectangles)
148
+
149
+
150
+ @dataclass
151
+ class FootprintDisplay:
152
+ lon: np.ndarray
153
+ lat: np.ndarray
154
+ values: np.ndarray
155
+ support: BaseGeometry
156
+
157
+
158
+ def prepare_footprint_display(
159
+ lon: np.ndarray,
160
+ lat: np.ndarray,
161
+ values: np.ndarray,
162
+ geometry: BaseGeometry,
163
+ *,
164
+ analysis_res: float,
165
+ display_res: float,
166
+ smooth_sigma: float | None = None,
167
+ ) -> FootprintDisplay:
168
+ """Resample a fixed field and return its invariant clipping geometry.
169
+
170
+ The renderer must clip the colored layer to ``support``. Coarse display
171
+ cells may span analysis holes; finite display values alone do not describe
172
+ valid coverage. Analysis spacing is supplied by the caller.
173
+ """
174
+ from rsplot.geo.processing import prepare_display_grid, region_cell_mask
175
+
176
+ finite = np.isfinite(values)
177
+ support = valid_grid_geometry(lon, lat, finite, analysis_res).intersection(
178
+ geometry
179
+ )
180
+ # Smooth only within the fixed analysis lattice, retaining QA/data holes.
181
+ prepared = prepare_display_grid(
182
+ lon, lat, values, geometry, smooth_sigma=smooth_sigma
183
+ )
184
+ if display_res == analysis_res:
185
+ # Use the already remapped target grid directly: no second remapping.
186
+ return FootprintDisplay(lon, lat, prepared, support)
187
+ x = grid_edges(lon[0], analysis_res)
188
+ y = grid_edges(lat[:, 0], analysis_res)
189
+ display_lon, display_lat = regular_grid(
190
+ (x[0], x[-1], y[0], y[-1]), display_res
191
+ )
192
+ cx, cy = rectangle_corners(lon, lat, analysis_res)
193
+ finite = np.isfinite(prepared).ravel()
194
+ display = overlap_mean(
195
+ cx[finite],
196
+ cy[finite],
197
+ prepared.ravel()[finite],
198
+ display_lon,
199
+ display_lat,
200
+ display_res,
201
+ )
202
+ display = np.where(
203
+ region_cell_mask(display_lon, display_lat, geometry), display, np.nan
204
+ )
205
+ return FootprintDisplay(display_lon, display_lat, display, support)