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,263 @@
1
+ """Regional hourly ERA5 single-level weather for China-time hours.
2
+
3
+ ERA5 keeps one file per UTC day and field. Each requested China hour is
4
+ read from the UTC day file holding it; every cell whose centre lies in the
5
+ region (border included) counts equally. Derived quantities (relative
6
+ humidity, wind speed) are computed per cell and hour before the regional
7
+ mean, so the regional value is the mean of the cell values.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import dataclass
13
+ from datetime import datetime, timedelta
14
+ from pathlib import Path
15
+ from typing import TYPE_CHECKING
16
+
17
+ import numpy as np
18
+
19
+ from rsplot.errors import RsplotError
20
+ from rsplot.readers.era5 import TIME_NAMES, nearest_era5_hours
21
+ from rsplot.readers.netcdf import open_netcdf
22
+
23
+ if TYPE_CHECKING:
24
+ from shapely.geometry.base import BaseGeometry
25
+
26
+ UTC_OFFSET = timedelta(hours=8)
27
+ # Raw field -> (archive folder, unit the arithmetic below expects).
28
+ FIELDS = {
29
+ "t2m": ("2m_temperature", "K"),
30
+ "d2m": ("2m_dewpoint_temperature", "K"),
31
+ "ssrd": ("surface_solar_radiation_downwards", "J m**-2"),
32
+ "blh": ("boundary_layer_height", "m"),
33
+ "tp": ("total_precipitation", "m"),
34
+ "u10": ("10m_u_component_of_wind", "m s**-1"),
35
+ "v10": ("10m_v_component_of_wind", "m s**-1"),
36
+ }
37
+ # Derived hourly quantity -> raw fields it needs.
38
+ QUANTITIES = {
39
+ "t2m": ("t2m",),
40
+ "rh": ("t2m", "d2m"),
41
+ "ssrd": ("ssrd",),
42
+ "blh": ("blh",),
43
+ "tp": ("tp",),
44
+ "wind_speed": ("u10", "v10"),
45
+ "wind_u": ("u10",),
46
+ "wind_v": ("v10",),
47
+ }
48
+
49
+
50
+ @dataclass
51
+ class RegionWeatherHours:
52
+ """Regional means per China hour; NaN where a needed field is missing.
53
+
54
+ ``values`` hold t2m in degC, rh in %, ssrd in MJ/m2 per hour, blh in m,
55
+ tp in mm per hour and wind in m/s.
56
+ """
57
+
58
+ hours: list[str]
59
+ values: dict[str, np.ndarray]
60
+ n_cells: int
61
+ source_files: list[str]
62
+ failed_files: dict[str, str]
63
+ missing: dict[str, list[str]] # raw field -> China hours not read
64
+
65
+
66
+ def read_region_weather_hours(
67
+ data_dir: str,
68
+ hours: list[str],
69
+ geometry: BaseGeometry,
70
+ extent: tuple[float, float, float, float],
71
+ *,
72
+ workers: int = 1,
73
+ ) -> RegionWeatherHours:
74
+ """Read China ``YYYYMMDDHH`` hours as regional hourly means."""
75
+ root = Path(data_dir)
76
+ utc = [datetime.strptime(hour, "%Y%m%d%H") - UTC_OFFSET for hour in hours]
77
+ days: dict[str, list[int]] = {}
78
+ for index, moment in enumerate(utc):
79
+ days.setdefault(moment.strftime("%Y%m%d"), []).append(index)
80
+ region = geometry.buffer(1e-9)
81
+ jobs = [
82
+ (root, day, [utc[index].hour for index in indices], extent, region)
83
+ for day, indices in days.items()
84
+ ]
85
+ if workers > 1 and len(jobs) > 1:
86
+ from concurrent.futures import ProcessPoolExecutor
87
+
88
+ with ProcessPoolExecutor(max_workers=min(workers, len(jobs))) as pool:
89
+ results = list(pool.map(_read_day, jobs))
90
+ else:
91
+ results = [_read_day(job) for job in jobs]
92
+
93
+ values = {name: np.full(len(hours), np.nan) for name in QUANTITIES}
94
+ missing: dict[str, list[str]] = {name: [] for name in FIELDS}
95
+ source_files: list[str] = []
96
+ failed_files: dict[str, str] = {}
97
+ n_cells = 0
98
+ for indices, result in zip(days.values(), results, strict=True):
99
+ day_values, day_missing, files, failures, cells = result
100
+ for name, series in day_values.items():
101
+ values[name][indices] = series
102
+ for name, positions in day_missing.items():
103
+ missing[name].extend(hours[indices[item]] for item in positions)
104
+ source_files.extend(files)
105
+ failed_files.update(failures)
106
+ n_cells = max(n_cells, cells)
107
+ if not source_files:
108
+ first = root / utc[0].strftime("%Y%m%d") / "single_level"
109
+ path = first / FIELDS["t2m"][0] / "surface.nc"
110
+ before, after = nearest_era5_hours(path, utc[0])
111
+ raise RsplotError(
112
+ "data_not_found",
113
+ f"未找到 {hours[0]}~{hours[-1]} 的 ERA5 气象文件: {path};"
114
+ f"最近可用时次: 之前 {before or '无'},之后 {after or '无'}。",
115
+ details={
116
+ "path": str(path),
117
+ "nearest_before": before,
118
+ "nearest_after": after,
119
+ },
120
+ )
121
+ for name in missing:
122
+ missing[name].sort()
123
+ return RegionWeatherHours(
124
+ hours=hours,
125
+ values=values,
126
+ n_cells=n_cells,
127
+ source_files=source_files,
128
+ failed_files=failed_files,
129
+ missing=missing,
130
+ )
131
+
132
+
133
+ def relative_humidity(t_kelvin: np.ndarray, d_kelvin: np.ndarray):
134
+ """Relative humidity (%) over water from temperature and dew point."""
135
+ t = t_kelvin - 273.15
136
+ d = d_kelvin - 273.15
137
+ return 100.0 * np.exp(17.67 * d / (d + 243.5) - 17.67 * t / (t + 243.5))
138
+
139
+
140
+ def _read_day(job) -> tuple:
141
+ """One UTC day: regional means per requested hour and what is missing.
142
+
143
+ Returns (values, missing positions per field, files read, failures,
144
+ number of region cells). Failures are reported, never raised, so a
145
+ worker process never has to pickle an exception.
146
+ """
147
+ root, day, utc_hours, extent, region = job
148
+ count = len(utc_hours)
149
+ cells: dict[str, np.ndarray] = {}
150
+ missing: dict[str, list[int]] = {}
151
+ files: list[str] = []
152
+ failures: dict[str, str] = {}
153
+ n_cells = 0
154
+ for name, (folder, unit) in FIELDS.items():
155
+ path = root / day / "single_level" / folder / "surface.nc"
156
+ relative = str(path.relative_to(root))
157
+ data = np.full((count, 0), np.nan)
158
+ if path.exists():
159
+ try:
160
+ data, found = _read_field(
161
+ path, name, unit, day, utc_hours, extent, region
162
+ )
163
+ files.append(str(path))
164
+ except (RsplotError, OSError, KeyError, ValueError) as error:
165
+ failures[relative] = str(error).splitlines()[0]
166
+ found = np.zeros(count, dtype=bool)
167
+ else:
168
+ found = np.zeros(count, dtype=bool)
169
+ if data.shape[1]:
170
+ n_cells = data.shape[1]
171
+ cells[name] = data
172
+ missing[name] = [int(item) for item in np.flatnonzero(~found)]
173
+
174
+ values = {}
175
+ for quantity, needed in QUANTITIES.items():
176
+ if any(cells[name].shape[1] == 0 for name in needed):
177
+ values[quantity] = np.full(count, np.nan)
178
+ continue
179
+ values[quantity] = _regional_mean(_derive(quantity, cells))
180
+ return values, missing, files, failures, n_cells
181
+
182
+
183
+ def _derive(quantity: str, cells: dict[str, np.ndarray]) -> np.ndarray:
184
+ """Per cell and hour value of a quantity in its display unit."""
185
+ if quantity == "t2m":
186
+ return cells["t2m"] - 273.15
187
+ if quantity == "rh":
188
+ return relative_humidity(cells["t2m"], cells["d2m"])
189
+ if quantity == "ssrd":
190
+ return cells["ssrd"] / 1e6
191
+ if quantity == "tp":
192
+ return cells["tp"] * 1000.0
193
+ if quantity == "wind_speed":
194
+ return np.hypot(cells["u10"], cells["v10"])
195
+ if quantity == "wind_u":
196
+ return cells["u10"]
197
+ if quantity == "wind_v":
198
+ return cells["v10"]
199
+ return cells[quantity]
200
+
201
+
202
+ def _regional_mean(values: np.ndarray) -> np.ndarray:
203
+ """Equal-weight mean over cells; NaN unless every cell is valid."""
204
+ complete = np.isfinite(values).all(axis=1)
205
+ return np.where(complete, values.mean(axis=1), np.nan)
206
+
207
+
208
+ def _read_field(
209
+ path: Path,
210
+ name: str,
211
+ unit: str,
212
+ day: str,
213
+ utc_hours: list[int],
214
+ extent: tuple[float, float, float, float],
215
+ region,
216
+ ) -> tuple[np.ndarray, np.ndarray]:
217
+ """(hours, region cells) values of one field and which hours exist."""
218
+ from shapely import contains_xy
219
+
220
+ with open_netcdf(path) as ds:
221
+ time_name = next((n for n in TIME_NAMES if n in ds.variables), None)
222
+ if time_name is None or name not in ds.variables:
223
+ raise KeyError(f"缺少变量: {name if time_name else 'valid_time'}")
224
+ source_unit = str(ds[name].attrs.get("units", ""))
225
+ if source_unit != unit:
226
+ raise ValueError(f"{name} 单位应为 {unit},实际为 {source_unit}")
227
+ lon_raw = np.asarray(ds["longitude"].values, dtype=float)
228
+ lat_raw = np.asarray(ds["latitude"].values, dtype=float)
229
+ lon_normalized = (lon_raw + 180.0) % 360.0 - 180.0
230
+ lon_min, lon_max, lat_min, lat_max = extent
231
+ lon_index = np.flatnonzero(
232
+ (lon_normalized >= lon_min) & (lon_normalized <= lon_max)
233
+ )
234
+ lat_index = np.flatnonzero((lat_raw >= lat_min) & (lat_raw <= lat_max))
235
+ lon, lat = np.meshgrid(lon_normalized[lon_index], lat_raw[lat_index])
236
+ inside = contains_xy(region, lon, lat)
237
+ if not inside.any():
238
+ raise ValueError("区域内没有 ERA5 网格中心")
239
+
240
+ times = np.asarray(ds[time_name].values).astype("datetime64[ns]")
241
+ start = np.datetime64(datetime.strptime(day, "%Y%m%d"), "ns")
242
+ wanted = start + np.array(utc_hours, dtype="timedelta64[h]")
243
+ positions = [np.flatnonzero(times == moment) for moment in wanted]
244
+ found = np.array([len(item) > 0 for item in positions])
245
+ out = np.full((len(utc_hours), int(inside.sum())), np.nan)
246
+ if found.any():
247
+ time_index = [int(item[0]) for item in positions if len(item)]
248
+ first, last = min(time_index), max(time_index)
249
+ block = np.asarray(
250
+ ds[name]
251
+ .isel(
252
+ {
253
+ time_name: slice(first, last + 1),
254
+ "latitude": slice(lat_index[0], lat_index[-1] + 1),
255
+ "longitude": slice(lon_index[0], lon_index[-1] + 1),
256
+ }
257
+ )
258
+ .values,
259
+ dtype=float,
260
+ )
261
+ rows = [index - first for index in time_index]
262
+ out[found] = block[rows][:, inside]
263
+ return out, found
rsplot/readers/guokong.py CHANGED
@@ -384,13 +384,17 @@ def read_station_series(
384
384
  )
385
385
 
386
386
 
387
+ class NoRegionStations(ValueError):
388
+ """No station of the hourly files lies inside the requested region."""
389
+
390
+
387
391
  def read_region_station_series(
388
392
  data_dir: str,
389
393
  dates: list[str],
390
394
  var_name: str,
391
395
  geometry: BaseGeometry,
392
396
  ) -> RegionStationSeries:
393
- """Read an aligned station-by-hour matrix inside ``geometry``.
397
+ """Read an aligned station-by-hour matrix for hours 00–23 of ``dates``.
394
398
 
395
399
  Each hourly file is opened at most once, regardless of the number of
396
400
  stations in the selected region. Stations appearing or disappearing
@@ -398,108 +402,171 @@ def read_region_station_series(
398
402
  """
