Bottleneck can only take integer axis, not tuple, so this function
    takes all the axes to be operated on and combines them into the
    first dimension of the array so that we can then use axis=0
344410
def _move_tuple_axes_first(array, axis):
    

    # Figure out how many axes we are operating over
    naxis = len(axis)

    # Add remaining axes to the axis tuple
    axis += tuple(i for i in range(array.ndim) if i not in axis)

    # The new position of each axis is just in order
    destination = tuple(range(array.ndim))

    # Reorder the array so that the axes being operated on are at the beginning
    array_new = np.moveaxis(array, axis, destination)

    # Figure out the size of the product of the dimensions being operated on
    first = np.prod(array_new.shape[:naxis])

    # Collapse the dimensions being operated on into a single dimension so that
    # we can then use axis=0 with the bottleneck functions
    array_new = array_new.reshape((first,) + array_new.shape[naxis:])

    return array_new
1365574
def tensor_vstack(tensor_list, pad=0):
    
    if len(tensor_list) == 1:
        return tensor_list[0][np.newaxis, :]

    ndim = len(tensor_list[0].shape)
    dimensions = [len(tensor_list)]  # first dim is batch size
    for dim in range(ndim):
        dimensions.append(max([tensor.shape[dim] for tensor in tensor_list]))

    dtype = tensor_list[0].dtype
    if pad == 0:
        all_tensor = np.zeros(tuple(dimensions), dtype=dtype)
    elif pad == 1:
        all_tensor = np.ones(tuple(dimensions), dtype=dtype)
    else:
        all_tensor = np.full(tuple(dimensions), pad, dtype=dtype)
    if ndim == 1:
        for ind, tensor in enumerate(tensor_list):
            all_tensor[ind, :tensor.shape[0]] = tensor
    elif ndim == 2:
        for ind, tensor in enumerate(tensor_list):
            all_tensor[ind, :tensor.shape[0], :tensor.shape[1]] = tensor
    elif ndim == 3:
        for ind, tensor in enumerate(tensor_list):
            all_tensor[ind, :tensor.shape[0], :tensor.shape[1], :tensor.shape[2]] = tensor
    else:
        raise Exception('Sorry, unimplemented.')
    return all_tensor
153796
def reduce_cpu(f, x, axes, dtype):
    """"""
    axes = _get_axes(axes, x.ndim)
    if not axes:
        return x

    permute = [n for n in range(x.ndim) if n not in axes]
    permute = axes + permute

    T = x.transpose(permute=permute)

    N = len(axes)
    t = T.type.at(N, dtype=dtype)
    acc = x.empty(t, device=x.device)

    if f.identity is not None:
        _copyto(acc, f.identity)
        tl = T
    elif N == 1 and T.type.shape[0] > 0:
        hd, tl = T[0], T[1:]
        acc[()] = hd
    else:
        raise ValueError(
            "reduction not possible for function without an identity element")

    return fold(f, acc, tl)
14624
def _construct_axes_dict_for_slice(self, axes=None, **kwargs):
        """"""
        d = {self._AXIS_SLICEMAP[a]: self._get_axis(a)
             for a in (axes or self._AXIS_ORDERS)}
        d.update(kwargs)
        return d
19461
def get_axes(x, y):
    
    n=int(np.sqrt(len(x)))
    if n**2 != len(x):
        raise ValueError("lenght of input array given as %s is not square of integer number!" % (len(x)))
    x_image = x.reshape(n,n)
    y_image = y.reshape(n,n)
    x_axes = x_image[0,:]
    y_axes = y_image[:,0]
    return x_axes, y_axes
285152
def _maybe_to_sparse(array):
    
    if isinstance(array, ABCSparseSeries):
        array = array.values.copy()
    return array
311011
def get_axis(array, axis, slice_num):
    """"""

    slice_list = [slice(None)] * array.ndim
    slice_list[axis] = slice_num
    slice_data = array[tuple(slice_list)].T  # transpose for proper orientation

    return slice_data
82371
def _process_non_parallel(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, cluster_array: np.ndarray):
        
        for gap_value, n_clusters in [self._calculate_gap(X, n_refs, n_clusters)
                                      for n_clusters in cluster_array]:
            yield (gap_value, n_clusters)
