eccopy 1.0.0__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 (79) hide show
  1. eccopy/__init__.py +46 -0
  2. eccopy/core/__init__.py +55 -0
  3. eccopy/core/classification.py +1023 -0
  4. eccopy/core/colormaps.py +267 -0
  5. eccopy/core/convectivity.py +43 -0
  6. eccopy/core/coords.py +245 -0
  7. eccopy/core/data/disk_decomp/disk_decomp_r15_info.mat +0 -0
  8. eccopy/core/data/disk_decomp/disk_decomp_r15_step1.mat +0 -0
  9. eccopy/core/data/disk_decomp/disk_decomp_r15_step2.mat +0 -0
  10. eccopy/core/data/disk_decomp/disk_decomp_r15_step3.mat +0 -0
  11. eccopy/core/data/disk_decomp/disk_decomp_r15_step4.mat +0 -0
  12. eccopy/core/data/disk_decomp/disk_decomp_r15_step5.mat +0 -0
  13. eccopy/core/data/disk_decomp/disk_decomp_r15_step6.mat +0 -0
  14. eccopy/core/data/disk_decomp/disk_decomp_r25_info.mat +0 -0
  15. eccopy/core/data/disk_decomp/disk_decomp_r25_step1.mat +0 -0
  16. eccopy/core/data/disk_decomp/disk_decomp_r25_step2.mat +0 -0
  17. eccopy/core/data/disk_decomp/disk_decomp_r25_step3.mat +0 -0
  18. eccopy/core/data/disk_decomp/disk_decomp_r25_step4.mat +0 -0
  19. eccopy/core/data/disk_decomp/disk_decomp_r25_step5.mat +0 -0
  20. eccopy/core/data/disk_decomp/disk_decomp_r25_step6.mat +0 -0
  21. eccopy/core/data/disk_strels/disk_strel_r15.mat +0 -0
  22. eccopy/core/data/disk_strels/disk_strel_r25.mat +0 -0
  23. eccopy/core/data/disk_strels/disk_strel_r3.mat +0 -0
  24. eccopy/core/data/disk_strels/disk_strel_r5.mat +0 -0
  25. eccopy/core/debug.py +493 -0
  26. eccopy/core/disk.py +178 -0
  27. eccopy/core/temperature.py +250 -0
  28. eccopy/core/texture.py +1398 -0
  29. eccopy/eccopy1d/__init__.py +2 -0
  30. eccopy/eccopy1d/classify.py +273 -0
  31. eccopy/eccopy2d_h/__init__.py +2 -0
  32. eccopy/eccopy2d_h/classify.py +281 -0
  33. eccopy/eccopy2d_h/clumping.py +265 -0
  34. eccopy/eccopy2d_v/__init__.py +2 -0
  35. eccopy/eccopy2d_v/classify.py +288 -0
  36. eccopy/eccopy3d/__init__.py +2 -0
  37. eccopy/eccopy3d/classify.py +421 -0
  38. eccopy/eccopy3d/clumping.py +477 -0
  39. eccopy/params/__init__.py +6 -0
  40. eccopy/params/classification_params.py +151 -0
  41. eccopy/params/texture_params.py +66 -0
  42. eccopy/params/vertical_params.py +54 -0
  43. eccopy/params/window.py +141 -0
  44. eccopy/stats/__init__.py +56 -0
  45. eccopy/stats/basic_stats.py +370 -0
  46. eccopy/tests/__init__.py +0 -0
  47. eccopy/tests/_reference_impls/__init__.py +0 -0
  48. eccopy/tests/_reference_impls/isotherm_height_reference.py +54 -0
  49. eccopy/tests/_reference_impls/sliding_texture_reference.py +77 -0
  50. eccopy/tests/_reference_impls/texture_2d_reference.py +309 -0
  51. eccopy/tests/test_classification_1d_filter.py +151 -0
  52. eccopy/tests/test_classification_rain_below_melt.py +130 -0
  53. eccopy/tests/test_colormaps.py +213 -0
  54. eccopy/tests/test_coords.py +127 -0
  55. eccopy/tests/test_debug.py +226 -0
  56. eccopy/tests/test_disk_generator.py +82 -0
  57. eccopy/tests/test_eccopy1d.py +209 -0
  58. eccopy/tests/test_eccopy2d_h.py +185 -0
  59. eccopy/tests/test_eccopy2d_h_clumping.py +105 -0
  60. eccopy/tests/test_eccopy2d_v.py +359 -0
  61. eccopy/tests/test_eccopy3d.py +282 -0
  62. eccopy/tests/test_examples.py +84 -0
  63. eccopy/tests/test_min_valid_dbz.py +144 -0
  64. eccopy/tests/test_notebooks.py +111 -0
  65. eccopy/tests/test_numba_cross_validation.py +331 -0
  66. eccopy/tests/test_packaging.py +144 -0
  67. eccopy/tests/test_refl_texture_1d.py +167 -0
  68. eccopy/tests/test_stats.py +117 -0
  69. eccopy/tests/test_stats_sentinel.py +74 -0
  70. eccopy/tests/test_temperature.py +207 -0
  71. eccopy/tests/test_texture_kernel_modes.py +82 -0
  72. eccopy/tests/test_texture_params_implemented.py +148 -0
  73. eccopy/tests/test_vert_levels_type.py +180 -0
  74. eccopy/tests/test_window.py +80 -0
  75. eccopy-1.0.0.dist-info/METADATA +420 -0
  76. eccopy-1.0.0.dist-info/RECORD +79 -0
  77. eccopy-1.0.0.dist-info/WHEEL +5 -0
  78. eccopy-1.0.0.dist-info/licenses/LICENSE +39 -0
  79. eccopy-1.0.0.dist-info/top_level.txt +1 -0