399
403
  if not dates:
400
404
  raise ValueError("日期窗口不能为空")
405
+ timestamps = [f"{date}{hour:02d}" for date in dates for hour in range(24)]
406
+ return read_region_station_hours(
407
+ data_dir, timestamps, var_name, geometry, window=(dates[0], dates[-1])
408
+ )
401
409
 
402
- from shapely import contains_xy
403
410
 
404
- root = Path(data_dir)
405
- timestamps = [f"{date}{hour:02d}" for date in dates for hour in range(24)]
406
- hourly_values: list[dict[str, float]] = []
407
- station_meta: dict[str, tuple[float, float]] = {}
408
- source_files: list[str] = []
409
- missing_files: list[str] = []
410
- failed_files: dict[str, str] = {}
411
- existing_files = 0
412
- region_geometry = geometry.buffer(1e-9)
411
+ def read_region_station_hours(
412
+ data_dir: str,
413
+ timestamps: list[str],
414
+ var_name: str,
415
+ geometry: BaseGeometry,
416
+ *,
417
+ window: tuple[str, str],
418
+ workers: int = 1,
419
+ ) -> RegionStationSeries:
420
+ """Read ``timestamps`` as an aligned station-by-hour matrix.
413
421
 
414
- for timestamp in timestamps:
415
- path = root / f"{timestamp}.nc"
416
- if not path.exists():
417
- missing_files.append(timestamp)
418
- hourly_values.append({})
419
- continue
422
+ ``workers`` > 1 reads the files in that many processes; HDF5 is not
423
+ thread-safe, so the hours are never read on threads.
424
+ """
425
+ return read_station_hour_variables(
426
+ data_dir,
427
+ timestamps,
428
+ (var_name,),
429
+ geometry=geometry,
430
+ window=window,
431
+ workers=workers,
432
+ )[var_name]
420
433
 