198741
def _parse_var_array(self, X: np.ndarray) -> dict:
        
        arg_vars = {}
        # Get the shape and tensor rank
        shape = X.shape
        tensor_rank = len(shape)
        T = self._check_forward_mode_input_array(X)
        if tensor_rank == 0:
            #there is only 1 var name, so this will only run once
            for var_name in self.var_names:
                arg_vars[var_name] = X
        if tensor_rank == 1 and T == shape[0]:
            #there is only 1 var name, so this will only run once
            for var_name in self.var_names:
                arg_vars[var_name] = X.squeeze()
        elif tensor_rank == 1:
            for j, var_name in enumerate(sorted(self.var_names)):
                arg_vars[var_name] = X[j].squeeze()
        elif tensor_rank == 2:
            for j, var_name in enumerate(sorted(self.var_names)):
                arg_vars[var_name] = X[:,j].squeeze()
        return arg_vars
987132
def axis_bounds(self) -> Dict[str, Tuple[float, float]]:
        
        return {ax: (0, pos+.05) for ax, pos
                in self._smoothie_driver.homed_position.items()
                if ax not in 'BC'}
183042
def transform(self, X, y=None):
        '''
        
        '''
        return Parallel(n_jobs=self.n_jobs)(delayed(self._transform)(x)
                                            for x in X)
186619
def tanh_discrete_bottleneck(x, bottleneck_bits, bottleneck_noise,
                             discretize_warmup_steps, mode):
  """"""
  x = tf.layers.dense(x, bottleneck_bits, name="tanh_discrete_bottleneck")
  d0 = tf.stop_gradient(2.0 * tf.to_float(tf.less(0.0, x))) - 1.0
  if mode == tf.estimator.ModeKeys.TRAIN:
    x += tf.truncated_normal(
        common_layers.shape_list(x), mean=0.0, stddev=0.2)
  x = tf.tanh(x)
  d = x + tf.stop_gradient(2.0 * tf.to_float(tf.less(0.0, x)) - 1.0 - x)
  if mode == tf.estimator.ModeKeys.TRAIN:
    noise = tf.random_uniform(common_layers.shape_list(x))
    noise = 2.0 * tf.to_float(tf.less(bottleneck_noise, noise)) - 1.0
    d *= noise
  d = common_layers.mix(d, x, discretize_warmup_steps,
                        mode == tf.estimator.ModeKeys.TRAIN)
  return d, d0
1286989
def _ixs(self, i, axis=0):
        
        # irow
        if axis == 0:
            if isinstance(i, slice):
                return self[i]
            else:
                label = self.index[i]
                if isinstance(label, Index):
                    # a location index by definition
                    result = self.take(i, axis=axis)
                    copy = True
                else:
                    new_values = self._data.fast_xs(i)
                    if is_scalar(new_values):
                        return new_values

                    # if we are a copy, mark as such
                    copy = (isinstance(new_values, np.ndarray) and
                            new_values.base is None)
                    result = self._constructor_sliced(new_values,
                                                      index=self.columns,
                                                      name=self.index[i],
                                                      dtype=new_values.dtype)
                result._set_is_copy(self, copy=copy)
                return result

        # icol
        else:
            label = self.columns[i]
            if isinstance(i, slice):
                # need to return view
                lab_slice = slice(label[0], label[-1])
                return self.loc[:, lab_slice]
            else:
                if isinstance(label, Index):
                    return self._take(i, axis=1)

                index_len = len(self.index)

                # if the values returned are not the same length
                # as the index (iow a not found value), iget returns
                # a 0-len ndarray. This is effectively catching
                # a numpy error (as numpy should really raise)
                values = self._data.iget(i)

                if index_len and not len(values):
                    values = np.array([np.nan] * index_len, dtype=object)
                result = self._box_col_values(values, label)

                # this is a cached value, mark it so
                result._set_as_cached(label, self)

                return result
362480
def reduce(self, dimensions=None, function=None, **reduce_map):
        
        function, dims = self._reduce_map(dimensions, function, reduce_map)
        if len(dims) == self.ndims:
            if isinstance(function, np.ufunc):
                return function.reduce(self.data, axis=None)
            else:
                return function(self.data)
        else:
            dimension = dims[0]
            other_dimension = [d for d in self.kdims if d.name != dimension]
            oidx = self.get_dimension_index(other_dimension[0])
            x_vals = self.dimension_values(other_dimension[0].name, False)
            reduced = function(self._zdata, axis=oidx)
            if oidx and hasattr(self, 'bounds'):
                reduced = reduced[::-1]
            data = zip(x_vals, reduced)
            params = dict(dict(self.get_param_values(onlychanged=True)),
                          kdims=other_dimension, vdims=self.vdims)
            params.pop('bounds', None)
            params.pop('extents', None)
            return Table(data, **params)
