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,267 @@
1
+ """Colormaps and echo-type plotting utilities."""
2
+
3
+ from __future__ import annotations
4
+ import numpy as np
5
+ from matplotlib.colors import ListedColormap, BoundaryNorm, LinearSegmentedColormap, Normalize
6
+
7
+ # Sub-classified echo-type code → 1-based plot index (9-colour map)
8
+ ECHO_TYPE_TO_IDX = {14: 1, 16: 2, 18: 3, 25: 4,
9
+ 30: 5, 32: 6, 34: 7, 36: 8, 38: 9}
10
+
11
+ ECHO_TYPE_LABELS = [
12
+ "Strat Low", "Strat Mid", "Strat High",
13
+ "Mixed",
14
+ "Conv", "Conv Elev", "Conv Shallow", "Conv Mid", "Conv Deep",
15
+ ]
16
+
17
+ # Basic-only echo-type code (1=Strat, 2=Mixed, 3=Conv) → 1-based plot index
18
+ # (3-colour map), used by eccopy1d, eccopy2d_h, and eccopy2d_v/eccopy3d when
19
+ # no height/temp field is supplied.
20
+ BASIC_ECHO_TYPE_TO_IDX = {1: 1, 2: 2, 3: 3}
21
+ BASIC_ECHO_TYPE_LABELS = ["Stratiform", "Mixed", "Convective"]
22
+
23
+ _BASIC_ECHO_TYPE_COLORS = np.array([
24
+ [0.38, 0.42, 0.96], # 1 Stratiform
25
+ [0.32, 0.78, 0.59], # 2 Mixed
26
+ [1.00, 0.00, 0.00], # 3 Convective
27
+ ])
28
+
29
+ _ECHO_TYPE_COLORS = np.array([
30
+ [0, 0.10, 0.60], # 1 Strat Low
31
+ [0.38, 0.42, 0.96], # 2 Strat Mid
32
+ [0.65, 0.74, 0.86], # 3 Strat High
33
+ [0.32, 0.78, 0.59], # 4 Mixed
34
+ [1.00, 0.00, 0.00], # 5 Conv
35
+ [1.00, 0.00, 1.00], # 6 Conv Elev
36
+ [1.00, 1.00, 0.00], # 7 Conv Shallow
37
+ [0.99, 0.77, 0.22], # 8 Conv Mid
38
+ [0.70, 0.00, 0.00], # 9 Conv Deep
39
+ ])
40
+
41
+ def echo_type_cmap() -> ListedColormap:
42
+ """
43
+ 9-colour ListedColormap for sub-classified echo-type plotting.
44
+ Use with vmin=0.5, vmax=9.5.
45
+ """
46
+ return ListedColormap(_ECHO_TYPE_COLORS, name="echo_type")
47
+
48
+
49
+ def echo_type_norm() -> BoundaryNorm:
50
+ """BoundaryNorm that places each echo-type colour in the correct cell."""
51
+ boundaries = np.arange(0.5, 10.5)
52
+ return BoundaryNorm(boundaries, ncolors=9)
53
+
54
+
55
+ def basic_echo_type_cmap() -> ListedColormap:
56
+ """3-colour ListedColormap for basic (Strat/Mixed/Conv) echo-type plotting."""
57
+ return ListedColormap(_BASIC_ECHO_TYPE_COLORS, name="basic_echo_type")
58
+
59
+
60
+ def basic_echo_type_norm() -> BoundaryNorm:
61
+ """BoundaryNorm for the 3-colour basic echo-type map."""
62
+ boundaries = np.arange(0.5, 4.5)
63
+ return BoundaryNorm(boundaries, ncolors=3)
64
+
65
+
66
+ def remap_echo_type(echo_type: np.ndarray) -> np.ndarray:
67
+ """
68
+ Remap echo-type integer codes to 1-based plot indices.
69
+
70
+ Auto-detects whether `echo_type` contains basic codes (1, 2, 3 - no
71
+ sub-classification, from eccopy1d / eccopy2d_h / eccopy2d_v|eccopy3d
72
+ without height or temp) or sub-classified codes (14, 16, 18, 25, 30,
73
+ 32, 34, 36, 38), and remaps using the matching table. Use
74
+ basic_echo_type_cmap()/basic_echo_type_norm() for the former, and
75
+ echo_type_cmap()/echo_type_norm() for the latter.
76
+ """
77
+ present = set(np.unique(echo_type[~np.isnan(echo_type)]).astype(int).tolist())
78
+ is_basic = present.issubset(set(BASIC_ECHO_TYPE_TO_IDX.keys()))
79
+
80
+ table = BASIC_ECHO_TYPE_TO_IDX if is_basic else ECHO_TYPE_TO_IDX
81
+ out = np.full_like(echo_type, np.nan, dtype=float)
82
+ for code, idx in table.items():
83
+ out[echo_type == code] = idx
84
+ return out
85
+
86
+
87
+ # ---------------------------------------------------------------------------
88
+ # Convectivity colormap - continuous, 0-1
89
+ # ---------------------------------------------------------------------------
90
+ #
91
+ # Shares hue language with the classification colormaps above (blue for
92
+ # stratiform, teal for mixed, red for convective), but unlike those this
93
+ # map is continuous within each class and has HARD BREAKS at the two
94
+ # convectivity thresholds. Reading a convectivity panel therefore tells
95
+ # you the class directly -- blue pixels are stratiform, teal are mixed,
96
+ # red are convective -- while the ramp within each band still shows how
97
+ # marginal or how firmly-held that classification is.
98
+ #
99
+ # Blue band : dark blue -> light blue (stratiform)
100
+ # Teal band : dark teal -> light teal (mixed)
101
+ # Red band : light red -> dark red (convective)
102
+ _CONVECTIVITY_BLUE = [(0.0, 0.0, 1.0), (0.5, 0.75, 1.0)] # dark -> light blue
103
+ _CONVECTIVITY_TEAL = [(0.0, 0.5, 0.5), (0.0, 1.0, 1.0)] # dark -> light teal
104
+ _CONVECTIVITY_RED = [(1.0, 0.75, 0.75), (1.0, 0.0, 0.0)] # light -> dark red
105
+
106
+ _CONVECTIVITY_N = 1024
107
+
108
+
109
+ def _convectivity_stops(strat_mixed: float, mixed_conv: float, n: int):
110
+ """
111
+ Build the (position, color) stop list for convectivity_cmap().
112
+
113
+ The duplicated positions are what create the hard breaks. Each break is
114
+ nudged half a LUT bin BELOW its threshold, because the classifier is
115
+ inclusive on the upper side (`conv >= strat_mixed` is Mixed, see
116
+ core.classification.class_basic) whereas LinearSegmentedColormap resolves
117
+ a duplicated stop to the lower band. Without the nudge, a convectivity of
118
+ exactly `strat_mixed` renders stratiform-blue while classifying as mixed.
119
+ """
120
+ eps = 0.5 / n
121
+ lo = strat_mixed - eps
122
+ hi = mixed_conv - eps
123
+ return [
124
+ (0.0, _CONVECTIVITY_BLUE[0]),
125
+ (lo, _CONVECTIVITY_BLUE[1]),
126
+ (lo, _CONVECTIVITY_TEAL[0]),
127
+ (hi, _CONVECTIVITY_TEAL[1]),
128
+ (hi, _CONVECTIVITY_RED[0]),
129
+ (1.0, _CONVECTIVITY_RED[1]),
130
+ ]
131
+
132
+
133
+ def convectivity_cmap(strat_mixed: float = 0.4,
134
+ mixed_conv: float = 0.5) -> LinearSegmentedColormap:
135
+ """
136
+ Continuous colormap for convectivity (0-1), with hard breaks at the
137
+ strat/mixed and mixed/conv thresholds. Use with convectivity_norm()
138
+ (or vmin=0, vmax=1 directly).
139
+
140
+ Parameters
141
+ ----------
142
+ strat_mixed, mixed_conv : float
143
+ Convectivity thresholds the breaks are placed at. Defaults match
144
+ ClassificationParams. If you run a classification with non-default
145
+ thresholds, pass the same values here so the colors keep agreeing
146
+ with the echo-type panel, e.g.::
147
+
148
+ cmap = convectivity_cmap(params.strat_mixed, params.mixed_conv)
149
+ """
150
+ stops = _convectivity_stops(strat_mixed, mixed_conv, _CONVECTIVITY_N)
151
+ return LinearSegmentedColormap.from_list("convectivity", stops,
152
+ N=_CONVECTIVITY_N)
153
+
154
+
155
+ def convectivity_norm(vmin: float = 0.0, vmax: float = 1.0) -> Normalize:
156
+ """Normalize for convectivity_cmap(). Convectivity is defined on [0, 1]."""
157
+ return Normalize(vmin=vmin, vmax=vmax)
158
+
159
+
160
+ # ---------------------------------------------------------------------------
161
+ # Texture-window footprint overlay
162
+ # ---------------------------------------------------------------------------
163
+
164
+
165
+ def draw_window_ring(ax, coords_x, coords_y, radius_km,
166
+ center=None, label=True, color="black", alpha=0.9,
167
+ coord_units="km"):
168
+ """
169
+ Draw the texture window's footprint as a circle in data coordinates,
170
+ so users can see how large the texture neighbourhood is relative to
171
+ the features in a plan-view (2D-H or 3D-slice) panel.
172
+
173
+ The window is a circular neighbourhood of physical radius `radius_km`
174
+ (``result.texture_radius``). On an isotropic plan-view grid drawn with
175
+ equal aspect, that footprint is a true circle in km space, which is
176
+ what this draws. On a strongly anisotropic grid (dx != dy) the actual
177
+ per-axis pixel reach differs; the km circle is still the correct
178
+ physical footprint, but bear in mind the pixel counts along X and Y
179
+ won't match.
180
+
181
+ Parameters
182
+ ----------
183
+ ax : matplotlib Axes
184
+ A plan-view axis, in the units named by `coord_units`.
185
+ coords_x, coords_y : np.ndarray
186
+ The 1-D coordinate axes of the panel, in the units named by
187
+ `coord_units`. Used to place the ring at the domain centre by
188
+ default.
189
+ radius_km : float or None
190
+ Physical window radius in km (``result.texture_radius``). If None,
191
+ non-finite, or <= 0, nothing is drawn and None is returned (so a
192
+ bare-pixel WindowSpec on a unit-agnostic grid degrades quietly).
193
+ center : (x, y) tuple or None
194
+ Ring centre in km. Domain centre if None.
195
+ label : bool
196
+ Annotate the ring with its radius.
197
+ color, alpha : matplotlib color / float
198
+ Ring styling.
199
+ coord_units : {"km", "degrees"}
200
+ Units of `coords_x`/`coords_y` and of the axis. Use "degrees" when
201
+ the panel is plotted in longitude/latitude, as plan-view 2-D-H
202
+ output usually is: a circle of fixed physical radius spans more
203
+ degrees of longitude than of latitude, and more longitude nearer
204
+ the pole, so the footprint is drawn as an ellipse sized from the
205
+ ring centre's latitude. Passing degree axes while leaving this at
206
+ "km" draws a figure that is wrong by a factor of ~100.
207
+
208
+ Returns
209
+ -------
210
+ matplotlib.patches.Circle, matplotlib.patches.Ellipse, or None
211
+ The patch added to `ax`, or None if nothing was drawn.
212
+ """
213
+ import numpy as _np
214
+ from matplotlib.patches import Circle as _Circle, Ellipse as _Ellipse
215
+
216
+ if coord_units not in ("km", "degrees"):
217
+ raise ValueError(
218
+ f"coord_units must be 'km' or 'degrees'; got {coord_units!r}"
219
+ )
220
+
221
+ if radius_km is None:
222
+ return None
223
+ try:
224
+ radius_km = float(radius_km)
225
+ except (TypeError, ValueError):
226
+ return None
227
+ if not _np.isfinite(radius_km) or radius_km <= 0:
228
+ return None
229
+
230
+ coords_x = _np.asarray(coords_x, dtype=float)
231
+ coords_y = _np.asarray(coords_y, dtype=float)
232
+ if center is None:
233
+ cx = float(_np.mean([coords_x[0], coords_x[-1]]))
234
+ cy = float(_np.mean([coords_y[0], coords_y[-1]]))
235
+ else:
236
+ cx, cy = float(center[0]), float(center[1])
237
+
238
+ if coord_units == "km":
239
+ ring = _Circle((cx, cy), radius_km, fill=False, ls="--", lw=1.6,
240
+ ec=color, alpha=alpha, zorder=5)
241
+ label_dy = radius_km
242
+ else:
243
+ # A circle of fixed physical radius is an ellipse in degree space:
244
+ # a degree of latitude is a constant distance, while a degree of
245
+ # longitude shrinks as cos(latitude). Uses the same spherical
246
+ # earth radius as core.coords, so the footprint agrees with the
247
+ # spacing that latlon_to_xy_spacing() produced.
248
+ from .coords import EARTH_RADIUS_KM as _R
249
+ km_per_deg_lat = _np.pi * _R / 180.0
250
+ km_per_deg_lon = km_per_deg_lat * max(_np.cos(_np.radians(cy)), 1e-6)
251
+ half_h = radius_km / km_per_deg_lat
252
+ half_w = radius_km / km_per_deg_lon
253
+ ring = _Ellipse((cx, cy), 2.0 * half_w, 2.0 * half_h, fill=False,
254
+ ls="--", lw=1.6, ec=color, alpha=alpha, zorder=5)
255
+ label_dy = half_h
256
+ ax.add_patch(ring)
257
+ ax.plot([cx], [cy], marker="+", ms=8, mew=1.4, color=color,
258
+ alpha=alpha, zorder=6)
259
+ if label:
260
+ ax.annotate(f"texture window\nr = {radius_km:.1f} km",
261
+ xy=(cx, cy + label_dy), xytext=(0, 5),
262
+ textcoords="offset points", ha="center", va="bottom",
263
+ fontsize=7, color=color,
264
+ bbox=dict(boxstyle="round,pad=0.2", fc="white",
265
+ ec=color, alpha=0.75, lw=0.8),
266
+ zorder=7)
267
+ return ring
@@ -0,0 +1,43 @@
1
+ """
2
+ Texture to convectivity transfer function.
3
+
4
+ Port of ConvStratFinder::_computeConvectivity(). Convectivity is missing
5
+ rather than zero where texture falls below texture_limit_low. The
6
+ coverage condition the C++ applies alongside it - missing where
7
+ fractionActive < minValidFractionForTexture - is applied upstream by
8
+ refl_texture_2d(), which returns NaN texture at those points.
9
+ """
10
+
11
+ from __future__ import annotations
12
+ import numpy as np
13
+
14
+
15
+ def texture_to_convectivity_linear(texture: np.ndarray,
16
+ upper_lim: float,
17
+ lower_lim: float = 0.0) -> np.ndarray:
18
+ """
19
+ Linear scaling of texture onto convectivity.
20
+
21
+ texture < lower_lim -> NaN (missing)
22
+ texture > upper_lim -> 1.0
23
+ otherwise -> (texture - lower_lim) / (upper_lim - lower_lim)
24
+
25
+ Port of the convectivity loop in ConvStratFinder::_computeConvectivity().
26
+ At the default lower_lim of 0 this reduces to texture / upper_lim
27
+ clipped to [0, 1].
28
+
29
+ NaN where texture is NaN.
30
+ """
31
+ span = upper_lim - lower_lim
32
+ if span <= 0:
33
+ raise ValueError(
34
+ f"texture_limit_high ({upper_lim}) must exceed texture_limit_low "
35
+ f"({lower_lim})"
36
+ )
37
+ conv = (texture - lower_lim) / span
38
+ conv = np.clip(conv, 0.0, 1.0)
39
+ # Below lower_lim is missing, not zero - matching the C++, which leaves
40
+ # convectivity at its missing value rather than flooring it.
41
+ if lower_lim > 0.0:
42
+ conv = np.where(texture < lower_lim, np.nan, conv)
43
+ return conv
eccopy/core/coords.py ADDED
@@ -0,0 +1,245 @@
1
+ """
2
+ Coordinate helpers for EccoPy.
3
+
4
+ EccoPy is data-agnostic: it never reads files and never assumes a
5
+ particular coordinate system. Distances between grid points must be
6
+ supplied explicitly, either as:
7
+
8
+ - Position/coordinate arrays (e.g. x_km giving each point's location),
9
+ from which local point-to-point spacing is derived, or
10
+ - Pre-computed spacing/delta arrays (the distance between adjacent
11
+ points directly), or
12
+ - Latitude/longitude grids, converted to local x/y distance arrays
13
+ via haversine() below.
14
+
15
+ This module provides:
16
+ haversine_distance() - great-circle distance between two lat/lon points
17
+ latlon_to_xy_spacing() - convert a lat/lon grid into local dx/dy spacing
18
+ arrays (same shape as the input grid)
19
+ resolve_spacing() - internal: turn either a position array or a
20
+ pre-computed spacing array into a spacing array
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from typing import Tuple
26
+
27
+ import numpy as np
28
+
29
+ EARTH_RADIUS_KM = 6371.0088
30
+
31
+
32
+ def haversine_distance(lat1: float, lon1: float,
33
+ lat2: float, lon2: float,
34
+ radius_km: float = EARTH_RADIUS_KM) -> float:
35
+ """
36
+ Great-circle distance between two points on a sphere.
37
+
38
+ Parameters
39
+ ----------
40
+ lat1, lon1, lat2, lon2 : float, degrees
41
+ radius_km : float, default Earth's mean radius
42
+
43
+ Returns
44
+ -------
45
+ distance_km : float
46
+ """
47
+ lat1, lon1, lat2, lon2 = map(np.radians, (lat1, lon1, lat2, lon2))
48
+ dlat = lat2 - lat1
49
+ dlon = lon2 - lon1
50
+ a = (np.sin(dlat / 2.0) ** 2
51
+ + np.cos(lat1) * np.cos(lat2) * np.sin(dlon / 2.0) ** 2)
52
+ c = 2.0 * np.arcsin(np.minimum(1.0, np.sqrt(a)))
53
+ return radius_km * c
54
+
55
+
56
+ def latlon_to_xy_spacing(lat: np.ndarray,
57
+ lon: np.ndarray,
58
+ radius_km: float = EARTH_RADIUS_KM
59
+ ) -> Tuple[np.ndarray, np.ndarray]:
60
+ """
61
+ Convert a lat/lon grid into local x/y point-to-point spacing arrays
62
+ using the haversine formula.
63
+
64
+ Parameters
65
+ ----------
66
+ lat, lon : np.ndarray, same shape, degrees
67
+ Latitude/longitude at every grid point. Any number of dimensions
68
+ is supported as long as the LAST axis is "x" (e.g. longitude
69
+ varies fastest) and the second-to-last axis is "y", matching the
70
+ convention used elsewhere in EccoPy (..., Y, X).
71
+
72
+ Returns
73
+ -------
74
+ dy_km, dx_km : np.ndarray, same shape as lat/lon
75
+ Local spacing to the next point along the y-axis / x-axis.
76
+ The last row/column repeats the previous spacing value (so the
77
+ output shape matches the input shape exactly).
78
+
79
+ Notes
80
+ -----
81
+ This computes the distance from each point to its neighbour at
82
+ index+1 along the relevant axis - i.e. dx_km[..., i] is the distance
83
+ from point i to point i+1 (and the final column duplicates the
84
+ second-to-last value so the array shape is preserved).
85
+ """
86
+ lat = np.asarray(lat, dtype=float)
87
+ lon = np.asarray(lon, dtype=float)
88
+ if lat.shape != lon.shape:
89
+ raise ValueError(f"lat and lon must have the same shape, got "
90
+ f"{lat.shape} and {lon.shape}")
91
+
92
+ # --- x-spacing: distance along the last axis ---
93
+ lat_a = lat[..., :-1]
94
+ lon_a = lon[..., :-1]
95
+ lat_b = lat[..., 1:]
96
+ lon_b = lon[..., 1:]
97
+ dx_inner = haversine_distance(lat_a, lon_a, lat_b, lon_b, radius_km)
98
+ dx_km = np.concatenate([dx_inner, dx_inner[..., -1:]], axis=-1)
99
+
100
+ # --- y-spacing: distance along the second-to-last axis ---
101
+ if lat.ndim < 2:
102
+ dy_km = np.zeros_like(dx_km)
103
+ else:
104
+ lat_a = lat[..., :-1, :]
105
+ lon_a = lon[..., :-1, :]
106
+ lat_b = lat[..., 1:, :]
107
+ lon_b = lon[..., 1:, :]
108
+ dy_inner = haversine_distance(lat_a, lon_a, lat_b, lon_b, radius_km)
109
+ dy_km = np.concatenate([dy_inner, dy_inner[..., -1:, :]], axis=-2)
110
+
111
+ return dy_km, dx_km
112
+
113
+
114
+ def time_to_distance_km(time: np.ndarray,
115
+ wind_speed_ms: np.ndarray,
116
+ mode: str = "auto") -> np.ndarray:
117
+ """
118
+ Convert a 1-D time series into a pseudo-spatial "position" coordinate
119
+ via Taylor's frozen-turbulence hypothesis: distance = integral(|speed|
120
+ dt). This is the standard way to turn a fixed-point time series (e.g.
121
+ a vertically-pointing or scanning radar sampling a field advected past
122
+ it by the wind) into something a spatial texture/classification window
123
+ can be sized against in km, instead of only being able to size a
124
+ window in raw time.
125
+
126
+ This is a stand-alone, composable helper -- like haversine_distance /
127
+ latlon_to_xy_spacing above, it is NOT called automatically by
128
+ eccopy1d.run(). EccoPy is data-agnostic and does not assume a wind
129
+ field exists; a caller with wind speed available derives a distance
130
+ coordinate here FIRST, then passes the result into eccopy1d.run() as
131
+ `coords` (with `coord_mode="position"`) exactly as they would a
132
+ directly-measured distance array. A caller without wind data simply
133
+ keeps using `coords` as time or grid position, unchanged -- this
134
+ function is purely additive.
135
+
136
+ Parameters
137
+ ----------
138
+ time : array-like, shape (N,)
139
+ Either cumulative time (seconds) at each sample, or already-
140
+ computed point-to-point time spacing -- interpreted according to
141
+ `mode`, same convention as resolve_spacing().
142
+ wind_speed_ms : array-like, shape (N,), or scalar
143
+ Wind speed, m/s, at each sample (or a single constant speed
144
+ broadcast to every sample). Only magnitude matters -- sign/
145
+ direction is not used, since this produces a monotonically
146
+ non-decreasing along-track distance, not a signed displacement.
147
+ NaN propagates: a missing wind sample makes every subsequent
148
+ cumulative distance value NaN (see Notes).
149
+ mode : {"auto", "position", "spacing"}
150
+ How to interpret `time` -- passed straight through to
151
+ resolve_spacing().
152
+
153
+ Returns
154
+ -------
155
+ distance_km : np.ndarray, shape (N,)
156
+ Cumulative along-track distance, km, starting at 0 for the first
157
+ sample. Monotonically non-decreasing (strictly increasing
158
+ wherever wind_speed_ms != 0). Intended to be passed directly as
159
+ `coords` to eccopy1d.run() with `coord_mode="position"`.
160
+
161
+ Notes
162
+ -----
163
+ Because NaN propagates through np.cumsum, a single missing wind
164
+ sample poisons every distance value after it. If wind data has gaps,
165
+ fill them (e.g. interpolate) before calling this function -- EccoPy
166
+ does not do this for you, matching its data-agnostic, no-hidden-
167
+ imputation design elsewhere (see refl_texture_1d's NaN handling for
168
+ the one deliberate exception, which is documented there).
169
+
170
+ Also note "auto" mode's monotonicity heuristic in resolve_spacing()
171
+ can misfire on a `time` array that is already point-to-point spacing
172
+ with irregular (but always-positive) gaps -- pass mode="position" or
173
+ mode="spacing" explicitly if there's any doubt.
174
+ """
175
+ dt_s = resolve_spacing(np.asarray(time, dtype=float), axis=0, mode=mode)
176
+ speed = np.broadcast_to(
177
+ np.abs(np.asarray(wind_speed_ms, dtype=float)), dt_s.shape
178
+ )
179
+ dx_km = speed * dt_s / 1000.0
180
+ # dx_km[i] is the distance covered going FROM point i TO point i+1
181
+ # (same point-to-point convention as resolve_spacing's spacing
182
+ # output), so the cumulative position at point i is the running sum
183
+ # of all PRIOR segments, with the first point pinned at 0.
184
+ distance_km = np.concatenate(([0.0], np.cumsum(dx_km[:-1])))
185
+ return distance_km
186
+
187
+
188
+ def resolve_spacing(coord_or_spacing: np.ndarray,
189
+ axis: int,
190
+ mode: str = "auto") -> np.ndarray:
191
+ """
192
+ Turn either a position/coordinate array or a pre-computed spacing
193
+ array into a spacing array (distance to the next point along `axis`).
194
+
195
+ Parameters
196
+ ----------
197
+ coord_or_spacing : np.ndarray
198
+ Either point positions (e.g. cumulative distance / coordinate
199
+ value at each grid point) or already-computed point-to-point
200
+ spacing.
201
+ axis : int
202
+ Axis along which spacing is measured.
203
+ mode : {"auto", "position", "spacing"}
204
+ "position": treat input as coordinate values; spacing is
205
+ np.diff along axis (with the last point repeating the final
206
+ spacing value so the shape is preserved).
207
+ "spacing": treat input as already being point-to-point spacing;
208
+ returned unchanged.
209
+ "auto" (default): treat as "position" if values are monotonically
210
+ increasing or decreasing along `axis` (typical of coordinate
211
+ arrays); otherwise treat as "spacing" directly. This heuristic
212
+ covers the common cases but "position"/"spacing" can be
213
+ specified explicitly to avoid ambiguity.
214
+
215
+ Returns
216
+ -------
217
+ spacing : np.ndarray, same shape as coord_or_spacing
218
+ """
219
+ arr = np.asarray(coord_or_spacing, dtype=float)
220
+
221
+ if mode not in ("auto", "position", "spacing"):
222
+ raise ValueError(f"mode must be 'auto', 'position', or 'spacing', got {mode!r}")
223
+
224
+ if mode == "spacing":
225
+ return arr
226
+
227
+ if mode == "auto":
228
+ diffs = np.diff(arr, axis=axis)
229
+ finite = diffs[np.isfinite(diffs)]
230
+ if finite.size == 0:
231
+ mode = "spacing"
232
+ else:
233
+ all_pos = np.all(finite > 0)
234
+ all_neg = np.all(finite < 0)
235
+ mode = "position" if (all_pos or all_neg) else "spacing"
236
+
237
+ if mode == "spacing":
238
+ return arr
239
+
240
+ # mode == "position": derive spacing via diff, pad last slice
241
+ spacing = np.abs(np.diff(arr, axis=axis))
242
+ pad_widths = [(0, 0)] * arr.ndim
243
+ pad_widths[axis] = (0, 1)
244
+ spacing = np.pad(spacing, pad_widths, mode="edge")
245
+ return spacing