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
@@ -0,0 +1,2 @@
1
+ from .classify import run, Result1D
2
+ __all__ = ["run", "Result1D"]
@@ -0,0 +1,273 @@
1
+ """
2
+ EccoPy-1D public entry point.
3
+
4
+ Input shape: (T,) or (N,) - one-dimensional array along time or distance.
5
+ Output: echo_type array of the same shape, with integer codes:
6
+ 1 = Stratiform
7
+ 2 = Mixed
8
+ 3 = Convective
9
+ (No sub-classification is possible without a vertical axis.)
10
+
11
+ Classification engine
12
+ ----------------------
13
+ The strat/mixed/conv classification itself is NOT a separate 1-D
14
+ implementation -- it reshapes `conv` to (1, N) and calls the exact same
15
+ class_basic() used (and validated against real MATLAB ECCO-V output) by
16
+ EccoPy-2D-V. This works correctly, not just "runs without erroring":
17
+ class_basic()'s disk-based morphology can only see a structuring
18
+ element's CENTER ROW when the input has one row (every other row offset
19
+ points off-array), and that center row is confirmed full-width at every
20
+ validated disk radius (3, 5, 15, 25) -- so the (1, N) reshape degenerates
21
+ exactly to 1-D horizontal dilation/erosion/closing at those radii, with
22
+ no separate 1-D port to maintain or independently validate. There is
23
+ currently no MATLAB or C++ "ECCO-1D" reference output to check the
24
+ end-to-end numbers against, unlike EccoPy-2D-V's SEA/SPOL cases -- see
25
+ core/classification.py's module docstring for the disk-mask verification
26
+ this claim rests on.
27
+
28
+ Unit-typed coordinates for time-series input
29
+ ---------------------------------------------
30
+ `coords` is intentionally left as "whatever unit you have" (km, seconds,
31
+ raw grid index) -- EccoPy-1D does not assume a wind field or any other
32
+ conversion exists. If you have a fixed-point time series and want to
33
+ size the texture window in physical distance (Taylor's frozen-turbulence
34
+ hypothesis: distance = integral(|wind speed| dt)) rather than time, use
35
+ `eccopy.core.coords.time_to_distance_km()` to convert time + wind speed
36
+ into a distance array FIRST, then pass that as `coords` here with
37
+ coord_mode="position" -- exactly like any other pre-computed position
38
+ array. This mirrors how haversine-derived lat/lon spacing is handled
39
+ elsewhere in the package: conversion helpers are separate, composable
40
+ functions, not hidden inside run().
41
+
42
+ Minimum-length clump filter
43
+ -----------------------------
44
+ `min_convective_length`, if given, demotes any contiguous run of
45
+ Convective points shorter than the specified physical length (or pixel
46
+ count) to Mixed -- guarding against a brief, possibly-erroneous
47
+ high-convectivity blip getting labeled Convective just because it
48
+ survived class_basic()'s morphological cleanup. This has no MATLAB/C++
49
+ analogue to port; it is a 1-D-specific design addition modeled on
50
+ EccoPy-3D's clump volume filter (see core/classification.py's
51
+ filter_short_convective_runs_1d() docstring for the full rationale).
52
+
53
+ Typical usage
54
+ -------------
55
+ import numpy as np
56
+ from eccopy import eccopy1d
57
+ from eccopy.params import WindowSpec
58
+
59
+ dbz = np.array([...]) # shape (T,)
60
+ spacing = np.array([...]) # shape (T,) - time (s) or distance (km)
61
+
62
+ result = eccopy1d.run(dbz, spacing, window=WindowSpec((5, 'km')))
63
+ echo = result.echo_type # shape (T,), values in {1, 2, 3}
64
+
65
+ # Time-series with wind-advected distance + a 5-minute minimum
66
+ # convective-duration filter:
67
+ from eccopy.core.coords import time_to_distance_km
68
+ dist_km = time_to_distance_km(time_s, wind_speed_ms)
69
+ result = eccopy1d.run(
70
+ dbz, dist_km, coord_mode="position",
71
+ window=WindowSpec((5, 'km')),
72
+ min_convective_length=WindowSpec((5, 'min')),
73
+ )
74
+ """
75
+
76
+ from __future__ import annotations
77
+ from dataclasses import dataclass
78
+ from typing import Optional, Union
79
+
80
+ import numpy as np
81
+
82
+ from ..core.coords import resolve_spacing
83
+ from ..core.texture import refl_texture_1d, refl_texture_1d_with_fit
84
+ from ..core.convectivity import texture_to_convectivity_linear
85
+ from ..core.classification import class_basic, filter_short_convective_runs_1d
86
+ from ..params.window import WindowSpec
87
+ from ..params import TextureParams, ClassificationParams
88
+
89
+
90
+ @dataclass
91
+ class Result1D:
92
+ """Output of eccopy1d.run()."""
93
+ echo_type: np.ndarray # shape (N,), int {1=Strat, 2=Mixed, 3=Conv}
94
+ convectivity: np.ndarray # shape (N,), float [0, 1]
95
+ texture: np.ndarray # shape (N,), float [0, ~30]
96
+ # Populated ONLY when run(..., return_intermediates=True) is passed;
97
+ # None otherwise (default, zero extra cost). See core.texture's
98
+ # refl_texture_1d_with_fit() docstring for exactly what these are.
99
+ fitted_dbz: Optional[np.ndarray] = None # shape (N,) - local linear-fit value at each point
100
+ detrended_dbz: Optional[np.ndarray] = None # shape (N,) - fit removed + re-centred, clipped >= 1
101
+
102
+
103
+ def _resolve_base_spacing(window: Union[WindowSpec, int, None],
104
+ spacing: np.ndarray) -> np.ndarray:
105
+ """
106
+ Convert a spacing array (in the caller's original coords unit --
107
+ km for length axes, seconds for time axes) into the base unit a
108
+ physical-size WindowSpec expects (metres / seconds). Pixel-based
109
+ WindowSpecs (or a bare int) don't need conversion -- the caller-side
110
+ logic that uses this treats a pixel WindowSpec as "count of points"
111
+ directly and never multiplies by this function's output in that case.
112
+ Shared between the texture window and min_convective_length so both
113
+ interpret the same `coords` consistently.
114
+ """
115
+ if isinstance(window, WindowSpec) and not window.is_pixel:
116
+ if window.base_kind == "length_m":
117
+ return spacing * 1000.0 # km -> m
118
+ return spacing # already seconds
119
+ return spacing
120
+
121
+
122
+ def run(dbz: Union[np.ndarray, list],
123
+ coords: Union[np.ndarray, list],
124
+ window: Union[WindowSpec, int] = WindowSpec((7, 'km')),
125
+ coord_mode: str = "auto",
126
+ texture_params: Optional[TextureParams] = None,
127
+ class_params: Optional[ClassificationParams] = None,
128
+ min_convective_length: Optional[Union[WindowSpec, int]] = None,
129
+ kernel_mode: str = "uniform",
130
+ return_intermediates: bool = False) -> Result1D:
131
+ """
132
+ Run EccoPy-1D: texture → convectivity → basic classification.
133
+
134
+ Parameters
135
+ ----------
136
+ dbz : array-like, shape (N,)
137
+ Reflectivity, dBZ. NaN where missing.
138
+ coords : array-like, shape (N,)
139
+ Either point positions (e.g. time in seconds, or distance in km)
140
+ or pre-computed point-to-point spacing. Interpreted according to
141
+ `coord_mode`. Units must match the WindowSpec unit. For
142
+ wind-advected time series, see the module docstring's
143
+ time_to_distance_km() example.
144
+ window : WindowSpec or int
145
+ Texture window half-width.
146
+ WindowSpec(7) - fixed 7-pixel radius
147
+ WindowSpec((5, 'km')) - 5 km radius (coords must be in km)
148
+ WindowSpec((3, 'min')) - 3-minute radius (coords must be in seconds)
149
+ coord_mode : {'auto', 'position', 'spacing'}
150
+ How to interpret `coords`:
151
+ 'position' - cumulative distance/time at each point; spacing is
152
+ derived as the difference between adjacent values.
153
+ 'spacing' - already the point-to-point spacing.
154
+ 'auto' - detect automatically (monotonic → position,
155
+ otherwise → spacing).
156
+ texture_params : TextureParams, optional
157
+ class_params : ClassificationParams, optional
158
+ min_convective_length : WindowSpec or int, optional
159
+ If given, any contiguous run of Convective points shorter than
160
+ this length/duration (or point count, for a pixel WindowSpec) is
161
+ demoted to Mixed. Must be in the same coordinate family as
162
+ `coords`/`window` (a length WindowSpec if coords are distance, a
163
+ time WindowSpec if coords are time) -- see module docstring and
164
+ core.classification.filter_short_convective_runs_1d(). Default
165
+ None disables the filter entirely (fully backward compatible).
166
+ kernel_mode : {"uniform", "varying"}
167
+ How to resolve the texture window's physical size into a pixel
168
+ radius when `coords` gives non-uniform spacing (e.g. irregular
169
+ sampling gaps in a time series):
170
+ "uniform" (default) - one radius, resolved from the GLOBAL
171
+ median spacing across the whole track, applied everywhere.
172
+ Identical to "varying" whenever spacing is actually uniform
173
+ (the common case) -- see core.texture.refl_texture_1d's
174
+ kernel_mode docstring for why "uniform" is the default here
175
+ (fidelity to the fact that per-point resolution has never
176
+ been checked against ground truth in a case where it does
177
+ something nontrivial, not a performance concern).
178
+ "varying" - resolve a distinct radius at every point from its
179
+ own local spacing. Physically more correct for genuinely
180
+ irregular sampling, but unvalidated in that configuration.
181
+ return_intermediates : bool
182
+ If True, also compute and attach `fitted_dbz` and `detrended_dbz`
183
+ to the returned Result1D (the per-point local-linear-fit value
184
+ and the detrended/clipped value that feeds the texture
185
+ statistic - see core.texture.refl_texture_1d_with_fit()). Costs
186
+ a little extra Numba compute but no extra passes over the data;
187
+ default False leaves both fields as None.
188
+
189
+ Returns
190
+ -------
191
+ Result1D
192
+ """
193
+ dbz = np.asarray(dbz, dtype=float)
194
+ if dbz.ndim != 1:
195
+ raise ValueError(f"eccopy1d expects a 1-D dbz array; got shape {dbz.shape}")
196
+
197
+ coords = np.asarray(coords, dtype=float)
198
+ if coords.shape != dbz.shape:
199
+ raise ValueError(
200
+ f"coords shape {coords.shape} must match dbz shape {dbz.shape}"
201
+ )
202
+
203
+ tp = texture_params or TextureParams()
204
+ cp = class_params or ClassificationParams()
205
+
206
+ # Resolve coords → spacing (in km or seconds as appropriate)
207
+ spacing = resolve_spacing(coords, axis=0, mode=coord_mode)
208
+
209
+ # For WindowSpec with physical units, spacing must be in the same
210
+ # base unit as the window (km→metres, min→seconds internally in
211
+ # WindowSpec). Pass the spacing array unchanged - WindowSpec stores
212
+ # its target size in metres/seconds and the user supplies coords in
213
+ # km or seconds, so we multiply km→m here for length windows.
214
+ spacing_for_window = _resolve_base_spacing(window, spacing)
215
+
216
+ # 1. Texture
217
+ # None resolves to no gating here: min_valid_dbz ports a
218
+ # ConvStratFinder prefilter with no f_reflTexture.m analog. An
219
+ # explicitly-set value is honoured. See TextureParams.
220
+ min_valid = tp.resolve_min_valid_dbz(-np.inf)
221
+
222
+ fitted_dbz = detrended_dbz = None
223
+ if return_intermediates:
224
+ texture, fitted_dbz, detrended_dbz = refl_texture_1d_with_fit(
225
+ dbz, window, spacing=spacing_for_window, dbz_base=tp.dbz_base,
226
+ min_valid_dbz=min_valid, kernel_mode=kernel_mode,
227
+ )
228
+ else:
229
+ texture = refl_texture_1d(
230
+ dbz, window, spacing=spacing_for_window, dbz_base=tp.dbz_base,
231
+ min_valid_dbz=min_valid, kernel_mode=kernel_mode,
232
+ )
233
+
234
+ # 2. Convectivity
235
+ conv = texture_to_convectivity_linear(
236
+ texture,
237
+ upper_lim=tp.texture_limit_high,
238
+ lower_lim=tp.texture_limit_low,
239
+ )
240
+
241
+ # 3. Basic classification (strat/mixed/conv - no sub-types in 1D)
242
+ # class_basic operates on >=2-D arrays (its morphological structuring
243
+ # elements are 2-D). For genuinely 1-D EccoPy-1D input, treat the
244
+ # array as a single row, run classification, and squeeze back.
245
+ # See module docstring "Classification engine" note for why this is
246
+ # a validated equivalence, not just a convenient reshape.
247
+ echo = class_basic(
248
+ conv[np.newaxis, :],
249
+ strat_mixed=cp.max_convectivity_for_stratiform,
250
+ mixed_conv=cp.min_convectivity_for_convective,
251
+ melt=None, enlarge_mixed=cp.enlarge_mixed, enlarge_conv=cp.enlarge_conv,
252
+ )[0]
253
+
254
+ # 4. Optional minimum-convective-length clump filter (1-D-specific;
255
+ # see module docstring "Minimum-length clump filter" and
256
+ # core.classification.filter_short_convective_runs_1d()).
257
+ if min_convective_length is not None:
258
+ mcl = (min_convective_length if isinstance(min_convective_length, WindowSpec)
259
+ else WindowSpec(min_convective_length))
260
+ if mcl.is_pixel:
261
+ min_len_base = float(mcl.size)
262
+ spacing_base_len = np.ones_like(spacing)
263
+ else:
264
+ min_len_base = mcl.base_value
265
+ spacing_base_len = _resolve_base_spacing(mcl, spacing)
266
+ # demote to basic Mixed (2), not CATEGORY_MIXED (25): eccopy1d's
267
+ # echo_type is the basic {1,2,3} scheme, so the 3-D clump constant
268
+ # would inject stray 25s that break {1,2,3} consumers / colormaps.
269
+ echo = filter_short_convective_runs_1d(
270
+ echo, spacing_base_len, min_len_base, demote_to=2)
271
+
272
+ return Result1D(echo_type=echo, convectivity=conv, texture=texture,
273
+ fitted_dbz=fitted_dbz, detrended_dbz=detrended_dbz)
@@ -0,0 +1,2 @@
1
+ from .classify import run, Result2DH
2
+ __all__ = ["run", "Result2DH"]
@@ -0,0 +1,281 @@
1
+ """
2
+ EccoPy-2D-H (Horizontal single-level / composite) public entry point.
3
+
4
+ Input shapes:
5
+ dbz : (Y, X) - single horizontal level (e.g. composite)
6
+ coords_y: (Y,) or (Y, X) - N-S coordinate or spacing (km)
7
+ coords_x: (X,) or (Y, X) - E-W coordinate or spacing (km)
8
+
9
+ No sub-classification into shallow/mid/deep is possible on a single
10
+ horizontal level. Output echo type codes:
11
+ 1 = Stratiform, 2 = Mixed, 3 = Convective
12
+
13
+ Uses the same 2D radial texture + planar-detrend algorithm as eccopy3d
14
+ (a circular neighbourhood kernel with a best-fit plane removed), as
15
+ validated against LROSE ConvStratFinder output.
16
+
17
+ Classification engine
18
+ ---------------------
19
+ Classification runs through the same 2-D dual-threshold clumping
20
+ architecture as EccoPy-3D (find_clumps_3d) rather than a morphological
21
+ enlarge/close/fill/erode path. See eccopy2d_h/clumping.py's module
22
+ docstring for what is shared with the 3-D path and where the two differ.
23
+
24
+ core/classification.py's class_basic_isotropic() remains available as a
25
+ simpler, non-clumping alternative. It is not called by this module, but
26
+ can be applied directly to the `convectivity` field this module returns.
27
+
28
+ Minimum clump area
29
+ --------------------
30
+ `min_convective_area`, if given (km²), drops any clump -- whether from
31
+ straightforward single-threshold labeling or a dual-threshold sub-split
32
+ -- smaller than this area, demoting its pixels to Mixed instead of
33
+ Convective. None (default) disables this floor: clumps are still found
34
+ and (if use_dual_thresholds) split, just never dropped for size alone.
35
+ Same opt-in convention as eccopy1d's min_convective_length, for the same
36
+ reason -- no validated default exists for composite data yet.
37
+
38
+ Typical usage
39
+ -------------
40
+ from eccopy import eccopy2d_h
41
+ from eccopy.params import WindowSpec
42
+
43
+ result = eccopy2d_h.run(
44
+ dbz_composite,
45
+ coords_y=y_km, coords_x=x_km,
46
+ window=WindowSpec((7, 'km')),
47
+ min_convective_area=4.0, # km^2, optional
48
+ )
49
+ echo = result.echo_type # shape (Y, X), values in {1, 2, 3}
50
+ n_clumps = result.n_clumps
51
+ """
52
+
53
+ from __future__ import annotations
54
+ from dataclasses import dataclass
55
+ from typing import Optional, Union
56
+
57
+ import numpy as np
58
+
59
+ from ..core.coords import resolve_spacing
60
+ from ..core.texture import refl_texture_2d
61
+ from ..core.convectivity import texture_to_convectivity_linear
62
+ from ..core.classification import assign_echo_type_2d
63
+ from ..eccopy2d_h.clumping import find_clumps_2d
64
+ from ..params.window import WindowSpec
65
+ from ..params import TextureParams, ClassificationParams
66
+
67
+
68
+ @dataclass
69
+ class Result2DH:
70
+ """Output of eccopy2d_h.run()."""
71
+ echo_type: np.ndarray # shape (Y, X), int {1=Strat, 2=Mixed, 3=Conv}
72
+ convectivity: np.ndarray # shape (Y, X), float
73
+ texture: np.ndarray # shape (Y, X), float
74
+ fraction_active: np.ndarray # shape (Y, X), float (echo coverage fraction)
75
+ n_clumps: int
76
+ # Physical radius (km) of the texture window actually used, resolved
77
+ # from the `window` argument against the grid spacing. Available for
78
+ # plotting the window footprint (see core.colormaps.draw_window_ring()).
79
+ # None only for a bare-pixel window on a unit-agnostic grid.
80
+ texture_radius: Optional[float] = None
81
+ # Populated ONLY when run(..., return_intermediates=True) is passed;
82
+ # None otherwise (default, zero extra cost -- see run()'s docstring,
83
+ # this is SLOW, a plain Python double loop over every grid point).
84
+ fitted_dbz: Optional[np.ndarray] = None # shape (Y, X)
85
+ detrended_dbz: Optional[np.ndarray] = None # shape (Y, X)
86
+
87
+
88
+ def run(dbz: Union[np.ndarray, list],
89
+ coords_y: Union[np.ndarray, list],
90
+ coords_x: Union[np.ndarray, list],
91
+ window: Union[WindowSpec, int, float] = WindowSpec((7, 'km')),
92
+ coord_mode: str = "auto",
93
+ kernel_mode: str = "uniform",
94
+ texture_params: Optional[TextureParams] = None,
95
+ class_params: Optional[ClassificationParams] = None,
96
+ min_convective_area: Optional[float] = None,
97
+ n_threads: int = 1,
98
+ return_intermediates: bool = False) -> Result2DH:
99
+ """
100
+ Run EccoPy-2D-H: 2D radial texture → convectivity → 2D dual-threshold
101
+ clumping → echo type classification.
102
+
103
+ Parameters
104
+ ----------
105
+ dbz : array-like, shape (Y, X)
106
+ Reflectivity, dBZ. NaN where missing.
107
+ coords_y : array-like, shape (Y,) or (Y, X)
108
+ N-S position or spacing, km.
109
+ coords_x : array-like, shape (X,) or (Y, X)
110
+ E-W position or spacing, km.
111
+ window : WindowSpec or float (km)
112
+ Texture window radius. Must be a length unit (km); bare pixel
113
+ WindowSpec is also accepted.
114
+ coord_mode : {'auto', 'position', 'spacing'}
115
+ kernel_mode : {'uniform', 'varying'}
116
+ How to handle spatially-varying grid spacing (e.g. lat/lon grids,
117
+ where dx shrinks with cos(latitude)):
118
+ 'uniform' (default) - one representative kernel for the whole
119
+ grid, built from the median dy/dx. Matches what the
120
+ validated LROSE ConvStratFinder algorithm itself does for
121
+ lat/lon grids (it uses a single dx/dy computed at the
122
+ domain's mean latitude). Fast; becomes approximate for
123
+ domains spanning a wide latitude range.
124
+ 'varying' - rebuilds the kernel from the local spacing at
125
+ every grid point, so the physical kernel size stays
126
+ correct across large/non-uniform domains. This is NOT
127
+ what LROSE does and is unvalidated against LROSE output;
128
+ substantially slower (no kernel reuse). Recommended only
129
+ for domains where 'uniform' is known to break down (e.g.
130
+ continental-scale lat/lon grids).
131
+ texture_params : TextureParams, optional
132
+ class_params : ClassificationParams, optional
133
+ use_dual_thresholds, secondary_convectivity,
134
+ all_subclumps_min_area_frac, each_subclump_min_area_frac, and
135
+ each_subclump_min_area_km2 are reused directly from here for the
136
+ 2-D clumping step -- see eccopy2d_h/clumping.py's module
137
+ docstring for how each_subclump_min_area_km2's meaning differs
138
+ (genuine area) from its 3-D usage. CAUTION: because of that
139
+ difference, a ClassificationParams instance tuned/validated
140
+ against eccopy3d cases should NOT be reused as-is here -- the
141
+ same each_subclump_min_area_km2 value gates a different physical
142
+ quantity in each module. Tune it separately for eccopy2d_h.
143
+ min_convective_area : float, optional
144
+ Minimum clump area, km². Clumps (whether unsplit or emitted by a
145
+ dual-threshold split) smaller than this are dropped -- their
146
+ pixels become Mixed rather than Convective. None (default)
147
+ disables this floor entirely; see module docstring.
148
+ n_threads : int
149
+ Number of parallel threads for the texture computation. Has no
150
+ effect here since the input is a single level, but accepted for
151
+ API consistency with eccopy3d.
152
+ return_intermediates : bool
153
+ If True, also compute and attach `fitted_dbz` and `detrended_dbz`
154
+ (the plane-fit value and detrended value at each point's own
155
+ location, prior to texture -- see
156
+ core.debug.refl_texture_2d_field_debug()). This is SLOW: it is a
157
+ plain Python double loop over every grid point (unlike
158
+ eccopy1d/eccopy2d_v's return_intermediates, which reuses the
159
+ fast Numba core) -- expect it to take much longer than the rest
160
+ of run() combined on anything beyond a small grid. Default False
161
+ skips it entirely at no cost.
162
+
163
+ Returns
164
+ -------
165
+ Result2DH
166
+ """
167
+ dbz = np.asarray(dbz, dtype=float)
168
+ if dbz.ndim != 2:
169
+ raise ValueError(
170
+ f"eccopy2d_h expects a 2-D (Y, X) dbz array; got shape {dbz.shape}"
171
+ )
172
+ ny, nx = dbz.shape
173
+
174
+ tp = texture_params or TextureParams()
175
+ cp = class_params or ClassificationParams()
176
+
177
+ # --- resolve coords → per-point spacing (km) ---
178
+ coords_y = np.asarray(coords_y, dtype=float)
179
+ coords_x = np.asarray(coords_x, dtype=float)
180
+
181
+ if coords_y.ndim == 1:
182
+ if coords_y.shape[0] != ny:
183
+ raise ValueError(f"coords_y length {coords_y.shape[0]} != Y={ny}")
184
+ sp_y_1d = resolve_spacing(coords_y, axis=0, mode=coord_mode)
185
+ sp_y = np.broadcast_to(sp_y_1d[:, np.newaxis], (ny, nx)).copy()
186
+ else:
187
+ sp_y = resolve_spacing(coords_y, axis=0, mode=coord_mode)
188
+
189
+ if coords_x.ndim == 1:
190
+ if coords_x.shape[0] != nx:
191
+ raise ValueError(f"coords_x length {coords_x.shape[0]} != X={nx}")
192
+ sp_x_1d = resolve_spacing(coords_x, axis=0, mode=coord_mode)
193
+ sp_x = np.broadcast_to(sp_x_1d[np.newaxis, :], (ny, nx)).copy()
194
+ else:
195
+ sp_x = resolve_spacing(coords_x, axis=1, mode=coord_mode)
196
+
197
+ # refl_texture_2d expects shape (nz, ny, nx); wrap the single level
198
+ dbz_3d = dbz[np.newaxis, :, :] # (1, Y, X)
199
+
200
+ # Resolve window radius in km
201
+ if isinstance(window, (int, float)):
202
+ radius_km = float(window)
203
+ elif isinstance(window, WindowSpec):
204
+ if window.is_pixel:
205
+ # Convert pixel radius to km using median spacing
206
+ med_sp = float(np.nanmedian(np.stack([sp_y, sp_x])))
207
+ radius_km = window.size * med_sp
208
+ else:
209
+ if window.base_kind != "length_m":
210
+ raise ValueError(
211
+ "eccopy2d_h texture window must be a length unit (km); "
212
+ f"got unit kind '{window.base_kind}'."
213
+ )
214
+ radius_km = window.base_value / 1000.0
215
+ else:
216
+ radius_km = float(window)
217
+
218
+ # 1. 2D radial texture (one level)
219
+ texture_3d, fraction_active = refl_texture_2d(
220
+ dbz_3d,
221
+ texture_radius=radius_km,
222
+ dy=sp_y,
223
+ dx=sp_x,
224
+ base_dbz=tp.dbz_base,
225
+ min_valid_dbz=tp.resolve_min_valid_dbz(0.0),
226
+ min_frac_texture=tp.min_frac_texture,
227
+ min_frac_fit=tp.min_frac_fit,
228
+ n_threads=1,
229
+ kernel_mode=kernel_mode,
230
+ )
231
+ texture = texture_3d[0] # back to (Y, X)
232
+
233
+ # 2. Convectivity
234
+ conv = texture_to_convectivity_linear(
235
+ texture,
236
+ upper_lim=tp.texture_limit_high,
237
+ lower_lim=tp.texture_limit_low,
238
+ )
239
+
240
+ # 3. 2D dual-threshold clumping (see eccopy2d_h/clumping.py)
241
+ clumps = find_clumps_2d(
242
+ conv,
243
+ spacing_y=sp_y,
244
+ spacing_x=sp_x,
245
+ min_conv=cp.min_convectivity_for_convective,
246
+ min_area_km2=min_convective_area,
247
+ use_dual_thresholds=cp.use_dual_thresholds,
248
+ secondary_threshold=cp.secondary_convectivity,
249
+ all_subclumps_min_area_frac=cp.all_subclumps_min_area_frac,
250
+ each_subclump_min_area_frac=cp.each_subclump_min_area_frac,
251
+ each_subclump_min_area_km2=cp.each_subclump_min_area_km2,
252
+ )
253
+
254
+ # 4. Assign echo type codes - basic 1/2/3 only, no sub-typing
255
+ # (see core.classification.assign_echo_type_2d docstring).
256
+ echo = assign_echo_type_2d(
257
+ conv,
258
+ clumps=clumps,
259
+ max_conv_for_strat=cp.max_convectivity_for_stratiform,
260
+ )
261
+
262
+ fitted_dbz = detrended_dbz = None
263
+ if return_intermediates:
264
+ from ..core.debug import refl_texture_2d_field_debug
265
+ fitted_dbz, detrended_dbz, _ = refl_texture_2d_field_debug(
266
+ dbz, radius_km, dy=sp_y, dx=sp_x,
267
+ base_dbz=tp.dbz_base, min_valid_dbz=tp.resolve_min_valid_dbz(0.0),
268
+ min_frac_texture=tp.min_frac_texture, min_frac_fit=tp.min_frac_fit,
269
+ kernel_mode=kernel_mode,
270
+ )
271
+
272
+ return Result2DH(
273
+ echo_type=echo,
274
+ convectivity=conv,
275
+ texture=texture,
276
+ fraction_active=fraction_active,
277
+ n_clumps=len(clumps),
278
+ texture_radius=radius_km,
279
+ fitted_dbz=fitted_dbz,
280
+ detrended_dbz=detrended_dbz,
281
+ )