Make an ndarray with a rolling window of axis-th dimension.
    The rolling dimension will be placed at the last dimension.
198603
def rolling_window(array, axis, window, center, fill_value):
    
    if isinstance(array, dask_array_type):
        return dask_array_ops.rolling_window(
            array, axis, window, center, fill_value)
    else:  # np.ndarray
        return nputils.rolling_window(
            array, axis, window, center, fill_value)
1259221
def dimension_set(self, p_dim, s_dim=None, dimensions=None, extant=set()):
        

        if not dimensions:
            dimensions = self.primary_dimensions

        key = p_dim.name

        if s_dim:
            key += '/' + s_dim.name

        # Ignore if the key already exists or the primary and secondary dims are the same
        if key in extant or p_dim == s_dim:
            return

        # Don't allow geography to be a secondary dimension. It must either be a primary dimension
        # ( to make a map ) or a filter, or a small-multiple
        if s_dim and s_dim.valuetype_class.is_geo():
            return

        extant.add(key)

        filtered = {}

        for d in dimensions:
            if d != p_dim and d != s_dim:
                filtered[d.name] = d.pstats.uvalues.keys()

        if p_dim.valuetype_class.is_time():
            value_type = 'time'
            chart_type = 'line'
        elif p_dim.valuetype_class.is_geo():
            value_type = 'geo'
            chart_type = 'map'
        else:
            value_type = 'general'
            chart_type = 'bar'

        return dict(
            key=key,
            p_dim=p_dim.name,
            p_dim_type=value_type,
            p_label=p_dim.label_or_self.name,
            s_dim=s_dim.name if s_dim else None,
            s_label=s_dim.label_or_self.name if s_dim else None,
            filters=filtered,
            chart_type=chart_type
        )
282025
def array_size(x, axis):
  """"""
  axis_shape = x.shape if axis is None else tuple(x.shape[a] for a in axis)
  return max(numpy.prod(axis_shape), 1)
1191318
def agg_dims(arr, stat):
    
    axis = None
    if arr.ndim > 2:
        axis = 1
        arr = arr.reshape(arr.shape[0], -1)
    module = np.ma if hasattr(arr, 'mask') else np
    return getattr(module, stat)(arr, axis)
1265398
def make_2d(array, verbose=True):
    
    array = np.asarray(array)
    if array.ndim < 2:
        msg = 'Expected 2D input data array, but found {}D. '\
              'Expanding to 2D.'.format(array.ndim)
        if verbose:
            warnings.warn(msg)
        array = np.atleast_1d(array)[:,None]
    return array
715893
def rolling_vwap(bars, window=200, min_periods=None):
    
    min_periods = window if min_periods is None else min_periods

    typical = ((bars['high'] + bars['low'] + bars['close']) / 3)
    volume = bars['volume']

    left = (volume * typical).rolling(window=window,
                                      min_periods=min_periods).sum()
    right = volume.rolling(window=window, min_periods=min_periods).sum()

    return pd.Series(index=bars.index, data=(left / right)).replace([np.inf, -np.inf], float('NaN')).ffill()
1320130
def fn_var(self, a, axis=None):
        

        return numpy.nanvar(self._to_ndarray(a), axis=axis)
1334216
def _init_iter(self, X, y, is_train):
        """"""
        if isinstance(X, (np.ndarray, nd.NDArray)):
            if y is None:
                if is_train:
                    raise ValueError('y must be specified when X is numpy.ndarray')
                else:
                    y = np.zeros(X.shape[0])
            if not isinstance(y, (np.ndarray, nd.NDArray)):
                raise TypeError('y must be ndarray when X is numpy.ndarray')
            if X.shape[0] != y.shape[0]:
                raise ValueError("The numbers of data points and labels not equal")
            if y.ndim == 2 and y.shape[1] == 1:
                y = y.flatten()
            if y.ndim != 1:
                raise ValueError("Label must be 1D or 2D (with 2nd dimension being 1)")
            if is_train:
                return io.NDArrayIter(X, y, min(X.shape[0], self.numpy_batch_size),
                                      shuffle=is_train, last_batch_handle='roll_over')
            else:
                return io.NDArrayIter(X, y, min(X.shape[0], self.numpy_batch_size), shuffle=False)
        if not isinstance(X, io.DataIter):
            raise TypeError('X must be DataIter, NDArray or numpy.ndarray')
        return X
