Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add optional rows parameter to unpack_ragged and apply_ragged #272

Merged
merged 3 commits into from
Sep 21, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 28 additions & 3 deletions clouddrift/analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ def apply_ragged(
arrays: list[np.ndarray],
rowsize: list[int],
*args: tuple,
rows: Union[int, Iterable[int]] = None,
executor: futures.Executor = futures.ThreadPoolExecutor(max_workers=None),
**kwargs: dict,
) -> Union[tuple[np.ndarray], np.ndarray]:
Expand Down Expand Up @@ -45,6 +46,9 @@ def apply_ragged(
List of integers specifying the number of data points in each row.
*args : tuple
Additional arguments to pass to ``func``.
rows : int or Iterable[int], optional
The row(s) of the ragged array to apply ``func`` to. If ``rows`` is
``None`` (default), then ``func`` will be applied to all rows.
executor : concurrent.futures.Executor, optional
Executor to use for concurrent execution. Default is ``ThreadPoolExecutor``
with the default number of ``max_workers``.
Expand Down Expand Up @@ -72,6 +76,15 @@ def apply_ragged(
array([1., 1., 2., 2., 2., 3., 3., 3., 3.]),
array([1., 1., 1., 1., 1., 1., 1., 1., 1.]))

To apply ``func`` to only a subset of rows, use the ``rows`` argument:

>>> u1, v1 = apply_ragged(velocity_from_position, [x, y, t], rowsize, rows=0, coord_system="cartesian")
array([1., 1.]),
array([1., 1.]))
>>> u1, v1 = apply_ragged(velocity_from_position, [x, y, t], rowsize, rows=[0, 1], coord_system="cartesian")
array([1., 1., 2., 2., 2.]),
array([1., 1., 1., 1., 1.]))

Raises
------
ValueError
Expand All @@ -88,7 +101,7 @@ def apply_ragged(
raise ValueError("The sum of rowsize must equal the length of arr.")

# split the array(s) into trajectories
arrays = [unpack_ragged(arr, rowsize) for arr in arrays]
arrays = [unpack_ragged(arr, rowsize, rows) for arr in arrays]
philippemiron marked this conversation as resolved.
Show resolved Hide resolved
iter = [[arrays[i][j] for i in range(len(arrays))] for j in range(len(arrays[0]))]

# parallel execution
Expand Down Expand Up @@ -1061,7 +1074,9 @@ def subset(


def unpack_ragged(
ragged_array: np.ndarray, rowsize: np.ndarray[int]
ragged_array: np.ndarray,
rowsize: np.ndarray[int],
rows: Union[int, Iterable[int]] = None,
) -> list[np.ndarray]:
"""Unpack a ragged array into a list of regular arrays.

Expand All @@ -1076,6 +1091,8 @@ def unpack_ragged(
rowsize : array-like
An array of integers whose values is the size of each row in the ragged
array
rows : int or Iterable[int], optional
A row or list of rows to unpack. Default is None, which unpacks all rows.

Returns
-------
Expand All @@ -1092,6 +1109,8 @@ def unpack_ragged(

lon = unpack_ragged(ds.lon, ds["rowsize"]) # return a list[xr.DataArray] (slower)
lon = unpack_ragged(ds.lon.values, ds["rowsize"]) # return a list[np.ndarray] (faster)
first_lon = unpack_ragged(ds.lon.values, ds["rowsize"], rows=0) # return only the first row
first_two_lons = unpack_ragged(ds.lon.values, ds["rowsize"], rows=[0, 1]) # return first two rows

Looping over trajectories in a ragged Xarray Dataset to compute velocities
for each:
Expand All @@ -1106,4 +1125,10 @@ def unpack_ragged(
u, v = velocity_from_position(lon, lat, time)
"""
indices = np.insert(np.cumsum(np.array(rowsize)), 0, 0)
return [ragged_array[indices[n] : indices[n + 1]] for n in range(indices.size - 1)]

if rows is None:
rows = range(indices.size - 1)
if isinstance(rows, int):
rows = [rows]

return [ragged_array[indices[n] : indices[n + 1]] for n in rows]
47 changes: 47 additions & 0 deletions tests/analysis_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -738,6 +738,23 @@ def test_velocity_ndarray(self):
)
)

def test_with_rows(self):
y = apply_ragged(
lambda x: x**2,
np.array([1, 2, 3, 4]),
[2, 2],
rows=0,
)
self.assertTrue(np.all(y == np.array([1, 4])))

y = apply_ragged(
lambda x: x**2,
np.array([1, 2, 3, 4]),
[2, 2],
rows=[0, 1],
)
self.assertTrue(np.all(y == np.array([1, 4, 9, 16])))

def test_velocity_dataarray(self):
for executor in [futures.ThreadPoolExecutor(), futures.ProcessPoolExecutor()]:
u, v = apply_ragged(
Expand Down Expand Up @@ -889,3 +906,33 @@ def test_unpack_ragged(self):
self.assertTrue(
np.all([lon[n].size == ds["rowsize"][n] for n in range(len(lon))])
)

def test_unpack_ragged_rows(self):
ds = sample_ragged_array().to_xarray()
x = ds.lon.values
rowsize = ds.rowsize.values

self.assertTrue(
all(
np.array_equal(a, b)
for a, b in zip(
unpack_ragged(x, rowsize, None), unpack_ragged(x, rowsize)
)
)
)
self.assertTrue(
all(
np.array_equal(a, b)
for a, b in zip(
unpack_ragged(x, rowsize, 0), unpack_ragged(x, rowsize)[:1]
)
)
)
self.assertTrue(
all(
np.array_equal(a, b)
for a, b in zip(
unpack_ragged(x, rowsize, [0, 1]), unpack_ragged(x, rowsize)[:2]
)
)
)