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,265 @@
1
+ """
2
+ 2-D clumping for EccoPy-2D-H (horizontal composite data).
3
+
4
+ This module has no upstream counterpart: there is no MATLAB or C++
5
+ "ECCO-H" clumping algorithm. It reuses the structure of
6
+ eccopy3d/clumping.py's two-stage dual-threshold clumping, which is a port
7
+ of ClumpingDualThresh. That reuse is direct rather than analogical: the
8
+ 3-D algorithm's Stage 2 already works on a 2-D composite, projecting each
9
+ clump to a (Y, X) maximum before splitting it. On single-level data that
10
+ projection is the identity, so the splitting mechanics here are the same
11
+ computation the 3-D path performs internally, minus the projection step.
12
+
13
+ Differences from eccopy3d/clumping.py:
14
+
15
+ - Area, not volume. 3-D clumps are filtered by volume; a single
16
+ horizontal level has no dz from which to build one. This module
17
+ computes area in km^2 from each pixel's own dy*dx and filters on
18
+ that.
19
+
20
+ Consequently `each_subclump_min_area_km2` - a ClassificationParams
21
+ field shared with eccopy3d - denotes a different physical quantity in
22
+ each module: true area here, a pseudo-volume in eccopy3d (where
23
+ ClumpProps multiplies the 2-D pixel count by dz at level 0). A single
24
+ ClassificationParams instance tuned for one module will not reproduce
25
+ its splitting behaviour in the other at the same numeric value. Tune
26
+ the field per module. See README "Parameters".
27
+
28
+ - Primary-envelope connectivity: 4-connectivity (matching _STRUCT_4,
29
+ the same convention eccopy3d/clumping.py's Stage-2 2-D composite
30
+ labeling uses, and matching LROSE/TITAN interval clumping at
31
+ min_overlap=1). class_basic() uses 8-connectivity (_CONN8, MATLAB's
32
+ bwconncomp convention) for its melt-correction region labeling, a
33
+ different convention for a different purpose - rain-below-melt column
34
+ detection rather than storm-cell identification.
35
+ - No height, temperature or vertical-extent geometry: there is nothing
36
+ to compute it from. Clumps carry only their index, area and point
37
+ count.
38
+
39
+ ARRAY CONVENTION: (Y, X), matching EccoPy-2D-H's data-agnostic shape
40
+ contract (see eccopy2d_h/classify.py).
41
+
42
+ PERFORMANCE: per-clump work is restricted to each clump's bounding box via
43
+ scipy.ndimage.find_objects(), same pattern as eccopy3d/clumping.py.
44
+ """
45
+
46
+ from __future__ import annotations
47
+ from typing import List, Optional
48
+ import numpy as np
49
+ from scipy.ndimage import label, find_objects
50
+
51
+ # Reused directly, unmodified, from the validated 3-D path -- both
52
+ # operate on plain (Y, X) arrays already, so no adaptation is needed.
53
+ from ..eccopy3d.clumping import _grow_regions, _STRUCT_4
54
+
55
+
56
+ def find_clumps_2d(convectivity: np.ndarray,
57
+ spacing_y: np.ndarray,
58
+ spacing_x: np.ndarray,
59
+ min_conv: float,
60
+ min_area_km2: Optional[float] = None,
61
+ use_dual_thresholds: bool = True,
62
+ secondary_threshold: float = 0.65,
63
+ all_subclumps_min_area_frac: float = 0.33,
64
+ each_subclump_min_area_frac: float = 0.02,
65
+ each_subclump_min_area_km2: float = 2.0) -> List[dict]:
66
+ """
67
+ Find 2-D convective clumps in horizontal composite data using the
68
+ same two-stage dual-threshold structure as eccopy3d/clumping.py's
69
+ find_clumps_3d() -- see module docstring for what is/isn't validated.
70
+
71
+ Parameters
72
+ ----------
73
+ convectivity : np.ndarray, shape (Y, X)
74
+ spacing_y, spacing_x : np.ndarray, shape (Y, X)
75
+ Local point-to-point spacing, km. Used for per-pixel area
76
+ (spacing_y * spacing_x) in all area filters.
77
+ min_conv : float
78
+ PRIMARY threshold -- builds the Stage-1 envelope clumps.
79
+ min_area_km2 : float, optional
80
+ Minimum clump area, applied BOTH before splitting (Stage 1) and
81
+ after (Stage 3) -- same two-checkpoint pattern as find_clumps_3d's
82
+ min_vol_km3. None (default) disables this floor entirely: clumps
83
+ are still found and (optionally) split, just never dropped for
84
+ being too small -- matching eccopy1d's min_convective_length
85
+ opt-in-filter convention, since there's no validated default to
86
+ offer here.
87
+ use_dual_thresholds : bool
88
+ If False, falls back to single-threshold 4-connected labeling at
89
+ min_conv with only the min_area_km2 filter, no splitting.
90
+ secondary_threshold : float
91
+ all_subclumps_min_area_frac, each_subclump_min_area_frac,
92
+ each_subclump_min_area_km2 : float
93
+ Same roles as find_clumps_3d's identically-named parameters
94
+ (reused ClassificationParams fields) -- each_subclump_min_area_km2
95
+ here means genuine area, unlike the 3-D quirk (see module
96
+ docstring). CAUTION: do not pass in a ClassificationParams
97
+ instance tuned/validated against eccopy3d cases and expect this
98
+ field's numeric value to mean the same thing here -- see module
99
+ docstring "AREA, not volume" and README "Parameters".
100
+
101
+ Returns
102
+ -------
103
+ clumps : list of dicts, each with:
104
+ index (an (iy_arr, ix_arr) tuple of integer index arrays -- use
105
+ as echo_type[clump['index']] = ...),
106
+ area_km2, n_pts_total
107
+ """
108
+ convectivity = np.asarray(convectivity, dtype=float)
109
+ spacing_y = np.asarray(spacing_y, dtype=float)
110
+ spacing_x = np.asarray(spacing_x, dtype=float)
111
+ if spacing_y.shape != convectivity.shape or spacing_x.shape != convectivity.shape:
112
+ raise ValueError(
113
+ f"spacing_y/spacing_x shape must match convectivity shape "
114
+ f"{convectivity.shape}; got {spacing_y.shape}, {spacing_x.shape}"
115
+ )
116
+ pixel_area = spacing_y * spacing_x
117
+ area_floor = min_area_km2 if min_area_km2 is not None else 0.0
118
+
119
+ def _geom_for_mask(local_mask, bbox, local_area):
120
+ iy_local, ix_local = np.where(local_mask)
121
+ y0, x0 = bbox[0].start, bbox[1].start
122
+ return {
123
+ 'index': (iy_local + y0, ix_local + x0),
124
+ 'area_km2': float(np.sum(local_area[local_mask])),
125
+ 'n_pts_total': int(len(iy_local)),
126
+ }
127
+
128
+ # ------------------------------------------------------------
129
+ # Fallback: no dual thresholds -- single-stage labeling, area filter.
130
+ # ------------------------------------------------------------
131
+ if not use_dual_thresholds:
132
+ active = (~np.isnan(convectivity)) & (convectivity >= min_conv)
133
+ labeled, n_clumps = label(active, structure=_STRUCT_4)
134
+ if n_clumps == 0:
135
+ return []
136
+ bboxes = find_objects(labeled, max_label=n_clumps)
137
+ clumps = []
138
+ for cid, bbox in enumerate(bboxes, start=1):
139
+ if bbox is None:
140
+ continue
141
+ local_mask = labeled[bbox] == cid
142
+ local_area = pixel_area[bbox]
143
+ clump = _geom_for_mask(local_mask, bbox, local_area)
144
+ if clump['area_km2'] >= area_floor:
145
+ clumps.append(clump)
146
+ return clumps
147
+
148
+ # ------------------------------------------------------------
149
+ # Stage 1: primary envelope clumping
150
+ # ------------------------------------------------------------
151
+ active_primary = (~np.isnan(convectivity)) & (convectivity >= min_conv)
152
+ labeled_primary, n_primary = label(active_primary, structure=_STRUCT_4)
153
+ if n_primary == 0:
154
+ return []
155
+
156
+ bboxes = find_objects(labeled_primary, max_label=n_primary)
157
+
158
+ clumps: List[dict] = []
159
+ for cid, bbox in enumerate(bboxes, start=1):
160
+ if bbox is None:
161
+ continue
162
+
163
+ primary_mask = labeled_primary[bbox] == cid
164
+ local_conv = convectivity[bbox]
165
+ local_area = pixel_area[bbox]
166
+
167
+ primary_area = float(np.sum(local_area[primary_mask]))
168
+ if primary_area < area_floor:
169
+ # Dropped entirely -- never split, never emitted (matches
170
+ # find_clumps_3d's outer volume check).
171
+ continue
172
+
173
+ # ------------------------------------------------------------
174
+ # Stage 2: dual-threshold split within this clump's bbox
175
+ # ------------------------------------------------------------
176
+ sub_masks = _dual_threshold_split_2d(
177
+ primary_mask, local_conv, local_area,
178
+ secondary_threshold=secondary_threshold,
179
+ all_frac=all_subclumps_min_area_frac,
180
+ each_frac=each_subclump_min_area_frac,
181
+ each_km2=each_subclump_min_area_km2,
182
+ )
183
+
184
+ # ------------------------------------------------------------
185
+ # Stage 3: final area filter, applied to EACH emitted piece
186
+ # ------------------------------------------------------------
187
+ for sub_mask in sub_masks:
188
+ clump = _geom_for_mask(sub_mask, bbox, local_area)
189
+ if clump['area_km2'] >= area_floor:
190
+ clumps.append(clump)
191
+
192
+ return clumps
193
+
194
+
195
+ def _dual_threshold_split_2d(primary_mask: np.ndarray,
196
+ local_conv: np.ndarray,
197
+ local_area: np.ndarray,
198
+ secondary_threshold: float,
199
+ all_frac: float,
200
+ each_frac: float,
201
+ each_km2: float) -> List[np.ndarray]:
202
+ """
203
+ 2-D analogue of eccopy3d/clumping.py's _dual_threshold_split(), for
204
+ ONE primary clump already restricted to its local bounding box.
205
+ There is no Z axis to project away here -- the "composite" is simply
206
+ the clump's own convectivity values, everywhere else masked out.
207
+
208
+ Returns a list of 2-D boolean masks (same local shape as
209
+ primary_mask), one per accepted sub-clump -- or a single-element list
210
+ containing primary_mask unchanged if splitting wasn't valid.
211
+ """
212
+ composite = np.where(primary_mask, local_conv, np.nan)
213
+ footprint = primary_mask
214
+
215
+ n_comp = int(np.sum(footprint))
216
+ if n_comp == 0:
217
+ return [primary_mask]
218
+
219
+ active_secondary = footprint & (composite >= secondary_threshold)
220
+ labeled_sec, n_secondary = label(active_secondary, structure=_STRUCT_4)
221
+
222
+ if n_secondary == 0:
223
+ return [primary_mask]
224
+
225
+ sizes_area = np.array([
226
+ float(np.sum(local_area[labeled_sec == i])) for i in range(1, n_secondary + 1)
227
+ ])
228
+ sizes_px = np.array([
229
+ int(np.sum(labeled_sec == i)) for i in range(1, n_secondary + 1)
230
+ ])
231
+ sum_px = float(np.sum(sizes_px))
232
+ frac_all_parts = sum_px / n_comp
233
+
234
+ frac_each = sizes_px.astype(float) / n_comp
235
+ valid = (frac_each >= each_frac) & (sizes_area >= each_km2)
236
+ n_large_enough = int(np.sum(valid))
237
+
238
+ if (frac_all_parts < all_frac) or (n_large_enough < 2):
239
+ return [primary_mask]
240
+
241
+ valid_grid = np.zeros_like(labeled_sec, dtype=int)
242
+ next_id = 0
243
+ for i in range(1, n_secondary + 1):
244
+ if valid[i - 1]:
245
+ next_id += 1
246
+ valid_grid[labeled_sec == i] = next_id
247
+
248
+ # Grow valid sub-clump seeds back out to fill the full envelope
249
+ # footprint -- reused directly from the validated 3-D path.
250
+ grown_grid = _grow_regions(valid_grid, np.where(footprint, local_conv, -np.inf), footprint)
251
+
252
+ out_masks = []
253
+ for sub_id in range(1, next_id + 1):
254
+ sub_mask = primary_mask & (grown_grid == sub_id)
255
+ if not np.any(sub_mask):
256
+ continue
257
+ # Unlike the 3-D case, a 2-D sub-region carved from a 4-connected
258
+ # primary clump via 4-connected growth is guaranteed 4-connected
259
+ # itself -- no "largest fragment" step is needed here.
260
+ out_masks.append(sub_mask)
261
+
262
+ if not out_masks:
263
+ return [primary_mask]
264
+
265
+ return out_masks
@@ -0,0 +1,2 @@
1
+ from .classify import run, Result2DV
2
+ __all__ = ["run", "Result2DV"]
@@ -0,0 +1,288 @@
1
+ """
2
+ EccoPy-2D-V - classification of vertical cross-sections.
3
+
4
+ Operates on a (Z, X) slice: an RHI, a gridded cross-section, or a
5
+ column-versus-time curtain. Texture slides along the X axis only; the
6
+ vertical direction never enters the window.
7
+
8
+ Upstream analogues (lrose-ecco @ ad85c56):
9
+ texture f_reflTexture.m
10
+ basic classification f_classBasic.m
11
+ sub-classification f_classSub.m
12
+ driver run_ecco_v_RHI_spol_gridded.m
13
+
14
+ Input shapes
15
+ ------------
16
+ dbz : (Z, X)
17
+ coords_z: (Z,) or (Z, X) vertical positions/spacing (km)
18
+ coords_x: (X,) or (Z, X) horizontal positions/spacing (km)
19
+ height : (Z, X) height field, km (MSL or AGL)
20
+ melt : (Z, X) or (Z,) melting-layer field
21
+ temp : (Z, X) or (Z,) temperature field, degC
22
+
23
+ Echo type codes
24
+ ---------------
25
+ Basic (height, melt or temp absent):
26
+ 1 Stratiform 2 Mixed 3 Convective
27
+
28
+ Sub-classified (height, melt and temp all present):
29
+ 14 Stratiform Low 16 Stratiform Mid 18 Stratiform High
30
+ 25 Mixed
31
+ 30 Convective 32 Convective Elevated
32
+ 34 Convective Shallow 36 Convective Mid 38 Convective Deep
33
+
34
+ Code 30 is reachable only by calling class_sub_2d() directly with its
35
+ `elev`/`first_row` arguments, which correspond to f_classSub.m's
36
+ airborne-radar branch. run() does not pass them.
37
+
38
+ Sub-classification inputs are all-or-nothing
39
+ --------------------------------------------
40
+ `height`, `melt` and `temp` must be supplied together. f_classSub.m uses
41
+ all three and has no path that takes a subset: melt drives the
42
+ shallow/low decision, temp separates mid from deep/high, and height
43
+ supplies the near-surface test. Given an incomplete subset this function
44
+ returns basic codes rather than running a reduced variant of the
45
+ algorithm.
46
+
47
+ VerticalParams does not apply here. Its thresholds are read only by the
48
+ 3-D path; f_classSub.m hardcodes its melt threshold of 15 and its
49
+ temperature threshold of -25 degC. The one tunable it does consult,
50
+ surf_alt_lim, lives on ClassificationParams.
51
+
52
+ Typical usage
53
+ -------------
54
+ from eccopy import eccopy2d_v
55
+ from eccopy.params import WindowSpec
56
+
57
+ result = eccopy2d_v.run(
58
+ dbz, coords_z=z_km, coords_x=x_km,
59
+ height=height_km, melt=melt_field, temp=temp_c,
60
+ window=WindowSpec((7, 'km')),
61
+ )
62
+ echo = result.echo_type # shape (Z, X)
63
+ """
64
+
65
+ from __future__ import annotations
66
+ from dataclasses import dataclass
67
+ from typing import Optional, Union
68
+
69
+ import numpy as np
70
+
71
+ from ..core.coords import resolve_spacing
72
+ from ..core.texture import refl_texture_1d, refl_texture_1d_with_fit
73
+ from ..core.convectivity import texture_to_convectivity_linear
74
+ from ..core.classification import class_basic, class_sub_2d
75
+ from ..core.temperature import broadcast_temp_field
76
+ from ..params.window import WindowSpec
77
+ from ..params import TextureParams, ClassificationParams
78
+
79
+
80
+ @dataclass
81
+ class Result2DV:
82
+ """Output of eccopy2d_v.run()."""
83
+ echo_type: np.ndarray # shape (Z, X)
84
+ convectivity: np.ndarray # shape (Z, X)
85
+ texture: np.ndarray # shape (Z, X)
86
+ # Populated only when run(..., return_intermediates=True).
87
+ fitted_dbz: Optional[np.ndarray] = None # (Z, X) local linear fit at each point
88
+ detrended_dbz: Optional[np.ndarray] = None # (Z, X) fit removed, re-centred, clipped >= 1
89
+ echo_basic: Optional[np.ndarray] = None # (Z, X) basic 1/2/3 codes, pre sub-classification
90
+
91
+
92
+ def run(dbz: Union[np.ndarray, list],
93
+ coords_z: Union[np.ndarray, list],
94
+ coords_x: Union[np.ndarray, list],
95
+ height: Optional[Union[np.ndarray, list]] = None,
96
+ melt: Optional[Union[np.ndarray, list]] = None,
97
+ temp: Optional[Union[np.ndarray, list]] = None,
98
+ topo: Optional[Union[np.ndarray, list]] = None,
99
+ window: Union[WindowSpec, int] = WindowSpec((7, 'km')),
100
+ coord_mode: str = "auto",
101
+ texture_params: Optional[TextureParams] = None,
102
+ class_params: Optional[ClassificationParams] = None,
103
+ kernel_mode: str = "uniform",
104
+ remove_surface_echo: bool = False,
105
+ return_intermediates: bool = False) -> Result2DV:
106
+ """
107
+ Run EccoPy-2D-V: texture -> convectivity -> classification.
108
+
109
+ Sub-classification runs only when `height`, `melt` and `temp` are all
110
+ supplied; otherwise basic codes are returned. See the module
111
+ docstring.
112
+
113
+ Parameters
114
+ ----------
115
+ dbz : array-like, shape (Z, X)
116
+ Reflectivity, dBZ. NaN where missing.
117
+ coords_z : array-like, shape (Z,) or (Z, X)
118
+ Vertical coordinate or spacing, km.
119
+ coords_x : array-like, shape (X,) or (Z, X)
120
+ Horizontal coordinate or spacing, km.
121
+ height : array-like, shape (Z, X), optional
122
+ Height field, km. AGL if `topo` is supplied, otherwise taken as
123
+ given. Required with `melt` and `temp` for sub-classification.
124
+ melt : array-like, shape (Z, X) or (Z,), optional
125
+ Melting-layer field, either a full field or a single profile
126
+ broadcast across every column. f_classSub.m thresholds it at 15;
127
+ the SPOL driver supplies a binary field of 10 (above freezing)
128
+ and 20 (below). Also enables f_classBasic.m's rain-below-melting-
129
+ layer correction. Required with `height` and `temp`.
130
+ temp : array-like, shape (Z, X) or (Z,), optional
131
+ Temperature, degC. Separates mid from deep/high once `melt` has
132
+ placed a point above the melting layer. Required with `height`
133
+ and `melt`.
134
+ topo : array-like, shape (X,) or (Z, X), optional
135
+ Terrain height, km, or for a fixed-elevation RHI the
136
+ earth-curvature beam-height correction per range gate -
137
+ f_classSub.m's `topo` argument. Used only with `height`, where
138
+ `height - topo` becomes the AGL height throughout class_sub_2d.
139
+ window : WindowSpec or int
140
+ Texture window half-width along X.
141
+ coord_mode : {'auto', 'position', 'spacing'}
142
+ How to interpret coords_z / coords_x.
143
+ texture_params : TextureParams, optional
144
+ class_params : ClassificationParams, optional
145
+ `surf_alt_lim` (metres) drives two independent things: the
146
+ near-surface convective test inside class_sub_2d, and - only when
147
+ `remove_surface_echo=True` - the pre-texture masking below.
148
+ kernel_mode : {"uniform", "varying"}
149
+ How a physical window size becomes a pixel radius when `coords_x`
150
+ spacing is non-uniform.
151
+
152
+ "uniform" resolves one radius for the whole array from its global
153
+ median spacing. This matches f_reflTexture.m, which takes a
154
+ single `pixRad`, and is the default.
155
+
156
+ "varying" resolves a radius per point, and per Z row when
157
+ `coords_x` is 2-D. Physically closer for genuinely non-uniform
158
+ range-gate spacing, but has no upstream counterpart. The two are
159
+ identical when spacing is uniform.
160
+ remove_surface_echo : bool
161
+ Set dbz to NaN where the `coords_z` altitude is below
162
+ `cp.surf_alt_lim`, before texture. Reproduces the driver-level
163
+ masking in run_ecco_v_RHI_spol_gridded.m. Off by default because
164
+ not every upstream driver applies it. The caller's array is not
165
+ mutated.
166
+ return_intermediates : bool
167
+ Also attach `fitted_dbz`, `detrended_dbz` and `echo_basic` to the
168
+ result. Default False leaves them None.
169
+
170
+ Returns
171
+ -------
172
+ Result2DV
173
+ """
174
+ dbz = np.asarray(dbz, dtype=float)
175
+ if dbz.ndim != 2:
176
+ raise ValueError(f"eccopy2d_v expects a 2-D (Z, X) dbz array; got shape {dbz.shape}")
177
+ nz, nx = dbz.shape
178
+
179
+ tp = texture_params or TextureParams()
180
+ cp = class_params or ClassificationParams()
181
+
182
+ # --- resolve coords to per-point spacing (km) ---
183
+ coords_z = np.asarray(coords_z, dtype=float)
184
+ coords_x = np.asarray(coords_x, dtype=float)
185
+
186
+ if coords_z.ndim == 1:
187
+ if coords_z.shape[0] != nz:
188
+ raise ValueError(f"coords_z length {coords_z.shape[0]} != Z={nz}")
189
+ elif coords_z.shape != (nz, nx):
190
+ raise ValueError(
191
+ f"coords_z shape {coords_z.shape} must be (Z,) or (Z, X) = {(nz, nx)}"
192
+ )
193
+
194
+ if coords_x.ndim == 1:
195
+ if coords_x.shape[0] != nx:
196
+ raise ValueError(f"coords_x length {coords_x.shape[0]} != X={nx}")
197
+ sp_x_1d = resolve_spacing(coords_x, axis=0, mode=coord_mode)
198
+ sp_x = np.broadcast_to(sp_x_1d[np.newaxis, :], (nz, nx)).copy()
199
+ else:
200
+ sp_x = resolve_spacing(coords_x, axis=1, mode=coord_mode)
201
+
202
+ # Pre-texture surface-echo removal, matching the driver-level step in
203
+ # run_ecco_v_RHI_spol_gridded.m:
204
+ # data.DBZ_F(data.Z .* 1000 < surfAltLim) = nan;
205
+ # Masking is on altitude (coords_z), not AGL: the driver does not
206
+ # subtract topo here. This is a distinct role from surf_alt_lim's use
207
+ # inside class_sub_2d. Opt-in because upstream drivers disagree - the
208
+ # SeaPol RHI driver leaves reflectivity unmasked and applies
209
+ # surfAltLim only in f_classSub.m.
210
+ if remove_surface_echo:
211
+ alt_km = coords_z if coords_z.ndim == 2 else coords_z[:, np.newaxis]
212
+ # np.where returns a new array; the caller's dbz is not mutated.
213
+ dbz = np.where(alt_km < (cp.surf_alt_lim / 1000.0), np.nan, dbz)
214
+
215
+ # Texture slides along X, so the window resolves against sp_x.
216
+ if isinstance(window, WindowSpec) and not window.is_pixel:
217
+ if window.base_kind == "length_m":
218
+ sp_x_for_window = sp_x * 1000.0
219
+ else:
220
+ sp_x_for_window = sp_x
221
+ else:
222
+ sp_x_for_window = sp_x
223
+
224
+ # 1. Texture - f_reflTexture.m, sliding along the last axis.
225
+ # min_valid_dbz resolves to no gating here: it ports a
226
+ # ConvStratFinder prefilter that f_reflTexture.m does not have. An
227
+ # explicit value is still honoured.
228
+ min_valid = tp.resolve_min_valid_dbz(-np.inf)
229
+
230
+ fitted_dbz = detrended_dbz = None
231
+ if return_intermediates:
232
+ texture, fitted_dbz, detrended_dbz = refl_texture_1d_with_fit(
233
+ dbz, window, spacing=sp_x_for_window, dbz_base=tp.dbz_base,
234
+ min_valid_dbz=min_valid, kernel_mode=kernel_mode,
235
+ )
236
+ else:
237
+ texture = refl_texture_1d(
238
+ dbz, window, spacing=sp_x_for_window, dbz_base=tp.dbz_base,
239
+ min_valid_dbz=min_valid, kernel_mode=kernel_mode,
240
+ )
241
+
242
+ # 2. Convectivity
243
+ conv = texture_to_convectivity_linear(
244
+ texture,
245
+ upper_lim=tp.texture_limit_high,
246
+ lower_lim=tp.texture_limit_low,
247
+ )
248
+
249
+ # Melt broadcasts like temp: a full field or a (Z,) profile. It is
250
+ # taken as given - melt is never derived from temp here. Use
251
+ # core.temperature.melt_layer_from_temp() to build one.
252
+ melt_arr = broadcast_temp_field(melt, dbz.shape) if melt is not None else None
253
+
254
+ # 3. Basic classification - f_classBasic.m. Passing melt enables its
255
+ # rain-below-melting-layer correction.
256
+ echo_basic = class_basic(
257
+ conv,
258
+ strat_mixed=cp.max_convectivity_for_stratiform,
259
+ mixed_conv=cp.min_convectivity_for_convective,
260
+ melt=melt_arr, enlarge_mixed=cp.enlarge_mixed, enlarge_conv=cp.enlarge_conv,
261
+ )
262
+
263
+ # Sub-classification needs all three inputs; a partial subset returns
264
+ # basic codes. See the module docstring.
265
+ if height is None or melt is None or temp is None:
266
+ return Result2DV(echo_type=echo_basic, convectivity=conv, texture=texture,
267
+ fitted_dbz=fitted_dbz, detrended_dbz=detrended_dbz,
268
+ echo_basic=echo_basic if return_intermediates else None)
269
+
270
+ # f_classSub.m works in metres throughout (`data.Z .* 1000`), so
271
+ # class_sub_2d does too. EccoPy's public contract is km; convert once
272
+ # here, at the boundary.
273
+ height_arr = np.asarray(height, dtype=float) * 1000.0
274
+ topo_arr = np.asarray(topo, dtype=float) * 1000.0 if topo is not None else np.zeros((nz, nx))
275
+ temp_arr = broadcast_temp_field(temp, dbz.shape)
276
+
277
+ echo_sub = class_sub_2d(
278
+ echo_basic,
279
+ height=height_arr,
280
+ topo=topo_arr,
281
+ melt=melt_arr,
282
+ temp=temp_arr,
283
+ surf_alt_lim=cp.surf_alt_lim,
284
+ )
285
+
286
+ return Result2DV(echo_type=echo_sub, convectivity=conv, texture=texture,
287
+ fitted_dbz=fitted_dbz, detrended_dbz=detrended_dbz,
288
+ echo_basic=echo_basic if return_intermediates else None)
@@ -0,0 +1,2 @@
1
+ from .classify import run, Result3D
2
+ __all__ = ["run", "Result3D"]