350070
def rolling(self, window, min_periods=None, center=False, win_type=None, on=None, axis=0, closed=None):
        
        kwds = {
            "window": window,
            "min_periods": min_periods,
            "center": center,
            "win_type": win_type,
            "on": on,
            "axis": axis,
            "closed": closed,
        }
        return Rolling(self._obj, self._npartitions, self._dask_threshold, self._scheduler, self._progress_bar, **kwds)
220736
def asarray_ndim(a, *ndims, **kwargs):
    
    allow_none = kwargs.pop('allow_none', False)
    kwargs.setdefault('copy', False)
    if a is None and allow_none:
        return None
    a = np.array(a, **kwargs)
    if a.ndim not in ndims:
        if len(ndims) > 1:
            expect_str = 'one of %s' % str(ndims)
        else:
            # noinspection PyUnresolvedReferences
            expect_str = '%s' % ndims[0]
        raise TypeError('bad number of dimensions: expected %s; found %s' %
                        (expect_str, a.ndim))
    return a
161780
def make_2d(ary):
    
    dim_0, *_ = np.atleast_1d(ary).shape
    return ary.reshape(dim_0, -1, order="F")
572534
def _rolling_window(a, window):
    
    # https://stackoverflow.com/a/6811241
    shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
    strides = a.strides + (a.strides[-1],)
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
324214
def reshape(x,input_dim):
    '''
    

    '''
    x = np.array(x)
    if x.size ==input_dim:
        x = x.reshape((1,input_dim))
    return x
273253
def _merge_dimensions(dimension, preferred=None, dont_extend=False):
        
        dimension = dimension or LayoutDimension()

        # When a preferred dimension was explicitly given to the Window,
        # ignore the UIControl.
        if dimension.preferred_specified:
            preferred = dimension.preferred

        # When a 'preferred' dimension is given by the UIControl, make sure
        # that it stays within the bounds of the Window.
        if preferred is not None:
            if dimension.max:
                preferred = min(preferred, dimension.max)

            if dimension.min:
                preferred = max(preferred, dimension.min)

        # When a `dont_extend` flag has been given, use the preferred dimension
        # also as the max dimension.
        if dont_extend and preferred is not None:
            max_ = min(dimension.max, preferred)
        else:
            max_ = dimension.max

        return LayoutDimension(
            min=dimension.min, max=max_,
            preferred=preferred, weight=dimension.weight)
1370788
def _center_window(self, result, window):
        
        if self.axis > result.ndim - 1:
            raise ValueError("Requested axis is larger then no. of argument "
                             "dimensions")

        offset = _offset(window, True)
        if offset > 0:
            if isinstance(result, (ABCSeries, ABCDataFrame)):
                result = result.slice_shift(-offset, axis=self.axis)
            else:
                lead_indexer = [slice(None)] * result.ndim
                lead_indexer[self.axis] = slice(offset, None)
                result = np.copy(result[tuple(lead_indexer)])
        return result
631807
def apply(self, im):
        
        from scipy.ndimage.interpolation import shift

        im = rollaxis(im, self.axis)
        im.setflags(write=True)
        for ind in range(0, im.shape[0]):
            im[ind] = shift(im[ind],  map(lambda x: -x, self.delta[ind]), mode='nearest')
        im = rollaxis(im, 0, self.axis+1)
        return im
177798
def dask_rolling_wrapper(moving_func, a, window, min_count=None, axis=-1):
    ''''''
    dtype, fill_value = dtypes.maybe_promote(a.dtype)
    a = a.astype(dtype)
    # inputs for overlap
    if axis < 0:
        axis = a.ndim + axis
    depth = {d: 0 for d in range(a.ndim)}
    depth[axis] = (window + 1) // 2
    boundary = {d: fill_value for d in range(a.ndim)}
    # Create overlap array.
    ag = overlap(a, depth=depth, boundary=boundary)
    # apply rolling func
    out = ag.map_blocks(moving_func, window, min_count=min_count,
                        axis=axis, dtype=a.dtype)
    # trim array
    result = trim_internal(out, depth)
    return result