421
- existing_files += 1
422
- try:
423
- with open_netcdf(path) as ds:
424
- required = ("id", "lon", "lat", var_name)
425
- missing_vars = [name for name in required if name not in ds]
426
- if missing_vars:
427
- raise KeyError(f"缺少变量: {', '.join(missing_vars)}")
428
434
 
429
- ids = _normalize_station_ids(ds["id"].values)
430
- lon = np.asarray(ds["lon"].values, dtype=float).ravel()
431
- lat = np.asarray(ds["lat"].values, dtype=float).ravel()
432
- raw = (
433
- np.asarray(ds[var_name].values)
434
- .astype(
435
- float,
436
- copy=True,
437
- )
438
- .ravel()
439
- )
440
- if not (len(ids) == len(lon) == len(lat) == len(raw)):
441
- raise ValueError("站点 ID、经纬度和变量数组长度不一致")
442
-
443
- raw[raw >= 65534] = np.nan
444
- inside = contains_xy(region_geometry, lon, lat)
445
- row: dict[str, float] = {}
446
- for index in np.flatnonzero(inside):
447
- station_id = str(ids[index])
448
- key = station_id.upper()
449
- if key in row:
450
- continue
451
- row[key] = float(raw[index])
452
- station_meta.setdefault(
453
- key,
454
- (float(lon[index]), float(lat[index])),
455
- )
456
- hourly_values.append(row)
457
- source_files.append(str(path))
458
- except (OSError, KeyError, ValueError, IndexError) as error:
459
- failed_files[timestamp] = str(error).splitlines()[0]
460
- hourly_values.append({})
435
+ @dataclass
436
+ class _StationHour:
437
+ locations: dict[str, tuple[float, float]]
438
+ values: dict[str, np.ndarray]
439
+ failures: dict[str, str]
461
440
 
