Return the index of the first item of a run of at least a given length.

        Parameters
        ----------
        ----------
        arr : N-dimensional Xarray data array  (boolean)
          Input array
        window : int
          Minimum duration of consecutive run to accumulate values.
        dim : Xarray dimension (default = 'time')
          Dimension along which to calculate consecutive run

        Returns
        -------
        out : N-dimensional xarray data array (int)
          Index of first item in first valid run. Returns np.nan if there are no valid run.

def first_run(da, window, dim='time'):
    """Return the index of the first item of a run of at least a given length.

        Parameters
        ----------
        ----------
        arr : N-dimensional Xarray data array  (boolean)
          Input array
        window : int
          Minimum duration of consecutive run to accumulate values.
        dim : Xarray dimension (default = 'time')
          Dimension along which to calculate consecutive run

        Returns
        -------
        out : N-dimensional xarray data array (int)
          Index of first item in first valid run. Returns np.nan if there are no valid run.
        """
    dims = list(da.dims)
    if 'time' not in dims:
        da['time'] = da[dim]
        da.swap_dims({dim: 'time'})
    da = da.astype('int')
    i = xr.DataArray(np.arange(da[dim].size), dims=dim).chunk({'time': 1})
    ind = xr.broadcast(i, da)[0].chunk(da.chunks)
    wind_sum = da.rolling(time=window).sum()
    out = ind.where(wind_sum >= window).min(dim=dim) - (
        window - 1)  # remove window -1 as rolling result index is last element of the moving window
    return out