1258344
def reduce_axis(data, reducer, block_reducer, mapper=None, axis=None,
                blen=None, storage=None, create='array', **kwargs):
    """"""

    # setup
    storage = _util.get_storage(storage)
    blen = _util.get_blen_array(data, blen)
    length = len(data)
    # normalise axis arg
    if isinstance(axis, int):
        axis = (axis,)

    # deal with 'out' kwarg if supplied, can arise if a chunked array is
    # passed as an argument to numpy.sum(), see also
    # https://github.com/cggh/scikit-allel/issues/66
    kwarg_out = kwargs.pop('out', None)
    if kwarg_out is not None:
        raise ValueError('keyword argument "out" is not supported')

    if axis is None or 0 in axis:
        # two-step reduction
        out = None
        for i in range(0, length, blen):
            j = min(i+blen, length)
            block = data[i:j]
            if mapper:
                block = mapper(block)
            res = reducer(block, axis=axis)
            if out is None:
                out = res
            else:
                out = block_reducer(out, res)
        if np.isscalar(out):
            return out
        elif len(out.shape) == 0:
            return out[()]
        else:
            return getattr(storage, create)(out, **kwargs)

    else:
        # first dimension is preserved, no need to reduce blocks
        out = None
        for i in range(0, length, blen):
            j = min(i+blen, length)
            block = data[i:j]
            if mapper:
                block = mapper(block)
            r = reducer(block, axis=axis)
            if out is None:
                out = getattr(storage, create)(r, expectedlen=length, **kwargs)
            else:
                out.append(r)
        return out
456599
def _fix_slice(self, inputs, new_attr):
        """"""
        begin = new_attr.get('begin')
        end = new_attr.get('end')
        axes = new_attr.get('axis', tuple(range(len(begin))))
        slice_op = mx.sym.slice_axis(inputs[0], axis=axes[0], begin=begin[0], end=end[0])
        if len(axes) > 1:
            for i, axis in enumerate(axes):
                slice_op = mx.sym.slice_axis(slice_op, axis=axis, begin=begin[i], end=end[i])
        return slice_op
772487
def axes(self, ndim=1,
             xlimits=None, ylimits=None, zlimits=None,
             xbins=1, ybins=1, zbins=1):
        
        if xlimits is None:
            xlimits = (0, 1)
        if ylimits is None:
            ylimits = (0, 1)
        if zlimits is None:
            zlimits = (0, 1)
        if ndim == 1:
            from .hist import Hist
            hist = Hist(1, xlimits[0], xlimits[1])
        elif ndim == 2:
            from .hist import Hist2D
            hist = Hist2D(1, xlimits[0], xlimits[1],
                          1, ylimits[0], ylimits[1])
        elif ndim == 3:
            from .hist import Hist3D
            hist = Hist3D(1, xlimits[0], xlimits[1],
                          1, ylimits[0], ylimits[1],
                          1, zlimits[0], zlimits[1])
        else:
            raise ValueError("ndim must be 1, 2, or 3")
        with self:
            hist.Draw('AXIS')
        xaxis = hist.xaxis
        yaxis = hist.yaxis
        if isinstance(xbins, (list, tuple)):
            xbins = array('d', xbins)
        if hasattr(xbins, '__iter__'):
            xaxis.Set(len(xbins) - 1, xbins)
        else:
            xaxis.Set(xbins, *xlimits)
        if ndim > 1:
            if isinstance(ybins, (list, tuple)):
                ybins = array('d', ybins)
            if hasattr(ybins, '__iter__'):
                yaxis.Set(len(ybins) - 1, ybins)
            else:
                yaxis.Set(ybins, *ylimits)
        else:
            yaxis.limits = ylimits
            yaxis.range_user = ylimits
        if ndim > 1:
            zaxis = hist.zaxis
            if ndim == 3:
                if isinstance(zbins, (list, tuple)):
                    zbins = array('d', zbins)
                if hasattr(zbins, '__iter__'):
                    zaxis.Set(len(zbins) - 1, zbins)
                else:
                    zaxis.Set(zbins, *zlimits)
            else:
                zaxis.limits = zlimits
                zaxis.range_user = zlimits
            return xaxis, yaxis, zaxis
        return xaxis, yaxis