462
- if existing_files == 0:
441
+
442
+ def read_station_hour_variables(
443
+ data_dir: str,
444
+ timestamps: list[str],
445
+ variables: tuple[str, ...],
446
+ *,
447
+ window: tuple[str, str],
448
+ geometry: BaseGeometry | None = None,
449
+ station_id: str | None = None,
450
+ workers: int = 1,
451
+ ) -> dict[str, RegionStationSeries]:
452
+ """Read each file once and align all columns to the same station IDs."""
453
+ if (geometry is None) == (station_id is None):
454
+ raise ValueError("请选择一个区域或站点")
455
+ if not variables:
456
+ raise ValueError("请选择至少一个站点变量")
457
+ root = Path(data_dir)
458
+ region = geometry.buffer(1e-9) if geometry is not None else None
459
+ target = station_id.strip().upper() if station_id is not None else None
460
+ paths = [root / f"{stamp}.nc" for stamp in timestamps]
461
+ existing = [path for path in paths if path.exists()]
462
+ if not existing:
463
463
  raise RsplotError(
464
464
  "data_not_found",
465
- f"窗口 {dates[0]}~{dates[-1]} 内未找到可读取的站点文件: "
465
+ f"窗口 {window[0]}~{window[1]} 内未找到可读取的站点文件: "
466
466
  f"{root}/YYYYMMDDHH.nc",
467
467
  details={"path": f"{root}/YYYYMMDDHH.nc"},
468
468
  )
