I am trying two calculate slope between sliding window(3x4) of two xarray dataset.you can imagine we want two calculate slope of dx and dy in put the value in the center of sliding window for x=3,y=4. I really appreciate if someone could help me to calculate slope or any function between sliding window of xarray in x,y dimension. There are examples for simpler calculation in stackoverflow like
Xarray rolling mean with weights
or an example without sliding window
Applying numpy.polyfit to xarray Dataset
Rolling correlation coefficients for two xarray DataArrays
I have tried to formulate it using following code but it doesn't do what i want
dv = xr.tutorial.open_dataset('air_temperature_gradient')
dx=dv.Tair.mean(dim='time')
de = dv.dTdx
def linear_trend(x, y):
pf = np.polyfit(x, y, 1)
return xr.DataArray(pf[0])
slopes = xr.apply_ufunc(linear_trend,
de.rolling(lat=3, lon=4, center=True).construct('window_dim'), dx.rolling(lat=3, lon=4, center=True).construct('window_dim'),
vectorize=True,
)
And I recieved following Error message
Output exceeds the size limit. Open the full output data in a text editor
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
/tmp/ipykernel_17440/286248495.py in <module>
10
11 slopes = xr.apply_ufunc(linear_trend,
---> 12 de.rolling(lat=3, lon=4, center=True).construct('window_dim'), dx.rolling(
13 lat=3, lon=4, center=True).construct('window_dim'),
14 vectorize=True,
~/anaconda3/envs/code/lib/python3.8/site-packages/xarray/core/rolling.py in construct(self, window_dim, stride, fill_value, keep_attrs, **window_dim_kwargs)
353 """
354
--> 355 return self._construct(
356 self.obj,
357 window_dim=window_dim,
~/anaconda3/envs/code/lib/python3.8/site-packages/xarray/core/rolling.py in _construct(self, obj, window_dim, stride, fill_value, keep_attrs, **window_dim_kwargs)
382 window_dim = {d: window_dim_kwargs[str(d)] for d in self.dim}
383
--> 384 window_dims = self._mapping_to_list(
385 window_dim, allow_default=False, allow_allsame=False # type: ignore[arg-type] # https://github.com/python/mypy/issues/12506
386 )
~/anaconda3/envs/code/lib/python3.8/site-packages/xarray/core/rolling.py in _mapping_to_list(self, arg, default, allow_default, allow_allsame)
214 if self.ndim == 1:
...
--> 216 raise ValueError(f"Mapping argument is necessary for {self.ndim}d-rolling.")
217
218 def _get_keep_attrs(self, keep_attrs):
ValueError: Mapping argument is necessary for 2d-rolling.