我正在尝试使用 xarray 的apply_ufunc
包装 numpy 的gradient
函数,以便沿一维获取梯度。然而,apply_ufunc
返回一个与使用的数组形状不同的数组np.gradient
直接返回:
import xarray as xr
import numpy as np
def wrapped_gradient(da, coord):
"""Finds the gradient along a given dimension of a dataarray."""
dims_of_coord = da.coords[coord].dims
if len(dims_of_coord) == 1:
dim = dims_of_coord[0]
else:
raise ValueError('Coordinate ' + coord + ' has multiple dimensions: ' + str(dims_of_coord))
coord_vals = da.coords[coord].values
return xr.apply_ufunc(np.gradient, da, coord_vals, kwargs={'axis': -1},
input_core_dims=[[dim]], output_core_dims=[[dim]],
output_dtypes=[da.dtype])
# Test it out by comparing with applying np.gradient directly:
orig = xr.DataArray(np.random.randn(4, 3), coords={'x': [5, 7, 9, 11]}, dims=('x', 'y'))
expected = np.gradient(orig.values, np.array([5, 7, 9, 11]), axis=0)
actual = wrapped_gradient(orig, 'x').values
我希望预期和实际是相同的,但相反它们是不同的:
print(expected.shape)
> (4,3)
print(actual.shape)
> (3,4)
(expected
and actual
也不只是彼此的转置版本。)我很困惑为什么 - 我的理解apply_ufunc
是核心尺寸移到最后,这样axis=-1
应该总是提供给ufunc?