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.
- eccopy/__init__.py +46 -0
- eccopy/core/__init__.py +55 -0
- eccopy/core/classification.py +1023 -0
- eccopy/core/colormaps.py +267 -0
- eccopy/core/convectivity.py +43 -0
- eccopy/core/coords.py +245 -0
- eccopy/core/data/disk_decomp/disk_decomp_r15_info.mat +0 -0
- eccopy/core/data/disk_decomp/disk_decomp_r15_step1.mat +0 -0
- eccopy/core/data/disk_decomp/disk_decomp_r15_step2.mat +0 -0
- eccopy/core/data/disk_decomp/disk_decomp_r15_step3.mat +0 -0
- eccopy/core/data/disk_decomp/disk_decomp_r15_step4.mat +0 -0
- eccopy/core/data/disk_decomp/disk_decomp_r15_step5.mat +0 -0
- eccopy/core/data/disk_decomp/disk_decomp_r15_step6.mat +0 -0
- eccopy/core/data/disk_decomp/disk_decomp_r25_info.mat +0 -0
- eccopy/core/data/disk_decomp/disk_decomp_r25_step1.mat +0 -0
- eccopy/core/data/disk_decomp/disk_decomp_r25_step2.mat +0 -0
- eccopy/core/data/disk_decomp/disk_decomp_r25_step3.mat +0 -0
- eccopy/core/data/disk_decomp/disk_decomp_r25_step4.mat +0 -0
- eccopy/core/data/disk_decomp/disk_decomp_r25_step5.mat +0 -0
- eccopy/core/data/disk_decomp/disk_decomp_r25_step6.mat +0 -0
- eccopy/core/data/disk_strels/disk_strel_r15.mat +0 -0
- eccopy/core/data/disk_strels/disk_strel_r25.mat +0 -0
- eccopy/core/data/disk_strels/disk_strel_r3.mat +0 -0
- eccopy/core/data/disk_strels/disk_strel_r5.mat +0 -0
- eccopy/core/debug.py +493 -0
- eccopy/core/disk.py +178 -0
- eccopy/core/temperature.py +250 -0
- eccopy/core/texture.py +1398 -0
- eccopy/eccopy1d/__init__.py +2 -0
- eccopy/eccopy1d/classify.py +273 -0
- eccopy/eccopy2d_h/__init__.py +2 -0
- eccopy/eccopy2d_h/classify.py +281 -0
- eccopy/eccopy2d_h/clumping.py +265 -0
- eccopy/eccopy2d_v/__init__.py +2 -0
- eccopy/eccopy2d_v/classify.py +288 -0
- eccopy/eccopy3d/__init__.py +2 -0
- eccopy/eccopy3d/classify.py +421 -0
- eccopy/eccopy3d/clumping.py +477 -0
- eccopy/params/__init__.py +6 -0
- eccopy/params/classification_params.py +151 -0
- eccopy/params/texture_params.py +66 -0
- eccopy/params/vertical_params.py +54 -0
- eccopy/params/window.py +141 -0
- eccopy/stats/__init__.py +56 -0
- eccopy/stats/basic_stats.py +370 -0
- eccopy/tests/__init__.py +0 -0
- eccopy/tests/_reference_impls/__init__.py +0 -0
- eccopy/tests/_reference_impls/isotherm_height_reference.py +54 -0
- eccopy/tests/_reference_impls/sliding_texture_reference.py +77 -0
- eccopy/tests/_reference_impls/texture_2d_reference.py +309 -0
- eccopy/tests/test_classification_1d_filter.py +151 -0
- eccopy/tests/test_classification_rain_below_melt.py +130 -0
- eccopy/tests/test_colormaps.py +213 -0
- eccopy/tests/test_coords.py +127 -0
- eccopy/tests/test_debug.py +226 -0
- eccopy/tests/test_disk_generator.py +82 -0
- eccopy/tests/test_eccopy1d.py +209 -0
- eccopy/tests/test_eccopy2d_h.py +185 -0
- eccopy/tests/test_eccopy2d_h_clumping.py +105 -0
- eccopy/tests/test_eccopy2d_v.py +359 -0
- eccopy/tests/test_eccopy3d.py +282 -0
- eccopy/tests/test_examples.py +84 -0
- eccopy/tests/test_min_valid_dbz.py +144 -0
- eccopy/tests/test_notebooks.py +111 -0
- eccopy/tests/test_numba_cross_validation.py +331 -0
- eccopy/tests/test_packaging.py +144 -0
- eccopy/tests/test_refl_texture_1d.py +167 -0
- eccopy/tests/test_stats.py +117 -0
- eccopy/tests/test_stats_sentinel.py +74 -0
- eccopy/tests/test_temperature.py +207 -0
- eccopy/tests/test_texture_kernel_modes.py +82 -0
- eccopy/tests/test_texture_params_implemented.py +148 -0
- eccopy/tests/test_vert_levels_type.py +180 -0
- eccopy/tests/test_window.py +80 -0
- eccopy-1.0.0.dist-info/METADATA +420 -0
- eccopy-1.0.0.dist-info/RECORD +79 -0
- eccopy-1.0.0.dist-info/WHEEL +5 -0
- eccopy-1.0.0.dist-info/licenses/LICENSE +39 -0
- eccopy-1.0.0.dist-info/top_level.txt +1 -0
eccopy/core/texture.py
ADDED
|
@@ -0,0 +1,1398 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Reflectivity texture calculations.
|
|
3
|
+
|
|
4
|
+
Two families of functions:
|
|
5
|
+
|
|
6
|
+
1-D sliding-window (EccoPy-1D / EccoPy-2D)
|
|
7
|
+
refl_texture_1d() - port of f_reflTexture.m, generalised to accept a
|
|
8
|
+
per-point pixel-radius array so the window size can vary along the
|
|
9
|
+
array (e.g. when resolved from a physical-unit WindowSpec against a
|
|
10
|
+
non-uniform spacing array).
|
|
11
|
+
|
|
12
|
+
2-D radial with planar detrend (EccoPy-3D)
|
|
13
|
+
refl_texture_2d() - port of ConvStratFinder::ComputeTexture::run(),
|
|
14
|
+
generalised to accept per-point dy/dx spacing arrays instead of
|
|
15
|
+
assuming a uniform grid.
|
|
16
|
+
|
|
17
|
+
Both carry the math of the LROSE-derived implementations unchanged; the
|
|
18
|
+
window/spacing resolution accepts per-point rather than globally uniform
|
|
19
|
+
spacing.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import warnings
|
|
25
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
26
|
+
from typing import Optional, Union
|
|
27
|
+
|
|
28
|
+
import numpy as np
|
|
29
|
+
from numba import njit
|
|
30
|
+
|
|
31
|
+
from ..params.window import WindowSpec
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
# ---------------------------------------------------------------------------
|
|
35
|
+
# Internal helpers
|
|
36
|
+
# ---------------------------------------------------------------------------
|
|
37
|
+
|
|
38
|
+
def _fillmissing_linear(arr: np.ndarray, axis: int) -> np.ndarray:
|
|
39
|
+
"""
|
|
40
|
+
Fill NaN values by linear interpolation + nearest-edge extrapolation
|
|
41
|
+
along the given axis. Mirrors MATLAB fillmissing(x,'linear','EndValues','nearest').
|
|
42
|
+
"""
|
|
43
|
+
result = np.moveaxis(arr.copy(), axis, -1)
|
|
44
|
+
shape = result.shape
|
|
45
|
+
result = result.reshape(-1, shape[-1])
|
|
46
|
+
x = np.arange(shape[-1], dtype=float)
|
|
47
|
+
for i in range(result.shape[0]):
|
|
48
|
+
row = result[i]
|
|
49
|
+
nans = np.isnan(row)
|
|
50
|
+
if nans.all() or not nans.any():
|
|
51
|
+
continue
|
|
52
|
+
good = ~nans
|
|
53
|
+
result[i] = np.interp(x, x[good], row[good])
|
|
54
|
+
result = result.reshape(shape)
|
|
55
|
+
return np.moveaxis(result, -1, axis)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _radius_field_along_axis(window: Union[WindowSpec, int],
|
|
59
|
+
spacing: Optional[np.ndarray],
|
|
60
|
+
n: int) -> np.ndarray:
|
|
61
|
+
"""
|
|
62
|
+
Resolve a window into a 1-D array of per-point integer pixel radii,
|
|
63
|
+
of length n, given a 1-D spacing array along the texture axis.
|
|
64
|
+
"""
|
|
65
|
+
if isinstance(window, int):
|
|
66
|
+
return np.full(n, window, dtype=int)
|
|
67
|
+
if isinstance(window, WindowSpec) and window.is_pixel:
|
|
68
|
+
# Bare-pixel WindowSpec never needs a spacing array, same as a
|
|
69
|
+
# raw int radius - resolve it directly without requiring spacing.
|
|
70
|
+
return window.pixel_radius_field(np.ones(n))
|
|
71
|
+
if spacing is None:
|
|
72
|
+
raise ValueError(
|
|
73
|
+
"A physical-unit WindowSpec requires a spacing array; "
|
|
74
|
+
"got spacing=None. Pass an integer pixel radius instead, "
|
|
75
|
+
"or provide a spacing array."
|
|
76
|
+
)
|
|
77
|
+
spacing = np.asarray(spacing, dtype=float)
|
|
78
|
+
if spacing.shape[-1] != n:
|
|
79
|
+
raise ValueError(
|
|
80
|
+
f"spacing array length ({spacing.shape[-1]}) along the texture "
|
|
81
|
+
f"axis must match the data length ({n})."
|
|
82
|
+
)
|
|
83
|
+
return window.pixel_radius_field(spacing)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@njit(cache=True)
|
|
87
|
+
def _sliding_texture_core(data_padded: np.ndarray,
|
|
88
|
+
radius_field: np.ndarray,
|
|
89
|
+
pad: int,
|
|
90
|
+
nRows: int,
|
|
91
|
+
nCols: int) -> np.ndarray:
|
|
92
|
+
"""
|
|
93
|
+
Core 1-D detrend + texture loop with a PER-POINT window radius.
|
|
94
|
+
|
|
95
|
+
Replicates MATLAB f_reflTexture.m exactly at each point:
|
|
96
|
+
- 1-D linear detrend per window
|
|
97
|
+
- texture = sqrt(sample_std(detrended^2)), using N-1 normalisation
|
|
98
|
+
to match MATLAB's std() default
|
|
99
|
+
- missing values are dropped (nanstd), not substituted
|
|
100
|
+
|
|
101
|
+
Parameters
|
|
102
|
+
----------
|
|
103
|
+
data_padded : (nRows, nCols + 2*pad) array, pre-filled (no NaN gaps)
|
|
104
|
+
radius_field : (nCols,) int array - per-point window half-width
|
|
105
|
+
pad : int - maximum radius used when padding (>= max(radius_field))
|
|
106
|
+
|
|
107
|
+
Implementation note
|
|
108
|
+
--------------------
|
|
109
|
+
This loops explicitly over (column, row, window-position) rather
|
|
110
|
+
than using NumPy's row-vectorized axis=1 reductions (np.nansum,
|
|
111
|
+
np.nanmean, np.nanstd, np.tile), because none of those are supported
|
|
112
|
+
in Numba's nopython mode. The math is identical - every sum below is
|
|
113
|
+
just the scalar equivalent of the array reduction it replaces - but
|
|
114
|
+
expressed as accumulation loops so this function can be JIT-compiled.
|
|
115
|
+
NaN values are skipped while accumulating sums (mirroring nansum's
|
|
116
|
+
drop-rather-than-substitute behaviour), with a running valid-count
|
|
117
|
+
used as the divisor in place of the window width.
|
|
118
|
+
"""
|
|
119
|
+
texture = np.full((nRows, nCols), np.nan)
|
|
120
|
+
|
|
121
|
+
for ii in range(nCols):
|
|
122
|
+
r = int(radius_field[ii])
|
|
123
|
+
if r < 1:
|
|
124
|
+
continue
|
|
125
|
+
lo = pad + ii - r
|
|
126
|
+
hi = pad + ii + r + 1
|
|
127
|
+
W = hi - lo
|
|
128
|
+
if W < 2:
|
|
129
|
+
continue
|
|
130
|
+
|
|
131
|
+
for row in range(nRows):
|
|
132
|
+
# --- accumulate sums for the linear fit, skipping NaNs ---
|
|
133
|
+
# (x-coordinate is 1..W along the window, same as the
|
|
134
|
+
# original np.arange(1, W+1) used for X)
|
|
135
|
+
sumX = 0.0
|
|
136
|
+
sumX2 = 0.0
|
|
137
|
+
sumY = 0.0
|
|
138
|
+
sumXY = 0.0
|
|
139
|
+
n_valid = 0
|
|
140
|
+
for jj in range(W):
|
|
141
|
+
x = jj + 1.0 # 1-indexed, matching np.arange(1, W+1)
|
|
142
|
+
sumX += x
|
|
143
|
+
sumX2 += x * x
|
|
144
|
+
y = data_padded[row, lo + jj]
|
|
145
|
+
if not np.isnan(y):
|
|
146
|
+
sumY += y
|
|
147
|
+
sumXY += x * y
|
|
148
|
+
n_valid += 1
|
|
149
|
+
|
|
150
|
+
denom = W * sumX2 - sumX * sumX
|
|
151
|
+
if denom != 0.0:
|
|
152
|
+
a = (sumY * sumX2 - sumX * sumXY) / denom
|
|
153
|
+
b = (W * sumXY - sumX * sumY) / denom
|
|
154
|
+
else:
|
|
155
|
+
a = 0.0
|
|
156
|
+
b = 0.0
|
|
157
|
+
|
|
158
|
+
mean_block = sumY / n_valid if n_valid > 0 else np.nan
|
|
159
|
+
|
|
160
|
+
# --- detrend, clip, and accumulate texture statistics ---
|
|
161
|
+
# (sample variance of corrected^2, N-1 normalization, NaNs
|
|
162
|
+
# dropped -- same as np.nanstd(corrected**2, ddof=1) on the
|
|
163
|
+
# original block; see fix note below)
|
|
164
|
+
sum_sq = 0.0
|
|
165
|
+
sum_sq2 = 0.0
|
|
166
|
+
n_corrected = 0
|
|
167
|
+
for jj in range(W):
|
|
168
|
+
y = data_padded[row, lo + jj]
|
|
169
|
+
if np.isnan(y):
|
|
170
|
+
continue
|
|
171
|
+
x = jj + 1.0
|
|
172
|
+
new_y = a + b * x
|
|
173
|
+
corrected = y - new_y + mean_block
|
|
174
|
+
if corrected < 1.0:
|
|
175
|
+
corrected = 1.0
|
|
176
|
+
csq = corrected * corrected
|
|
177
|
+
sum_sq += csq
|
|
178
|
+
sum_sq2 += csq * csq
|
|
179
|
+
n_corrected += 1
|
|
180
|
+
|
|
181
|
+
if n_corrected > 0:
|
|
182
|
+
mean_sq = sum_sq / n_corrected
|
|
183
|
+
# Sample variance (N-1 denominator), matching MATLAB's
|
|
184
|
+
# std(dbzCorr.^2, [], 2, 'omitnan') -- the `[]` selects
|
|
185
|
+
# MATLAB's DEFAULT normalization, which is N-1 (sample),
|
|
186
|
+
# NOT N (population). The previous version of this block
|
|
187
|
+
# computed population variance (N denominator), which is
|
|
188
|
+
# NOT what MATLAB's std() actually does by default despite
|
|
189
|
+
# the comment above claiming otherwise. Verified against
|
|
190
|
+
# real MATLAB CONVECTIVITY output (SPOL case): N-1 gives
|
|
191
|
+
# ~1e-17 mean absolute error (machine precision), N gave
|
|
192
|
+
# ~1.5e-3 -- small in raw convectivity terms, but enough
|
|
193
|
+
# to shift several threshold crossings and move downstream
|
|
194
|
+
# classification agreement from 98.2% to 99.4%.
|
|
195
|
+
if n_corrected > 1:
|
|
196
|
+
sum_sq_dev = sum_sq2 - n_corrected * mean_sq * mean_sq
|
|
197
|
+
var = sum_sq_dev / (n_corrected - 1)
|
|
198
|
+
if var < 0.0:
|
|
199
|
+
var = 0.0
|
|
200
|
+
else:
|
|
201
|
+
var = 0.0 # matches MATLAB's std() of a single sample == 0
|
|
202
|
+
# texture = sqrt(sample_std(corrected**2)), and
|
|
203
|
+
# std = sqrt(var) -- so this is sqrt(sqrt(var)), a
|
|
204
|
+
# FOURTH root, not sqrt(var). (Caught by exhaustive
|
|
205
|
+
# cross-validation against the pre-Numba reference -
|
|
206
|
+
# an earlier draft of this line wrote np.sqrt(var) and
|
|
207
|
+
# silently produced the SQUARE of the correct answer
|
|
208
|
+
# for most inputs; entry-point tests didn't catch it
|
|
209
|
+
# because they only check that plausible-looking output
|
|
210
|
+
# comes out, not exact values.)
|
|
211
|
+
texture[row, ii] = np.sqrt(np.sqrt(var))
|
|
212
|
+
# else: leave as NaN (matches np.nanstd on an all-NaN slice)
|
|
213
|
+
|
|
214
|
+
return texture
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
# ---------------------------------------------------------------------------
|
|
218
|
+
# Public 1-D sliding-window texture (used by EccoPy-1D and EccoPy-2D)
|
|
219
|
+
# ---------------------------------------------------------------------------
|
|
220
|
+
|
|
221
|
+
def refl_texture_1d(dbz: np.ndarray,
|
|
222
|
+
window: Union[WindowSpec, int],
|
|
223
|
+
spacing: Optional[np.ndarray] = None,
|
|
224
|
+
dbz_base: float = 0.0,
|
|
225
|
+
min_valid_dbz: float = -np.inf,
|
|
226
|
+
kernel_mode: str = "uniform") -> np.ndarray:
|
|
227
|
+
"""
|
|
228
|
+
Sliding 1-D reflectivity texture along the last axis.
|
|
229
|
+
|
|
230
|
+
Port of MATLAB f_reflTexture.m, generalised to a per-point window
|
|
231
|
+
radius so spacing may vary along the texture axis.
|
|
232
|
+
|
|
233
|
+
When `kernel_mode="varying"`, each row resolves its own radius from
|
|
234
|
+
its own spacing, so a genuinely row-varying (ndim > 1) `spacing`
|
|
235
|
+
array is honoured per row - relevant to eccopy2d_v with a 2-D
|
|
236
|
+
coords_x whose range-gate spacing changes with elevation angle.
|
|
237
|
+
|
|
238
|
+
kernel_mode mirrors refl_texture_2d's parameter of the same name.
|
|
239
|
+
f_reflTexture.m takes a single scalar `pixRad`, so "uniform" is the
|
|
240
|
+
default here; "varying" has no upstream counterpart.
|
|
241
|
+
|
|
242
|
+
Parameters
|
|
243
|
+
----------
|
|
244
|
+
dbz : np.ndarray, shape (..., N)
|
|
245
|
+
Reflectivity. Texture is computed along the LAST axis.
|
|
246
|
+
window : WindowSpec or int
|
|
247
|
+
Window radius. If a physical WindowSpec (e.g. WindowSpec((5,'km'))),
|
|
248
|
+
`spacing` must be provided.
|
|
249
|
+
spacing : np.ndarray, shape (N,) or (..., N), optional
|
|
250
|
+
Point-to-point spacing along the last axis, in the base unit
|
|
251
|
+
matching `window` (km for length, seconds for time - EccoPy's
|
|
252
|
+
run() entry points handle this conversion; see eccopy1d.run()
|
|
253
|
+
and `eccopy2d_v.run()` / `eccopy2d_h.run()`). Required if `window`
|
|
254
|
+
is a physical WindowSpec. A `(N,)` array (or an `(..., N)` array
|
|
255
|
+
whose leading dimensions are all size 1) is broadcast identically
|
|
256
|
+
to every row. An `(..., N)` array whose leading dimensions match
|
|
257
|
+
`dbz`'s (after flattening) supplies a genuinely DIFFERENT spacing
|
|
258
|
+
-- and therefore, in kernel_mode="varying", a different resolved
|
|
259
|
+
window radius -- to each row; anything in between raises a clear
|
|
260
|
+
error rather than silently guessing. Ignored entirely (not even
|
|
261
|
+
validated) if `window` is a bare pixel radius.
|
|
262
|
+
dbz_base : float
|
|
263
|
+
Subtracted from values before texture is computed.
|
|
264
|
+
min_valid_dbz : float
|
|
265
|
+
Values below this are treated as missing before texture is
|
|
266
|
+
computed. Defaults to -inf (no gating), matching f_reflTexture.m,
|
|
267
|
+
which has no such prefilter. See TextureParams.min_valid_dbz.
|
|
268
|
+
kernel_mode : {"uniform", "varying"}
|
|
269
|
+
"uniform" (default) - resolve ONE radius from the median of the
|
|
270
|
+
(validated/broadcast) spacing array, applied everywhere.
|
|
271
|
+
Matches per-point resolution exactly on uniform-spacing data.
|
|
272
|
+
"varying" - resolve a distinct radius at every point (and, for
|
|
273
|
+
multi-row input, every row) from its own local spacing. Not
|
|
274
|
+
validated against any ground truth in configurations where
|
|
275
|
+
it differs from "uniform" - see docstring above.
|
|
276
|
+
|
|
277
|
+
Returns
|
|
278
|
+
-------
|
|
279
|
+
texture : np.ndarray, same shape as dbz
|
|
280
|
+
"""
|
|
281
|
+
if kernel_mode not in ("uniform", "varying"):
|
|
282
|
+
raise ValueError(
|
|
283
|
+
f"kernel_mode must be 'uniform' or 'varying', got {kernel_mode!r}"
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
dbz = np.asarray(dbz, dtype=float)
|
|
287
|
+
# Null out dbz below min_valid_dbz BEFORE any downstream computation,
|
|
288
|
+
# mirroring refl_texture_2d(). Sub-threshold values left in place would
|
|
289
|
+
# otherwise participate as valid neighbours in the window statistic and
|
|
290
|
+
# inflate texture near the edges of valid-data regions.
|
|
291
|
+
#
|
|
292
|
+
# The default is -inf (no gating), NOT 0.0 as in the 2-D/3-D path:
|
|
293
|
+
# min_valid_dbz ports ConvStratFinder::computeEchoType()'s prefilter,
|
|
294
|
+
# which has no analog in f_reflTexture.m. EccoPy-2D-V agrees with real
|
|
295
|
+
# MATLAB ECCO-V output at 99.4-100% without it; gating at 0 dBZ moves
|
|
296
|
+
# that output by ~13%. Callers that want the C++ behaviour set it
|
|
297
|
+
# explicitly. See TextureParams.min_valid_dbz.
|
|
298
|
+
if min_valid_dbz > -np.inf:
|
|
299
|
+
dbz = np.where(dbz < min_valid_dbz, np.nan, dbz)
|
|
300
|
+
|
|
301
|
+
orig_shape = dbz.shape
|
|
302
|
+
n = orig_shape[-1]
|
|
303
|
+
|
|
304
|
+
if isinstance(window, int):
|
|
305
|
+
window = WindowSpec(window)
|
|
306
|
+
|
|
307
|
+
flat = dbz.reshape(-1, n)
|
|
308
|
+
nRows = flat.shape[0]
|
|
309
|
+
|
|
310
|
+
# Resolve a radius field, shape (nRows, n) -- per-point/per-row in
|
|
311
|
+
# kernel_mode="varying", or a single global value broadcast to that
|
|
312
|
+
# same shape in kernel_mode="uniform" (see docstring above).
|
|
313
|
+
if window.is_pixel:
|
|
314
|
+
radius_field_2d = np.full((nRows, n), int(window.size), dtype=int)
|
|
315
|
+
else:
|
|
316
|
+
if spacing is None:
|
|
317
|
+
raise ValueError(
|
|
318
|
+
"A physical-unit WindowSpec requires a spacing array; "
|
|
319
|
+
"got spacing=None. Pass an integer pixel radius instead, "
|
|
320
|
+
"or provide a spacing array."
|
|
321
|
+
)
|
|
322
|
+
spacing = np.asarray(spacing, dtype=float)
|
|
323
|
+
if spacing.ndim == 1:
|
|
324
|
+
if spacing.shape[0] != n:
|
|
325
|
+
raise ValueError(
|
|
326
|
+
f"spacing array length ({spacing.shape[0]}) along the "
|
|
327
|
+
f"texture axis must match the data length ({n})."
|
|
328
|
+
)
|
|
329
|
+
spacing_rows = np.broadcast_to(spacing, (nRows, n))
|
|
330
|
+
else:
|
|
331
|
+
if spacing.shape[-1] != n:
|
|
332
|
+
raise ValueError(
|
|
333
|
+
f"spacing array's last-axis length ({spacing.shape[-1]}) "
|
|
334
|
+
f"must match the data length ({n})."
|
|
335
|
+
)
|
|
336
|
+
spacing_rows = spacing.reshape(-1, n)
|
|
337
|
+
if spacing_rows.shape[0] == 1:
|
|
338
|
+
spacing_rows = np.broadcast_to(spacing_rows, (nRows, n))
|
|
339
|
+
elif spacing_rows.shape[0] != nRows:
|
|
340
|
+
raise ValueError(
|
|
341
|
+
f"spacing has {spacing_rows.shape[0]} row(s) after "
|
|
342
|
+
f"flattening its leading dimensions, but dbz has "
|
|
343
|
+
f"{nRows} row(s) after the same flattening; spacing "
|
|
344
|
+
f"must have either 1 row (shared across every row) or "
|
|
345
|
+
f"exactly {nRows} rows (one genuine spacing profile "
|
|
346
|
+
f"per row) -- anything else is ambiguous, so this "
|
|
347
|
+
f"raises rather than guessing which row(s) to use."
|
|
348
|
+
)
|
|
349
|
+
|
|
350
|
+
if kernel_mode == "uniform":
|
|
351
|
+
# ONE representative radius for the whole array -- the
|
|
352
|
+
# global median across every row and column of the
|
|
353
|
+
# (validated/broadcast) spacing, matching refl_texture_2d's
|
|
354
|
+
# "one kernel for the whole domain" convention exactly.
|
|
355
|
+
median_spacing = np.array(float(np.nanmedian(spacing_rows)))
|
|
356
|
+
r = int(window.pixel_radius_field(median_spacing))
|
|
357
|
+
radius_field_2d = np.full((nRows, n), r, dtype=int)
|
|
358
|
+
else:
|
|
359
|
+
# WindowSpec.pixel_radius_field is elementwise, so it
|
|
360
|
+
# resolves the WHOLE (nRows, n) spacing array to a (nRows, n)
|
|
361
|
+
# radius field in one call -- each row/point gets its OWN
|
|
362
|
+
# radius, resolved from its OWN spacing.
|
|
363
|
+
radius_field_2d = window.pixel_radius_field(spacing_rows)
|
|
364
|
+
|
|
365
|
+
pad = int(radius_field_2d.max()) if radius_field_2d.size else 0
|
|
366
|
+
|
|
367
|
+
if pad > 0:
|
|
368
|
+
padded = np.pad(flat, ((0, 0), (pad, pad)), mode="constant",
|
|
369
|
+
constant_values=np.nan)
|
|
370
|
+
else:
|
|
371
|
+
padded = flat.copy()
|
|
372
|
+
|
|
373
|
+
padded = _fillmissing_linear(padded, axis=1)
|
|
374
|
+
padded = padded - dbz_base
|
|
375
|
+
|
|
376
|
+
# _sliding_texture_core (the validated, Numba-JIT'd core loop) takes
|
|
377
|
+
# ONE radius_field shared by every row in a single call -- rather
|
|
378
|
+
# than changing that core's signature (and re-validating it against
|
|
379
|
+
# test_numba_cross_validation.py's frozen reference), row-batch here:
|
|
380
|
+
# the common case (every row resolved to the SAME radius field --
|
|
381
|
+
# always true in kernel_mode="uniform", and also true in "varying"
|
|
382
|
+
# whenever spacing happens to be uniform across rows, or window is a
|
|
383
|
+
# bare pixel radius) stays on the original single, fast call; only
|
|
384
|
+
# genuinely row-varying resolved radii pay for a per-row Python loop.
|
|
385
|
+
if nRows <= 1 or np.all(radius_field_2d == radius_field_2d[0]):
|
|
386
|
+
texture = _sliding_texture_core(padded, radius_field_2d[0], pad, nRows, n)
|
|
387
|
+
else:
|
|
388
|
+
texture = np.full((nRows, n), np.nan)
|
|
389
|
+
for row in range(nRows):
|
|
390
|
+
texture[row:row + 1] = _sliding_texture_core(
|
|
391
|
+
padded[row:row + 1], radius_field_2d[row], pad, 1, n
|
|
392
|
+
|
|
393
|
+
)
|
|
394
|
+
|
|
395
|
+
texture[np.isnan(flat)] = np.nan
|
|
396
|
+
|
|
397
|
+
return texture.reshape(orig_shape)
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
@njit(cache=True)
|
|
401
|
+
def _sliding_texture_core_with_fit(data_padded: np.ndarray,
|
|
402
|
+
radius_field: np.ndarray,
|
|
403
|
+
pad: int,
|
|
404
|
+
nRows: int,
|
|
405
|
+
nCols: int):
|
|
406
|
+
"""
|
|
407
|
+
DEBUG-ONLY variant of _sliding_texture_core that additionally records,
|
|
408
|
+
at every point, the value the point's own local linear fit predicts
|
|
409
|
+
AT THAT POINT (`fitted`), and the detrended/clipped value that value
|
|
410
|
+
turns into before being squared into the texture statistic
|
|
411
|
+
(`detrended`) -- i.e. the two intermediate fields requested for
|
|
412
|
+
debugging "the fitted dbz prior to texture".
|
|
413
|
+
|
|
414
|
+
This is a byte-for-byte duplicate of _sliding_texture_core's math
|
|
415
|
+
(never edit one without the other) with two extra writes; kept as a
|
|
416
|
+
separate function rather than adding an output-array flag to the
|
|
417
|
+
validated core so the hot, non-debug path is never touched by this
|
|
418
|
+
change. See test_debug.py's cross-validation test, which checks this
|
|
419
|
+
function's `texture` output against _sliding_texture_core's output
|
|
420
|
+
on the same input.
|
|
421
|
+
"""
|
|
422
|
+
texture = np.full((nRows, nCols), np.nan)
|
|
423
|
+
fitted = np.full((nRows, nCols), np.nan)
|
|
424
|
+
detrended = np.full((nRows, nCols), np.nan)
|
|
425
|
+
|
|
426
|
+
for ii in range(nCols):
|
|
427
|
+
r = int(radius_field[ii])
|
|
428
|
+
if r < 1:
|
|
429
|
+
continue
|
|
430
|
+
lo = pad + ii - r
|
|
431
|
+
hi = pad + ii + r + 1
|
|
432
|
+
W = hi - lo
|
|
433
|
+
if W < 2:
|
|
434
|
+
continue
|
|
435
|
+
jj_center = r # position of point `ii` within its own window
|
|
436
|
+
|
|
437
|
+
for row in range(nRows):
|
|
438
|
+
sumX = 0.0
|
|
439
|
+
sumX2 = 0.0
|
|
440
|
+
sumY = 0.0
|
|
441
|
+
sumXY = 0.0
|
|
442
|
+
n_valid = 0
|
|
443
|
+
for jj in range(W):
|
|
444
|
+
x = jj + 1.0
|
|
445
|
+
sumX += x
|
|
446
|
+
sumX2 += x * x
|
|
447
|
+
y = data_padded[row, lo + jj]
|
|
448
|
+
if not np.isnan(y):
|
|
449
|
+
sumY += y
|
|
450
|
+
sumXY += x * y
|
|
451
|
+
n_valid += 1
|
|
452
|
+
|
|
453
|
+
denom = W * sumX2 - sumX * sumX
|
|
454
|
+
if denom != 0.0:
|
|
455
|
+
a = (sumY * sumX2 - sumX * sumXY) / denom
|
|
456
|
+
b = (W * sumXY - sumX * sumY) / denom
|
|
457
|
+
else:
|
|
458
|
+
a = 0.0
|
|
459
|
+
b = 0.0
|
|
460
|
+
|
|
461
|
+
mean_block = sumY / n_valid if n_valid > 0 else np.nan
|
|
462
|
+
|
|
463
|
+
x_center = jj_center + 1.0
|
|
464
|
+
fitted_center = a + b * x_center
|
|
465
|
+
fitted[row, ii] = fitted_center
|
|
466
|
+
y_center = data_padded[row, pad + ii]
|
|
467
|
+
if not np.isnan(y_center):
|
|
468
|
+
dtr = y_center - fitted_center + mean_block
|
|
469
|
+
if dtr < 1.0:
|
|
470
|
+
dtr = 1.0
|
|
471
|
+
detrended[row, ii] = dtr
|
|
472
|
+
|
|
473
|
+
sum_sq = 0.0
|
|
474
|
+
sum_sq2 = 0.0
|
|
475
|
+
n_corrected = 0
|
|
476
|
+
for jj in range(W):
|
|
477
|
+
y = data_padded[row, lo + jj]
|
|
478
|
+
if np.isnan(y):
|
|
479
|
+
continue
|
|
480
|
+
x = jj + 1.0
|
|
481
|
+
new_y = a + b * x
|
|
482
|
+
corrected = y - new_y + mean_block
|
|
483
|
+
if corrected < 1.0:
|
|
484
|
+
corrected = 1.0
|
|
485
|
+
csq = corrected * corrected
|
|
486
|
+
sum_sq += csq
|
|
487
|
+
sum_sq2 += csq * csq
|
|
488
|
+
n_corrected += 1
|
|
489
|
+
|
|
490
|
+
if n_corrected > 0:
|
|
491
|
+
mean_sq = sum_sq / n_corrected
|
|
492
|
+
if n_corrected > 1:
|
|
493
|
+
sum_sq_dev = sum_sq2 - n_corrected * mean_sq * mean_sq
|
|
494
|
+
var = sum_sq_dev / (n_corrected - 1)
|
|
495
|
+
if var < 0.0:
|
|
496
|
+
var = 0.0
|
|
497
|
+
else:
|
|
498
|
+
var = 0.0
|
|
499
|
+
texture[row, ii] = np.sqrt(np.sqrt(var))
|
|
500
|
+
|
|
501
|
+
return texture, fitted, detrended
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def refl_texture_1d_with_fit(dbz: np.ndarray,
|
|
505
|
+
window: Union[WindowSpec, int],
|
|
506
|
+
spacing: Optional[np.ndarray] = None,
|
|
507
|
+
dbz_base: float = 0.0,
|
|
508
|
+
min_valid_dbz: float = -np.inf,
|
|
509
|
+
kernel_mode: str = "uniform"):
|
|
510
|
+
"""
|
|
511
|
+
DEBUG-ONLY entry point: same texture calculation as refl_texture_1d,
|
|
512
|
+
but also returns the per-point fitted trend value and the detrended
|
|
513
|
+
(clipped) value at each point -- i.e. "the fitted dbz prior to
|
|
514
|
+
texture" -- so you can inspect why a point got the texture value it
|
|
515
|
+
did without calling refl_texture_1d_debug() one index at a time.
|
|
516
|
+
|
|
517
|
+
`texture` from this function is identical to refl_texture_1d(...)
|
|
518
|
+
on the same inputs (see test_debug.py's cross-validation test).
|
|
519
|
+
Not used by any production run() path unless return_intermediates=True
|
|
520
|
+
is passed; costs nothing when that flag is left at its default False.
|
|
521
|
+
|
|
522
|
+
Parameters
|
|
523
|
+
----------
|
|
524
|
+
Same as refl_texture_1d.
|
|
525
|
+
|
|
526
|
+
Returns
|
|
527
|
+
-------
|
|
528
|
+
texture, fitted_dbz, detrended_dbz : np.ndarray, each same shape as dbz
|
|
529
|
+
fitted_dbz -- value the local linear fit predicts at that point
|
|
530
|
+
detrended_dbz -- fitted_dbz removed and re-centred on the window
|
|
531
|
+
mean, clipped to >= 1 (dbz_base already added
|
|
532
|
+
back) -- the value that gets squared into the
|
|
533
|
+
texture statistic. NaN wherever the original
|
|
534
|
+
input was NaN or the point falls in the un-
|
|
535
|
+
computed border (matching refl_texture_1d).
|
|
536
|
+
"""
|
|
537
|
+
if kernel_mode not in ("uniform", "varying"):
|
|
538
|
+
raise ValueError(
|
|
539
|
+
f"kernel_mode must be 'uniform' or 'varying', got {kernel_mode!r}"
|
|
540
|
+
)
|
|
541
|
+
|
|
542
|
+
dbz = np.asarray(dbz, dtype=float)
|
|
543
|
+
# Null out dbz below min_valid_dbz BEFORE any downstream computation,
|
|
544
|
+
# mirroring refl_texture_2d(). Sub-threshold values left in place would
|
|
545
|
+
# otherwise participate as valid neighbours in the window statistic and
|
|
546
|
+
# inflate texture near the edges of valid-data regions.
|
|
547
|
+
#
|
|
548
|
+
# The default is -inf (no gating), NOT 0.0 as in the 2-D/3-D path:
|
|
549
|
+
# min_valid_dbz ports ConvStratFinder::computeEchoType()'s prefilter,
|
|
550
|
+
# which has no analog in f_reflTexture.m. EccoPy-2D-V agrees with real
|
|
551
|
+
# MATLAB ECCO-V output at 99.4-100% without it; gating at 0 dBZ moves
|
|
552
|
+
# that output by ~13%. Callers that want the C++ behaviour set it
|
|
553
|
+
# explicitly. See TextureParams.min_valid_dbz.
|
|
554
|
+
if min_valid_dbz > -np.inf:
|
|
555
|
+
dbz = np.where(dbz < min_valid_dbz, np.nan, dbz)
|
|
556
|
+
|
|
557
|
+
orig_shape = dbz.shape
|
|
558
|
+
n = orig_shape[-1]
|
|
559
|
+
|
|
560
|
+
if isinstance(window, int):
|
|
561
|
+
window = WindowSpec(window)
|
|
562
|
+
|
|
563
|
+
flat = dbz.reshape(-1, n)
|
|
564
|
+
nRows = flat.shape[0]
|
|
565
|
+
|
|
566
|
+
if window.is_pixel:
|
|
567
|
+
radius_field_2d = np.full((nRows, n), int(window.size), dtype=int)
|
|
568
|
+
else:
|
|
569
|
+
if spacing is None:
|
|
570
|
+
raise ValueError(
|
|
571
|
+
"A physical-unit WindowSpec requires a spacing array; "
|
|
572
|
+
"got spacing=None. Pass an integer pixel radius instead, "
|
|
573
|
+
"or provide a spacing array."
|
|
574
|
+
)
|
|
575
|
+
spacing = np.asarray(spacing, dtype=float)
|
|
576
|
+
if spacing.ndim == 1:
|
|
577
|
+
if spacing.shape[0] != n:
|
|
578
|
+
raise ValueError(
|
|
579
|
+
f"spacing array length ({spacing.shape[0]}) along the "
|
|
580
|
+
f"texture axis must match the data length ({n})."
|
|
581
|
+
)
|
|
582
|
+
spacing_rows = np.broadcast_to(spacing, (nRows, n))
|
|
583
|
+
else:
|
|
584
|
+
if spacing.shape[-1] != n:
|
|
585
|
+
raise ValueError(
|
|
586
|
+
f"spacing array's last-axis length ({spacing.shape[-1]}) "
|
|
587
|
+
f"must match the data length ({n})."
|
|
588
|
+
)
|
|
589
|
+
spacing_rows = spacing.reshape(-1, n)
|
|
590
|
+
if spacing_rows.shape[0] == 1:
|
|
591
|
+
spacing_rows = np.broadcast_to(spacing_rows, (nRows, n))
|
|
592
|
+
elif spacing_rows.shape[0] != nRows:
|
|
593
|
+
raise ValueError(
|
|
594
|
+
f"spacing has {spacing_rows.shape[0]} row(s) after "
|
|
595
|
+
f"flattening its leading dimensions, but dbz has "
|
|
596
|
+
f"{nRows} row(s) after the same flattening; spacing "
|
|
597
|
+
f"must have either 1 row (shared across every row) or "
|
|
598
|
+
f"exactly {nRows} rows (one genuine spacing profile "
|
|
599
|
+
f"per row) -- anything else is ambiguous, so this "
|
|
600
|
+
f"raises rather than guessing which row(s) to use."
|
|
601
|
+
)
|
|
602
|
+
|
|
603
|
+
if kernel_mode == "uniform":
|
|
604
|
+
median_spacing = np.array(float(np.nanmedian(spacing_rows)))
|
|
605
|
+
r = int(window.pixel_radius_field(median_spacing))
|
|
606
|
+
radius_field_2d = np.full((nRows, n), r, dtype=int)
|
|
607
|
+
else:
|
|
608
|
+
radius_field_2d = window.pixel_radius_field(spacing_rows)
|
|
609
|
+
|
|
610
|
+
pad = int(radius_field_2d.max()) if radius_field_2d.size else 0
|
|
611
|
+
|
|
612
|
+
if pad > 0:
|
|
613
|
+
padded = np.pad(flat, ((0, 0), (pad, pad)), mode="constant",
|
|
614
|
+
constant_values=np.nan)
|
|
615
|
+
else:
|
|
616
|
+
padded = flat.copy()
|
|
617
|
+
|
|
618
|
+
padded = _fillmissing_linear(padded, axis=1)
|
|
619
|
+
padded = padded - dbz_base
|
|
620
|
+
|
|
621
|
+
if nRows <= 1 or np.all(radius_field_2d == radius_field_2d[0]):
|
|
622
|
+
texture, fitted, detrended = _sliding_texture_core_with_fit(
|
|
623
|
+
padded, radius_field_2d[0], pad, nRows, n)
|
|
624
|
+
else:
|
|
625
|
+
texture = np.full((nRows, n), np.nan)
|
|
626
|
+
fitted = np.full((nRows, n), np.nan)
|
|
627
|
+
detrended = np.full((nRows, n), np.nan)
|
|
628
|
+
for row in range(nRows):
|
|
629
|
+
t, f, d = _sliding_texture_core_with_fit(
|
|
630
|
+
padded[row:row + 1], radius_field_2d[row], pad, 1, n)
|
|
631
|
+
texture[row:row + 1] = t
|
|
632
|
+
fitted[row:row + 1] = f
|
|
633
|
+
detrended[row:row + 1] = d
|
|
634
|
+
|
|
635
|
+
nan_mask = np.isnan(flat)
|
|
636
|
+
texture[nan_mask] = np.nan
|
|
637
|
+
detrended[nan_mask] = np.nan
|
|
638
|
+
|
|
639
|
+
return (texture.reshape(orig_shape), fitted.reshape(orig_shape) + dbz_base,
|
|
640
|
+
detrended.reshape(orig_shape) + dbz_base)
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
|
|
645
|
+
# ---------------------------------------------------------------------------
|
|
646
|
+
# 2-D radial texture (used by EccoPy-3D)
|
|
647
|
+
# ---------------------------------------------------------------------------
|
|
648
|
+
|
|
649
|
+
def _build_kernel_offsets_uniform(radius_km: float, dx_km: float, dy_km: float):
|
|
650
|
+
"""
|
|
651
|
+
Pre-compute kernel offsets for a UNIFORM-spacing approximation,
|
|
652
|
+
identical to ConvStratFinder::_computeKernels(). LROSE itself uses
|
|
653
|
+
this approach even for lat/lon grids: a single dx_km/dy_km computed
|
|
654
|
+
once at the domain's mean latitude (see refl_texture_2d's
|
|
655
|
+
kernel_mode="uniform").
|
|
656
|
+
|
|
657
|
+
Returns offsets as a list of (jdx, jdy, xx, yy) tuples. This is the
|
|
658
|
+
interface used by eccopy.core.debug (which iterates the list
|
|
659
|
+
directly); see _build_kernel_offsets_uniform_arrays() for the
|
|
660
|
+
typed-array equivalent used internally by the JIT-compiled texture
|
|
661
|
+
functions, which cannot accept Python lists of tuples.
|
|
662
|
+
"""
|
|
663
|
+
r_km = radius_km
|
|
664
|
+
ny_tex = int(np.floor(r_km / dy_km + 0.5))
|
|
665
|
+
nx_tex = int(np.floor(r_km / dx_km + 0.5))
|
|
666
|
+
while ny_tex < 2 or nx_tex < 2:
|
|
667
|
+
r_km *= 1.1
|
|
668
|
+
ny_tex = int(np.floor(r_km / dy_km + 0.5))
|
|
669
|
+
nx_tex = int(np.floor(r_km / dx_km + 0.5))
|
|
670
|
+
|
|
671
|
+
offsets = []
|
|
672
|
+
for jdy in range(-ny_tex, ny_tex + 1):
|
|
673
|
+
yy = jdy * dy_km
|
|
674
|
+
for jdx in range(-nx_tex, nx_tex + 1):
|
|
675
|
+
xx = jdx * dx_km
|
|
676
|
+
if np.sqrt(yy * yy + xx * xx) <= r_km:
|
|
677
|
+
offsets.append((jdx, jdy, xx, yy))
|
|
678
|
+
return offsets, nx_tex, ny_tex
|
|
679
|
+
|
|
680
|
+
|
|
681
|
+
def _build_kernel_offsets_uniform_arrays(radius_km: float, dx_km: float, dy_km: float):
|
|
682
|
+
"""
|
|
683
|
+
Same kernel as _build_kernel_offsets_uniform(), but returned as four
|
|
684
|
+
typed NumPy arrays (jdx, jdy, xx, yy) instead of a list of tuples -
|
|
685
|
+
the form the JIT-compiled texture functions need, since Numba's
|
|
686
|
+
nopython mode cannot work with Python lists of heterogeneous tuples.
|
|
687
|
+
"""
|
|
688
|
+
offsets, nx_tex, ny_tex = _build_kernel_offsets_uniform(radius_km, dx_km, dy_km)
|
|
689
|
+
n = len(offsets)
|
|
690
|
+
jdx_arr = np.empty(n, dtype=np.int64)
|
|
691
|
+
jdy_arr = np.empty(n, dtype=np.int64)
|
|
692
|
+
xx_arr = np.empty(n, dtype=np.float64)
|
|
693
|
+
yy_arr = np.empty(n, dtype=np.float64)
|
|
694
|
+
for k, (jdx, jdy, xx, yy) in enumerate(offsets):
|
|
695
|
+
jdx_arr[k] = jdx
|
|
696
|
+
jdy_arr[k] = jdy
|
|
697
|
+
xx_arr[k] = xx
|
|
698
|
+
yy_arr[k] = yy
|
|
699
|
+
return jdx_arr, jdy_arr, xx_arr, yy_arr, nx_tex, ny_tex
|
|
700
|
+
|
|
701
|
+
|
|
702
|
+
@njit(cache=True)
|
|
703
|
+
def _max_half_width_core(radius_km: float, dx_km: np.ndarray, dy_km: np.ndarray):
|
|
704
|
+
"""
|
|
705
|
+
JIT-compiled core for _max_half_width(). Uses an explicit scan for
|
|
706
|
+
the minimum positive spacing rather than boolean-mask fancy indexing
|
|
707
|
+
(dx_km[dx_km > 0]) - equivalent result, but the form Numba compiles
|
|
708
|
+
most efficiently for this access pattern.
|
|
709
|
+
"""
|
|
710
|
+
min_dy = np.inf
|
|
711
|
+
found_dy = False
|
|
712
|
+
for v in dy_km.flat:
|
|
713
|
+
if v > 0 and v < min_dy:
|
|
714
|
+
min_dy = v
|
|
715
|
+
found_dy = True
|
|
716
|
+
if not found_dy:
|
|
717
|
+
min_dy = radius_km
|
|
718
|
+
|
|
719
|
+
min_dx = np.inf
|
|
720
|
+
found_dx = False
|
|
721
|
+
for v in dx_km.flat:
|
|
722
|
+
if v > 0 and v < min_dx:
|
|
723
|
+
min_dx = v
|
|
724
|
+
found_dx = True
|
|
725
|
+
if not found_dx:
|
|
726
|
+
min_dx = radius_km
|
|
727
|
+
|
|
728
|
+
ny_tex = max(1, int(np.floor(radius_km / min_dy + 0.5)))
|
|
729
|
+
nx_tex = max(1, int(np.floor(radius_km / min_dx + 0.5)))
|
|
730
|
+
return nx_tex, ny_tex
|
|
731
|
+
|
|
732
|
+
|
|
733
|
+
def _max_half_width(radius_km: float, dx_km: np.ndarray, dy_km: np.ndarray):
|
|
734
|
+
"""
|
|
735
|
+
Conservative (worst-case) half-width in grid cells needed to contain
|
|
736
|
+
a `radius_km` circle anywhere on a varying-spacing grid - used to
|
|
737
|
+
size the border that must be excluded from per-point kernel mode
|
|
738
|
+
(the finest spacing anywhere in the grid determines the largest
|
|
739
|
+
possible cell count).
|
|
740
|
+
|
|
741
|
+
Uses the same floor(r/spacing + 0.5) convention as
|
|
742
|
+
_build_kernel_offsets_uniform / _point_kernel_offsets, so that on a
|
|
743
|
+
perfectly uniform grid this produces exactly the same margin as the
|
|
744
|
+
uniform-kernel path (kernel_mode="uniform" and "varying" should
|
|
745
|
+
agree exactly on a uniform grid).
|
|
746
|
+
"""
|
|
747
|
+
return _max_half_width_core(radius_km, dx_km, dy_km)
|
|
748
|
+
|
|
749
|
+
|
|
750
|
+
def _point_kernel_offsets(radius_km: float, dx_km_pt: float, dy_km_pt: float):
|
|
751
|
+
"""
|
|
752
|
+
Build kernel offsets for ONE point's local spacing (per-point mode).
|
|
753
|
+
Returns a list of (jdx, jdy, xx, yy) tuples - the interface used by
|
|
754
|
+
eccopy.core.debug; see _point_kernel_offsets_arrays() for the
|
|
755
|
+
typed-array equivalent used internally by the JIT-compiled texture
|
|
756
|
+
functions.
|
|
757
|
+
"""
|
|
758
|
+
r_km = radius_km
|
|
759
|
+
ny_tex = max(1, int(np.floor(r_km / dy_km_pt + 0.5)))
|
|
760
|
+
nx_tex = max(1, int(np.floor(r_km / dx_km_pt + 0.5)))
|
|
761
|
+
offsets = []
|
|
762
|
+
for jdy in range(-ny_tex, ny_tex + 1):
|
|
763
|
+
yy = jdy * dy_km_pt
|
|
764
|
+
for jdx in range(-nx_tex, nx_tex + 1):
|
|
765
|
+
xx = jdx * dx_km_pt
|
|
766
|
+
if np.sqrt(yy * yy + xx * xx) <= r_km:
|
|
767
|
+
offsets.append((jdx, jdy, xx, yy))
|
|
768
|
+
return offsets, nx_tex, ny_tex
|
|
769
|
+
|
|
770
|
+
|
|
771
|
+
@njit(cache=True)
|
|
772
|
+
def _point_kernel_offsets_arrays(radius_km: float, dx_km_pt: float, dy_km_pt: float):
|
|
773
|
+
"""
|
|
774
|
+
Same kernel as _point_kernel_offsets(), but returned as typed NumPy
|
|
775
|
+
arrays instead of a list of tuples, and JIT-compiled directly since
|
|
776
|
+
this gets called fresh at EVERY grid point in kernel_mode="varying"
|
|
777
|
+
(unlike the uniform-grid kernel, which is built once and reused).
|
|
778
|
+
"""
|
|
779
|
+
r_km = radius_km
|
|
780
|
+
ny_tex = max(1, int(np.floor(r_km / dy_km_pt + 0.5)))
|
|
781
|
+
nx_tex = max(1, int(np.floor(r_km / dx_km_pt + 0.5)))
|
|
782
|
+
|
|
783
|
+
count = 0
|
|
784
|
+
for jdy in range(-ny_tex, ny_tex + 1):
|
|
785
|
+
yy = jdy * dy_km_pt
|
|
786
|
+
for jdx in range(-nx_tex, nx_tex + 1):
|
|
787
|
+
xx = jdx * dx_km_pt
|
|
788
|
+
if np.sqrt(yy * yy + xx * xx) <= r_km:
|
|
789
|
+
count += 1
|
|
790
|
+
|
|
791
|
+
jdx_arr = np.empty(count, dtype=np.int64)
|
|
792
|
+
jdy_arr = np.empty(count, dtype=np.int64)
|
|
793
|
+
xx_arr = np.empty(count, dtype=np.float64)
|
|
794
|
+
yy_arr = np.empty(count, dtype=np.float64)
|
|
795
|
+
k = 0
|
|
796
|
+
for jdy in range(-ny_tex, ny_tex + 1):
|
|
797
|
+
yy = jdy * dy_km_pt
|
|
798
|
+
for jdx in range(-nx_tex, nx_tex + 1):
|
|
799
|
+
xx = jdx * dx_km_pt
|
|
800
|
+
if np.sqrt(yy * yy + xx * xx) <= r_km:
|
|
801
|
+
jdx_arr[k] = jdx
|
|
802
|
+
jdy_arr[k] = jdy
|
|
803
|
+
xx_arr[k] = xx
|
|
804
|
+
yy_arr[k] = yy
|
|
805
|
+
k += 1
|
|
806
|
+
|
|
807
|
+
return jdx_arr, jdy_arr, xx_arr, yy_arr, nx_tex, ny_tex
|
|
808
|
+
|
|
809
|
+
|
|
810
|
+
@njit(cache=True)
|
|
811
|
+
def _compute_fraction_active_varying(dbz_col_max: np.ndarray,
|
|
812
|
+
radius_km: float,
|
|
813
|
+
dx_km: np.ndarray,
|
|
814
|
+
dy_km: np.ndarray,
|
|
815
|
+
min_valid_dbz: float,
|
|
816
|
+
max_nx_tex: int,
|
|
817
|
+
max_ny_tex: int) -> np.ndarray:
|
|
818
|
+
"""
|
|
819
|
+
Coverage fraction array using a PER-POINT kernel, rebuilt from the
|
|
820
|
+
local dx_km[y,x]/dy_km[y,x] at every grid point. Slower than the
|
|
821
|
+
uniform-grid version but correct on grids where spacing varies
|
|
822
|
+
significantly (e.g. large lat/lon domains).
|
|
823
|
+
|
|
824
|
+
JIT-compiled, including the per-point kernel rebuild (via
|
|
825
|
+
_point_kernel_offsets_arrays, itself @njit) - Numba supports calling
|
|
826
|
+
one JIT-compiled function from another directly.
|
|
827
|
+
"""
|
|
828
|
+
ny, nx = dbz_col_max.shape
|
|
829
|
+
fraction = np.zeros((ny, nx), dtype=np.float64)
|
|
830
|
+
|
|
831
|
+
for iy in range(max_ny_tex, ny - max_ny_tex):
|
|
832
|
+
for ix in range(max_nx_tex, nx - max_nx_tex):
|
|
833
|
+
jdx_arr, jdy_arr, xx_arr, yy_arr, _, _ = _point_kernel_offsets_arrays(
|
|
834
|
+
radius_km, dx_km[iy, ix], dy_km[iy, ix]
|
|
835
|
+
)
|
|
836
|
+
n_kernel = len(jdx_arr)
|
|
837
|
+
if n_kernel == 0:
|
|
838
|
+
continue
|
|
839
|
+
count = 0
|
|
840
|
+
for k in range(n_kernel):
|
|
841
|
+
if dbz_col_max[iy + jdy_arr[k], ix + jdx_arr[k]] >= min_valid_dbz:
|
|
842
|
+
count += 1
|
|
843
|
+
fraction[iy, ix] = count / n_kernel
|
|
844
|
+
|
|
845
|
+
return fraction
|
|
846
|
+
|
|
847
|
+
|
|
848
|
+
@njit(cache=True)
|
|
849
|
+
def _compute_texture_one_level_varying(dbz_level: np.ndarray,
|
|
850
|
+
fraction_active: np.ndarray,
|
|
851
|
+
radius_km: float,
|
|
852
|
+
dx_km: np.ndarray,
|
|
853
|
+
dy_km: np.ndarray,
|
|
854
|
+
base_dbz: float,
|
|
855
|
+
min_frac_texture: float,
|
|
856
|
+
min_frac_fit: float,
|
|
857
|
+
max_nx_tex: int,
|
|
858
|
+
max_ny_tex: int) -> np.ndarray:
|
|
859
|
+
"""
|
|
860
|
+
Per-point-kernel version of _compute_texture_one_level: the circular
|
|
861
|
+
kernel footprint is rebuilt from the LOCAL dx_km[y,x]/dy_km[y,x] at
|
|
862
|
+
every point, so the physical kernel radius stays consistent even
|
|
863
|
+
when grid spacing varies substantially across the domain (e.g. a
|
|
864
|
+
lat/lon grid spanning a wide latitude range, where dx shrinks with
|
|
865
|
+
cos(latitude) but dy stays roughly constant).
|
|
866
|
+
|
|
867
|
+
This is NOT what the validated LROSE ConvStratFinder algorithm does
|
|
868
|
+
(LROSE uses a single dx_km/dy_km for the whole grid, computed at the
|
|
869
|
+
domain's mean latitude - see _build_kernel_offsets_uniform). Results
|
|
870
|
+
from this mode have not been validated against LROSE output and may
|
|
871
|
+
differ from it on grids where LROSE's single-kernel approximation
|
|
872
|
+
breaks down.
|
|
873
|
+
|
|
874
|
+
JIT-compiled; see _compute_texture_one_level_core()'s docstring for
|
|
875
|
+
the same notes on the normal-equations plane fit replacing
|
|
876
|
+
np.linalg.lstsq (not supported in Numba's nopython mode), which
|
|
877
|
+
apply identically here.
|
|
878
|
+
"""
|
|
879
|
+
ny, nx = dbz_level.shape
|
|
880
|
+
texture = np.full((ny, nx), np.nan, dtype=np.float64)
|
|
881
|
+
|
|
882
|
+
for iy in range(max_ny_tex, ny - max_ny_tex):
|
|
883
|
+
for ix in range(max_nx_tex, nx - max_nx_tex):
|
|
884
|
+
if fraction_active[iy, ix] < min_frac_texture:
|
|
885
|
+
continue
|
|
886
|
+
center_val = dbz_level[iy, ix]
|
|
887
|
+
if np.isnan(center_val):
|
|
888
|
+
continue
|
|
889
|
+
|
|
890
|
+
jdx_arr, jdy_arr, xx_arr, yy_arr, _, _ = _point_kernel_offsets_arrays(
|
|
891
|
+
radius_km, dx_km[iy, ix], dy_km[iy, ix]
|
|
892
|
+
)
|
|
893
|
+
n_kernel = len(jdx_arr)
|
|
894
|
+
if n_kernel == 0:
|
|
895
|
+
continue
|
|
896
|
+
|
|
897
|
+
min_pts_texture = int(min_frac_texture * n_kernel + 0.5)
|
|
898
|
+
min_pts_fit = int(min_frac_fit * n_kernel + 0.5)
|
|
899
|
+
|
|
900
|
+
vals = np.empty(n_kernel, dtype=np.float64)
|
|
901
|
+
vxx = np.empty(n_kernel, dtype=np.float64)
|
|
902
|
+
vyy = np.empty(n_kernel, dtype=np.float64)
|
|
903
|
+
|
|
904
|
+
count = 0
|
|
905
|
+
sum_dbz = 0.0
|
|
906
|
+
for k in range(n_kernel):
|
|
907
|
+
v = dbz_level[iy + jdy_arr[k], ix + jdx_arr[k]]
|
|
908
|
+
if not np.isnan(v):
|
|
909
|
+
vals[count] = v
|
|
910
|
+
vxx[count] = xx_arr[k]
|
|
911
|
+
vyy[count] = yy_arr[k]
|
|
912
|
+
sum_dbz += v
|
|
913
|
+
count += 1
|
|
914
|
+
|
|
915
|
+
if count < min_pts_texture:
|
|
916
|
+
continue
|
|
917
|
+
|
|
918
|
+
mean_dbz = sum_dbz / count
|
|
919
|
+
if mean_dbz < 1.0:
|
|
920
|
+
mean_dbz = 1.0
|
|
921
|
+
|
|
922
|
+
if count >= min_pts_fit:
|
|
923
|
+
Sx = 0.0; Sy = 0.0; Sxx = 0.0; Syy = 0.0; Sxy = 0.0
|
|
924
|
+
Sz = 0.0; Sxz = 0.0; Syz = 0.0
|
|
925
|
+
for i in range(count):
|
|
926
|
+
x = vxx[i]; y = vyy[i]; z = vals[i]
|
|
927
|
+
Sx += x; Sy += y
|
|
928
|
+
Sxx += x * x; Syy += y * y; Sxy += x * y
|
|
929
|
+
Sz += z; Sxz += x * z; Syz += y * z
|
|
930
|
+
n = float(count)
|
|
931
|
+
|
|
932
|
+
m00 = Sxx; m01 = Sxy; m02 = Sx
|
|
933
|
+
m10 = Sxy; m11 = Syy; m12 = Sy
|
|
934
|
+
m20 = Sx; m21 = Sy; m22 = n
|
|
935
|
+
b0 = Sxz; b1 = Syz; b2 = Sz
|
|
936
|
+
|
|
937
|
+
det = (m00 * (m11 * m22 - m12 * m21)
|
|
938
|
+
- m01 * (m10 * m22 - m12 * m20)
|
|
939
|
+
+ m02 * (m10 * m21 - m11 * m20))
|
|
940
|
+
|
|
941
|
+
if abs(det) > 1e-12:
|
|
942
|
+
aa = (b0 * (m11 * m22 - m12 * m21)
|
|
943
|
+
- m01 * (b1 * m22 - m12 * b2)
|
|
944
|
+
+ m02 * (b1 * m21 - m11 * b2)) / det
|
|
945
|
+
bb = (m00 * (b1 * m22 - m12 * b2)
|
|
946
|
+
- b0 * (m10 * m22 - m12 * m20)
|
|
947
|
+
+ m02 * (m10 * b2 - b1 * m20)) / det
|
|
948
|
+
for i in range(count):
|
|
949
|
+
vals[i] -= aa * vxx[i] + bb * vyy[i]
|
|
950
|
+
|
|
951
|
+
sum_sq = 0.0
|
|
952
|
+
sum_sq2 = 0.0
|
|
953
|
+
nn = 0.0
|
|
954
|
+
for i in range(count):
|
|
955
|
+
val = vals[i] - base_dbz
|
|
956
|
+
if val < 1.0:
|
|
957
|
+
val = 1.0
|
|
958
|
+
dbz_sq = val * val
|
|
959
|
+
sum_sq += dbz_sq
|
|
960
|
+
sum_sq2 += dbz_sq * dbz_sq
|
|
961
|
+
nn += 1.0
|
|
962
|
+
|
|
963
|
+
n_missing = n_kernel - count
|
|
964
|
+
if n_missing > 0:
|
|
965
|
+
min_sq = mean_dbz * mean_dbz
|
|
966
|
+
sum_sq += n_missing * min_sq
|
|
967
|
+
sum_sq2 += n_missing * min_sq * min_sq
|
|
968
|
+
nn += n_missing
|
|
969
|
+
|
|
970
|
+
if nn < 1:
|
|
971
|
+
continue
|
|
972
|
+
|
|
973
|
+
mean_sq = sum_sq / nn
|
|
974
|
+
var = sum_sq2 / nn - mean_sq * mean_sq
|
|
975
|
+
if var < 0.0:
|
|
976
|
+
var = 0.0
|
|
977
|
+
tex = np.sqrt(np.sqrt(var))
|
|
978
|
+
if not np.isnan(tex):
|
|
979
|
+
texture[iy, ix] = tex
|
|
980
|
+
|
|
981
|
+
return texture
|
|
982
|
+
|
|
983
|
+
|
|
984
|
+
@njit(cache=True)
|
|
985
|
+
def _compute_fraction_active_core(dbz_col_max: np.ndarray,
|
|
986
|
+
jdx_arr: np.ndarray,
|
|
987
|
+
jdy_arr: np.ndarray,
|
|
988
|
+
nx_tex: int,
|
|
989
|
+
ny_tex: int,
|
|
990
|
+
min_valid_dbz: float) -> np.ndarray:
|
|
991
|
+
"""JIT-compiled core for _compute_fraction_active()."""
|
|
992
|
+
ny, nx = dbz_col_max.shape
|
|
993
|
+
n_kernel = len(jdx_arr)
|
|
994
|
+
fraction = np.zeros((ny, nx), dtype=np.float64)
|
|
995
|
+
|
|
996
|
+
for iy in range(ny_tex, ny - ny_tex):
|
|
997
|
+
for ix in range(nx_tex, nx - nx_tex):
|
|
998
|
+
count = 0
|
|
999
|
+
for k in range(n_kernel):
|
|
1000
|
+
v = dbz_col_max[iy + jdy_arr[k], ix + jdx_arr[k]]
|
|
1001
|
+
if v >= min_valid_dbz:
|
|
1002
|
+
count += 1
|
|
1003
|
+
fraction[iy, ix] = count / n_kernel
|
|
1004
|
+
|
|
1005
|
+
return fraction
|
|
1006
|
+
|
|
1007
|
+
|
|
1008
|
+
def _compute_fraction_active(dbz_col_max: np.ndarray,
|
|
1009
|
+
offsets: list,
|
|
1010
|
+
nx_tex: int,
|
|
1011
|
+
ny_tex: int,
|
|
1012
|
+
min_valid_dbz: float) -> np.ndarray:
|
|
1013
|
+
"""
|
|
1014
|
+
Coverage fraction array from column-max DBZ (uniform-grid kernel).
|
|
1015
|
+
|
|
1016
|
+
`offsets` is a list of (jdx, jdy, xx, yy) tuples, matching
|
|
1017
|
+
_build_kernel_offsets_uniform()'s return value - kept as the public
|
|
1018
|
+
interface (used directly by eccopy.core.debug) while the actual
|
|
1019
|
+
computation happens in the JIT-compiled _compute_fraction_active_core().
|
|
1020
|
+
"""
|
|
1021
|
+
n = len(offsets)
|
|
1022
|
+
jdx_arr = np.empty(n, dtype=np.int64)
|
|
1023
|
+
jdy_arr = np.empty(n, dtype=np.int64)
|
|
1024
|
+
for k, (jdx, jdy, _, _) in enumerate(offsets):
|
|
1025
|
+
jdx_arr[k] = jdx
|
|
1026
|
+
jdy_arr[k] = jdy
|
|
1027
|
+
return _compute_fraction_active_core(dbz_col_max, jdx_arr, jdy_arr,
|
|
1028
|
+
nx_tex, ny_tex, min_valid_dbz)
|
|
1029
|
+
|
|
1030
|
+
|
|
1031
|
+
@njit(cache=True)
|
|
1032
|
+
def _compute_texture_one_level_core(dbz_level: np.ndarray,
|
|
1033
|
+
fraction_active: np.ndarray,
|
|
1034
|
+
jdx_arr: np.ndarray,
|
|
1035
|
+
jdy_arr: np.ndarray,
|
|
1036
|
+
xx_arr: np.ndarray,
|
|
1037
|
+
yy_arr: np.ndarray,
|
|
1038
|
+
nx_tex: int,
|
|
1039
|
+
ny_tex: int,
|
|
1040
|
+
base_dbz: float,
|
|
1041
|
+
min_frac_texture: float,
|
|
1042
|
+
min_frac_fit: float) -> np.ndarray:
|
|
1043
|
+
"""
|
|
1044
|
+
JIT-compiled core for _compute_texture_one_level().
|
|
1045
|
+
|
|
1046
|
+
Implementation notes vs. the original:
|
|
1047
|
+
- The plane fit (z = a*x + b*y, fit by least squares over the
|
|
1048
|
+
valid kernel points) is solved via the 2x2 normal equations
|
|
1049
|
+
instead of np.linalg.lstsq, since lstsq is not supported in
|
|
1050
|
+
Numba's nopython mode. This is mathematically equivalent to
|
|
1051
|
+
lstsq EXCEPT when the system is singular/rank-deficient (e.g.
|
|
1052
|
+
all valid points collinear) - the original handled that via
|
|
1053
|
+
`except np.linalg.LinAlgError: pass` (silently skip detrending);
|
|
1054
|
+
this version checks the normal-equations determinant directly
|
|
1055
|
+
and does the same thing if it's too close to zero to invert
|
|
1056
|
+
reliably.
|
|
1057
|
+
- Per-point working buffers (vals/xx/yy) are pre-allocated to the
|
|
1058
|
+
kernel size and reused, rather than appending to Python lists
|
|
1059
|
+
(also unsupported in nopython mode for this access pattern).
|
|
1060
|
+
"""
|
|
1061
|
+
ny, nx = dbz_level.shape
|
|
1062
|
+
n_kernel = len(jdx_arr)
|
|
1063
|
+
texture = np.full((ny, nx), np.nan, dtype=np.float64)
|
|
1064
|
+
|
|
1065
|
+
min_pts_texture = int(min_frac_texture * n_kernel + 0.5)
|
|
1066
|
+
min_pts_fit = int(min_frac_fit * n_kernel + 0.5)
|
|
1067
|
+
|
|
1068
|
+
vals = np.empty(n_kernel, dtype=np.float64)
|
|
1069
|
+
vxx = np.empty(n_kernel, dtype=np.float64)
|
|
1070
|
+
vyy = np.empty(n_kernel, dtype=np.float64)
|
|
1071
|
+
|
|
1072
|
+
for iy in range(ny_tex, ny - ny_tex):
|
|
1073
|
+
for ix in range(nx_tex, nx - nx_tex):
|
|
1074
|
+
if fraction_active[iy, ix] < min_frac_texture:
|
|
1075
|
+
continue
|
|
1076
|
+
center_val = dbz_level[iy, ix]
|
|
1077
|
+
if np.isnan(center_val):
|
|
1078
|
+
continue
|
|
1079
|
+
|
|
1080
|
+
count = 0
|
|
1081
|
+
sum_dbz = 0.0
|
|
1082
|
+
for k in range(n_kernel):
|
|
1083
|
+
v = dbz_level[iy + jdy_arr[k], ix + jdx_arr[k]]
|
|
1084
|
+
if not np.isnan(v):
|
|
1085
|
+
vals[count] = v
|
|
1086
|
+
vxx[count] = xx_arr[k]
|
|
1087
|
+
vyy[count] = yy_arr[k]
|
|
1088
|
+
sum_dbz += v
|
|
1089
|
+
count += 1
|
|
1090
|
+
|
|
1091
|
+
if count < min_pts_texture:
|
|
1092
|
+
continue
|
|
1093
|
+
|
|
1094
|
+
mean_dbz = sum_dbz / count
|
|
1095
|
+
if mean_dbz < 1.0:
|
|
1096
|
+
mean_dbz = 1.0
|
|
1097
|
+
|
|
1098
|
+
if count >= min_pts_fit:
|
|
1099
|
+
# Plane fit z = a*x + b*y + c via 3x3 normal equations
|
|
1100
|
+
# (equivalent to np.linalg.lstsq for this 3-parameter
|
|
1101
|
+
# fit, except when singular - see docstring above).
|
|
1102
|
+
Sx = 0.0; Sy = 0.0; Sxx = 0.0; Syy = 0.0; Sxy = 0.0
|
|
1103
|
+
Sz = 0.0; Sxz = 0.0; Syz = 0.0
|
|
1104
|
+
for i in range(count):
|
|
1105
|
+
x = vxx[i]; y = vyy[i]; z = vals[i]
|
|
1106
|
+
Sx += x; Sy += y
|
|
1107
|
+
Sxx += x * x; Syy += y * y; Sxy += x * y
|
|
1108
|
+
Sz += z; Sxz += x * z; Syz += y * z
|
|
1109
|
+
n = float(count)
|
|
1110
|
+
|
|
1111
|
+
m00 = Sxx; m01 = Sxy; m02 = Sx
|
|
1112
|
+
m10 = Sxy; m11 = Syy; m12 = Sy
|
|
1113
|
+
m20 = Sx; m21 = Sy; m22 = n
|
|
1114
|
+
b0 = Sxz; b1 = Syz; b2 = Sz
|
|
1115
|
+
|
|
1116
|
+
det = (m00 * (m11 * m22 - m12 * m21)
|
|
1117
|
+
- m01 * (m10 * m22 - m12 * m20)
|
|
1118
|
+
+ m02 * (m10 * m21 - m11 * m20))
|
|
1119
|
+
|
|
1120
|
+
if abs(det) > 1e-12:
|
|
1121
|
+
aa = (b0 * (m11 * m22 - m12 * m21)
|
|
1122
|
+
- m01 * (b1 * m22 - m12 * b2)
|
|
1123
|
+
+ m02 * (b1 * m21 - m11 * b2)) / det
|
|
1124
|
+
bb = (m00 * (b1 * m22 - m12 * b2)
|
|
1125
|
+
- b0 * (m10 * m22 - m12 * m20)
|
|
1126
|
+
+ m02 * (m10 * b2 - b1 * m20)) / det
|
|
1127
|
+
for i in range(count):
|
|
1128
|
+
vals[i] -= aa * vxx[i] + bb * vyy[i]
|
|
1129
|
+
# else: singular system (e.g. all points collinear) -
|
|
1130
|
+
# skip detrending, same as the original's
|
|
1131
|
+
# `except np.linalg.LinAlgError: pass`.
|
|
1132
|
+
|
|
1133
|
+
sum_sq = 0.0
|
|
1134
|
+
sum_sq2 = 0.0
|
|
1135
|
+
nn = 0.0
|
|
1136
|
+
for i in range(count):
|
|
1137
|
+
val = vals[i] - base_dbz
|
|
1138
|
+
if val < 1.0:
|
|
1139
|
+
val = 1.0
|
|
1140
|
+
dbz_sq = val * val
|
|
1141
|
+
sum_sq += dbz_sq
|
|
1142
|
+
sum_sq2 += dbz_sq * dbz_sq
|
|
1143
|
+
nn += 1.0
|
|
1144
|
+
|
|
1145
|
+
n_missing = n_kernel - count
|
|
1146
|
+
if n_missing > 0:
|
|
1147
|
+
min_sq = mean_dbz * mean_dbz
|
|
1148
|
+
sum_sq += n_missing * min_sq
|
|
1149
|
+
sum_sq2 += n_missing * min_sq * min_sq
|
|
1150
|
+
nn += n_missing
|
|
1151
|
+
|
|
1152
|
+
if nn < 1:
|
|
1153
|
+
continue
|
|
1154
|
+
|
|
1155
|
+
mean_sq = sum_sq / nn
|
|
1156
|
+
var = sum_sq2 / nn - mean_sq * mean_sq
|
|
1157
|
+
if var < 0.0:
|
|
1158
|
+
var = 0.0
|
|
1159
|
+
tex = np.sqrt(np.sqrt(var))
|
|
1160
|
+
if not np.isnan(tex):
|
|
1161
|
+
texture[iy, ix] = tex
|
|
1162
|
+
|
|
1163
|
+
return texture
|
|
1164
|
+
|
|
1165
|
+
|
|
1166
|
+
def _compute_texture_one_level(dbz_level: np.ndarray,
|
|
1167
|
+
fraction_active: np.ndarray,
|
|
1168
|
+
offsets: list,
|
|
1169
|
+
nx_tex: int,
|
|
1170
|
+
ny_tex: int,
|
|
1171
|
+
base_dbz: float,
|
|
1172
|
+
min_frac_texture: float,
|
|
1173
|
+
min_frac_fit: float) -> np.ndarray:
|
|
1174
|
+
"""
|
|
1175
|
+
2-D circular-neighbourhood texture with planar detrend, for one level.
|
|
1176
|
+
|
|
1177
|
+
Exact port of ConvStratFinder::ComputeTexture::run() (see module
|
|
1178
|
+
docstring in the original validated implementation):
|
|
1179
|
+
1. Skip center if fractionActive < min_frac_texture or center missing.
|
|
1180
|
+
2. Collect valid kernel neighbours; fit a plane; subtract it.
|
|
1181
|
+
3. Clamp each value to >= 1; missing kernel points substituted
|
|
1182
|
+
with mean_dbz^2.
|
|
1183
|
+
4. texture = sqrt(sqrt(population_var(dbz^2)))
|
|
1184
|
+
|
|
1185
|
+
`offsets` is a list of (jdx, jdy, xx, yy) tuples, matching
|
|
1186
|
+
_build_kernel_offsets_uniform()'s return value - kept as the public
|
|
1187
|
+
interface (used directly by eccopy.core.debug) while the actual
|
|
1188
|
+
computation happens in the JIT-compiled _compute_texture_one_level_core().
|
|
1189
|
+
"""
|
|
1190
|
+
n = len(offsets)
|
|
1191
|
+
jdx_arr = np.empty(n, dtype=np.int64)
|
|
1192
|
+
jdy_arr = np.empty(n, dtype=np.int64)
|
|
1193
|
+
xx_arr = np.empty(n, dtype=np.float64)
|
|
1194
|
+
yy_arr = np.empty(n, dtype=np.float64)
|
|
1195
|
+
for k, (jdx, jdy, xx, yy) in enumerate(offsets):
|
|
1196
|
+
jdx_arr[k] = jdx
|
|
1197
|
+
jdy_arr[k] = jdy
|
|
1198
|
+
xx_arr[k] = xx
|
|
1199
|
+
yy_arr[k] = yy
|
|
1200
|
+
return _compute_texture_one_level_core(
|
|
1201
|
+
dbz_level, fraction_active, jdx_arr, jdy_arr, xx_arr, yy_arr,
|
|
1202
|
+
nx_tex, ny_tex, base_dbz, min_frac_texture, min_frac_fit,
|
|
1203
|
+
)
|
|
1204
|
+
|
|
1205
|
+
|
|
1206
|
+
def refl_texture_2d(dbz: np.ndarray,
|
|
1207
|
+
texture_radius: Union["WindowSpec", float],
|
|
1208
|
+
dy: np.ndarray,
|
|
1209
|
+
dx: np.ndarray,
|
|
1210
|
+
base_dbz: float = 0.0,
|
|
1211
|
+
min_valid_dbz: float = 0.0,
|
|
1212
|
+
min_frac_texture: float = 0.25,
|
|
1213
|
+
min_frac_fit: float = 0.67,
|
|
1214
|
+
n_threads: int = 1,
|
|
1215
|
+
kernel_mode: str = "uniform") -> tuple:
|
|
1216
|
+
"""
|
|
1217
|
+
2-D circular-neighbourhood texture with planar detrend, per horizontal
|
|
1218
|
+
level, for EccoPy-3D / EccoPy-2D-H.
|
|
1219
|
+
|
|
1220
|
+
Port of ConvStratFinder::ComputeTexture::run() from lrose-core, with
|
|
1221
|
+
a choice of how to handle spatially-varying grid spacing (relevant
|
|
1222
|
+
for e.g. lat/lon grids, where dx shrinks with cos(latitude) but dy
|
|
1223
|
+
stays roughly constant):
|
|
1224
|
+
|
|
1225
|
+
kernel_mode="uniform" (default)
|
|
1226
|
+
Builds ONE kernel from a single representative dx_km/dy_km
|
|
1227
|
+
(the median of the supplied dy/dx arrays), reused at every
|
|
1228
|
+
point. This is what the validated LROSE ConvStratFinder
|
|
1229
|
+
algorithm itself does for lat/lon grids - it computes one
|
|
1230
|
+
dxKm/dyKm pair at the domain's mean latitude and applies it
|
|
1231
|
+
everywhere, rather than adjusting per point. Fast (one kernel
|
|
1232
|
+
built once); matches validated behaviour; becomes increasingly
|
|
1233
|
+
approximate as the domain's latitude range grows (the kernel
|
|
1234
|
+
is the wrong physical size away from the representative
|
|
1235
|
+
latitude). Appropriate for radar-sized domains (up to a few
|
|
1236
|
+
hundred km) or any grid where spacing doesn't vary much.
|
|
1237
|
+
|
|
1238
|
+
kernel_mode="varying"
|
|
1239
|
+
Rebuilds the kernel from the LOCAL dy[y,x]/dx[y,x] at every
|
|
1240
|
+
single grid point, so the kernel's physical footprint stays
|
|
1241
|
+
correct everywhere regardless of domain size. This is NOT what
|
|
1242
|
+
LROSE does, and has not been validated against LROSE output -
|
|
1243
|
+
it is a genuine algorithmic extension for domains where the
|
|
1244
|
+
single-kernel approximation breaks down (e.g. continental or
|
|
1245
|
+
global lat/lon grids). Substantially slower: a new kernel is
|
|
1246
|
+
built and a new plane fit performed at every point, rather than
|
|
1247
|
+
reusing one fixed kernel.
|
|
1248
|
+
|
|
1249
|
+
Parameters
|
|
1250
|
+
----------
|
|
1251
|
+
dbz : np.ndarray, shape (nz, ny, nx)
|
|
1252
|
+
Reflectivity volume. NaN where missing.
|
|
1253
|
+
texture_radius : WindowSpec or float (km)
|
|
1254
|
+
dy, dx : np.ndarray, shape (ny, nx)
|
|
1255
|
+
Local point-to-point spacing in km along y and x respectively
|
|
1256
|
+
(e.g. from eccopy.core.coords.latlon_to_xy_spacing, or derived
|
|
1257
|
+
from coordinate arrays via resolve_spacing()).
|
|
1258
|
+
base_dbz : float
|
|
1259
|
+
min_valid_dbz : float
|
|
1260
|
+
min_frac_texture : float
|
|
1261
|
+
min_frac_fit : float
|
|
1262
|
+
n_threads : int
|
|
1263
|
+
kernel_mode : {"uniform", "varying"}
|
|
1264
|
+
See above.
|
|
1265
|
+
|
|
1266
|
+
Returns
|
|
1267
|
+
-------
|
|
1268
|
+
texture : np.ndarray, shape (nz, ny, nx)
|
|
1269
|
+
fraction_active : np.ndarray, shape (ny, nx)
|
|
1270
|
+
"""
|
|
1271
|
+
if kernel_mode not in ("uniform", "varying"):
|
|
1272
|
+
raise ValueError(
|
|
1273
|
+
f"kernel_mode must be 'uniform' or 'varying', got {kernel_mode!r}"
|
|
1274
|
+
)
|
|
1275
|
+
|
|
1276
|
+
dbz = np.asarray(dbz, dtype=float)
|
|
1277
|
+
nz, ny, nx = dbz.shape
|
|
1278
|
+
dy = np.asarray(dy, dtype=float)
|
|
1279
|
+
dx = np.asarray(dx, dtype=float)
|
|
1280
|
+
if dy.shape != (ny, nx) or dx.shape != (ny, nx):
|
|
1281
|
+
raise ValueError(
|
|
1282
|
+
f"dy/dx must have shape (ny, nx) = {(ny, nx)}; "
|
|
1283
|
+
f"got dy.shape={dy.shape}, dx.shape={dx.shape}"
|
|
1284
|
+
)
|
|
1285
|
+
|
|
1286
|
+
# Null out dbz below min_valid_dbz before any downstream computation.
|
|
1287
|
+
# Port of ConvStratFinder::computeEchoType()'s prefiltering loop,
|
|
1288
|
+
# applied once to the whole volume before column-max, fraction_active
|
|
1289
|
+
# and per-level texture are computed from it. Gating only the
|
|
1290
|
+
# fraction_active coverage count would leave sub-threshold values
|
|
1291
|
+
# (e.g. -25 dBZ when min_valid_dbz=0) still participated as valid
|
|
1292
|
+
# neighbours in the texture plane-fit/variance calc, inflating texture
|
|
1293
|
+
# and convectivity near the edges of valid-data regions relative to
|
|
1294
|
+
# the C++ reference. Found via SPOL LOW truth comparison: ~191k pixels
|
|
1295
|
+
# where truth=Missing but EccoPy assigned a stratiform/mixed echo type.
|
|
1296
|
+
if min_valid_dbz > -np.inf:
|
|
1297
|
+
dbz = np.where(dbz < min_valid_dbz, np.nan, dbz)
|
|
1298
|
+
|
|
1299
|
+
# Resolve the texture radius in km.
|
|
1300
|
+
from ..params.window import WindowSpec as _WS
|
|
1301
|
+
if isinstance(texture_radius, (int, float)):
|
|
1302
|
+
radius_km = float(texture_radius)
|
|
1303
|
+
elif isinstance(texture_radius, _WS):
|
|
1304
|
+
if texture_radius.is_pixel:
|
|
1305
|
+
raise ValueError(
|
|
1306
|
+
"refl_texture_2d requires a physical (km) radius, not a "
|
|
1307
|
+
"bare pixel-count WindowSpec. Pass a float (km) or "
|
|
1308
|
+
"WindowSpec((radius, 'km'))."
|
|
1309
|
+
)
|
|
1310
|
+
# WindowSpec stores its physical size internally in base units
|
|
1311
|
+
# (metres for length); convert to km for this function's use.
|
|
1312
|
+
radius_km = texture_radius._base_value / 1000.0
|
|
1313
|
+
else:
|
|
1314
|
+
radius_km = float(texture_radius)
|
|
1315
|
+
|
|
1316
|
+
dbz_yx = np.transpose(dbz, (1, 2, 0)) # (ny, nx, nz)
|
|
1317
|
+
with warnings.catch_warnings():
|
|
1318
|
+
# An all-NaN column (no valid data at any level) is expected and
|
|
1319
|
+
# already handled below (replaced with -9999.0); suppress the
|
|
1320
|
+
# resulting "All-NaN slice encountered" RuntimeWarning from numpy.
|
|
1321
|
+
warnings.filterwarnings("ignore", message="All-NaN slice encountered")
|
|
1322
|
+
dbz_col_max = np.nanmax(dbz_yx, axis=2)
|
|
1323
|
+
dbz_col_max = np.where(np.isnan(dbz_col_max), -9999.0, dbz_col_max)
|
|
1324
|
+
|
|
1325
|
+
if kernel_mode == "uniform":
|
|
1326
|
+
# Single representative dx_km/dy_km for the whole grid - matches
|
|
1327
|
+
# LROSE's own mean-latitude approach for lat/lon grids.
|
|
1328
|
+
dy_km = float(np.nanmedian(dy))
|
|
1329
|
+
dx_km = float(np.nanmedian(dx))
|
|
1330
|
+
|
|
1331
|
+
# Built once as typed arrays (not the list-of-tuples form used
|
|
1332
|
+
# by eccopy.core.debug) and reused across every z-level below -
|
|
1333
|
+
# avoids rebuilding/reconverting the kernel per level.
|
|
1334
|
+
jdx_arr, jdy_arr, xx_arr, yy_arr, nx_tex, ny_tex = (
|
|
1335
|
+
_build_kernel_offsets_uniform_arrays(radius_km, dx_km, dy_km)
|
|
1336
|
+
)
|
|
1337
|
+
|
|
1338
|
+
fraction_active = _compute_fraction_active_core(
|
|
1339
|
+
dbz_col_max, jdx_arr, jdy_arr, nx_tex, ny_tex, min_valid_dbz
|
|
1340
|
+
)
|
|
1341
|
+
|
|
1342
|
+
def _process_level(iz):
|
|
1343
|
+
level = dbz_yx[:, :, iz].copy()
|
|
1344
|
+
t = _compute_texture_one_level_core(
|
|
1345
|
+
level, fraction_active, jdx_arr, jdy_arr, xx_arr, yy_arr,
|
|
1346
|
+
nx_tex, ny_tex, base_dbz, min_frac_texture, min_frac_fit
|
|
1347
|
+
)
|
|
1348
|
+
return iz, t
|
|
1349
|
+
|
|
1350
|
+
else: # kernel_mode == "varying"
|
|
1351
|
+
max_nx_tex, max_ny_tex = _max_half_width(radius_km, dx, dy)
|
|
1352
|
+
|
|
1353
|
+
# Warn if the texture radius is smaller than the local grid
|
|
1354
|
+
# spacing anywhere in the domain - the kernel degenerates to just
|
|
1355
|
+
# the center point there, making texture meaningless (always 0)
|
|
1356
|
+
# at those locations regardless of kernel_mode.
|
|
1357
|
+
coarsest_dx = float(np.nanmax(dx[dx > 0])) if np.any(dx > 0) else np.nan
|
|
1358
|
+
coarsest_dy = float(np.nanmax(dy[dy > 0])) if np.any(dy > 0) else np.nan
|
|
1359
|
+
if (np.isfinite(coarsest_dx) and coarsest_dx > radius_km) or \
|
|
1360
|
+
(np.isfinite(coarsest_dy) and coarsest_dy > radius_km):
|
|
1361
|
+
warnings.warn(
|
|
1362
|
+
f"texture_radius ({radius_km:.2f} km) is smaller than the "
|
|
1363
|
+
f"local grid spacing at some points (max dx={coarsest_dx:.2f} "
|
|
1364
|
+
f"km, max dy={coarsest_dy:.2f} km). At those points the "
|
|
1365
|
+
f"kernel degenerates to a single cell and texture will be "
|
|
1366
|
+
f"exactly 0 there (no meaningful neighbourhood exists). "
|
|
1367
|
+
f"Use a larger texture_radius or coarsen the grid for "
|
|
1368
|
+
f"physically meaningful results everywhere.",
|
|
1369
|
+
stacklevel=2,
|
|
1370
|
+
)
|
|
1371
|
+
|
|
1372
|
+
fraction_active = _compute_fraction_active_varying(
|
|
1373
|
+
dbz_col_max, radius_km, dx, dy, min_valid_dbz,
|
|
1374
|
+
max_nx_tex, max_ny_tex,
|
|
1375
|
+
)
|
|
1376
|
+
|
|
1377
|
+
def _process_level(iz):
|
|
1378
|
+
level = dbz_yx[:, :, iz].copy()
|
|
1379
|
+
t = _compute_texture_one_level_varying(
|
|
1380
|
+
level, fraction_active, radius_km, dx, dy,
|
|
1381
|
+
base_dbz, min_frac_texture, min_frac_fit,
|
|
1382
|
+
max_nx_tex, max_ny_tex,
|
|
1383
|
+
)
|
|
1384
|
+
return iz, t
|
|
1385
|
+
|
|
1386
|
+
texture_yx = np.full((ny, nx, nz), np.nan, dtype=float)
|
|
1387
|
+
|
|
1388
|
+
if n_threads > 1:
|
|
1389
|
+
with ThreadPoolExecutor(max_workers=n_threads) as ex:
|
|
1390
|
+
for iz, t in ex.map(_process_level, range(nz)):
|
|
1391
|
+
texture_yx[:, :, iz] = t
|
|
1392
|
+
else:
|
|
1393
|
+
for iz in range(nz):
|
|
1394
|
+
_, t = _process_level(iz)
|
|
1395
|
+
texture_yx[:, :, iz] = t
|
|
1396
|
+
|
|
1397
|
+
texture = np.transpose(texture_yx, (2, 0, 1)) # (nz, ny, nx)
|
|
1398
|
+
return texture, fraction_active
|