提交 071c4eb8 authored 作者: Ricardo Vieira's avatar Ricardo Vieira 提交者: Ricardo Vieira

Implement diff for XTensorVariables

上级 c2f54fd8
...@@ -611,6 +611,15 @@ class XTensorVariable(Variable[_XTensorTypeType, OptionalApplyType]): ...@@ -611,6 +611,15 @@ class XTensorVariable(Variable[_XTensorTypeType, OptionalApplyType]):
def cumprod(self, dim=None): def cumprod(self, dim=None):
return px.reduction.cumprod(self, dim) return px.reduction.cumprod(self, dim)
def diff(self, dim, n=1):
"""Compute the n-th discrete difference along the given dimension."""
slice1 = {dim: slice(1, None)}
slice2 = {dim: slice(None, -1)}
x = self
for _ in range(n):
x = x[slice1] - x[slice2]
return x
# Reshaping and reorganizing # Reshaping and reorganizing
# https://docs.xarray.dev/en/latest/api.html#id8 # https://docs.xarray.dev/en/latest/api.html#id8
def transpose( def transpose(
......
...@@ -491,3 +491,22 @@ def test_indexing_renames_into_update_variable(): ...@@ -491,3 +491,22 @@ def test_indexing_renames_into_update_variable():
expected_result = x_test.copy() expected_result = x_test.copy()
expected_result[idx_test] = y_test expected_result[idx_test] = y_test
xr_assert_allclose(result, expected_result) xr_assert_allclose(result, expected_result)
@pytest.mark.parametrize("n", ["implicit", 1, 2])
@pytest.mark.parametrize("dim", ["a", "b"])
def test_diff(dim, n):
x = xtensor(dims=("a", "b"), shape=(7, 11))
if n == "implicit":
out = x.diff(dim)
else:
out = x.diff(dim, n=n)
fn = xr_function([x], out)
x_test = xr_arange_like(x)
res = fn(x_test)
if n == "implicit":
expected_res = x_test.diff(dim)
else:
expected_res = x_test.diff(dim, n=n)
xr_assert_allclose(res, expected_res)
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论