469
- if not source_files:
470
- examples = "; ".join(
471
- f"{timestamp}: {message}"
472
- for timestamp, message in list(failed_files.items())[:3]
469
+ jobs = [(path, variables, region, target) for path in existing]
470
+ if workers > 1 and len(jobs) > 1:
471
+ from concurrent.futures import ProcessPoolExecutor
472
+
473
+ with ProcessPoolExecutor(max_workers=min(workers, len(jobs))) as pool:
474
+ results = list(pool.map(_read_station_hour, jobs, chunksize=4))
475
+ else:
476
+ results = [_read_station_hour(job) for job in jobs]
477
+
478
+ if not any(hour.values for hour in results):
479
+ raise RsplotError(
480
+ "read_failed",
481
+ f"窗口 {window[0]}~{window[1]} 内读取变量失败: "
482
+ f"{next(iter(results[0].failures.values()))}",
483
+ details={"path": str(existing[0])},
473
484
  )
474
- raise ValueError(
475
- f"窗口 {dates[0]}~{dates[-1]} 内无法读取变量 "
476
- f"'{var_name}': {examples}"
485
+ locations: dict[str, tuple[float, float]] = {}
486
+ for hour in results:
487
+ for key, coords in hour.locations.items():
488
+ locations.setdefault(key, coords)
489
+ if not locations:
490
+ if target is not None:
491
+ raise RsplotError(
492
+ "region_not_found",
493
+ f"窗口内未找到站点 '{target}'",
494
+ details={"station_id": target},
495
+ )
496
+ raise NoRegionStations(
497
+ f"窗口 {window[0]}~{window[1]} 内目标区域没有国控站点"
477
498
  )
478
- if not station_meta:
479
- raise ValueError(f"窗口 {dates[0]}~{dates[-1]} 内目标区域没有国控站点")
480
499
 
481
- station_ids = np.asarray(sorted(station_meta), dtype=str)
482
- station_lookup = {
483
- station_id: index for index, station_id in enumerate(station_ids)
500
+ ids = np.asarray(sorted(locations), dtype=str)
501
+ lookup = {key: index for index, key in enumerate(ids)}
502
+ lon, lat = np.asarray([locations[key] for key in ids]).T
503
+ columns = {stamp: index for index, stamp in enumerate(timestamps)}
504
+ found = {path.stem for path in existing}
505
+ missing = [stamp for stamp in timestamps if stamp not in found]
506
+ series = {
507
+ var: RegionStationSeries(
508
+ ids,
509
+ lon,
510
+ lat,
511
+ timestamps,
512
+ np.full((len(ids), len(paths)), np.nan),
513
+ var,
514
+ missing_files=missing,
515
+ )
516
+ for var in variables
484
517
  }
485
- values = np.full((len(station_ids), len(timestamps)), np.nan, dtype=float)
486
- for hour_index, row in enumerate(hourly_values):
487
- for station_id, value in row.items():
488
- values[station_lookup[station_id], hour_index] = value
489
-
490
- lon = np.asarray([station_meta[key][0] for key in station_ids])
491
- lat = np.asarray([station_meta[key][1] for key in station_ids])
492
- return RegionStationSeries(
493
- station_ids=station_ids,
494
- lon=lon,
495
- lat=lat,
496
- timestamps=timestamps,
497
- values=values,
498
- var_name=var_name,
499
- source_files=source_files,
500
- missing_files=missing_files,
501
- failed_files=failed_files,
502
- )
518
+ for path, hour in zip(existing, results, strict=True):
519
+ rows = [lookup[key] for key in hour.locations]
520
+ for var, values in hour.values.items():
521
+ series[var].values[rows, columns[path.stem]] = values
522
+ series[var].source_files.append(str(path))
523
+ for var, failure in hour.failures.items():
524
+ series[var].failed_files[path.stem] = failure
525
+ return series
526
+
527
+
528
+ def _read_station_hour(
529
+ job: tuple[Path, tuple[str, ...], BaseGeometry | None, str | None],
530
+ ) -> _StationHour:
531
+ """Select stations once, retaining independent failures per column."""
532
+ from shapely import contains_xy
533
+
534
+ path, variables, region, target = job
535
+ values = {}
536
+ failures = {}
537
+ try:
538
+ with open_netcdf(path) as ds:
539
+ ids = np.char.upper(_normalize_station_ids(ds["id"].values))
540
+ lon = np.asarray(ds["lon"].values, dtype=float).ravel()
541
+ lat = np.asarray(ds["lat"].values, dtype=float).ravel()
542
+ if not (len(ids) == len(lon) == len(lat)):
543
+ raise ValueError("站点 ID 与坐标数量不一致")
544
+ selected = (
545
+ ids == target
546
+ if region is None
547
+ else contains_xy(region, lon, lat)
548
+ )
549
+ indices = np.flatnonzero(selected)
550
+ _, first = np.unique(ids[indices], return_index=True)
551
+ indices = indices[first]
552
+ locations = {ids[i]: (lon[i], lat[i]) for i in indices}
553
+ for var in variables:
554
+ try:
555
+ if var not in ds:
556
+ raise KeyError(f"缺少变量: {var}")
557
+ raw = np.asarray(ds[var].values, dtype=float).ravel()
558
+ if len(raw) != len(ids):
559
+ raise ValueError(f"站点 ID 与 {var} 数量不一致")
560
+ column = raw[indices]
561
+ column[(column >= 65534) | ~np.isfinite(column)] = np.nan
562
+ values[var] = column
563
+ except (OSError, KeyError, ValueError, IndexError) as error:
564
+ failures[var] = str(error).splitlines()[0]
565
+ except (OSError, KeyError, ValueError, IndexError) as error:
566
+ return _StationHour(
567
+ {}, {}, dict.fromkeys(variables, str(error).splitlines()[0])
568
+ )
569
+ return _StationHour(locations if values else {}, values, failures)
503
570
 
504
571
 
505
572
  def mask_stations_to_region(
@@ -2,6 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import math
5
6
  from typing import TYPE_CHECKING, Any
6
7
 
7
8
  import numpy as np
@@ -220,3 +221,104 @@ def grid_boundary_policy(
220
221
  "n_cells_with_centers_outside": int((visible & ~inside).sum()),
221
222
  },
222
223
  }
224
+
225
+
226
+ def extract_plumes(
227
+ lon: np.ndarray,
228
+ lat: np.ndarray,
229
+ grid: np.ndarray,
230
+ counted: np.ndarray,
231
+ areas_gdf: gpd.GeoDataFrame | None,
232
+ *,
233
+ percentile: int = 90,
234
+ min_cells: int = 2,
235
+ max_items: int = 3,
236
+ ) -> dict[str, Any]:
237
+ """Extract 8-connected high-value plumes from the statistical grid."""
238
+ from scipy.ndimage import label as ndimage_label
239
+
240
+ valid_mask = np.asarray(counted, dtype=bool) & np.isfinite(grid)
241
+ finite = grid[valid_mask]
242
+ if finite.size < 4 or float(np.ptp(finite)) == 0.0:
243
+ return {
244
+ "threshold_percentile": percentile,
245
+ "threshold": None,
246
+ "items": [],
247
+ "total": 0,
248
+ "truncated": False,
249
+ }
250
+
251
+ threshold = float(np.percentile(finite, percentile))
252
+ high_mask = valid_mask & (grid >= threshold)
253
+ # When >90% of cells tie at the floor, >= selects the entire background.
254
+ if int(high_mask.sum()) > finite.size * 0.5:
255
+ high_mask = valid_mask & (grid > threshold)
256
+ labeled, n_features = ndimage_label(
257
+ high_mask, structure=np.ones((3, 3), dtype=int)
258
+ )
259
+
260
+ lats_1d = np.asarray(lat)[:, 0] if lat.ndim == 2 else np.asarray(lat)
261
+ lons_1d = np.asarray(lon)[0, :] if lon.ndim == 2 else np.asarray(lon)
262
+ dlat = abs(float(lats_1d[1] - lats_1d[0])) if lats_1d.size > 1 else 0.0
263
+ dlon = abs(float(lons_1d[1] - lons_1d[0])) if lons_1d.size > 1 else 0.0
264
+
265
+ admin_masks: list[tuple[str, np.ndarray]] = []
266
+ if areas_gdf is not None and len(areas_gdf) > 0:
267
+ from shapely import contains_xy
268
+
269
+ for _, row in areas_gdf.iterrows():
270
+ admin_masks.append(
271
+ (str(row["name"]), contains_xy(row.geometry, lon, lat))
272
+ )
273
+
274
+ components: list[dict[str, Any]] = []
275
+ for cid in range(1, n_features + 1):
276
+ mask = labeled == cid
277
+ cells = int(mask.sum())
278
+ if cells < min_cells:
279
+ continue
280
+ vals = grid[mask]
281
+ c_lons = lon[mask]
282
+ c_lats = lat[mask]
283
+ peak_idx = int(np.argmax(vals))
284
+ mean_lat = float(np.mean(c_lats))
285
+ cell_area = (
286
+ (dlat * 111.32)
287
+ * (dlon * 111.32 * max(math.cos(math.radians(mean_lat)), 0.0))
288
+ )
289
+ admins_counts = []
290
+ for name, amask in admin_masks:
291
+ hits = int((mask & amask).sum())
292
+ if hits > 0:
293
+ admins_counts.append((hits, name))
294
+ admins_counts.sort(key=lambda item: (-item[0], item[1]))
295
+ admins = [name for _, name in admins_counts]
296
+ components.append(
297
+ {
298
+ "cells": cells,
299
+ "area_km2": round(cells * cell_area, 1),
300
+ "centroid_lon": round(float(np.mean(c_lons)), 4),
301
+ "centroid_lat": round(mean_lat, 4),
302
+ "peak_lon": round(float(c_lons[peak_idx]), 4),
303
+ "peak_lat": round(float(c_lats[peak_idx]), 4),
304
+ "mean": round_finite(float(np.mean(vals))),
305
+ "max": round_finite(float(np.max(vals))),
306
+ "admins": admins,
307
+ "cross_border": len(admins) > 1,
308
+ }
309
+ )
310
+
311
+ components.sort(
312
+ key=lambda item: (
313
+ -(item["max"] if item["max"] is not None else -math.inf),
314
+ -item["cells"],
315
+ )
316
+ )
317
+ total = len(components)
318
+ return {
319
+ "threshold_percentile": percentile,
320
+ "threshold": round_finite(threshold),
321
+ "items": components[:max_items],
322
+ "total": total,
323
+ "truncated": total > max_items,
324
+ }