eccopy/core/debug.py ADDED
@@ -0,0 +1,493 @@
1
+ """
2
+ Debug / introspection helpers for EccoPy's texture calculations.
3
+
4
+ These functions are NOT used by the production pipeline (refl_texture_1d,
5
+ refl_texture_2d) - they exist purely so you can inspect the intermediate
6
+ quantities that the validated production code computes and discards:
7
+ the raw windowed data, the fitted trend, and the detrended residual.
8
+
9
+ Use these when you want to understand or sanity-check WHY a particular
10
+ point got the texture value it did, not as a substitute for the
11
+ production functions (which are faster and operate on the whole array
12
+ at once).
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from dataclasses import dataclass
18
+ from typing import Optional, Union
19
+
20
+ import numpy as np
21
+
22
+ from ..params.window import WindowSpec
23
+ from .texture import _fillmissing_linear, _radius_field_along_axis
24
+
25
+
26
+ @dataclass
27
+ class TextureDebug1D:
28
+ """Intermediate quantities for one point's 1-D texture calculation."""
29
+ index: int # index in the original (unpadded) array
30
+ radius: int # window half-width used at this point (grid cells)
31
+ window_indices: np.ndarray # original-array indices included in the window
32
+ window_dbz: np.ndarray # raw dBZ values in the window (NaN-filled if gaps existed)
33
+ fit_x: np.ndarray # 1..W, the x-coordinate used for the linear fit
34
+ fit_slope: float # fitted line slope (b)
35
+ fit_intercept: float # fitted line intercept (a)
36
+ fitted_line: np.ndarray # a + b*x - the trend that gets removed
37
+ mean_dbz: float # mean of window_dbz (added back after detrending)
38
+ detrended: np.ndarray # window_dbz - fitted_line + mean_dbz, clipped to >= 1
39
+ texture: float # sqrt(population_std(detrended**2))
40
+
41
+
42
+ def refl_texture_1d_debug(dbz: np.ndarray,
43
+ window: Union[WindowSpec, int],
44
+ index: int,
45
+ spacing: Optional[np.ndarray] = None,
46
+ dbz_base: float = 0.0) -> TextureDebug1D:
47
+ """
48
+ Run the EccoPy-1D texture calculation for ONE point, returning every
49
+ intermediate quantity instead of just the final texture value.
50
+
51
+ This reuses the exact same fill/pad/detrend math as refl_texture_1d
52
+ (same NaN-filling, same window resolution from WindowSpec) so the
53
+ `texture` value returned here will exactly match
54
+ `refl_texture_1d(dbz, window, spacing)[index]`.
55
+
56
+ Parameters
57
+ ----------
58
+ dbz : np.ndarray, shape (N,)
59
+ Same input you would pass to refl_texture_1d.
60
+ window : WindowSpec or int
61
+ Same window you would pass to refl_texture_1d.
62
+ index : int
63
+ Which point (0-based, into the ORIGINAL unpadded array) to inspect.
64
+ spacing : np.ndarray, optional
65
+ Same spacing array you would pass to refl_texture_1d (already
66
+ converted to the window's base unit - e.g. metres for a
67
+ WindowSpec((_, 'km')) - exactly as eccopy1d.run() does internally;
68
+ see that function if you want to replicate it from km coords).
69
+ dbz_base : float
70
+ Same dbz_base you would pass to refl_texture_1d.
71
+
72
+ Returns
73
+ -------
74
+ TextureDebug1D
75
+ """
76
+ dbz = np.asarray(dbz, dtype=float)
77
+ if dbz.ndim != 1:
78
+ raise ValueError(f"refl_texture_1d_debug expects a 1-D array; got shape {dbz.shape}")
79
+ n = dbz.shape[0]
80
+ if not (0 <= index < n):
81
+ raise ValueError(f"index {index} out of range for array of length {n}")
82
+
83
+ radius_field = _radius_field_along_axis(window, spacing, n)
84
+ r = int(radius_field[index])
85
+ pad = int(radius_field.max()) if radius_field.size else 0
86
+
87
+ # Production re-masks texture to NaN at any point where the ORIGINAL
88
+ # input was NaN, even though the window around it gets gap-filled to
89
+ # compute OTHER points' texture. Reproduce that here so this debug
90
+ # function never disagrees with production at originally-missing points.
91
+ original_was_nan = bool(np.isnan(dbz[index]))
92
+
93
+ padded = np.pad(dbz[np.newaxis, :], ((0, 0), (pad, pad)),
94
+ mode="constant", constant_values=np.nan)
95
+ padded = _fillmissing_linear(padded, axis=1)
96
+ padded = padded - dbz_base
97
+
98
+ if original_was_nan:
99
+ filled_value = float(padded[0, pad + index])
100
+ return TextureDebug1D(
101
+ index=index, radius=r,
102
+ window_indices=np.array([index]),
103
+ window_dbz=np.array([dbz[index]]), # NaN, the true raw value
104
+ fit_x=np.array([1.0]), fit_slope=0.0, fit_intercept=filled_value,
105
+ fitted_line=np.array([filled_value]), mean_dbz=filled_value,
106
+ detrended=np.array([filled_value]),
107
+ texture=float("nan"), # matches production's final re-mask
108
+ )
109
+
110
+ if r < 1:
111
+ return TextureDebug1D(
112
+ index=index, radius=r,
113
+ window_indices=np.array([index]),
114
+ window_dbz=np.array([dbz[index]]),
115
+ fit_x=np.array([1.0]), fit_slope=0.0, fit_intercept=float(dbz[index]),
116
+ fitted_line=np.array([dbz[index]]), mean_dbz=float(dbz[index]),
117
+ detrended=np.array([max(dbz[index] - dbz_base, 1.0)]),
118
+ texture=0.0,
119
+ )
120
+
121
+ lo = pad + index - r
122
+ hi = pad + index + r + 1
123
+ block = padded[0, lo:hi] # (W,) - the raw (gap-filled) window
124
+ W = block.shape[0]
125
+
126
+ window_indices = np.arange(index - r, index + r + 1)
127
+
128
+ x = np.arange(1, W + 1, dtype=float)
129
+ sumX = np.sum(x)
130
+ sumY = np.nansum(block)
131
+ sumXY = np.nansum(block * x)
132
+ sumX2 = np.sum(x ** 2)
133
+ denom = W * sumX2 - sumX ** 2
134
+
135
+ if denom == 0:
136
+ a, b = 0.0, 0.0
137
+ else:
138
+ a = (sumY * sumX2 - sumX * sumXY) / denom
139
+ b = (W * sumXY - sumX * sumY) / denom
140
+
141
+ fitted_line = a + b * x
142
+ mean_block = np.nanmean(block)
143
+ detrended = block - fitted_line + mean_block
144
+ detrended = np.where(detrended < 1, 1.0, detrended)
145
+
146
+ # Sample variance (N-1 denominator) of detrended**2, NaNs dropped.
147
+ # Must match refl_texture_1d's Numba core, which uses ddof=1 to
148
+ # follow MATLAB's std() default. ddof=0 here would silently break
149
+ # this function's contract of reproducing refl_texture_1d(...)[index].
150
+ finite = detrended[~np.isnan(detrended)] ** 2
151
+ n_valid_pts = finite.size
152
+ if n_valid_pts > 1:
153
+ var = float(np.var(finite, ddof=1))
154
+ if var < 0.0:
155
+ var = 0.0
156
+ elif n_valid_pts == 1:
157
+ var = 0.0 # matches MATLAB's std() of a single sample == 0
158
+ else:
159
+ var = float("nan")
160
+ texture = float(np.sqrt(np.sqrt(var)))
161
+
162
+ return TextureDebug1D(
163
+ index=index, radius=r,
164
+ window_indices=window_indices,
165
+ window_dbz=block.copy(),
166
+ fit_x=x, fit_slope=float(b), fit_intercept=float(a),
167
+ fitted_line=fitted_line,
168
+ mean_dbz=float(mean_block),
169
+ detrended=detrended,
170
+ texture=texture,
171
+ )
172
+
173
+
174
+ @dataclass
175
+ class TextureDebug2D:
176
+ """Intermediate quantities for one point's 2-D radial texture calculation."""
177
+ iy: int
178
+ ix: int
179
+ n_kernel: int # total points in the circular kernel footprint
180
+ n_valid: int # non-NaN points actually used
181
+ fraction_active: float # coverage fraction at this point
182
+ kernel_dx: np.ndarray # x-offset (km) of each valid kernel point
183
+ kernel_dy: np.ndarray # y-offset (km) of each valid kernel point
184
+ kernel_dbz: np.ndarray # raw dBZ at each valid kernel point
185
+ plane_fit_used: bool # whether enough points existed to fit a plane
186
+ plane_a: float # fitted plane: value = a*dx + b*dy
187
+ plane_b: float
188
+ detrended: np.ndarray # kernel_dbz with the fitted plane removed
189
+ mean_dbz: float # mean dBZ used for missing-point substitution
190
+ texture: float # sqrt(sqrt(population_variance(corrected**2)))
191
+
192
+
193
+ def refl_texture_2d_debug(dbz_level: np.ndarray,
194
+ texture_radius_km: float,
195
+ dy: np.ndarray,
196
+ dx: np.ndarray,
197
+ iy: int,
198
+ ix: int,
199
+ base_dbz: float = 0.0,
200
+ min_valid_dbz: float = 0.0,
201
+ min_frac_texture: float = 0.25,
202
+ min_frac_fit: float = 0.67,
203
+ kernel_mode: str = "uniform",
204
+ dbz_col_max: Optional[np.ndarray] = None) -> TextureDebug2D:
205
+ """
206
+ Run the EccoPy-3D / EccoPy-2D-H radial texture calculation for ONE
207
+ point on ONE level, returning every intermediate quantity instead of
208
+ just the final texture value.
209
+
210
+ Parameters
211
+ ----------
212
+ dbz_level : np.ndarray, shape (ny, nx)
213
+ A single horizontal level (e.g. dbz[iz] from a 3-D array, or the
214
+ whole array for EccoPy-2D-H).
215
+ texture_radius_km : float
216
+ Same radius (in km) you would resolve from your WindowSpec.
217
+ dy, dx : np.ndarray, shape (ny, nx)
218
+ Same spacing arrays you would pass to refl_texture_2d.
219
+ iy, ix : int
220
+ Which point to inspect.
221
+ base_dbz, min_frac_texture, min_frac_fit : float
222
+ Same parameters you would pass to refl_texture_2d.
223
+ min_valid_dbz : float
224
+ Same parameter you would pass to refl_texture_2d. Used (together
225
+ with dbz_col_max) to compute fraction_active exactly as
226
+ production does - NOT simply "is this kernel point non-NaN".
227
+ kernel_mode : {"uniform", "varying"}
228
+ Whether to build the kernel from this point's local spacing
229
+ ("varying") or from the grid's median spacing ("uniform") - see
230
+ refl_texture_2d's kernel_mode documentation. Matching whichever
231
+ mode you used in the real run will reproduce its exact kernel.
232
+ dbz_col_max : np.ndarray, shape (ny, nx), optional
233
+ The column-maximum reflectivity used to compute fraction_active.
234
+ For genuinely single-level data (EccoPy-2D-H, or a 3-D volume
235
+ with only one level), this equals dbz_level and may be omitted.
236
+ For one level WITHIN a 3-D volume, fraction_active is computed
237
+ from the FULL volume's column-max, not from this level alone -
238
+ pass that column-max array here (np.nanmax(dbz_3d, axis=0)) to
239
+ get a fraction_active that matches production exactly. If
240
+ omitted, dbz_level is used as a stand-in, which is only exact
241
+ for single-level data.
242
+
243
+ Returns
244
+ -------
245
+ TextureDebug2D
246
+ If (iy, ix) falls within the border excluded by production (width
247
+ ny_tex/nx_tex cells from each edge - the kernel would extend past
248
+ the array there), this returns texture=NaN with empty kernel
249
+ arrays, matching production's behaviour exactly: that border is
250
+ never computed regardless of whether enough valid data exists,
251
+ because the kernel can't be built at all near the edge.
252
+ fraction_active is reported as 0.0 at border points (not NaN),
253
+ matching production's fraction_active array, which is
254
+ initialised to all-zero and never written to within the border.
255
+ """
256
+ from .texture import _build_kernel_offsets_uniform, _point_kernel_offsets
257
+
258
+ dbz_level = np.asarray(dbz_level, dtype=float)
259
+ dy = np.asarray(dy, dtype=float)
260
+ dx = np.asarray(dx, dtype=float)
261
+ ny, nx = dbz_level.shape
262
+
263
+ if dbz_col_max is None:
264
+ dbz_col_max = dbz_level
265
+ else:
266
+ dbz_col_max = np.asarray(dbz_col_max, dtype=float)
267
+ if dbz_col_max.shape != (ny, nx):
268
+ raise ValueError(
269
+ f"dbz_col_max shape {dbz_col_max.shape} must match "
270
+ f"dbz_level shape {(ny, nx)}"
271
+ )
272
+
273
+ if kernel_mode == "uniform":
274
+ dy_km = float(np.nanmedian(dy))
275
+ dx_km = float(np.nanmedian(dx))
276
+ offsets, nx_tex, ny_tex = _build_kernel_offsets_uniform(texture_radius_km, dx_km, dy_km)
277
+ elif kernel_mode == "varying":
278
+ offsets, nx_tex, ny_tex = _point_kernel_offsets(texture_radius_km, dx[iy, ix], dy[iy, ix])
279
+ else:
280
+ raise ValueError(f"kernel_mode must be 'uniform' or 'varying', got {kernel_mode!r}")
281
+
282
+ # The production functions (_compute_texture_one_level /
283
+ # _compute_texture_one_level_varying) hard-exclude a border of width
284
+ # ny_tex/nx_tex from computation entirely - points there are left NaN
285
+ # even if the kernel COULD be clipped to fit, because the production
286
+ # loop's range() never visits them. Reproduce that here so this debug
287
+ # function never silently disagrees with production at edge points.
288
+ if not (ny_tex <= iy < ny - ny_tex) or not (nx_tex <= ix < nx - nx_tex):
289
+ return TextureDebug2D(
290
+ iy=iy, ix=ix, n_kernel=len(offsets), n_valid=0,
291
+ fraction_active=0.0,
292
+ kernel_dx=np.array([]), kernel_dy=np.array([]), kernel_dbz=np.array([]),
293
+ plane_fit_used=False, plane_a=0.0, plane_b=0.0,
294
+ detrended=np.array([]), mean_dbz=float("nan"), texture=float("nan"),
295
+ )
296
+
297
+ n_kernel = len(offsets)
298
+
299
+ # fraction_active is computed from dbz_col_max >= min_valid_dbz over
300
+ # the kernel footprint - this is what production's _compute_fraction_
301
+ # active() does, computed once from the column-max field (which, for
302
+ # one level within a 3-D volume, is NOT the same as this level's own
303
+ # valid-point count; see the dbz_col_max parameter note above).
304
+ n_active = 0
305
+ for (jdx, jdy, _, _) in offsets:
306
+ py, px = iy + jdy, ix + jdx
307
+ if 0 <= py < ny and 0 <= px < nx:
308
+ cm = dbz_col_max[py, px]
309
+ if not np.isnan(cm) and cm >= min_valid_dbz:
310
+ n_active += 1
311
+ fraction_active = n_active / n_kernel if n_kernel else 0.0
312
+
313
+ # Production's FIRST gate: fraction_active < min_frac_texture -> skip
314
+ # entirely (this happens BEFORE the center-NaN check).
315
+ if fraction_active < min_frac_texture:
316
+ return TextureDebug2D(
317
+ iy=iy, ix=ix, n_kernel=n_kernel, n_valid=0,
318
+ fraction_active=fraction_active,
319
+ kernel_dx=np.array([]), kernel_dy=np.array([]), kernel_dbz=np.array([]),
320
+ plane_fit_used=False, plane_a=0.0, plane_b=0.0,
321
+ detrended=np.array([]), mean_dbz=float("nan"), texture=float("nan"),
322
+ )
323
+
324
+ # Production's SECOND gate: the center value itself is NaN -> skip.
325
+ if np.isnan(dbz_level[iy, ix]):
326
+ return TextureDebug2D(
327
+ iy=iy, ix=ix, n_kernel=n_kernel, n_valid=0,
328
+ fraction_active=fraction_active,
329
+ kernel_dx=np.array([]), kernel_dy=np.array([]), kernel_dbz=np.array([]),
330
+ plane_fit_used=False, plane_a=0.0, plane_b=0.0,
331
+ detrended=np.array([]), mean_dbz=float("nan"), texture=float("nan"),
332
+ )
333
+
334
+ vals, xx_list, yy_list = [], [], []
335
+ sum_dbz = 0.0
336
+ for (jdx, jdy, xx, yy) in offsets:
337
+ py, px = iy + jdy, ix + jdx
338
+ if 0 <= py < ny and 0 <= px < nx:
339
+ v = dbz_level[py, px]
340
+ if not np.isnan(v):
341
+ vals.append(v); xx_list.append(xx); yy_list.append(yy)
342
+ sum_dbz += v
343
+
344
+ n_valid = len(vals)
345
+
346
+ # Production's THIRD gate: this level's own valid-kernel-point count
347
+ # (NOT fraction_active) must meet min_pts_texture, computed from
348
+ # min_frac_texture * n_kernel - same threshold value, different
349
+ # variable than the fraction_active check above.
350
+ min_pts_texture = int(min_frac_texture * n_kernel + 0.5)
351
+ if n_valid < min_pts_texture:
352
+ return TextureDebug2D(
353
+ iy=iy, ix=ix, n_kernel=n_kernel, n_valid=n_valid,
354
+ fraction_active=fraction_active,
355
+ kernel_dx=np.array([]), kernel_dy=np.array([]), kernel_dbz=np.array([]),
356
+ plane_fit_used=False, plane_a=0.0, plane_b=0.0,
357
+ detrended=np.array([]), mean_dbz=float("nan"), texture=float("nan"),
358
+ )
359
+
360
+ mean_dbz = max(sum_dbz / n_valid, 1.0)
361
+ vals_arr = np.array(vals)
362
+ xx_arr = np.array(xx_list)
363
+ yy_arr = np.array(yy_list)
364
+
365
+ min_pts_fit = int(min_frac_fit * n_kernel + 0.5)
366
+ plane_fit_used = n_valid >= min_pts_fit
367
+ aa = bb = 0.0
368
+ detrended = vals_arr.copy()
369
+
370
+ if plane_fit_used:
371
+ A = np.column_stack([xx_arr, yy_arr, np.ones(n_valid)])
372
+ try:
373
+ coeffs, _, _, _ = np.linalg.lstsq(A, vals_arr, rcond=None)
374
+ aa, bb = float(coeffs[0]), float(coeffs[1])
375
+ detrended = vals_arr - (aa * xx_arr + bb * yy_arr)
376
+ except np.linalg.LinAlgError:
377
+ plane_fit_used = False
378
+
379
+ clipped = np.maximum(detrended - base_dbz, 1.0)
380
+ sum_sq = float(np.sum(clipped ** 2))
381
+ sum_sq2 = float(np.sum(clipped ** 4))
382
+ nn = float(n_valid)
383
+
384
+ n_missing = n_kernel - n_valid
385
+ if n_missing > 0:
386
+ min_sq = mean_dbz * mean_dbz
387
+ sum_sq += n_missing * min_sq
388
+ sum_sq2 += n_missing * min_sq * min_sq
389
+ nn += n_missing
390
+
391
+ min_pts_texture = int(min_frac_texture * n_kernel + 0.5)
392
+ if n_valid < min_pts_texture or nn < 1:
393
+ texture = float("nan")
394
+ else:
395
+ mean_sq = sum_sq / nn
396
+ var = max(sum_sq2 / nn - mean_sq * mean_sq, 0.0)
397
+ texture = float(np.sqrt(np.sqrt(var)))
398
+
399
+ return TextureDebug2D(
400
+ iy=iy, ix=ix, n_kernel=n_kernel, n_valid=n_valid,
401
+ fraction_active=fraction_active,
402
+ kernel_dx=xx_arr, kernel_dy=yy_arr, kernel_dbz=vals_arr,
403
+ plane_fit_used=plane_fit_used, plane_a=aa, plane_b=bb,
404
+ detrended=detrended, mean_dbz=mean_dbz, texture=texture,
405
+ )
406
+
407
+
408
+ # ---------------------------------------------------------------------------
409
+ # Full-field intermediate output for the 2-D radial (plane-fit) texture path
410
+ # ---------------------------------------------------------------------------
411
+
412
+ def refl_texture_2d_field_debug(dbz_level: np.ndarray,
413
+ texture_radius_km: float,
414
+ dy: np.ndarray,
415
+ dx: np.ndarray,
416
+ base_dbz: float = 0.0,
417
+ min_valid_dbz: float = 0.0,
418
+ min_frac_texture: float = 0.25,
419
+ min_frac_fit: float = 0.67,
420
+ kernel_mode: str = "uniform",
421
+ dbz_col_max: Optional[np.ndarray] = None):
422
+ """
423
+ DEBUG-ONLY, whole-LEVEL counterpart of refl_texture_2d_debug(): loops
424
+ refl_texture_2d_debug() over every (iy, ix) in `dbz_level` and
425
+ assembles full-field arrays of the fitted plane's centre-point value
426
+ ("fitted dbz prior to texture") and the detrended value that feeds
427
+ the texture statistic, plus fraction_active -- for the 2-D radial
428
+ plane-fit texture used by EccoPy-3D and EccoPy-2D-H.
429
+
430
+ This is intentionally implemented by calling the already-validated
431
+ per-point refl_texture_2d_debug() at every point rather than adding
432
+ a new Numba code path (unlike the 1-D case's
433
+ refl_texture_1d_with_fit(), which was cheap enough to duplicate as a
434
+ fast core) -- correctness here leans entirely on
435
+ refl_texture_2d_debug() already being cross-validated against
436
+ refl_texture_2d() point-by-point (see test_debug.py). It is a plain
437
+ Python double loop and is SLOW relative to refl_texture_2d itself
438
+ (which is Numba-JIT'd) -- expect this to take much longer than the
439
+ production texture call on the same array. It exists for debugging
440
+ a specific level or region, not as something to run routinely on
441
+ full 3-D volumes; see `eccopy3d.run(..., return_intermediates=True)`,
442
+ which calls this only for the levels you ask it to.
443
+
444
+ Parameters
445
+ ----------
446
+ Same as refl_texture_2d_debug, but dbz_level (and dbz_col_max, if
447
+ given) is the FULL (ny, nx) level and no single (iy, ix) is picked.
448
+
449
+ Returns
450
+ -------
451
+ fitted_dbz, detrended_dbz, fraction_active : np.ndarray, shape (ny, nx)
452
+ fitted_dbz -- the point's own value with the fitted plane's
453
+ local contribution removed (production's
454
+ `detrended` value evaluated at that point's own
455
+ kernel offset, i.e. the index of
456
+ (dx, dy) == (0, 0) within kernel_dx/kernel_dy)
457
+ subtracted from the point's own detrended value
458
+ -- NaN wherever refl_texture_2d_debug reports
459
+ texture=NaN (border, low coverage, or a NaN
460
+ centre pixel).
461
+ detrended_dbz -- the centre pixel's own detrended value (same
462
+ condition as fitted_dbz).
463
+ fraction_active : np.ndarray, shape (ny, nx)
464
+ Always populated (0.0 in the border, matching production's
465
+ fraction_active array -- see refl_texture_2d_debug's Returns
466
+ docstring).
467
+ """
468
+ dbz_level = np.asarray(dbz_level, dtype=float)
469
+ ny, nx = dbz_level.shape
470
+
471
+ fitted_dbz = np.full((ny, nx), np.nan)
472
+ detrended_dbz = np.full((ny, nx), np.nan)
473
+ fraction_active = np.zeros((ny, nx))
474
+
475
+ for iy in range(ny):
476
+ for ix in range(nx):
477
+ dbg = refl_texture_2d_debug(
478
+ dbz_level, texture_radius_km, dy, dx, iy, ix,
479
+ base_dbz=base_dbz, min_valid_dbz=min_valid_dbz,
480
+ min_frac_texture=min_frac_texture, min_frac_fit=min_frac_fit,
481
+ kernel_mode=kernel_mode, dbz_col_max=dbz_col_max,
482
+ )
483
+ fraction_active[iy, ix] = dbg.fraction_active
484
+ if dbg.detrended.size == 0:
485
+ continue
486
+ center = np.where((dbg.kernel_dx == 0) & (dbg.kernel_dy == 0))[0]
487
+ if center.size == 0:
488
+ continue
489
+ c = center[0]
490
+ fitted_dbz[iy, ix] = dbg.kernel_dbz[c] - dbg.detrended[c]
491
+ detrended_dbz[iy, ix] = dbg.detrended[c]
492
+
493
+ return fitted_dbz, detrended_dbz, fraction_active
eccopy/core/disk.py ADDED
@@ -0,0 +1,178 @@
1
+ """
2
+ eccopy.core.disk - MATLAB-faithful disk structuring elements, generated
3
+ in pure Python for ARBITRARY radius (no MATLAB, no pre-exported .mat).
4
+
5
+ Reproduces MATLAB's ``strel('disk', r)`` (default ``n = 4`` periodic-line
6
+ approximation) and its ``getsequence()`` decomposition, bit-for-bit,
7
+ without requiring anyone to pre-export a .mat file per radius. Validated
8
+ bit-exact against the MATLAB ground truth bundled in ``core/data/``
9
+ (strel radii 3, 5, 15, 25; decomposition radii 15, 25) - see
10
+ ``tests/test_disk_generator.py``.
11
+
12
+ Why this exists
13
+ ---------------
14
+ ``strel('disk', r)`` with the default ``n = 4`` does **not** return a
15
+ Euclidean disk. It returns an OCTAGON built by dilating a single point
16
+ with four periodic-line structuring elements (0°, 45°, 90°, 135°) plus
17
+ two unit correction lines - the radial decomposition of Rolf Adams,
18
+ *Radial Decomposition of Discs and Spheres* (CVGIP: GMIP, 1993). EccoPy
19
+ generates these in pure Python, so disk-based operations are not
20
+ restricted to any pre-exported set of radii.
21
+
22
+ The geometry below reproduces MATLAB's ``n = 4`` algorithm exactly, so
23
+ this is not a divergence: only the source of the arrays changes, from
24
+ pre-exported files to on-demand computation.
25
+
26
+ Geometry (n = 4), for r >= 3
27
+ ----------------------------
28
+ The neighborhood is a ``(2r-1) x (2r-1)`` octagon with::
29
+
30
+ A = r - 1 half-width at the centre row
31
+ d = floor((3r - 5) / 10) diagonal periodic-line half-extent
32
+ a = r - 2 - 2*d axis periodic-line half-extent
33
+ B = 2*d corner chamfer depth
34
+
35
+ and the ``getsequence`` decomposition is the ordered list::
36
+
37
+ [ vert(a), diag_main(d), horiz(a), diag_anti(d), horiz(1), vert(1) ]
38
+
39
+ where ``line(h)`` is a periodic line of half-length ``h`` (so ``2h+1``
40
+ pixels). ``a + 2*d + 1 == A`` holds identically, so the closed-form
41
+ octagon and the decomposition-built neighborhood agree for every radius.
42
+ These four relations were recovered from, and verified against, the
43
+ exported MATLAB masks.
44
+
45
+ Small radii
46
+ -----------
47
+ Only ``r >= 3`` is checked against MATLAB ground truth. ``r`` in {1, 2}
48
+ uses the same closed form (a filled ``(2r-1)`` square) and is flagged
49
+ unverified; ``disk_neighborhood`` warns rather than silently guessing.
50
+ ``n = 0`` returns the true Euclidean disk for callers who explicitly want
51
+ it, but ``n = 4`` is the default everywhere in EccoPy because that is what
52
+ ECCO's MATLAB / LROSE path uses and what the validation cases were run
53
+ against.
54
+ """
55
+
56
+ from __future__ import annotations
57
+
58
+ import warnings
59
+ from typing import List
60
+
61
+ import numpy as np
62
+ from scipy.ndimage import binary_dilation
63
+
64
+ # Radii with bundled MATLAB ground truth (used by the regression tests).
65
+ MATLAB_VERIFIED_STREL_RADII = (3, 5, 15, 25)
66
+ MATLAB_VERIFIED_DECOMP_RADII = (15, 25)
67
+
68
+
69
+ def _periodic_line(dy: int, dx: int, half: int) -> np.ndarray:
70
+ """
71
+ Minimal boolean periodic-line structuring element: the pixels
72
+ ``t * (dy, dx)`` for ``t`` in ``[-half, half]``, packed into the
73
+ smallest array that holds them (origin at the geometric centre).
74
+
75
+ ``half == 0`` yields a 1x1 single-pixel element (a dilation identity).
76
+ """
77
+ if half == 0:
78
+ return np.ones((1, 1), dtype=bool)
79
+ ts = np.arange(-half, half + 1)
80
+ ys, xs = ts * dy, ts * dx
81
+ m = np.zeros((ys.max() - ys.min() + 1, xs.max() - xs.min() + 1), dtype=bool)
82
+ m[ys - ys.min(), xs - xs.min()] = True
83
+ return m
84
+
85
+
86
+ def _disk_params(r: int):
87
+ """(A, a, d, B) for the n=4 octagon of radius r. See module docstring."""
88
+ d = max((3 * r - 5) // 10, 0) # floor((3r-5)/10), clamped
89
+ a = max(r - 2 - 2 * d, 0)
90
+ A = r - 1
91
+ B = 2 * d
92
+ return A, a, d, B
93
+
94
+
95
+ def disk_decomposition(r: int, n: int = 4) -> List[np.ndarray]:
96
+ """
97
+ MATLAB ``getsequence(strel('disk', r, n))`` primitives.
98
+
99
+ Parameters
100
+ ----------
101
+ r : int
102
+ Disk radius (pixels).
103
+ n : int
104
+ Periodic-line count. Only ``4`` (MATLAB default, the EccoPy path)
105
+ and ``0`` (no decomposition - a single Euclidean-disk element)
106
+ are supported.
107
+
108
+ Returns
109
+ -------
110
+ list of 2-D bool arrays
111
+ The line structuring elements, in MATLAB's order
112
+ ``[vert, diag_main, horiz, diag_anti, horiz_corr, vert_corr]``.
113
+ Pure 1x1 identity elements (which arise only for tiny radii) are
114
+ dropped, since they do not affect any dilation / erosion / close.
115
+ """
116
+ r = int(r)
117
+ if n == 0:
118
+ return [disk_neighborhood(r, n=0)]
119
+ if n != 4:
120
+ raise ValueError(f"disk_decomposition supports n in {{0, 4}}; got n={n}. "
121
+ "ECCO uses MATLAB's default n=4.")
122
+ _, a, d, _ = _disk_params(r)
123
+ steps = [
124
+ _periodic_line(1, 0, a), # vertical axis line
125
+ _periodic_line(1, 1, d), # main diagonal (top-left -> bottom-right)
126
+ _periodic_line(0, 1, a), # horizontal axis line
127
+ _periodic_line(1, -1, d), # anti-diagonal (top-right -> bottom-left)
128
+ _periodic_line(0, 1, 1), # horizontal unit correction (length 3)
129
+ _periodic_line(1, 0, 1), # vertical unit correction (length 3)
130
+ ]
131
+ return [s for s in steps if s.size > 1]
132
+
133
+
134
+ def disk_neighborhood(r: int, n: int = 4) -> np.ndarray:
135
+ """
136
+ MATLAB ``strel('disk', r, n).Neighborhood`` as a boolean array.
137
+
138
+ ``n = 4`` (default) returns the periodic-line octagon, bit-exact to
139
+ MATLAB. ``n = 0`` returns
140
+ the true Euclidean disk (``x^2 + y^2 <= r^2``), a ``(2r+1)`` array,
141
+ for callers who explicitly want the un-approximated shape.
142
+ """
143
+ r = int(r)
144
+ if n == 0:
145
+ yy, xx = np.mgrid[-r:r + 1, -r:r + 1]
146
+ return (xx * xx + yy * yy) <= r * r
147
+ if n != 4:
148
+ raise ValueError(f"disk_neighborhood supports n in {{0, 4}}; got n={n}.")
149
+ if r < 3:
150
+ warnings.warn(
151
+ f"disk_neighborhood(r={r}, n=4): radii below 3 are not checked "
152
+ "against MATLAB ground truth; returning the closed-form octagon "
153
+ "(a filled (2r-1) square for r in {1,2}).",
154
+ stacklevel=2,
155
+ )
156
+ A, a, d, B = _disk_params(r)
157
+ if A < 0: # r == 0 -> empty; be defensive
158
+ return np.zeros((1, 1), dtype=bool)
159
+ yy, xx = np.mgrid[-A:A + 1, -A:A + 1]
160
+ half_width = A - np.maximum(0, np.abs(yy) - (A - B))
161
+ return np.abs(xx) <= half_width
162
+
163
+
164
+ def neighborhood_from_decomposition(r: int, n: int = 4) -> np.ndarray:
165
+ """
166
+ Build the neighborhood by actually dilating a point through the
167
+ decomposition - the way MATLAB derives ``.Neighborhood`` from
168
+ ``getsequence``. Equal to ``disk_neighborhood(r, n)`` for all r; kept
169
+ as an independent cross-check (see the reconstruction test).
170
+ """
171
+ steps = disk_decomposition(r, n=n)
172
+ sz = 4 * int(r) + 5
173
+ img = np.zeros((sz, sz), dtype=bool)
174
+ img[sz // 2, sz // 2] = True
175
+ for s in steps:
176
+ img = binary_dilation(img, structure=s)
177
+ ys, xs = np.where(img)
178
+ return img[ys.min():ys.max() + 1, xs.min():xs.max() + 1]