0

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.
  • can you explain using math or a simple numerical example exactly what you want to happen to the data, and also explain why your code either fails (please provide the traceback) or doesn't do what you want? I'm having a hard time understanding what a slope between a sliding window is... – Michael Delgado Sep 05 '22 at 00:05
  • let's imagine you have two image from surface temprature and elevation of an area. you can easily calculate regression between two image and extract slope and intercept.I want to do this instead of whole image for smaller window siliding over image and calculate just for center of sliding window slope value. Does it help ?@MichaelDelgado – Mohammad Mohseni Aref Sep 05 '22 at 05:45
  • got it - I think it is probably worth taking a look at [`xr.DataArrayRolling.construct`](https://docs.xarray.dev/en/stable/generated/xarray.core.rolling.DataArrayRolling.construct.html) - essentially if you do `da.rolling(...).construct('window_dim')` you'll have a new array with the data rolled over the windowed dim. it's essentially giving you many staggered views into the array. You could do this for both of your arrays and build the regression using the rolling.construct views. I haven't tried doing this in 2 dimensions though – Michael Delgado Sep 05 '22 at 06:16
  • Thanks so much @MichaelDelgado , I have tried one by modifiying 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, ) , but It didn't work, I updated my question with error message – Mohammad Mohseni Aref Sep 05 '22 at 06:23

0 Answers0