def _get_submatrix(self, slice0, slice1):

slice0, slice1 = self._swap((slice0,slice1))<EOL>shape0, shape1 = self._swap(self.shape)<EOL>def _process_slice(sl, num):<EOL><INDENT>if isinstance(sl, slice):<EOL><INDENT>i0, i1 = sl.start, sl.stop<EOL>if i0 is None:<EOL><INDENT>i0 = <NUM_LIT:0><EOL><DEDENT>elif i0 < <NUM_LIT:0>:<EOL><INDENT>i0 = num + i0<EOL><DEDENT>if i1 is None:<EOL><INDENT>i1 = num<EOL><DEDENT>elif i1 < <NUM_LIT:0>:<EOL><INDENT>i1 = num + i1<EOL><DEDENT>return i0, i1<EOL><DEDENT>elif np.isscalar(sl):<EOL><INDENT>if sl < <NUM_LIT:0>:<EOL><INDENT>sl += num<EOL><DEDENT>return sl, sl + <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>return sl[<NUM_LIT:0>], sl[<NUM_LIT:1>]<EOL><DEDENT><DEDENT>def _in_bounds(i0, i1, num):<EOL><INDENT>if not (<NUM_LIT:0> <= i0 < num) or not (<NUM_LIT:0> < i1 <= num) or not (i0 < i1):<EOL><INDENT>raise IndexError("<STR_LIT>" %<EOL>(i0, num, i1, num, i0, i1))<EOL><DEDENT><DEDENT>i0, i1 = _process_slice(slice0, shape0)<EOL>j0, j1 = _process_slice(slice1, shape1)<EOL>_in_bounds(i0, i1, shape0)<EOL>_in_bounds(j0, j1, shape1)<EOL>aux = _sparsetools.get_csr_submatrix(shape0, shape1,<EOL>self.indptr, self.indices,<EOL>self.data,<EOL>i0, i1, j0, j1)<EOL>data, indices, indptr = aux[<NUM_LIT:2>], aux[<NUM_LIT:1>], aux[<NUM_LIT:0>]<EOL>shape = self._swap((i1 - i0, j1 - j0))<EOL>return self.__class__((data, indices, indptr), shape=shape)<EOL>

Return a submatrix of this matrix (new matrix is created).


major_dim,minor_dim = self._swap(self.shape)<EOL>data = self.data<EOL>minor_indices = self.indices<EOL>if copy:<EOL><INDENT>data = data.copy()<EOL>minor_indices = minor_indices.copy()<EOL><DEDENT>major_indices = np.empty(len(minor_indices), dtype=self.indices.dtype)<EOL>_sparsetools.expandptr(major_dim,self.indptr,major_indices)<EOL>row,col = self._swap((major_indices,minor_indices))<EOL>from .coo import coo_matrix<EOL>return coo_matrix((data,(row,col)), self.shape)<EOL>

Return a COOrdinate representation of this matrix

        When copy=False the index and data arrays are not copied.


def toarray(self, order=None, out=None):

return self.tocoo(copy=False).toarray(order=order, out=out)<EOL>

See the docstring for `spmatrix.toarray`.


fn = _sparsetools.csr_eliminate_zeros<EOL>M,N = self._swap(self.shape)<EOL>fn(M, N, self.indptr, self.indices, self.data)<EOL>self.prune()<EOL>

Remove zero entries from the matrix

        This is an *in place* operation


<EOL>if not getattr(self, '<STR_LIT>', True):<EOL><INDENT>self._has_canonical_format = False<EOL><DEDENT>elif not hasattr(self, '<STR_LIT>'):<EOL><INDENT>fn = _sparsetools.csr_has_canonical_format<EOL>self.has_canonical_format =fn(len(self.indptr) - <NUM_LIT:1>, self.indptr, self.indices)<EOL><DEDENT>return self._has_canonical_format<EOL>

Determine whether the matrix has sorted indices and no duplicates

        Returns
            - True: if the above applies
            - False: otherwise

        has_canonical_format implies has_sorted_indices, so if the latter flag
        is False, so will the former be; if the former is found True, the
        latter flag is also set.


if self.has_canonical_format:<EOL><INDENT>return<EOL><DEDENT>self.sort_indices()<EOL>fn = _sparsetools.csr_sum_duplicates<EOL>M,N = self._swap(self.shape)<EOL>fn(M, N, self.indptr, self.indices, self.data)<EOL>self.prune()  <EOL>self.has_canonical_format = True<EOL>

Eliminate duplicate matrix entries by adding them together

        The is an *in place* operation


<EOL>if not hasattr(self,'<STR_LIT>'):<EOL><INDENT>fn = _sparsetools.csr_has_sorted_indices<EOL>self._has_sorted_indices =fn(len(self.indptr) - <NUM_LIT:1>, self.indptr, self.indices)<EOL><DEDENT>return self._has_sorted_indices<EOL>

Determine whether the matrix has sorted indices

        Returns
            - True: if the indices of the matrix are in sorted order
            - False: otherwise


A = self.copy()<EOL>A.sort_indices()<EOL>return A<EOL>

Return a copy of this matrix with sorted indices


if not self.has_sorted_indices:<EOL><INDENT>fn = _sparsetools.csr_sort_indices<EOL>fn(len(self.indptr) - <NUM_LIT:1>, self.indptr, self.indices, self.data)<EOL>self.has_sorted_indices = True<EOL><DEDENT>

Sort the indices of this matrix *in place*


major_dim = self._swap(self.shape)[<NUM_LIT:0>]<EOL>if len(self.indptr) != major_dim + <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if len(self.indices) < self.nnz:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if len(self.data) < self.nnz:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>self.data = self.data[:self.nnz]<EOL>self.indices = self.indices[:self.nnz]<EOL>

Remove empty space after all non-zero elements.


Returns a matrix with the same sparsity structure as self,
        but with different data.  By default the structure arrays
        (i.e. .indptr and .indices) are copied.


other = self.__class__(other)<EOL>fn = getattr(_sparsetools, self.format + op + self.format)<EOL>maxnnz = self.nnz + other.nnz<EOL>idx_dtype = get_index_dtype((self.indptr, self.indices,<EOL>other.indptr, other.indices),<EOL>maxval=maxnnz)<EOL>indptr = np.empty(self.indptr.shape, dtype=idx_dtype)<EOL>indices = np.empty(maxnnz, dtype=idx_dtype)<EOL>bool_ops = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>if op in bool_ops:<EOL><INDENT>data = np.empty(maxnnz, dtype=np.bool_)<EOL><DEDENT>else:<EOL><INDENT>data = np.empty(maxnnz, dtype=upcast(self.dtype, other.dtype))<EOL><DEDENT>fn(self.shape[<NUM_LIT:0>], self.shape[<NUM_LIT:1>],<EOL>np.asarray(self.indptr, dtype=idx_dtype),<EOL>np.asarray(self.indices, dtype=idx_dtype),<EOL>self.data,<EOL>np.asarray(other.indptr, dtype=idx_dtype),<EOL>np.asarray(other.indices, dtype=idx_dtype),<EOL>other.data,<EOL>indptr, indices, data)<EOL>actual_nnz = indptr[-<NUM_LIT:1>]<EOL>indices = indices[:actual_nnz]<EOL>data = data[:actual_nnz]<EOL>if actual_nnz < maxnnz // <NUM_LIT:2>:<EOL><INDENT>indices = indices.copy()<EOL>data = data.copy()<EOL><DEDENT>A = self.__class__((data, indices, indptr), shape=self.shape)<EOL>return A<EOL>

apply the binary operation fn to two sparse matrices.


if other.shape != self.shape:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>r = self._binopt(other, '<STR_LIT>')<EOL>if np.issubdtype(r.dtype, np.inexact):<EOL><INDENT>out = np.empty(self.shape, dtype=self.dtype)<EOL>out.fill(np.nan)<EOL>r = r.tocoo()<EOL>out[r.row, r.col] = r.data<EOL>out = np.matrix(out)<EOL><DEDENT>else:<EOL><INDENT>out = r<EOL><DEDENT>return out<EOL>

Divide this matrix by a second sparse matrix.


t = _upcast_memo.get(hash(args))<EOL>if t is not None:<EOL><INDENT>return t<EOL><DEDENT>if np.all([np.issubdtype(np.bool, arg) for arg in args]):<EOL><INDENT>upcast = np.bool<EOL><DEDENT>else:<EOL><INDENT>upcast = np.find_common_type(args, [])<EOL><DEDENT>for t in supported_dtypes:<EOL><INDENT>if np.can_cast(upcast, t):<EOL><INDENT>_upcast_memo[hash(args)] = t<EOL>return t<EOL><DEDENT><DEDENT>raise TypeError('<STR_LIT>' % (args,))<EOL>

Returns the nearest supported sparse dtype for the
    combination of one or more types.

    upcast(t0, t1, ..., tn) -> T  where T is a supported dtype

    Examples
    --------

    >>> upcast('int32')
    <type 'numpy.int32'>
    >>> upcast('bool')
    <type 'numpy.bool_'>
    >>> upcast('int32','float32')
    <type 'numpy.float64'>
    >>> upcast('bool',complex,float)
    <type 'numpy.complex128'>


t = _upcast_memo.get(args)<EOL>if t is not None:<EOL><INDENT>return t<EOL><DEDENT>t = upcast(*map(np.dtype, args))<EOL>_upcast_memo[args] = t<EOL>return t<EOL>

Same as `upcast` but taking dtype.char as input (faster).


return (np.array([<NUM_LIT:0>], dtype=dtype) * scalar).dtype<EOL>

Determine data type for binary operation between an array of
    type `dtype` and a scalar.


if arr.dtype.itemsize > np.dtype(np.intp).itemsize:<EOL><INDENT>if arr.size == <NUM_LIT:0>:<EOL><INDENT>return arr.astype(np.intp)<EOL><DEDENT>maxval = arr.max()<EOL>minval = arr.min()<EOL>if maxval > np.iinfo(np.intp).max or minval < np.iinfo(np.intp).min:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>return arr.astype(np.intp)<EOL><DEDENT>return arr<EOL>

Down-cast index array to np.intp dtype if it is of a larger dtype.

Raise an error if the array contains a value that is too large for
intp.


def getdtype(dtype, a=None, default=None):

<EOL>canCast = True<EOL>if dtype is None:<EOL><INDENT>try:<EOL><INDENT>newdtype = a.dtype<EOL><DEDENT>except AttributeError:<EOL><INDENT>if default is not None:<EOL><INDENT>newdtype = np.dtype(default)<EOL>canCast = False<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>newdtype = np.dtype(dtype)<EOL>if newdtype == np.object_:<EOL><INDENT>warnings.warn("<STR_LIT>")<EOL><DEDENT><DEDENT>return newdtype<EOL>

Function used to simplify argument processing.  If 'dtype' is not
    specified (is None), returns a.dtype; otherwise returns a np.dtype
    object created from the specified dtype argument.  If 'dtype' and 'a'
    are both None, construct a data type out of the 'default' parameter.
    Furthermore, 'dtype' must be in 'allowed' set.


def get_index_dtype(arrays=(), maxval=None, check_contents=False):

int32max = np.iinfo(np.int32).max<EOL>dtype = np.intc<EOL>if maxval is not None:<EOL><INDENT>if maxval > int32max:<EOL><INDENT>dtype = np.int64<EOL><DEDENT><DEDENT>if isinstance(arrays, np.ndarray):<EOL><INDENT>arrays = (arrays,)<EOL><DEDENT>for arr in arrays:<EOL><INDENT>arr = np.asarray(arr)<EOL>if arr.dtype > np.int32:<EOL><INDENT>if check_contents:<EOL><INDENT>if arr.size == <NUM_LIT:0>:<EOL><INDENT>continue<EOL><DEDENT>elif np.issubdtype(arr.dtype, np.integer):<EOL><INDENT>maxval = arr.max()<EOL>minval = arr.min()<EOL>if minval >= np.iinfo(np.int32).min and maxval <= np.iinfo(np.int32).max:<EOL><INDENT>continue<EOL><DEDENT><DEDENT><DEDENT>dtype = np.int64<EOL>break<EOL><DEDENT><DEDENT>return dtype<EOL>

Based on input (integer) arrays `a`, determine a suitable index data
type that can hold the data in the arrays.

Parameters
----------
arrays : tuple of array_like
    Input arrays whose types/contents to check
maxval : float, optional
    Maximum value needed
check_contents : bool, optional
    Whether to check the values in the arrays and not just their types.
    Default: False (check only the types)

Returns
-------
dtype : dtype
    Suitable index data type (int32 or int64)


return np.isscalar(x) or (isdense(x) and x.ndim == <NUM_LIT:0>)<EOL>

Is x either a scalar, an array scalar, or a 0-dim array?


if issequence(x):<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>if int(x) == x:<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>except TypeError:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>

Is x appropriate as an index into a sparse matrix? Returns True
    if it can be cast safely to a machine int.


try:<EOL><INDENT>(M, N) = x<EOL><DEDENT>except:<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>if isintlike(M) and isintlike(N):<EOL><INDENT>if np.ndim(M) == <NUM_LIT:0> and np.ndim(N) == <NUM_LIT:0>:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL><DEDENT>


def _compat_unique_impl(ar, return_index=False, return_inverse=False):

try:<EOL><INDENT>ar = ar.flatten()<EOL><DEDENT>except AttributeError:<EOL><INDENT>if not return_inverse and not return_index:<EOL><INDENT>items = sorted(set(ar))<EOL>return np.asarray(items)<EOL><DEDENT>else:<EOL><INDENT>ar = np.asanyarray(ar).flatten()<EOL><DEDENT><DEDENT>if ar.size == <NUM_LIT:0>:<EOL><INDENT>if return_inverse and return_index:<EOL><INDENT>return ar, np.empty(<NUM_LIT:0>, np.bool), np.empty(<NUM_LIT:0>, np.bool)<EOL><DEDENT>elif return_inverse or return_index:<EOL><INDENT>return ar, np.empty(<NUM_LIT:0>, np.bool)<EOL><DEDENT>else:<EOL><INDENT>return ar<EOL><DEDENT><DEDENT>if return_inverse or return_index:<EOL><INDENT>if return_index:<EOL><INDENT>perm = ar.argsort(kind='<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>perm = ar.argsort()<EOL><DEDENT>aux = ar[perm]<EOL>flag = np.concatenate(([True], aux[<NUM_LIT:1>:] != aux[:-<NUM_LIT:1>]))<EOL>if return_inverse:<EOL><INDENT>iflag = np.cumsum(flag) - <NUM_LIT:1><EOL>iperm = perm.argsort()<EOL>if return_index:<EOL><INDENT>return aux[flag], perm[flag], iflag[iperm]<EOL><DEDENT>else:<EOL><INDENT>return aux[flag], iflag[iperm]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return aux[flag], perm[flag]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>ar.sort()<EOL>flag = np.concatenate(([True], ar[<NUM_LIT:1>:] != ar[:-<NUM_LIT:1>]))<EOL>return ar[flag]<EOL><DEDENT>

Copy of numpy.unique() from Numpy 1.7.1.

Earlier versions have bugs in how return_index behaves.


def _compat_bincount_impl(x, weights=None, minlength=None):

if weights is None:<EOL><INDENT>x = np.bincount(x)<EOL><DEDENT>else:<EOL><INDENT>x = np.bincount(x, weights=weights)<EOL><DEDENT>if minlength is not None:<EOL><INDENT>if x.shape[<NUM_LIT:0>] < minlength:<EOL><INDENT>x = np.r_[x, np.zeros((minlength - x.shape[<NUM_LIT:0>],))]<EOL><DEDENT><DEDENT>return x<EOL>

Bincount with minlength keyword added for Numpy 1.5.


start, stop, step = j.indices(shape)<EOL>return np.arange(start, stop, step)<EOL>

Given a slice object, use numpy arange to change it to a 1D
        array.


<EOL>from .base import spmatrix  <EOL>if (isinstance(index, (spmatrix, np.ndarray)) and<EOL>(index.ndim == <NUM_LIT:2>) and index.dtype.kind == '<STR_LIT:b>'):<EOL><INDENT>return index.nonzero()<EOL><DEDENT>index = self._check_ellipsis(index)<EOL>if isinstance(index, tuple):<EOL><INDENT>if len(index) == <NUM_LIT:2>:<EOL><INDENT>row, col = index<EOL><DEDENT>elif len(index) == <NUM_LIT:1>:<EOL><INDENT>row, col = index[<NUM_LIT:0>], slice(None)<EOL><DEDENT>else:<EOL><INDENT>raise IndexError('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>row, col = index, slice(None)<EOL><DEDENT>row, col = self._check_boolean(row, col)<EOL>return row, col<EOL>

Parse index. Always return a tuple of the form (row, col).
        Where row/col is a integer, slice, or array of integers.


if index is Ellipsis:<EOL><INDENT>return (slice(None), slice(None))<EOL><DEDENT>elif isinstance(index, tuple):<EOL><INDENT>for j, v in enumerate(index):<EOL><INDENT>if v is Ellipsis:<EOL><INDENT>first_ellipsis = j<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>first_ellipsis = None<EOL><DEDENT>if first_ellipsis is not None:<EOL><INDENT>if len(index) == <NUM_LIT:1>:<EOL><INDENT>return (slice(None), slice(None))<EOL><DEDENT>elif len(index) == <NUM_LIT:2>:<EOL><INDENT>if first_ellipsis == <NUM_LIT:0>:<EOL><INDENT>if index[<NUM_LIT:1>] is Ellipsis:<EOL><INDENT>return (slice(None), slice(None))<EOL><DEDENT>else:<EOL><INDENT>return (slice(None), index[<NUM_LIT:1>])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return (index[<NUM_LIT:0>], slice(None))<EOL><DEDENT><DEDENT>tail = ()<EOL>for v in index[first_ellipsis+<NUM_LIT:1>:]:<EOL><INDENT>if v is not Ellipsis:<EOL><INDENT>tail = tail + (v,)<EOL><DEDENT><DEDENT>nd = first_ellipsis + len(tail)<EOL>nslice = max(<NUM_LIT:0>, <NUM_LIT:2> - nd)<EOL>return index[:first_ellipsis] + (slice(None),)*nslice + tail<EOL><DEDENT><DEDENT>return index<EOL>

Process indices with Ellipsis. Returns modified index.


if axis is None:<EOL><INDENT>return sum([len(rowvals) for rowvals in self.data])<EOL><DEDENT>if axis < <NUM_LIT:0>:<EOL><INDENT>axis += <NUM_LIT:2><EOL><DEDENT>if axis == <NUM_LIT:0>:<EOL><INDENT>out = np.zeros(self.shape[<NUM_LIT:1>])<EOL>for row in self.rows:<EOL><INDENT>out[row] += <NUM_LIT:1><EOL><DEDENT>return out<EOL><DEDENT>elif axis == <NUM_LIT:1>:<EOL><INDENT>return np.array([len(rowvals) for rowvals in self.data])<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>

Get the count of explicitly-stored values (nonzeros)

        Parameters
        ----------
        axis : None, 0, or 1
            Select between the number of values across the whole matrix, in
            each column, or in each row.


new = lil_matrix((<NUM_LIT:1>, self.shape[<NUM_LIT:1>]), dtype=self.dtype)<EOL>new.rows[<NUM_LIT:0>] = self.rows[i]<EOL>new.data[<NUM_LIT:0>] = self.data[i]<EOL>return new<EOL>

Returns a view of the 'i'th row (without copying).


new = lil_matrix((<NUM_LIT:1>, self.shape[<NUM_LIT:1>]), dtype=self.dtype)<EOL>new.rows[<NUM_LIT:0>] = self.rows[i][:]<EOL>new.data[<NUM_LIT:0>] = self.data[i][:]<EOL>return new<EOL>


<EOL>if isinstance(index, tuple) and len(index) == <NUM_LIT:2>:<EOL><INDENT>i, j = index<EOL>if ((isinstance(i, int) or isinstance(i, np.integer)) and<EOL>(isinstance(j, int) or isinstance(j, np.integer))):<EOL><INDENT>v = _csparsetools.lil_get1(self.shape[<NUM_LIT:0>], self.shape[<NUM_LIT:1>],<EOL>self.rows, self.data,<EOL>i, j)<EOL>return self.dtype.type(v)<EOL><DEDENT><DEDENT>i, j = self._unpack_index(index)<EOL>if isscalarlike(i) and isscalarlike(j):<EOL><INDENT>v = _csparsetools.lil_get1(self.shape[<NUM_LIT:0>], self.shape[<NUM_LIT:1>],<EOL>self.rows, self.data,<EOL>i, j)<EOL>return self.dtype.type(v)<EOL><DEDENT>i, j = self._index_to_arrays(i, j)<EOL>if i.size == <NUM_LIT:0>:<EOL><INDENT>return lil_matrix(i.shape, dtype=self.dtype)<EOL><DEDENT>new = lil_matrix(i.shape, dtype=self.dtype)<EOL>i, j = _csparsetools.prepare_index_for_memoryview(i, j)<EOL>_csparsetools.lil_fancy_get(self.shape[<NUM_LIT:0>], self.shape[<NUM_LIT:1>],<EOL>self.rows, self.data,<EOL>new.rows, new.data,<EOL>i, j)<EOL>return new<EOL>

Return the element(s) index=(i, j), where j may be a slice.
        This always returns a copy for consistency, since slices into
        Python lists return copies.


d = self._process_toarray_args(order, out)<EOL>for i, row in enumerate(self.rows):<EOL><INDENT>for pos, j in enumerate(row):<EOL><INDENT>d[i, j] = self.data[i][pos]<EOL><DEDENT><DEDENT>return d<EOL>

See the docstring for `spmatrix.toarray`.


lst = [len(x) for x in self.rows]<EOL>idx_dtype = get_index_dtype(maxval=max(self.shape[<NUM_LIT:1>], sum(lst)))<EOL>indptr = np.asarray(lst, dtype=idx_dtype)<EOL>indptr = np.concatenate((np.array([<NUM_LIT:0>], dtype=idx_dtype),<EOL>np.cumsum(indptr, dtype=idx_dtype)))<EOL>indices = []<EOL>for x in self.rows:<EOL><INDENT>indices.extend(x)<EOL><DEDENT>indices = np.asarray(indices, dtype=idx_dtype)<EOL>data = []<EOL>for x in self.data:<EOL><INDENT>data.extend(x)<EOL><DEDENT>data = np.asarray(data, dtype=self.dtype)<EOL>from .csr import csr_matrix<EOL>return csr_matrix((data, indices, indptr), shape=self.shape)<EOL>

Return Compressed Sparse Row format arrays for this matrix.


return self.tocsr().tocsc()<EOL>

Return Compressed Sparse Column format arrays for this matrix.


return self._min_or_max(axis, np.maximum)<EOL>

Maximum of the elements of this matrix.

        This takes all elements into account, not just the non-zero ones.

        Returns
        -------
        amax : self.dtype
            Maximum element.


return self._min_or_max(axis, np.minimum)<EOL>

Minimum of the elements of this matrix.

        This takes all elements into account, not just the non-zero ones.

        Returns
        -------
        amin : self.dtype
            Minimum element.


fp_types = ['<STR_LIT:f>','<STR_LIT:d>','<STR_LIT:F>','<STR_LIT:D>']<EOL>if self.dtype.char in fp_types:<EOL><INDENT>return self<EOL><DEDENT>else:<EOL><INDENT>for fp_type in fp_types:<EOL><INDENT>if self.dtype <= np.dtype(fp_type):<EOL><INDENT>return self.astype(fp_type)<EOL><DEDENT><DEDENT>raise TypeError('<STR_LIT>'<EOL>'<STR_LIT>' % self.dtype.name)<EOL><DEDENT>

Upcast matrix to a floating point format (if necessary)


if format is None or format == self.format:<EOL><INDENT>return self<EOL><DEDENT>else:<EOL><INDENT>return getattr(self,'<STR_LIT:to>' + format)()<EOL><DEDENT>

Return this matrix in a given sparse format

        Parameters
        ----------
        format : {string, None}
            desired sparse matrix format
                - None for no format conversion
                - "csr" for csr_matrix format
                - "csc" for csc_matrix format
                - "lil" for lil_matrix format
                - "dok" for dok_matrix format and so on


return self.tocsr().multiply(other)<EOL>

Point-wise multiplication by another matrix


return self * other<EOL>

Ordinary dot product

        Examples
        --------
        >>> import numpy as np
        >>> from scipy.sparse import csr_matrix
        >>> A = csr_matrix([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
        >>> v = np.array([1, 0, -1])
        >>> A.dot(v)
        array([ 1, -3, -1], dtype=int64)


M,N = self.shape<EOL>if other.__class__ is np.ndarray:<EOL><INDENT>if other.shape == (N,):<EOL><INDENT>return self._mul_vector(other)<EOL><DEDENT>elif other.shape == (N, <NUM_LIT:1>):<EOL><INDENT>return self._mul_vector(other.ravel()).reshape(M, <NUM_LIT:1>)<EOL><DEDENT>elif other.ndim == <NUM_LIT:2> and other.shape[<NUM_LIT:0>] == N:<EOL><INDENT>return self._mul_multivector(other)<EOL><DEDENT><DEDENT>if isscalarlike(other):<EOL><INDENT>return self._mul_scalar(other)<EOL><DEDENT>if issparse(other):<EOL><INDENT>if self.shape[<NUM_LIT:1>] != other.shape[<NUM_LIT:0>]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return self._mul_sparse_matrix(other)<EOL><DEDENT>try:<EOL><INDENT>other.shape<EOL><DEDENT>except AttributeError:<EOL><INDENT>other_a = np.asanyarray(other)<EOL>if other_a.ndim == <NUM_LIT:0> and other_a.dtype == np.object_:<EOL><INDENT>return NotImplemented<EOL><DEDENT>other = other_a<EOL><DEDENT>if other.ndim == <NUM_LIT:1> or other.ndim == <NUM_LIT:2> and other.shape[<NUM_LIT:1>] == <NUM_LIT:1>:<EOL><INDENT>if other.shape != (N,) and other.shape != (N,<NUM_LIT:1>):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>result = self._mul_vector(np.ravel(other))<EOL>if isinstance(other, np.matrix):<EOL><INDENT>result = np.asmatrix(result)<EOL><DEDENT>if other.ndim == <NUM_LIT:2> and other.shape[<NUM_LIT:1>] == <NUM_LIT:1>:<EOL><INDENT>result = result.reshape(-<NUM_LIT:1>,<NUM_LIT:1>)<EOL><DEDENT>return result<EOL><DEDENT>elif other.ndim == <NUM_LIT:2>:<EOL><INDENT>if other.shape[<NUM_LIT:0>] != self.shape[<NUM_LIT:1>]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>result = self._mul_multivector(np.asarray(other))<EOL>if isinstance(other, np.matrix):<EOL><INDENT>result = np.asmatrix(result)<EOL><DEDENT>return result<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>

interpret other and call one of the following

        self._mul_scalar()
        self._mul_vector()
        self._mul_multivector()
        self._mul_sparse_matrix()


<EOL>A = self.tocoo()<EOL>nz_mask = A.data != <NUM_LIT:0><EOL>return (A.row[nz_mask],A.col[nz_mask])<EOL>

nonzero indices

        Returns a tuple of arrays (row,col) containing the indices
        of the non-zero elements of the matrix.

        Examples
        --------
        >>> from scipy.sparse import csr_matrix
        >>> A = csr_matrix([[1,2,0],[0,0,3],[4,0,5]])
        >>> A.nonzero()
        (array([0, 0, 1, 2, 2]), array([0, 1, 2, 0, 2]))


<EOL>from .csc import csc_matrix<EOL>n = self.shape[<NUM_LIT:1>]<EOL>if j < <NUM_LIT:0>:<EOL><INDENT>j += n<EOL><DEDENT>if j < <NUM_LIT:0> or j >= n:<EOL><INDENT>raise IndexError("<STR_LIT>")<EOL><DEDENT>col_selector = csc_matrix(([<NUM_LIT:1>], [[j], [<NUM_LIT:0>]]), shape=(n,<NUM_LIT:1>), dtype=self.dtype)<EOL>return self * col_selector<EOL>

Returns a copy of column j of the matrix, as an (m x 1) sparse
        matrix (column vector).


<EOL>from .csr import csr_matrix<EOL>m = self.shape[<NUM_LIT:0>]<EOL>if i < <NUM_LIT:0>:<EOL><INDENT>i += m<EOL><DEDENT>if i < <NUM_LIT:0> or i >= m:<EOL><INDENT>raise IndexError("<STR_LIT>")<EOL><DEDENT>row_selector = csr_matrix(([<NUM_LIT:1>], [[<NUM_LIT:0>], [i]]), shape=(<NUM_LIT:1>,m), dtype=self.dtype)<EOL>return row_selector * self<EOL>

Returns a copy of row i of the matrix, as a (1 x n) sparse
        matrix (row vector).


def todense(self, order=None, out=None):

return np.asmatrix(self.toarray(order=order, out=out))<EOL>

Return a dense matrix representation of this matrix.

Parameters
----------
order : {'C', 'F'}, optional
    Whether to store multi-dimensional data in C (row-major)
    or Fortran (column-major) order in memory. The default
    is 'None', indicating the NumPy default of C-ordered.
    Cannot be specified in conjunction with the `out`
    argument.

out : ndarray, 2-dimensional, optional
    If specified, uses this array (or `numpy.matrix`) as the
    output buffer instead of allocating a new array to
    return. The provided array must have the same shape and
    dtype as the sparse matrix on which you are calling the
    method.

Returns
-------
arr : numpy.matrix, 2-dimensional
    A NumPy matrix object with the same shape and containing
    the same data represented by the sparse matrix, with the
    requested memory order. If `out` was passed and was an
    array (rather than a `numpy.matrix`), it will be filled
    with the appropriate values and returned wrapped in a
    `numpy.matrix` object that shares the same memory.


return self.tocoo().toarray(order=order, out=out)<EOL>

Return a dense ndarray representation of this matrix.

Parameters
----------
order : {'C', 'F'}, optional
    Whether to store multi-dimensional data in C (row-major)
    or Fortran (column-major) order in memory. The default
    is 'None', indicating the NumPy default of C-ordered.
    Cannot be specified in conjunction with the `out`
    argument.

out : ndarray, 2-dimensional, optional
    If specified, uses this array as the output buffer
    instead of allocating a new array to return. The provided
    array must have the same shape and dtype as the sparse
    matrix on which you are calling the method. For most
    sparse types, `out` is required to be memory contiguous
    (either C or Fortran ordered).

Returns
-------
arr : ndarray, 2-dimensional
    An array with the same shape and containing the same
    data represented by the sparse matrix, with the requested
    memory order. If `out` was passed, the same object is
    returned after being modified in-place to contain the
    appropriate values.


<EOL>m, n = self.shape<EOL>if np.issubdtype(self.dtype, np.float_):<EOL><INDENT>res_dtype = np.float_<EOL><DEDENT>elif (np.issubdtype(self.dtype, np.int_) or<EOL>np.issubdtype(self.dtype, np.bool_)):<EOL><INDENT>res_dtype = np.int_<EOL><DEDENT>elif np.issubdtype(self.dtype, np.complex_):<EOL><INDENT>res_dtype = np.complex_<EOL><DEDENT>else:<EOL><INDENT>res_dtype = self.dtype<EOL><DEDENT>if axis is None:<EOL><INDENT>return (self * np.asmatrix(np.ones((n, <NUM_LIT:1>), dtype=res_dtype))).sum()<EOL><DEDENT>if axis < <NUM_LIT:0>:<EOL><INDENT>axis += <NUM_LIT:2><EOL><DEDENT>if axis == <NUM_LIT:0>:<EOL><INDENT>return np.asmatrix(np.ones((<NUM_LIT:1>, m), dtype=res_dtype)) * self<EOL><DEDENT>elif axis == <NUM_LIT:1>:<EOL><INDENT>return self * np.asmatrix(np.ones((n, <NUM_LIT:1>), dtype=res_dtype))<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>

Sum the matrix over the given axis.  If the axis is None, sum
        over both rows and columns, returning a scalar.


<EOL>if (np.issubdtype(self.dtype, np.float_) or<EOL>np.issubdtype(self.dtype, np.int_) or<EOL>self.dtype in [np.dtype('<STR_LIT>'), np.dtype('<STR_LIT>')] or<EOL>np.issubdtype(self.dtype, np.bool_)):<EOL><INDENT>res_dtype = np.float_<EOL><DEDENT>elif np.issubdtype(self.dtype, np.complex_):<EOL><INDENT>res_dtype = np.complex_<EOL><DEDENT>else:<EOL><INDENT>res_dtype = self.dtype<EOL><DEDENT>if axis is None:<EOL><INDENT>return self.sum(None) * <NUM_LIT:1.0> / (self.shape[<NUM_LIT:0>]*self.shape[<NUM_LIT:1>])<EOL><DEDENT>if axis < <NUM_LIT:0>:<EOL><INDENT>axis += <NUM_LIT:2><EOL><DEDENT>if axis == <NUM_LIT:0>:<EOL><INDENT>mean = self.astype(res_dtype).sum(<NUM_LIT:0>)<EOL>mean *= <NUM_LIT:1.0> / self.shape[<NUM_LIT:0>]<EOL>return mean<EOL><DEDENT>elif axis == <NUM_LIT:1>:<EOL><INDENT>mean = self.astype(res_dtype).sum(<NUM_LIT:1>)<EOL>mean *= <NUM_LIT:1.0> / self.shape[<NUM_LIT:1>]<EOL>return mean<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>

Average the matrix over the given axis.  If the axis is None,
        average over both rows and columns, returning a scalar.


<EOL>return self.tocsr().diagonal()<EOL>


def setdiag(self, values, k=<NUM_LIT:0>):

M, N = self.shape<EOL>if (k > <NUM_LIT:0> and k >= N) or (k < <NUM_LIT:0> and -k >= M):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self._setdiag(np.asarray(values), k)<EOL>

Set diagonal or off-diagonal elements of the array.

Parameters
----------
values : array_like
    New values of the diagonal elements.

    Values may have any length.  If the diagonal is longer than values,
    then the remaining diagonal entries will not be set.  If values if
    longer than the diagonal, then the remaining values are ignored.

    If a scalar value is given, all of the diagonal is set to it.

k : int, optional
    Which off-diagonal to set, corresponding to elements a[i,i+k].
    Default: 0 (the main diagonal).


def __numpy_ufunc__(self, func, method, pos, inputs, **kwargs):

if any(not isinstance(x, spmatrix) and np.asarray(x).dtype == object<EOL>for x in inputs):<EOL><INDENT>with_self = list(inputs)<EOL>with_self[pos] = np.asarray(self, dtype=object)<EOL>return getattr(func, method)(*with_self, **kwargs)<EOL><DEDENT>out = kwargs.pop('<STR_LIT>', None)<EOL>if method != '<STR_LIT>' or kwargs:<EOL><INDENT>return NotImplemented<EOL><DEDENT>without_self = list(inputs)<EOL>del without_self[pos]<EOL>without_self = tuple(without_self)<EOL>if func is np.multiply:<EOL><INDENT>result = self.multiply(*without_self)<EOL><DEDENT>elif func is np.add:<EOL><INDENT>result = self.__add__(*without_self)<EOL><DEDENT>elif func is np.dot:<EOL><INDENT>if pos == <NUM_LIT:0>:<EOL><INDENT>result = self.__mul__(inputs[<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>result = self.__rmul__(inputs[<NUM_LIT:0>])<EOL><DEDENT><DEDENT>elif func is np.subtract:<EOL><INDENT>if pos == <NUM_LIT:0>:<EOL><INDENT>result = self.__sub__(inputs[<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>result = self.__rsub__(inputs[<NUM_LIT:0>])<EOL><DEDENT><DEDENT>elif func is np.divide:<EOL><INDENT>true_divide = (sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>)<EOL>rdivide = (pos == <NUM_LIT:1>)<EOL>result = self._divide(*without_self,<EOL>true_divide=true_divide,<EOL>rdivide=rdivide)<EOL><DEDENT>elif func is np.true_divide:<EOL><INDENT>rdivide = (pos == <NUM_LIT:1>)<EOL>result = self._divide(*without_self, true_divide=True, rdivide=rdivide)<EOL><DEDENT>elif func is np.maximum:<EOL><INDENT>result = self.maximum(*without_self)<EOL><DEDENT>elif func is np.minimum:<EOL><INDENT>result = self.minimum(*without_self)<EOL><DEDENT>elif func is np.absolute:<EOL><INDENT>result = abs(self)<EOL><DEDENT>elif func in (np.sin, np.tan, np.arcsin, np.arctan, np.sinh, np.tanh,<EOL>np.arcsinh, np.arctanh, np.rint, np.sign, np.expm1, np.log1p,<EOL>np.deg2rad, np.rad2deg, np.floor, np.ceil, np.trunc, np.sqrt):<EOL><INDENT>func_name = func.__name__<EOL>if hasattr(self, func_name):<EOL><INDENT>result = getattr(self, func_name)()<EOL><DEDENT>else:<EOL><INDENT>result = getattr(self.tocsr(), func_name)()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return NotImplemented<EOL><DEDENT>if out is not None:<EOL><INDENT>if not isinstance(out, spmatrix) and isinstance(result, spmatrix):<EOL><INDENT>out[...] = result.todense()<EOL><DEDENT>else:<EOL><INDENT>out[...] = result<EOL><DEDENT>result = out<EOL><DEDENT>return result<EOL>

Method for compatibility with NumPy's ufuncs and dot
        functions.


return (x[<NUM_LIT:0>],x[<NUM_LIT:1>])<EOL>

swap the members of x if this is a column-oriented matrix


return self._get_submatrix(i, slice(None))<EOL>

Returns a copy of row i of the matrix, as a (1 x n)
        CSR matrix (row vector).


return self._get_submatrix(slice(None), i)<EOL>

Returns a copy of column i of the matrix, as a (m x 1)
        CSR matrix (column vector).


if i < <NUM_LIT:0>:<EOL><INDENT>i += self.shape[<NUM_LIT:0>]<EOL><DEDENT>if i < <NUM_LIT:0> or i >= self.shape[<NUM_LIT:0>]:<EOL><INDENT>raise IndexError('<STR_LIT>' % i)<EOL><DEDENT>start, stop, stride = cslice.indices(self.shape[<NUM_LIT:1>])<EOL>if stride == <NUM_LIT:1>:<EOL><INDENT>row_slice = self._get_submatrix(i, cslice)<EOL><DEDENT>else:<EOL><INDENT>row_indices = self.indices[self.indptr[i]:self.indptr[i + <NUM_LIT:1>]]<EOL>row_data = self.data[self.indptr[i]:self.indptr[i + <NUM_LIT:1>]]<EOL>if stride > <NUM_LIT:0>:<EOL><INDENT>ind = (row_indices >= start) & (row_indices < stop)<EOL><DEDENT>elif stride < <NUM_LIT:0>:<EOL><INDENT>ind = (row_indices <= start) & (row_indices > stop)<EOL><DEDENT>if abs(stride) > <NUM_LIT:1>:<EOL><INDENT>ind = ind & ((row_indices - start) % stride == <NUM_LIT:0>)<EOL><DEDENT>row_indices = (row_indices[ind] - start) // stride<EOL>row_data = row_data[ind]<EOL>row_indptr = np.array([<NUM_LIT:0>, len(row_indices)])<EOL>if stride < <NUM_LIT:0>:<EOL><INDENT>row_data = row_data[::-<NUM_LIT:1>]<EOL>row_indices = abs(row_indices[::-<NUM_LIT:1>])<EOL><DEDENT>shape = (<NUM_LIT:1>, int(np.ceil(float(stop - start) / stride)))<EOL>row_slice = csr_matrix((row_data, row_indices, row_indptr),<EOL>shape=shape)<EOL><DEDENT>return row_slice<EOL>


def _get_submatrix(self, row_slice, col_slice):

M,N = self.shape<EOL>def process_slice(sl, num):<EOL><INDENT>if isinstance(sl, slice):<EOL><INDENT>if sl.step not in (<NUM_LIT:1>, None):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>i0, i1 = sl.start, sl.stop<EOL>if i0 is None:<EOL><INDENT>i0 = <NUM_LIT:0><EOL><DEDENT>elif i0 < <NUM_LIT:0>:<EOL><INDENT>i0 = num + i0<EOL><DEDENT>if i1 is None:<EOL><INDENT>i1 = num<EOL><DEDENT>elif i1 < <NUM_LIT:0>:<EOL><INDENT>i1 = num + i1<EOL><DEDENT>return i0, i1<EOL><DEDENT>elif isintlike(sl):<EOL><INDENT>if sl < <NUM_LIT:0>:<EOL><INDENT>sl += num<EOL><DEDENT>return sl, sl + <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT><DEDENT>def check_bounds(i0, i1, num):<EOL><INDENT>if not (<NUM_LIT:0> <= i0 <= num) or not (<NUM_LIT:0> <= i1 <= num) or not (i0 <= i1):<EOL><INDENT>raise IndexError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % (i0, num, i1, num, i0, i1))<EOL><DEDENT><DEDENT>i0, i1 = process_slice(row_slice, M)<EOL>j0, j1 = process_slice(col_slice, N)<EOL>check_bounds(i0, i1, M)<EOL>check_bounds(j0, j1, N)<EOL>indptr, indices, data = get_csr_submatrix(M, N,<EOL>self.indptr, self.indices, self.data,<EOL>int(i0), int(i1), int(j0), int(j1))<EOL>shape = (i1 - i0, j1 - j0)<EOL>return self.__class__((data,indices,indptr), shape=shape)<EOL>

Return a submatrix of this matrix (new matrix is created).


if N == <NUM_LIT:1>:<EOL><INDENT>diags = asarray([[<NUM_LIT:4>]],dtype=dtype)<EOL>return dia_matrix((diags,[<NUM_LIT:0>]), shape=(<NUM_LIT:1>,<NUM_LIT:1>)).asformat(format)<EOL><DEDENT>offsets = array([<NUM_LIT:0>,-N,N,-<NUM_LIT:1>,<NUM_LIT:1>])<EOL>diags = empty((<NUM_LIT:5>,N**<NUM_LIT:2>),dtype=dtype)<EOL>diags[<NUM_LIT:0>] = <NUM_LIT:4>  <EOL>diags[<NUM_LIT:1>:] = -<NUM_LIT:1>  <EOL>diags[<NUM_LIT:3>,N-<NUM_LIT:1>::N] = <NUM_LIT:0>  <EOL>diags[<NUM_LIT:4>,N::N] = <NUM_LIT:0>  <EOL>return dia_matrix((diags,offsets),shape=(N**<NUM_LIT:2>,N**<NUM_LIT:2>)).asformat(format)<EOL>

Return a sparse matrix for the 2D Poisson problem
with standard 5-point finite difference stencil on a
square N-by-N grid.


matrices = []<EOL>matrices.append(('<STR_LIT>', <NUM_LIT>, <NUM_LIT:10>))<EOL>matrices.append(('<STR_LIT>', <NUM_LIT>, <NUM_LIT>))<EOL>matrices.append(('<STR_LIT>', <NUM_LIT>, <NUM_LIT:50>))<EOL>matrices.append(('<STR_LIT>', <NUM_LIT>, <NUM_LIT:100>))<EOL>matrices.append(('<STR_LIT>', <NUM_LIT>, <NUM_LIT:200>))<EOL>print()<EOL>print('<STR_LIT>')<EOL>print('<STR_LIT>')<EOL>print('<STR_LIT>')<EOL>print('<STR_LIT>')<EOL>fmt = '<STR_LIT>'<EOL>for name,N,K in matrices:<EOL><INDENT>N = int(N)<EOL>A = random_sparse(N,N,K)<EOL>start = time.clock()<EOL>iter = <NUM_LIT:0><EOL>while iter < <NUM_LIT:5> and time.clock() - start < <NUM_LIT:1>:<EOL><INDENT>A.has_sorted_indices = False<EOL>A.indices[:<NUM_LIT:2>] = <NUM_LIT:2>,<NUM_LIT:1><EOL>A.sort_indices()<EOL>iter += <NUM_LIT:1><EOL><DEDENT>end = time.clock()<EOL>name = name.center(<NUM_LIT:12>)<EOL>shape = ("<STR_LIT:%s>" % (A.shape,)).center(<NUM_LIT:20>)<EOL>print(fmt % (A.format,name,shape,A.nnz,<NUM_LIT>*(end-start)/float(iter)))<EOL><DEDENT>


matrices = []<EOL>matrices.append(('<STR_LIT>',csr_matrix((<NUM_LIT>,<NUM_LIT>))))<EOL>matrices.append(('<STR_LIT>',sparse.eye(<NUM_LIT>)))<EOL>matrices.append(('<STR_LIT>', poisson2d(<NUM_LIT:100>)))<EOL>print()<EOL>print('<STR_LIT>')<EOL>print('<STR_LIT>')<EOL>print('<STR_LIT>')<EOL>print('<STR_LIT>')<EOL>fmt = '<STR_LIT>'<EOL>for name,A in matrices:<EOL><INDENT>A = A.tocoo()<EOL>for format in ['<STR_LIT>','<STR_LIT>']:<EOL><INDENT>start = time.clock()<EOL>iter = <NUM_LIT:0><EOL>while time.clock() < start + <NUM_LIT:0.5>:<EOL><INDENT>T = eval(format + '<STR_LIT>')(A.shape)<EOL>for i,j,v in zip(A.row,A.col,A.data):<EOL><INDENT>T[i,j] = v<EOL><DEDENT>iter += <NUM_LIT:1><EOL><DEDENT>end = time.clock()<EOL>del T<EOL>name = name.center(<NUM_LIT:12>)<EOL>shape = ("<STR_LIT:%s>" % (A.shape,)).center(<NUM_LIT:20>)<EOL>print(fmt % (format,name,shape,A.nnz,(end-start)/float(iter)))<EOL><DEDENT><DEDENT>

build matrices by inserting single values


if not isinstance(x, list):<EOL><INDENT>x = list(x)<EOL><DEDENT>return x<EOL>


if len(x) == <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>return functools.reduce(operator.mul, x)<EOL>

Product of a list of numbers; ~40x faster vs np.prod for Python tuples


def get(self, key, default=<NUM_LIT:0.>):

try:<EOL><INDENT>i, j = key<EOL>assert isintlike(i) and isintlike(j)<EOL><DEDENT>except (AssertionError, TypeError, ValueError):<EOL><INDENT>raise IndexError('<STR_LIT>')<EOL><DEDENT>if (i < <NUM_LIT:0> or i >= self.shape[<NUM_LIT:0>] or j < <NUM_LIT:0> or j >= self.shape[<NUM_LIT:1>]):<EOL><INDENT>raise IndexError('<STR_LIT>')<EOL><DEDENT>return dict.get(self, key, default)<EOL>

This overrides the dict.get method, providing type checking
        but otherwise equivalent functionality.


i, j = self._unpack_index(index)<EOL>i_intlike = isintlike(i)<EOL>j_intlike = isintlike(j)<EOL>if i_intlike and j_intlike:<EOL><INDENT>i = int(i)<EOL>j = int(j)<EOL>if i < <NUM_LIT:0>:<EOL><INDENT>i += self.shape[<NUM_LIT:0>]<EOL><DEDENT>if i < <NUM_LIT:0> or i >= self.shape[<NUM_LIT:0>]:<EOL><INDENT>raise IndexError('<STR_LIT>')<EOL><DEDENT>if j < <NUM_LIT:0>:<EOL><INDENT>j += self.shape[<NUM_LIT:1>]<EOL><DEDENT>if j < <NUM_LIT:0> or j >= self.shape[<NUM_LIT:1>]:<EOL><INDENT>raise IndexError('<STR_LIT>')<EOL><DEDENT>return dict.get(self, (i,j), <NUM_LIT:0.>)<EOL><DEDENT>elif ((i_intlike or isinstance(i, slice)) and<EOL>(j_intlike or isinstance(j, slice))):<EOL><INDENT>i_slice = slice(i, i+<NUM_LIT:1>) if i_intlike else i<EOL>j_slice = slice(j, j+<NUM_LIT:1>) if j_intlike else j<EOL>i_indices = i_slice.indices(self.shape[<NUM_LIT:0>])<EOL>j_indices = j_slice.indices(self.shape[<NUM_LIT:1>])<EOL>i_seq = xrange(*i_indices)<EOL>j_seq = xrange(*j_indices)<EOL>newshape = (len(i_seq), len(j_seq))<EOL>newsize = _prod(newshape)<EOL>if len(self) < <NUM_LIT:2>*newsize and newsize != <NUM_LIT:0>:<EOL><INDENT>return self._getitem_ranges(i_indices, j_indices, newshape)<EOL><DEDENT><DEDENT>i, j = self._index_to_arrays(i, j)<EOL>if i.size == <NUM_LIT:0>:<EOL><INDENT>return dok_matrix(i.shape, dtype=self.dtype)<EOL><DEDENT>min_i = i.min()<EOL>if min_i < -self.shape[<NUM_LIT:0>] or i.max() >= self.shape[<NUM_LIT:0>]:<EOL><INDENT>raise IndexError('<STR_LIT>' %<EOL>(i.min(), self.shape[<NUM_LIT:0>], self.shape[<NUM_LIT:0>]-<NUM_LIT:1>))<EOL><DEDENT>if min_i < <NUM_LIT:0>:<EOL><INDENT>i = i.copy()<EOL>i[i < <NUM_LIT:0>] += self.shape[<NUM_LIT:0>]<EOL><DEDENT>min_j = j.min()<EOL>if min_j < -self.shape[<NUM_LIT:0>] or j.max() >= self.shape[<NUM_LIT:1>]:<EOL><INDENT>raise IndexError('<STR_LIT>' %<EOL>(j.min(), self.shape[<NUM_LIT:1>], self.shape[<NUM_LIT:1>]-<NUM_LIT:1>))<EOL><DEDENT>if min_j < <NUM_LIT:0>:<EOL><INDENT>j = j.copy()<EOL>j[j < <NUM_LIT:0>] += self.shape[<NUM_LIT:1>]<EOL><DEDENT>newdok = dok_matrix(i.shape, dtype=self.dtype)<EOL>for a in xrange(i.shape[<NUM_LIT:0>]):<EOL><INDENT>for b in xrange(i.shape[<NUM_LIT:1>]):<EOL><INDENT>v = dict.get(self, (i[a,b], j[a,b]), <NUM_LIT:0.>)<EOL>if v != <NUM_LIT:0>:<EOL><INDENT>dict.__setitem__(newdok, (a, b), v)<EOL><DEDENT><DEDENT><DEDENT>return newdok<EOL>

If key=(i,j) is a pair of integers, return the corresponding
        element.  If either i or j is a slice or sequence, return a new sparse
        matrix with just these elements.


M, N = self.shape<EOL>new = dok_matrix((N, M), dtype=self.dtype)<EOL>for key, value in iteritems(self):<EOL><INDENT>new[key[<NUM_LIT:1>], key[<NUM_LIT:0>]] = value<EOL><DEDENT>return new<EOL>


M, N = self.shape<EOL>new = dok_matrix((N, M), dtype=self.dtype)<EOL>for key, value in iteritems(self):<EOL><INDENT>new[key[<NUM_LIT:1>], key[<NUM_LIT:0>]] = np.conj(value)<EOL><DEDENT>return new<EOL>


out = self.__class__((<NUM_LIT:1>, self.shape[<NUM_LIT:1>]), dtype=self.dtype)<EOL>for j in range(self.shape[<NUM_LIT:1>]):<EOL><INDENT>out[<NUM_LIT:0>, j] = self[i, j]<EOL><DEDENT>return out<EOL>

Returns a copy of row i of the matrix as a (1 x n)
        DOK matrix.


out = self.__class__((self.shape[<NUM_LIT:0>], <NUM_LIT:1>), dtype=self.dtype)<EOL>for i in range(self.shape[<NUM_LIT:0>]):<EOL><INDENT>out[i, <NUM_LIT:0>] = self[i, j]<EOL><DEDENT>return out<EOL>

Returns a copy of column j of the matrix as a (m x 1)
        DOK matrix.


from .coo import coo_matrix<EOL>if self.nnz == <NUM_LIT:0>:<EOL><INDENT>return coo_matrix(self.shape, dtype=self.dtype)<EOL><DEDENT>else:<EOL><INDENT>idx_dtype = get_index_dtype(maxval=max(self.shape[<NUM_LIT:0>], self.shape[<NUM_LIT:1>]))<EOL>data = np.asarray(_list(self.values()), dtype=self.dtype)<EOL>indices = np.asarray(_list(self.keys()), dtype=idx_dtype).T<EOL>return coo_matrix((data,indices), shape=self.shape, dtype=self.dtype)<EOL><DEDENT>

Return a copy of this matrix in COOrdinate format


return self.tocoo().tocsr()<EOL>

Return a copy of this matrix in Compressed Sparse Row format


return self.tocoo().tocsc()<EOL>

Return a copy of this matrix in Compressed Sparse Column format


return self.tocoo().toarray(order=order, out=out)<EOL>

See the docstring for `spmatrix.toarray`.


if not isshape(shape):<EOL><INDENT>raise TypeError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>newM, newN = shape<EOL>M, N = self.shape<EOL>if newM < M or newN < N:<EOL><INDENT>for (i, j) in list(self.keys()):<EOL><INDENT>if i >= newM or j >= newN:<EOL><INDENT>del self[i, j]<EOL><DEDENT><DEDENT><DEDENT>self._shape = shape<EOL>

Resize the matrix in-place to dimensions given by 'shape'.

        Any non-zero elements that lie outside the new shape are removed.


it_types = []<EOL>i_types = []<EOL>j = <NUM_LIT:0><EOL>getter_code = "<STR_LIT>"<EOL>for I_typenum, I_type in I_TYPES:<EOL><INDENT>piece = """<STR_LIT>"""<EOL>getter_code += piece % dict(I_typenum=I_typenum, j=j)<EOL>i_types.append((j, I_typenum, None, I_type, None))<EOL>j += <NUM_LIT:1><EOL>for T_typenum, T_type in T_TYPES:<EOL><INDENT>piece = """<STR_LIT>"""<EOL>getter_code += piece % dict(T_typenum=T_typenum, j=j)<EOL>it_types.append((j, I_typenum, T_typenum, I_type, T_type))<EOL>j += <NUM_LIT:1><EOL><DEDENT>getter_code += """<STR_LIT>"""<EOL><DEDENT>return i_types, it_types, GET_THUNK_CASE_TEMPLATE % dict(content=getter_code)<EOL>

Get a list containing cartesian product of data types, plus a getter routine.

Returns
-------
i_types : list [(j, I_typenum, None, I_type, None), ...]
     Pairing of index type numbers and the corresponding C++ types,
     and an unique index `j`. This is for routines that are parameterized
     only by I but not by T.
it_types : list [(j, I_typenum, T_typenum, I_type, T_type), ...]
     Same as `i_types`, but for routines parameterized both by T and I.
getter_code : str
     C++ code for a function that takes I_typenum, T_typenum and returns
     the unique index corresponding to the lists, or -1 if no match was
     found.


ret_spec = args[<NUM_LIT:0>]<EOL>arg_spec = args[<NUM_LIT:1>:]<EOL>def get_arglist(I_type, T_type):<EOL><INDENT>"""<STR_LIT>"""<EOL>args = []<EOL>next_is_writeable = False<EOL>j = <NUM_LIT:0><EOL>for t in arg_spec:<EOL><INDENT>const = '<STR_LIT>' if next_is_writeable else '<STR_LIT>'<EOL>next_is_writeable = False<EOL>if t == '<STR_LIT:*>':<EOL><INDENT>next_is_writeable = True<EOL>continue<EOL><DEDENT>elif t == '<STR_LIT:i>':<EOL><INDENT>args.append("<STR_LIT>" % (const + I_type, j))<EOL><DEDENT>elif t == '<STR_LIT:I>':<EOL><INDENT>args.append("<STR_LIT>" % (const + I_type, j))<EOL><DEDENT>elif t == '<STR_LIT:T>':<EOL><INDENT>args.append("<STR_LIT>" % (const + T_type, j))<EOL><DEDENT>elif t == '<STR_LIT:B>':<EOL><INDENT>args.append("<STR_LIT>" % (j,))<EOL><DEDENT>elif t == '<STR_LIT>':<EOL><INDENT>if const:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>args.append("<STR_LIT>" % (I_type, j,))<EOL><DEDENT>elif t == '<STR_LIT>':<EOL><INDENT>if const:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>args.append("<STR_LIT>" % (T_type, j,))<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % (t,))<EOL><DEDENT>j += <NUM_LIT:1><EOL><DEDENT>return "<STR_LIT:U+002CU+0020>".join(args)<EOL><DEDENT>thunk_content = """<STR_LIT>"""<EOL>for j, I_typenum, T_typenum, I_type, T_type in types:<EOL><INDENT>arglist = get_arglist(I_type, T_type)<EOL>if T_type is None:<EOL><INDENT>dispatch = "<STR_LIT:%s>" % (I_type,)<EOL><DEDENT>else:<EOL><INDENT>dispatch = "<STR_LIT>" % (I_type, T_type)<EOL><DEDENT>if '<STR_LIT:B>' in arg_spec:<EOL><INDENT>dispatch += "<STR_LIT>"<EOL><DEDENT>piece = """<STR_LIT>"""<EOL>if ret_spec == '<STR_LIT:v>':<EOL><INDENT>piece += """<STR_LIT>"""<EOL><DEDENT>else:<EOL><INDENT>piece += """<STR_LIT>"""<EOL><DEDENT>thunk_content += piece % dict(j=j, I_type=I_type, T_type=T_type,<EOL>I_typenum=I_typenum, T_typenum=T_typenum,<EOL>arglist=arglist, name=name,<EOL>dispatch=dispatch)<EOL><DEDENT>thunk_content += """<STR_LIT>"""<EOL>thunk_code = THUNK_TEMPLATE % dict(name=name,<EOL>thunk_content=thunk_content)<EOL>method_code = METHOD_TEMPLATE % dict(name=name,<EOL>ret_spec=ret_spec,<EOL>arg_spec=arg_spec)<EOL>return thunk_code, method_code<EOL>

Generate thunk and method code for a given routine.

Parameters
----------
name : str
    Name of the C++ routine
args : str
    Argument list specification (in format explained above)
types : list
    List of types to instantiate, as returned `get_thunk_type_set`


if axis is None:<EOL><INDENT>nnz = len(self.data)<EOL>if nnz != len(self.row) or nnz != len(self.col):<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>if self.data.ndim != <NUM_LIT:1> or self.row.ndim != <NUM_LIT:1> orself.col.ndim != <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return int(nnz)<EOL><DEDENT>if axis < <NUM_LIT:0>:<EOL><INDENT>axis += <NUM_LIT:2><EOL><DEDENT>if axis == <NUM_LIT:0>:<EOL><INDENT>return _compat_bincount(downcast_intp_index(self.col),<EOL>minlength=self.shape[<NUM_LIT:1>])<EOL><DEDENT>elif axis == <NUM_LIT:1>:<EOL><INDENT>return _compat_bincount(downcast_intp_index(self.row),<EOL>minlength=self.shape[<NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>

Get the count of explicitly-stored values (nonzeros)

        Parameters
        ----------
        axis : None, 0, or 1
            Select between the number of values across the whole matrix, in
            each column, or in each row.


nnz = self.nnz<EOL>if self.row.dtype.kind != '<STR_LIT:i>':<EOL><INDENT>warn("<STR_LIT>"<EOL>% self.row.dtype.name)<EOL><DEDENT>if self.col.dtype.kind != '<STR_LIT:i>':<EOL><INDENT>warn("<STR_LIT>"<EOL>% self.col.dtype.name)<EOL><DEDENT>idx_dtype = get_index_dtype(maxval=max(self.shape))<EOL>self.row = np.asarray(self.row, dtype=idx_dtype)<EOL>self.col = np.asarray(self.col, dtype=idx_dtype)<EOL>self.data = to_native(self.data)<EOL>if nnz > <NUM_LIT:0>:<EOL><INDENT>if self.row.max() >= self.shape[<NUM_LIT:0>]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if self.col.max() >= self.shape[<NUM_LIT:1>]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if self.row.min() < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if self.col.min() < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>


B = self._process_toarray_args(order, out)<EOL>fortran = int(B.flags.f_contiguous)<EOL>if not fortran and not B.flags.c_contiguous:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>M,N = self.shape<EOL>coo_todense(M, N, self.nnz, self.row, self.col, self.data,<EOL>B.ravel('<STR_LIT:A>'), fortran)<EOL>return B<EOL>


from .csc import csc_matrix<EOL>if self.nnz == <NUM_LIT:0>:<EOL><INDENT>return csc_matrix(self.shape, dtype=self.dtype)<EOL><DEDENT>else:<EOL><INDENT>M,N = self.shape<EOL>idx_dtype = get_index_dtype((self.col, self.row),<EOL>maxval=max(self.nnz, M))<EOL>indptr = np.empty(N + <NUM_LIT:1>, dtype=idx_dtype)<EOL>indices = np.empty(self.nnz, dtype=idx_dtype)<EOL>data = np.empty(self.nnz, dtype=upcast(self.dtype))<EOL>coo_tocsr(N, M, self.nnz,<EOL>self.col.astype(idx_dtype),<EOL>self.row.astype(idx_dtype),<EOL>self.data,<EOL>indptr, indices, data)<EOL>A = csc_matrix((data, indices, indptr), shape=self.shape)<EOL>A.sum_duplicates()<EOL>return A<EOL><DEDENT>

Return a copy of this matrix in Compressed Sparse Column format

        Duplicate entries will be summed together.

        Examples
        --------
        >>> from numpy import array
        >>> from scipy.sparse import coo_matrix
        >>> row  = array([0, 0, 1, 3, 1, 0, 0])
        >>> col  = array([0, 2, 1, 3, 1, 0, 0])
        >>> data = array([1, 1, 1, 1, 1, 1, 1])
        >>> A = coo_matrix((data, (row, col)), shape=(4, 4)).tocsc()
        >>> A.toarray()
        array([[3, 0, 1, 0],
               [0, 2, 0, 0],
               [0, 0, 0, 0],
               [0, 0, 0, 1]])


from .csr import csr_matrix<EOL>if self.nnz == <NUM_LIT:0>:<EOL><INDENT>return csr_matrix(self.shape, dtype=self.dtype)<EOL><DEDENT>else:<EOL><INDENT>M,N = self.shape<EOL>idx_dtype = get_index_dtype((self.row, self.col),<EOL>maxval=max(self.nnz, N))<EOL>indptr = np.empty(M + <NUM_LIT:1>, dtype=idx_dtype)<EOL>indices = np.empty(self.nnz, dtype=idx_dtype)<EOL>data = np.empty(self.nnz, dtype=upcast(self.dtype))<EOL>coo_tocsr(M, N, self.nnz,<EOL>self.row.astype(idx_dtype),<EOL>self.col.astype(idx_dtype),<EOL>self.data,<EOL>indptr,<EOL>indices,<EOL>data)<EOL>A = csr_matrix((data, indices, indptr), shape=self.shape)<EOL>A.sum_duplicates()<EOL>return A<EOL><DEDENT>

Return a copy of this matrix in Compressed Sparse Row format

        Duplicate entries will be summed together.

        Examples
        --------
        >>> from numpy import array
        >>> from scipy.sparse import coo_matrix
        >>> row  = array([0, 0, 1, 3, 1, 0, 0])
        >>> col  = array([0, 2, 1, 3, 1, 0, 0])
        >>> data = array([1, 1, 1, 1, 1, 1, 1])
        >>> A = coo_matrix((data, (row, col)), shape=(4, 4)).tocsr()
        >>> A.toarray()
        array([[3, 0, 1, 0],
               [0, 2, 0, 0],
               [0, 0, 0, 0],
               [0, 0, 0, 1]])


if copy:<EOL><INDENT>return coo_matrix((data, (self.row.copy(), self.col.copy())),<EOL>shape=self.shape, dtype=data.dtype)<EOL><DEDENT>else:<EOL><INDENT>return coo_matrix((data, (self.row, self.col)),<EOL>shape=self.shape, dtype=data.dtype)<EOL><DEDENT>

Returns a matrix with the same sparsity structure as self,
        but with different data.  By default the index arrays
        (i.e. .row and .col) are copied.


if self.has_canonical_format or len(self.data) == <NUM_LIT:0>:<EOL><INDENT>return<EOL><DEDENT>order = np.lexsort((self.row,self.col))<EOL>self.row = self.row[order]<EOL>self.col = self.col[order]<EOL>self.data = self.data[order]<EOL>unique_mask = ((self.row[<NUM_LIT:1>:] != self.row[:-<NUM_LIT:1>]) |<EOL>(self.col[<NUM_LIT:1>:] != self.col[:-<NUM_LIT:1>]))<EOL>unique_mask = np.append(True, unique_mask)<EOL>self.row = self.row[unique_mask]<EOL>self.col = self.col[unique_mask]<EOL>unique_inds, = np.nonzero(unique_mask)<EOL>self.data = np.add.reduceat(self.data, unique_inds, dtype=self.dtype)<EOL>self.has_canonical_format = True<EOL>

Eliminate duplicate matrix entries by adding them together

        This is an *in place* operation


<EOL>return self._get_submatrix(i, slice(None)).tocsr()<EOL>

Returns a copy of row i of the matrix, as a (1 x n)
        CSR matrix (row vector).


return self._get_submatrix(slice(None), i)<EOL>

Returns a copy of column i of the matrix, as a (m x 1)
        CSC matrix (column vector).


return (x[<NUM_LIT:1>],x[<NUM_LIT:0>])<EOL>

swap the members of x if this is a column-oriented matrix


A = coo_matrix(A).tocsr()  <EOL>A.eliminate_zeros()        <EOL>A = A.tocoo(copy=False)    <EOL>return A.row,A.col,A.data<EOL>

Return the indices and values of the nonzero elements of a matrix

    Parameters
    ----------
    A : dense or sparse matrix
        Matrix whose nonzero elements are desired.

    Returns
    -------
    (I,J,V) : tuple of arrays
        I,J, and V contain the row indices, column indices, and values
        of the nonzero matrix entries.

    Examples
    --------
    >>> from scipy.sparse import csr_matrix
    >>> A = csr_matrix([[7.0, 8.0, 0],[0, 0, 9.0]])
    >>> find(A)
    (array([0, 0, 1], dtype=int32), array([0, 1, 2], dtype=int32), array([ 7.,  8.,  9.]))


def tril(A, k=<NUM_LIT:0>, format=None):

<EOL>A = coo_matrix(A, copy=False)<EOL>mask = A.row + k >= A.col<EOL>row = A.row[mask]<EOL>col = A.col[mask]<EOL>data = A.data[mask]<EOL>return coo_matrix((data,(row,col)), shape=A.shape).asformat(format)<EOL>

Return the lower triangular portion of a matrix in sparse format

    Returns the elements on or below the k-th diagonal of the matrix A.
        - k = 0 corresponds to the main diagonal
        - k > 0 is above the main diagonal
        - k < 0 is below the main diagonal

    Parameters
    ----------
    A : dense or sparse matrix
        Matrix whose lower trianglar portion is desired.
    k : integer : optional
        The top-most diagonal of the lower triangle.
    format : string
        Sparse format of the result, e.g. format="csr", etc.

    Returns
    -------
    L : sparse matrix
        Lower triangular portion of A in sparse format.

    See Also
    --------
    triu : upper triangle in sparse format

    Examples
    --------
    >>> from scipy.sparse import csr_matrix
    >>> A = csr_matrix([[1, 2, 0, 0, 3], [4, 5, 0, 6, 7], [0, 0, 8, 9, 0]],
    ...                dtype='int32')
    >>> A.toarray()
    array([[1, 2, 0, 0, 3],
           [4, 5, 0, 6, 7],
           [0, 0, 8, 9, 0]])
    >>> tril(A).toarray()
    array([[1, 0, 0, 0, 0],
           [4, 5, 0, 0, 0],
           [0, 0, 8, 0, 0]])
    >>> tril(A).nnz
    4
    >>> tril(A, k=1).toarray()
    array([[1, 2, 0, 0, 0],
           [4, 5, 0, 0, 0],
           [0, 0, 8, 9, 0]])
    >>> tril(A, k=-1).toarray()
    array([[0, 0, 0, 0, 0],
           [4, 0, 0, 0, 0],
           [0, 0, 0, 0, 0]])
    >>> tril(A, format='csc')
    <3x5 sparse matrix of type '<type 'numpy.int32'>'
            with 4 stored elements in Compressed Sparse Column format>


def triu(A, k=<NUM_LIT:0>, format=None):

<EOL>A = coo_matrix(A, copy=False)<EOL>mask = A.row + k <= A.col<EOL>row = A.row[mask]<EOL>col = A.col[mask]<EOL>data = A.data[mask]<EOL>return coo_matrix((data,(row,col)), shape=A.shape).asformat(format)<EOL>

Return the upper triangular portion of a matrix in sparse format

    Returns the elements on or above the k-th diagonal of the matrix A.
        - k = 0 corresponds to the main diagonal
        - k > 0 is above the main diagonal
        - k < 0 is below the main diagonal

    Parameters
    ----------
    A : dense or sparse matrix
        Matrix whose upper trianglar portion is desired.
    k : integer : optional
        The bottom-most diagonal of the upper triangle.
    format : string
        Sparse format of the result, e.g. format="csr", etc.

    Returns
    -------
    L : sparse matrix
        Upper triangular portion of A in sparse format.

    See Also
    --------
    tril : lower triangle in sparse format

    Examples
    --------
    >>> from scipy.sparse import csr_matrix
    >>> A = csr_matrix([[1, 2, 0, 0, 3], [4, 5, 0, 6, 7], [0, 0, 8, 9, 0]],
    ...                dtype='int32')
    >>> A.toarray()
    array([[1, 2, 0, 0, 3],
           [4, 5, 0, 6, 7],
           [0, 0, 8, 9, 0]])
    >>> triu(A).toarray()
    array([[1, 2, 0, 0, 3],
           [0, 5, 0, 6, 7],
           [0, 0, 8, 9, 0]])
    >>> triu(A).nnz
    8
    >>> triu(A, k=1).toarray()
    array([[0, 2, 0, 0, 3],
           [0, 0, 0, 6, 7],
           [0, 0, 0, 9, 0]])
    >>> triu(A, k=-1).toarray()
    array([[1, 2, 0, 0, 3],
           [4, 5, 0, 6, 7],
           [0, 0, 8, 9, 0]])
    >>> triu(A, format='csc')
    <3x5 sparse matrix of type '<type 'numpy.int32'>'
            with 8 stored elements in Compressed Sparse Column format>


if not (isspmatrix_csr(A) or isspmatrix_csc(A)):<EOL><INDENT>A = csr_matrix(A)<EOL><DEDENT>if A.nnz == <NUM_LIT:0>:<EOL><INDENT>return (<NUM_LIT:1>,<NUM_LIT:1>)<EOL><DEDENT>if not <NUM_LIT:0> < efficiency < <NUM_LIT:1.0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>high_efficiency = (<NUM_LIT:1.0> + efficiency) / <NUM_LIT><EOL>nnz = float(A.nnz)<EOL>M,N = A.shape<EOL>if M % <NUM_LIT:2> == <NUM_LIT:0> and N % <NUM_LIT:2> == <NUM_LIT:0>:<EOL><INDENT>e22 = nnz / (<NUM_LIT:4> * count_blocks(A,(<NUM_LIT:2>,<NUM_LIT:2>)))<EOL><DEDENT>else:<EOL><INDENT>e22 = <NUM_LIT:0.0><EOL><DEDENT>if M % <NUM_LIT:3> == <NUM_LIT:0> and N % <NUM_LIT:3> == <NUM_LIT:0>:<EOL><INDENT>e33 = nnz / (<NUM_LIT:9> * count_blocks(A,(<NUM_LIT:3>,<NUM_LIT:3>)))<EOL><DEDENT>else:<EOL><INDENT>e33 = <NUM_LIT:0.0><EOL><DEDENT>if e22 > high_efficiency and e33 > high_efficiency:<EOL><INDENT>e66 = nnz / (<NUM_LIT> * count_blocks(A,(<NUM_LIT:6>,<NUM_LIT:6>)))<EOL>if e66 > efficiency:<EOL><INDENT>return (<NUM_LIT:6>,<NUM_LIT:6>)<EOL><DEDENT>else:<EOL><INDENT>return (<NUM_LIT:3>,<NUM_LIT:3>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if M % <NUM_LIT:4> == <NUM_LIT:0> and N % <NUM_LIT:4> == <NUM_LIT:0>:<EOL><INDENT>e44 = nnz / (<NUM_LIT:16> * count_blocks(A,(<NUM_LIT:4>,<NUM_LIT:4>)))<EOL><DEDENT>else:<EOL><INDENT>e44 = <NUM_LIT:0.0><EOL><DEDENT>if e44 > efficiency:<EOL><INDENT>return (<NUM_LIT:4>,<NUM_LIT:4>)<EOL><DEDENT>elif e33 > efficiency:<EOL><INDENT>return (<NUM_LIT:3>,<NUM_LIT:3>)<EOL><DEDENT>elif e22 > efficiency:<EOL><INDENT>return (<NUM_LIT:2>,<NUM_LIT:2>)<EOL><DEDENT>else:<EOL><INDENT>return (<NUM_LIT:1>,<NUM_LIT:1>)<EOL><DEDENT><DEDENT>

Attempt to determine the blocksize of a sparse matrix

    Returns a blocksize=(r,c) such that
        - A.nnz / A.tobsr( (r,c) ).nnz > efficiency


r,c = blocksize<EOL>if r < <NUM_LIT:1> or c < <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if isspmatrix_csr(A):<EOL><INDENT>M,N = A.shape<EOL>return csr_count_blocks(M,N,r,c,A.indptr,A.indices)<EOL><DEDENT>elif isspmatrix_csc(A):<EOL><INDENT>return count_blocks(A.T,(c,r))<EOL><DEDENT>else:<EOL><INDENT>return count_blocks(csr_matrix(A),blocksize)<EOL><DEDENT>

For a given blocksize=(r,c) count the number of occupied
    blocks in a sparse matrix A


M,N = self.shape<EOL>R,C = self.blocksize<EOL>if self.indptr.dtype.kind != '<STR_LIT:i>':<EOL><INDENT>warn("<STR_LIT>"<EOL>% self.indptr.dtype.name)<EOL><DEDENT>if self.indices.dtype.kind != '<STR_LIT:i>':<EOL><INDENT>warn("<STR_LIT>"<EOL>% self.indices.dtype.name)<EOL><DEDENT>idx_dtype = get_index_dtype((self.indices, self.indptr))<EOL>self.indptr = np.asarray(self.indptr, dtype=idx_dtype)<EOL>self.indices = np.asarray(self.indices, dtype=idx_dtype)<EOL>self.data = to_native(self.data)<EOL>if self.indices.ndim != <NUM_LIT:1> or self.indptr.ndim != <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if self.data.ndim != <NUM_LIT:3>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if (len(self.indptr) != M//R + <NUM_LIT:1>):<EOL><INDENT>raise ValueError("<STR_LIT>" %<EOL>(len(self.indptr), M//R + <NUM_LIT:1>))<EOL><DEDENT>if (self.indptr[<NUM_LIT:0>] != <NUM_LIT:0>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if (len(self.indices) != len(self.data)):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if (self.indptr[-<NUM_LIT:1>] > len(self.indices)):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>self.prune()<EOL>if full_check:<EOL><INDENT>if self.nnz > <NUM_LIT:0>:<EOL><INDENT>if self.indices.max() >= N//C:<EOL><INDENT>raise ValueError("<STR_LIT>" % (N//C, self.indices.max()))<EOL><DEDENT>if self.indices.min() < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if np.diff(self.indptr).min() < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT>

check whether the matrix format is valid

            *Parameters*:
                full_check:
                    True  - rigorous check, O(N) operations : default
                    False - basic check, O(1) operations


M,N = self.shape<EOL>R,C = self.blocksize<EOL>y = np.empty(min(M,N), dtype=upcast(self.dtype))<EOL>_sparsetools.bsr_diagonal(M//R, N//C, R, C,<EOL>self.indptr, self.indices,<EOL>np.ravel(self.data), y)<EOL>return y<EOL>


M,N = self.shape<EOL>R,C = self.blocksize<EOL>indptr_diff = np.diff(self.indptr)<EOL>if indptr_diff.dtype.itemsize > np.dtype(np.intp).itemsize:<EOL><INDENT>indptr_diff_limited = indptr_diff.astype(np.intp)<EOL>if np.any(indptr_diff_limited != indptr_diff):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>indptr_diff = indptr_diff_limited<EOL><DEDENT>row = (R * np.arange(M//R)).repeat(indptr_diff)<EOL>row = row.repeat(R*C).reshape(-<NUM_LIT:1>,R,C)<EOL>row += np.tile(np.arange(R).reshape(-<NUM_LIT:1>,<NUM_LIT:1>), (<NUM_LIT:1>,C))<EOL>row = row.reshape(-<NUM_LIT:1>)<EOL>col = (C * self.indices).repeat(R*C).reshape(-<NUM_LIT:1>,R,C)<EOL>col += np.tile(np.arange(C), (R,<NUM_LIT:1>))<EOL>col = col.reshape(-<NUM_LIT:1>)<EOL>data = self.data.reshape(-<NUM_LIT:1>)<EOL>if copy:<EOL><INDENT>data = data.copy()<EOL><DEDENT>from .coo import coo_matrix<EOL>return coo_matrix((data,(row,col)), shape=self.shape)<EOL>

Convert this matrix to COOrdinate format.

        When copy=False the data array will be shared between
        this matrix and the resultant coo_matrix.


if self.has_sorted_indices:<EOL><INDENT>return<EOL><DEDENT>R,C = self.blocksize<EOL>M,N = self.shape<EOL>bsr_sort_indices(M//R, N//C, R, C, self.indptr, self.indices, self.data.ravel())<EOL>self.has_sorted_indices = True<EOL>

Sort the indices of this matrix *in place*


R,C = self.blocksize<EOL>M,N = self.shape<EOL>if len(self.indptr) != M//R + <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>bnnz = self.indptr[-<NUM_LIT:1>]<EOL>if len(self.indices) < bnnz:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if len(self.data) < bnnz:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self.data = self.data[:bnnz]<EOL>self.indices = self.indices[:bnnz]<EOL>

Remove empty space after all non-zero elements.


def _binopt(self, other, op, in_shape=None, out_shape=None):

<EOL>other = self.__class__(other, blocksize=self.blocksize)<EOL>fn = getattr(_sparsetools, self.format + op + self.format)<EOL>R,C = self.blocksize<EOL>max_bnnz = len(self.data) + len(other.data)<EOL>idx_dtype = get_index_dtype((self.indptr, self.indices,<EOL>other.indptr, other.indices),<EOL>maxval=max_bnnz)<EOL>indptr = np.empty(self.indptr.shape, dtype=idx_dtype)<EOL>indices = np.empty(max_bnnz, dtype=idx_dtype)<EOL>bool_ops = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>if op in bool_ops:<EOL><INDENT>data = np.empty(R*C*max_bnnz, dtype=np.bool_)<EOL><DEDENT>else:<EOL><INDENT>data = np.empty(R*C*max_bnnz, dtype=upcast(self.dtype,other.dtype))<EOL><DEDENT>fn(self.shape[<NUM_LIT:0>]//R, self.shape[<NUM_LIT:1>]//C, R, C,<EOL>self.indptr.astype(idx_dtype),<EOL>self.indices.astype(idx_dtype),<EOL>np.ravel(self.data),<EOL>other.indptr.astype(idx_dtype),<EOL>other.indices.astype(idx_dtype),<EOL>np.ravel(other.data),<EOL>indptr,<EOL>indices,<EOL>data)<EOL>actual_bnnz = indptr[-<NUM_LIT:1>]<EOL>indices = indices[:actual_bnnz]<EOL>data = data[:R*C*actual_bnnz]<EOL>if actual_bnnz < max_bnnz/<NUM_LIT:2>:<EOL><INDENT>indices = indices.copy()<EOL>data = data.copy()<EOL><DEDENT>data = data.reshape(-<NUM_LIT:1>,R,C)<EOL>return self.__class__((data, indices, indptr), shape=self.shape)<EOL>

Apply the binary operation fn to two sparse matrices.


Returns a matrix with the same sparsity structure as self,
        but with different data.  By default the structure arrays
        (i.e. .indptr and .indices) are copied.


points = DATASETS[name]<EOL>ndim = points.shape[<NUM_LIT:1>]<EOL>opts = None<EOL>nmin = ndim + <NUM_LIT:2><EOL>if name == '<STR_LIT>':<EOL><INDENT>opts = '<STR_LIT>'<EOL><DEDENT>elif name == '<STR_LIT>':<EOL><INDENT>nmin = <NUM_LIT:12><EOL><DEDENT>chunks = [points[:nmin]]<EOL>for j in xrange(nmin, len(points), chunksize):<EOL><INDENT>chunks.append(points[j:j+chunksize])<EOL><DEDENT>new_name = "<STR_LIT>" % (name, chunksize)<EOL>assert new_name not in INCREMENTAL_DATASETS<EOL>INCREMENTAL_DATASETS[new_name] = (chunks, opts)<EOL>

Generate incremental datasets from basic data sets


def _check_barycentric_transforms(self, tri, err_msg="<STR_LIT>",<EOL>unit_cube=False,<EOL>unit_cube_tol=<NUM_LIT:0>):

vertices = tri.points[tri.vertices]<EOL>sc = <NUM_LIT:1>/(tri.ndim + <NUM_LIT:1.0>)<EOL>centroids = vertices.sum(axis=<NUM_LIT:1>) * sc<EOL>def barycentric_transform(tr, x):<EOL><INDENT>ndim = tr.shape[<NUM_LIT:1>]<EOL>r = tr[:,-<NUM_LIT:1>,:]<EOL>Tinv = tr[:,:-<NUM_LIT:1>,:]<EOL>return np.einsum('<STR_LIT>', Tinv, x - r)<EOL><DEDENT>eps = np.finfo(float).eps<EOL>c = barycentric_transform(tri.transform, centroids)<EOL>olderr = np.seterr(invalid="<STR_LIT:ignore>")<EOL>try:<EOL><INDENT>ok = np.isnan(c).all(axis=<NUM_LIT:1>) | (abs(c - sc)/sc < <NUM_LIT:0.1>).all(axis=<NUM_LIT:1>)<EOL><DEDENT>finally:<EOL><INDENT>np.seterr(**olderr)<EOL><DEDENT>assert_(ok.all(), "<STR_LIT>" % (err_msg, np.where(~ok)))<EOL>q = vertices[:,:-<NUM_LIT:1>,:] - vertices[:,-<NUM_LIT:1>,None,:]<EOL>volume = np.array([np.linalg.det(q[k,:,:])<EOL>for k in range(tri.nsimplex)])<EOL>ok = np.isfinite(tri.transform[:,<NUM_LIT:0>,<NUM_LIT:0>]) | (volume < np.sqrt(eps))<EOL>assert_(ok.all(), "<STR_LIT>" % (err_msg, np.where(~ok)))<EOL>j = tri.find_simplex(centroids)<EOL>ok = (j != -<NUM_LIT:1>) | np.isnan(tri.transform[:,<NUM_LIT:0>,<NUM_LIT:0>])<EOL>assert_(ok.all(), "<STR_LIT>" % (err_msg, np.where(~ok)))<EOL>if unit_cube:<EOL><INDENT>at_boundary = (centroids <= unit_cube_tol).any(axis=<NUM_LIT:1>)<EOL>at_boundary |= (centroids >= <NUM_LIT:1> - unit_cube_tol).any(axis=<NUM_LIT:1>)<EOL>ok = (j != -<NUM_LIT:1>) | at_boundary<EOL>assert_(ok.all(), "<STR_LIT>" % (err_msg, np.where(~ok)))<EOL><DEDENT>

Check that a triangulation has reasonable barycentric transforms


def _compare_qvoronoi(self, points, output, **kw):

<EOL>output = [list(map(float, x.split())) for x in output.strip().splitlines()]<EOL>nvertex = int(output[<NUM_LIT:1>][<NUM_LIT:0>])<EOL>vertices = list(map(tuple, output[<NUM_LIT:3>:<NUM_LIT:2>+nvertex]))  <EOL>nregion = int(output[<NUM_LIT:1>][<NUM_LIT:1>])<EOL>regions = [[int(y)-<NUM_LIT:1> for y in x[<NUM_LIT:1>:]]<EOL>for x in output[<NUM_LIT:2>+nvertex:<NUM_LIT:2>+nvertex+nregion]]<EOL>nridge = int(output[<NUM_LIT:2>+nvertex+nregion][<NUM_LIT:0>])<EOL>ridge_points = [[int(y) for y in x[<NUM_LIT:1>:<NUM_LIT:3>]]<EOL>for x in output[<NUM_LIT:3>+nvertex+nregion:]]<EOL>ridge_vertices = [[int(y)-<NUM_LIT:1> for y in x[<NUM_LIT:3>:]]<EOL>for x in output[<NUM_LIT:3>+nvertex+nregion:]]<EOL>vor = qhull.Voronoi(points, **kw)<EOL>def sorttuple(x):<EOL><INDENT>return tuple(sorted(x))<EOL><DEDENT>assert_allclose(vor.vertices, vertices)<EOL>assert_equal(set(map(tuple, vor.regions)),<EOL>set(map(tuple, regions)))<EOL>p1 = list(zip(list(map(sorttuple, ridge_points)), list(map(sorttuple, ridge_vertices))))<EOL>p2 = list(zip(list(map(sorttuple, vor.ridge_points.tolist())),<EOL>list(map(sorttuple, vor.ridge_vertices))))<EOL>p1.sort()<EOL>p2.sort()<EOL>assert_equal(p1, p2)<EOL>

Compare to output from 'qvoronoi o Fv < data' to Voronoi()


if a.base is not None:<EOL><INDENT>return a.copy()<EOL><DEDENT>elif np.issubsctype(a, np.float32):<EOL><INDENT>return np.array(a, dtype=np.double)<EOL><DEDENT>else:<EOL><INDENT>return a<EOL><DEDENT>

Copies the array if its base points to a parent array.


l = [_copy_array_if_base_present(a) for a in T]<EOL>return l<EOL>

Accepts a tuple of arrays T. Copies the array T[i] if its base array
points to an actual array. Otherwise, the reference is just copied.
This is useful if the arrays are being passed to a C function that
does not do proper striding.


u = _validate_vector(u)<EOL>v = _validate_vector(v)<EOL>if p < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>dist = norm(u - v, ord=p)<EOL>return dist<EOL>

Computes the Minkowski distance between two 1-D arrays.

The Minkowski distance between 1-D arrays `u` and `v`,
is defined as

.. math::

   {||u-v||}_p = (\\sum{|u_i - v_i|^p})^{1/p}.

Parameters
----------
u : (N,) array_like
    Input array.
v : (N,) array_like
    Input array.
p : int
    The order of the norm of the difference :math:`{||u-v||}_p`.

Returns
-------
d : double
    The Minkowski distance between vectors `u` and `v`.


u = _validate_vector(u)<EOL>v = _validate_vector(v)<EOL>w = _validate_vector(w)<EOL>if p < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>dist = norm(w * (u - v), ord=p)<EOL>return dist<EOL>

Computes the weighted Minkowski distance between two 1-D arrays.

The weighted Minkowski distance between `u` and `v`, defined as

.. math::

   \\left(\\sum{(w_i |u_i - v_i|^p)}\\right)^{1/p}.

Parameters
----------
u : (N,) array_like
    Input array.
v : (N,) array_like
    Input array.
p : int
    The order of the norm of the difference :math:`{||u-v||}_p`.
w : (N,) array_like
    The weight vector.

Returns
-------
wminkowski : double
    The weighted Minkowski distance between vectors `u` and `v`.


u = _validate_vector(u)<EOL>v = _validate_vector(v)<EOL>dist = norm(u - v)<EOL>return dist<EOL>

Computes the Euclidean distance between two 1-D arrays.

The Euclidean distance between 1-D arrays `u` and `v`, is defined as

.. math::

   {||u-v||}_2

Parameters
----------
u : (N,) array_like
    Input array.
v : (N,) array_like
    Input array.

Returns
-------
euclidean : double
    The Euclidean distance between vectors `u` and `v`.


<EOL>utype, vtype = None, None<EOL>if not (hasattr(u, "<STR_LIT>") and np.issubdtype(u.dtype, np.inexact)):<EOL><INDENT>utype = np.float64<EOL><DEDENT>if not (hasattr(v, "<STR_LIT>") and np.issubdtype(v.dtype, np.inexact)):<EOL><INDENT>vtype = np.float64<EOL><DEDENT>u = _validate_vector(u, dtype=utype)<EOL>v = _validate_vector(v, dtype=vtype)<EOL>u_v = u - v<EOL>return np.dot(u_v, u_v)<EOL>

Computes the squared Euclidean distance between two 1-D arrays.

The squared Euclidean distance between `u` and `v` is defined as

.. math::

   {||u-v||}_2^2.

Parameters
----------
u : (N,) array_like
    Input array.
v : (N,) array_like
    Input array.

Returns
-------
sqeuclidean : double
    The squared Euclidean distance between vectors `u` and `v`.


u = _validate_vector(u)<EOL>v = _validate_vector(v)<EOL>dist = <NUM_LIT:1.0> - np.dot(u, v) / (norm(u) * norm(v))<EOL>return dist<EOL>

Computes the Cosine distance between 1-D arrays.

The Cosine distance between `u` and `v`, is defined as

.. math::

   1 - \\frac{u \\cdot v}
            {||u||_2 ||v||_2}.

where :math:`u \\cdot v` is the dot product of :math:`u` and
:math:`v`.

Parameters
----------
u : (N,) array_like
    Input array.
v : (N,) array_like
    Input array.

Returns
-------
cosine : double
    The Cosine distance between vectors `u` and `v`.


u = _validate_vector(u)<EOL>v = _validate_vector(v)<EOL>umu = u.mean()<EOL>vmu = v.mean()<EOL>um = u - umu<EOL>vm = v - vmu<EOL>dist = <NUM_LIT:1.0> - np.dot(um, vm) / (norm(um) * norm(vm))<EOL>return dist<EOL>

Computes the correlation distance between two 1-D arrays.

The correlation distance between `u` and `v`, is
defined as

.. math::

   1 - \\frac{(u - \\bar{u}) \\cdot (v - \\bar{v})}
           {{||(u - \\bar{u})||}_2 {||(v - \\bar{v})||}_2}

where :math:`\\bar{u}` is the mean of the elements of `u`
and :math:`x \\cdot y` is the dot product of :math:`x` and :math:`y`.

Parameters
----------
u : (N,) array_like
    Input array.
v : (N,) array_like
    Input array.

Returns
-------
correlation : double
    The correlation distance between 1-D array `u` and `v`.


u = _validate_vector(u)<EOL>v = _validate_vector(v)<EOL>return (u != v).mean()<EOL>

Computes the Hamming distance between two 1-D arrays.

The Hamming distance between 1-D arrays `u` and `v`, is simply the
proportion of disagreeing components in `u` and `v`. If `u` and `v` are
boolean vectors, the Hamming distance is

.. math::

   \\frac{c_{01} + c_{10}}{n}

where :math:`c_{ij}` is the number of occurrences of
:math:`\\mathtt{u[k]} = i` and :math:`\\mathtt{v[k]} = j` for
:math:`k < n`.

Parameters
----------
u : (N,) array_like
    Input array.
v : (N,) array_like
    Input array.

Returns
-------
hamming : double
    The Hamming distance between vectors `u` and `v`.


u = _validate_vector(u)<EOL>v = _validate_vector(v)<EOL>dist = (np.double(np.bitwise_and((u != v),<EOL>np.bitwise_or(u != <NUM_LIT:0>, v != <NUM_LIT:0>)).sum())<EOL>/ np.double(np.bitwise_or(u != <NUM_LIT:0>, v != <NUM_LIT:0>).sum()))<EOL>return dist<EOL>

Computes the Jaccard-Needham dissimilarity between two boolean 1-D arrays.

The Jaccard-Needham dissimilarity between 1-D boolean arrays `u` and `v`,
is defined as

.. math::

   \\frac{c_{TF} + c_{FT}}
        {c_{TT} + c_{FT} + c_{TF}}

where :math:`c_{ij}` is the number of occurrences of
:math:`\\mathtt{u[k]} = i` and :math:`\\mathtt{v[k]} = j` for
:math:`k < n`.

Parameters
----------
u : (N,) array_like, bool
    Input array.
v : (N,) array_like, bool
    Input array.

Returns
-------
jaccard : double
    The Jaccard distance between vectors `u` and `v`.


u = _validate_vector(u)<EOL>v = _validate_vector(v)<EOL>n = float(len(u))<EOL>(nff, nft, ntf, ntt) = _nbool_correspond_all(u, v)<EOL>return (ntf + nft - ntt + n) / (ntf + nft + n)<EOL>

Computes the Kulsinski dissimilarity between two boolean 1-D arrays.

The Kulsinski dissimilarity between two boolean 1-D arrays `u` and `v`,
is defined as

.. math::

     \\frac{c_{TF} + c_{FT} - c_{TT} + n}
          {c_{FT} + c_{TF} + n}

where :math:`c_{ij}` is the number of occurrences of
:math:`\\mathtt{u[k]} = i` and :math:`\\mathtt{v[k]} = j` for
:math:`k < n`.

Parameters
----------
u : (N,) array_like, bool
    Input array.
v : (N,) array_like, bool
    Input array.

Returns
-------
kulsinski : double
    The Kulsinski distance between vectors `u` and `v`.


u = _validate_vector(u)<EOL>v = _validate_vector(v)<EOL>V = _validate_vector(V, dtype=np.float64)<EOL>if V.shape[<NUM_LIT:0>] != u.shape[<NUM_LIT:0>] or u.shape[<NUM_LIT:0>] != v.shape[<NUM_LIT:0>]:<EOL><INDENT>raise TypeError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>return np.sqrt(((u - v) ** <NUM_LIT:2> / V).sum())<EOL>

Returns the standardized Euclidean distance between two 1-D arrays.

The standardized Euclidean distance between `u` and `v`.

Parameters
----------
u : (N,) array_like
    Input array.
v : (N,) array_like
    Input array.
V : (N,) array_like
    `V` is an 1-D array of component variances. It is usually computed
    among a larger collection vectors.

Returns
-------
seuclidean : double
    The standardized Euclidean distance between vectors `u` and `v`.


u = _validate_vector(u)<EOL>v = _validate_vector(v)<EOL>return abs(u - v).sum()<EOL>

Computes the City Block (Manhattan) distance.

Computes the Manhattan distance between two 1-D arrays `u` and `v`,
which is defined as

.. math::

   \\sum_i {\\left| u_i - v_i \\right|}.

Parameters
----------
u : (N,) array_like
    Input array.
v : (N,) array_like
    Input array.

Returns
-------
cityblock : double
    The City Block (Manhattan) distance between vectors `u` and `v`.


u = _validate_vector(u)<EOL>v = _validate_vector(v)<EOL>VI = np.atleast_2d(VI)<EOL>delta = u - v<EOL>m = np.dot(np.dot(delta, VI), delta)<EOL>return np.sqrt(m)<EOL>

Computes the Mahalanobis distance between two 1-D arrays.

The Mahalanobis distance between 1-D arrays `u` and `v`, is defined as

.. math::

   \\sqrt{ (u-v) V^{-1} (u-v)^T }

where ``V`` is the covariance matrix.  Note that the argument `VI`
is the inverse of ``V``.

Parameters
----------
u : (N,) array_like
    Input array.
v : (N,) array_like
    Input array.
VI : ndarray
    The inverse of the covariance matrix.

Returns
-------
mahalanobis : double
    The Mahalanobis distance between vectors `u` and `v`.


u = _validate_vector(u)<EOL>v = _validate_vector(v)<EOL>return max(abs(u - v))<EOL>

Computes the Chebyshev distance.

Computes the Chebyshev distance between two 1-D arrays `u` and `v`,
which is defined as

.. math::

   \\max_i {|u_i-v_i|}.

Parameters
----------
u : (N,) array_like
    Input vector.
v : (N,) array_like
    Input vector.

Returns
-------
chebyshev : double
    The Chebyshev distance between vectors `u` and `v`.


u = _validate_vector(u)<EOL>v = _validate_vector(v, dtype=np.float64)<EOL>return abs(u - v).sum() / abs(u + v).sum()<EOL>

Computes the Bray-Curtis distance between two 1-D arrays.

Bray-Curtis distance is defined as

.. math::

   \\sum{|u_i-v_i|} / \\sum{|u_i+v_i|}

The Bray-Curtis distance is in the range [0, 1] if all coordinates are
positive, and is undefined if the inputs are of length zero.

Parameters
----------
u : (N,) array_like
    Input array.
v : (N,) array_like
    Input array.

Returns
-------
braycurtis : double
    The Bray-Curtis distance between 1-D arrays `u` and `v`.


u = _validate_vector(u)<EOL>v = _validate_vector(v, dtype=np.float64)<EOL>olderr = np.seterr(invalid='<STR_LIT:ignore>')<EOL>try:<EOL><INDENT>d = np.nansum(abs(u - v) / (abs(u) + abs(v)))<EOL><DEDENT>finally:<EOL><INDENT>np.seterr(**olderr)<EOL><DEDENT>return d<EOL>

Computes the Canberra distance between two 1-D arrays.

The Canberra distance is defined as

.. math::

     d(u,v) = \\sum_i \\frac{|u_i-v_i|}
                          {|u_i|+|v_i|}.

Parameters
----------
u : (N,) array_like
    Input array.
v : (N,) array_like
    Input array.

Returns
-------
canberra : double
    The Canberra distance between vectors `u` and `v`.

Notes
-----
When `u[i]` and `v[i]` are 0 for given i, then the fraction 0/0 = 0 is
used in the calculation.


u = _validate_vector(u)<EOL>v = _validate_vector(v)<EOL>(nff, nft, ntf, ntt) = _nbool_correspond_all(u, v)<EOL>return float(<NUM_LIT> * ntf * nft) / float(ntt * nff + ntf * nft)<EOL>

Computes the Yule dissimilarity between two boolean 1-D arrays.

The Yule dissimilarity is defined as

.. math::

     \\frac{R}{c_{TT} * c_{FF} + \\frac{R}{2}}

where :math:`c_{ij}` is the number of occurrences of
:math:`\\mathtt{u[k]} = i` and :math:`\\mathtt{v[k]} = j` for
:math:`k < n` and :math:`R = 2.0 * c_{TF} * c_{FT}`.

Parameters
----------
u : (N,) array_like, bool
    Input array.
v : (N,) array_like, bool
    Input array.

Returns
-------
yule : double
    The Yule dissimilarity between vectors `u` and `v`.


u = _validate_vector(u)<EOL>v = _validate_vector(v)<EOL>(nft, ntf) = _nbool_correspond_ft_tf(u, v)<EOL>return float(nft + ntf) / float(len(u))<EOL>

Computes the Matching dissimilarity between two boolean 1-D arrays.

The Matching dissimilarity between two boolean 1-D arrays
`u` and `v`, is defined as

.. math::

   \\frac{c_{TF} + c_{FT}}{n}

where :math:`c_{ij}` is the number of occurrences of
:math:`\\mathtt{u[k]} = i` and :math:`\\mathtt{v[k]} = j` for
:math:`k < n`.

Parameters
----------
u : (N,) array_like, bool
    Input array.
v : (N,) array_like, bool
    Input array.

Returns
-------
matching : double
    The Matching dissimilarity between vectors `u` and `v`.


u = _validate_vector(u)<EOL>v = _validate_vector(v)<EOL>if u.dtype == np.bool:<EOL><INDENT>ntt = (u & v).sum()<EOL><DEDENT>else:<EOL><INDENT>ntt = (u * v).sum()<EOL><DEDENT>(nft, ntf) = _nbool_correspond_ft_tf(u, v)<EOL>return float(ntf + nft) / float(<NUM_LIT> * ntt + ntf + nft)<EOL>

Computes the Dice dissimilarity between two boolean 1-D arrays.

The Dice dissimilarity between `u` and `v`, is

.. math::

     \\frac{c_{TF} + c_{FT}}
          {2c_{TT} + c_{FT} + c_{TF}}

where :math:`c_{ij}` is the number of occurrences of
:math:`\\mathtt{u[k]} = i` and :math:`\\mathtt{v[k]} = j` for
:math:`k < n`.

Parameters
----------
u : (N,) ndarray, bool
    Input 1-D array.
v : (N,) ndarray, bool
    Input 1-D array.

Returns
-------
dice : double
    The Dice dissimilarity between 1-D arrays `u` and `v`.


u = _validate_vector(u)<EOL>v = _validate_vector(v)<EOL>(nff, nft, ntf, ntt) = _nbool_correspond_all(u, v)<EOL>return float(<NUM_LIT> * (ntf + nft)) / float(ntt + nff + (<NUM_LIT> * (ntf + nft)))<EOL>

Computes the Rogers-Tanimoto dissimilarity between two boolean 1-D arrays.

The Rogers-Tanimoto dissimilarity between two boolean 1-D arrays
`u` and `v`, is defined as

.. math::
   \\frac{R}
        {c_{TT} + c_{FF} + R}

where :math:`c_{ij}` is the number of occurrences of
:math:`\\mathtt{u[k]} = i` and :math:`\\mathtt{v[k]} = j` for
:math:`k < n` and :math:`R = 2(c_{TF} + c_{FT})`.

Parameters
----------
u : (N,) array_like, bool
    Input array.
v : (N,) array_like, bool
    Input array.

Returns
-------
rogerstanimoto : double
    The Rogers-Tanimoto dissimilarity between vectors
    `u` and `v`.


u = _validate_vector(u)<EOL>v = _validate_vector(v)<EOL>if u.dtype == np.bool:<EOL><INDENT>ntt = (u & v).sum()<EOL><DEDENT>else:<EOL><INDENT>ntt = (u * v).sum()<EOL><DEDENT>return float(len(u) - ntt) / float(len(u))<EOL>

Computes the Russell-Rao dissimilarity between two boolean 1-D arrays.

The Russell-Rao dissimilarity between two boolean 1-D arrays, `u` and
`v`, is defined as

.. math::

  \\frac{n - c_{TT}}
       {n}

where :math:`c_{ij}` is the number of occurrences of
:math:`\\mathtt{u[k]} = i` and :math:`\\mathtt{v[k]} = j` for
:math:`k < n`.

Parameters
----------
u : (N,) array_like, bool
    Input array.
v : (N,) array_like, bool
    Input array.

Returns
-------
russellrao : double
    The Russell-Rao dissimilarity between vectors `u` and `v`.


u = _validate_vector(u)<EOL>v = _validate_vector(v)<EOL>if u.dtype == np.bool:<EOL><INDENT>ntt = (u & v).sum()<EOL>nff = (~u & ~v).sum()<EOL><DEDENT>else:<EOL><INDENT>ntt = (u * v).sum()<EOL>nff = ((<NUM_LIT:1.0> - u) * (<NUM_LIT:1.0> - v)).sum()<EOL><DEDENT>(nft, ntf) = _nbool_correspond_ft_tf(u, v)<EOL>return float(<NUM_LIT> * (ntf + nft)) / float(ntt + nff + <NUM_LIT> * (ntf + nft))<EOL>

Computes the Sokal-Michener dissimilarity between two boolean 1-D arrays.

The Sokal-Michener dissimilarity between boolean 1-D arrays `u` and `v`,
is defined as

.. math::

   \\frac{R}
        {S + R}

where :math:`c_{ij}` is the number of occurrences of
:math:`\\mathtt{u[k]} = i` and :math:`\\mathtt{v[k]} = j` for
:math:`k < n`, :math:`R = 2 * (c_{TF} + c_{FT})` and
:math:`S = c_{FF} + c_{TT}`.

Parameters
----------
u : (N,) array_like, bool
    Input array.
v : (N,) array_like, bool
    Input array.

Returns
-------
sokalmichener : double
    The Sokal-Michener dissimilarity between vectors `u` and `v`.


u = _validate_vector(u)<EOL>v = _validate_vector(v)<EOL>if u.dtype == np.bool:<EOL><INDENT>ntt = (u & v).sum()<EOL><DEDENT>else:<EOL><INDENT>ntt = (u * v).sum()<EOL><DEDENT>(nft, ntf) = _nbool_correspond_ft_tf(u, v)<EOL>denom = ntt + <NUM_LIT> * (ntf + nft)<EOL>if denom == <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>return float(<NUM_LIT> * (ntf + nft)) / denom<EOL>

Computes the Sokal-Sneath dissimilarity between two boolean 1-D arrays.

The Sokal-Sneath dissimilarity between `u` and `v`,

.. math::

   \\frac{R}
        {c_{TT} + R}

where :math:`c_{ij}` is the number of occurrences of
:math:`\\mathtt{u[k]} = i` and :math:`\\mathtt{v[k]} = j` for
:math:`k < n` and :math:`R = 2(c_{TF} + c_{FT})`.

Parameters
----------
u : (N,) array_like, bool
    Input array.
v : (N,) array_like, bool
    Input array.

Returns
-------
sokalsneath : double
    The Sokal-Sneath dissimilarity between vectors `u` and `v`.


def pdist(X, metric='<STR_LIT>', p=<NUM_LIT:2>, w=None, V=None, VI=None):

<EOL><INDENT>X = np.asarray(X, order='<STR_LIT:c>')<EOL>[X] = _copy_arrays_if_base_present([_convert_to_double(X)])<EOL>s = X.shape<EOL>if len(s) != <NUM_LIT:2>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>m, n = s<EOL>dm = np.zeros((m * (m - <NUM_LIT:1>)) // <NUM_LIT:2>, dtype=np.double)<EOL>wmink_names = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>if w is None and (metric == wminkowski or metric in wmink_names):<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>if callable(metric):<EOL><INDENT>if metric == minkowski:<EOL><INDENT>def dfun(u, v):<EOL><INDENT>return minkowski(u, v, p)<EOL><DEDENT><DEDENT>elif metric == wminkowski:<EOL><INDENT>def dfun(u, v):<EOL><INDENT>return wminkowski(u, v, p, w)<EOL><DEDENT><DEDENT>elif metric == seuclidean:<EOL><INDENT>def dfun(u, v):<EOL><INDENT>return seuclidean(u, v, V)<EOL><DEDENT><DEDENT>elif metric == mahalanobis:<EOL><INDENT>def dfun(u, v):<EOL><INDENT>return mahalanobis(u, v, V)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>dfun = metric<EOL><DEDENT>k = <NUM_LIT:0><EOL>for i in xrange(<NUM_LIT:0>, m - <NUM_LIT:1>):<EOL><INDENT>for j in xrange(i + <NUM_LIT:1>, m):<EOL><INDENT>dm[k] = dfun(X[i], X[j])<EOL>k = k + <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>elif isinstance(metric, string_types):<EOL><INDENT>mstr = metric.lower()<EOL>if mstr in set(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:e>']):<EOL><INDENT>_distance_wrap.pdist_euclidean_wrap(_convert_to_double(X), dm)<EOL><DEDENT>elif mstr in set(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']):<EOL><INDENT>_distance_wrap.pdist_sqeuclidean_wrap(_convert_to_double(X), dm)<EOL><DEDENT>elif mstr in set(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:c>']):<EOL><INDENT>_distance_wrap.pdist_city_block_wrap(X, dm)<EOL><DEDENT>elif mstr in set(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:h>']):<EOL><INDENT>if X.dtype == np.bool:<EOL><INDENT>_distance_wrap.pdist_hamming_bool_wrap(_convert_to_bool(X), dm)<EOL><DEDENT>else:<EOL><INDENT>_distance_wrap.pdist_hamming_wrap(_convert_to_double(X), dm)<EOL><DEDENT><DEDENT>elif mstr in set(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']):<EOL><INDENT>if X.dtype == np.bool:<EOL><INDENT>_distance_wrap.pdist_jaccard_bool_wrap(_convert_to_bool(X), dm)<EOL><DEDENT>else:<EOL><INDENT>_distance_wrap.pdist_jaccard_wrap(_convert_to_double(X), dm)<EOL><DEDENT><DEDENT>elif mstr in set(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']):<EOL><INDENT>_distance_wrap.pdist_chebyshev_wrap(_convert_to_double(X), dm)<EOL><DEDENT>elif mstr in set(['<STR_LIT>', '<STR_LIT>', '<STR_LIT:m>']):<EOL><INDENT>_distance_wrap.pdist_minkowski_wrap(_convert_to_double(X), dm, p)<EOL><DEDENT>elif mstr in wmink_names:<EOL><INDENT>_distance_wrap.pdist_weighted_minkowski_wrap(_convert_to_double(X),<EOL>dm, p, np.asarray(w))<EOL><DEDENT>elif mstr in set(['<STR_LIT>', '<STR_LIT>', '<STR_LIT:s>']):<EOL><INDENT>if V is not None:<EOL><INDENT>V = np.asarray(V, order='<STR_LIT:c>')<EOL>if type(V) != np.ndarray:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if V.dtype != np.double:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if len(V.shape) != <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>if V.shape[<NUM_LIT:0>] != n:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>[VV] = _copy_arrays_if_base_present([_convert_to_double(V)])<EOL><DEDENT>else:<EOL><INDENT>VV = np.var(X, axis=<NUM_LIT:0>, ddof=<NUM_LIT:1>)<EOL><DEDENT>_distance_wrap.pdist_seuclidean_wrap(_convert_to_double(X), VV, dm)<EOL><DEDENT>elif mstr in set(['<STR_LIT>', '<STR_LIT>']):<EOL><INDENT>norms = np.sqrt(np.sum(X * X, axis=<NUM_LIT:1>))<EOL>_distance_wrap.pdist_cosine_wrap(_convert_to_double(X), dm, norms)<EOL><DEDENT>elif mstr in set(['<STR_LIT>', '<STR_LIT>']):<EOL><INDENT>norms = np.sqrt(np.sum(X * X, axis=<NUM_LIT:1>))<EOL>nV = norms.reshape(m, <NUM_LIT:1>)<EOL>nm = np.dot(X, X.T)<EOL>de = np.dot(nV, nV.T)<EOL>dm = <NUM_LIT:1.0> - (nm / de)<EOL>dm[xrange(<NUM_LIT:0>, m), xrange(<NUM_LIT:0>, m)] = <NUM_LIT:0.0><EOL>dm = squareform(dm)<EOL><DEDENT>elif mstr in set(['<STR_LIT>', '<STR_LIT>']):<EOL><INDENT>X2 = X - X.mean(<NUM_LIT:1>)[:, np.newaxis]<EOL>norms = np.sqrt(np.sum(X2 * X2, axis=<NUM_LIT:1>))<EOL>_distance_wrap.pdist_cosine_wrap(_convert_to_double(X2),<EOL>_convert_to_double(dm),<EOL>_convert_to_double(norms))<EOL><DEDENT>elif mstr in set(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']):<EOL><INDENT>if VI is not None:<EOL><INDENT>VI = _convert_to_double(np.asarray(VI, order='<STR_LIT:c>'))<EOL>if type(VI) != np.ndarray:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if VI.dtype != np.double:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>[VI] = _copy_arrays_if_base_present([VI])<EOL><DEDENT>else:<EOL><INDENT>V = np.cov(X.T)<EOL>VI = _convert_to_double(np.linalg.inv(V).T.copy())<EOL><DEDENT>_distance_wrap.pdist_mahalanobis_wrap(_convert_to_double(X),<EOL>VI, dm)<EOL><DEDENT>elif mstr == '<STR_LIT>':<EOL><INDENT>_distance_wrap.pdist_canberra_wrap(_convert_to_double(X), dm)<EOL><DEDENT>elif mstr == '<STR_LIT>':<EOL><INDENT>_distance_wrap.pdist_bray_curtis_wrap(_convert_to_double(X), dm)<EOL><DEDENT>elif mstr == '<STR_LIT>':<EOL><INDENT>_distance_wrap.pdist_yule_bool_wrap(_convert_to_bool(X), dm)<EOL><DEDENT>elif mstr == '<STR_LIT>':<EOL><INDENT>_distance_wrap.pdist_matching_bool_wrap(_convert_to_bool(X), dm)<EOL><DEDENT>elif mstr == '<STR_LIT>':<EOL><INDENT>_distance_wrap.pdist_kulsinski_bool_wrap(_convert_to_bool(X), dm)<EOL><DEDENT>elif mstr == '<STR_LIT>':<EOL><INDENT>_distance_wrap.pdist_dice_bool_wrap(_convert_to_bool(X), dm)<EOL><DEDENT>elif mstr == '<STR_LIT>':<EOL><INDENT>_distance_wrap.pdist_rogerstanimoto_bool_wrap(_convert_to_bool(X),<EOL>dm)<EOL><DEDENT>elif mstr == '<STR_LIT>':<EOL><INDENT>_distance_wrap.pdist_russellrao_bool_wrap(_convert_to_bool(X), dm)<EOL><DEDENT>elif mstr == '<STR_LIT>':<EOL><INDENT>_distance_wrap.pdist_sokalmichener_bool_wrap(_convert_to_bool(X),<EOL>dm)<EOL><DEDENT>elif mstr == '<STR_LIT>':<EOL><INDENT>_distance_wrap.pdist_sokalsneath_bool_wrap(_convert_to_bool(X), dm)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = pdist(X, euclidean)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>if V is None:<EOL><INDENT>V = np.var(X, axis=<NUM_LIT:0>, ddof=<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>V = np.asarray(V, order='<STR_LIT:c>')<EOL><DEDENT>dm = pdist(X, lambda u, v: seuclidean(u, v, V))<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = pdist(X, braycurtis)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>if VI is None:<EOL><INDENT>V = np.cov(X.T)<EOL>VI = np.linalg.inv(V)<EOL><DEDENT>else:<EOL><INDENT>VI = np.asarray(VI, order='<STR_LIT:c>')<EOL><DEDENT>[VI] = _copy_arrays_if_base_present([VI])<EOL>dm = pdist(X, (lambda u, v: mahalanobis(u, v, VI)))<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = pdist(X, canberra)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = pdist(X, cityblock)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = pdist(X, minkowski, p=p)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = pdist(X, wminkowski, p=p, w=w)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = pdist(X, cosine)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = pdist(X, correlation)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = pdist(X, hamming)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = pdist(X, jaccard)<EOL><DEDENT>elif metric == '<STR_LIT>' or metric == '<STR_LIT>':<EOL><INDENT>dm = pdist(X, chebyshev)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = pdist(X, yule)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = pdist(X, matching)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = pdist(X, dice)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = pdist(X, kulsinski)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = pdist(X, rogerstanimoto)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = pdist(X, russellrao)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = pdist(X, sokalsneath)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = pdist(X, sokalmichener)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % mstr)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>return dm<EOL><DEDENT>

Pairwise distances between observations in n-dimensional space.

The following are common calling conventions.

1. ``Y = pdist(X, 'euclidean')``

   Computes the distance between m points using Euclidean distance
   (2-norm) as the distance metric between the points. The points
   are arranged as m n-dimensional row vectors in the matrix X.

2. ``Y = pdist(X, 'minkowski', p)``

   Computes the distances using the Minkowski distance
   :math:`||u-v||_p` (p-norm) where :math:`p \\geq 1`.

3. ``Y = pdist(X, 'cityblock')``

   Computes the city block or Manhattan distance between the
   points.

4. ``Y = pdist(X, 'seuclidean', V=None)``

   Computes the standardized Euclidean distance. The standardized
   Euclidean distance between two n-vectors ``u`` and ``v`` is

   .. math::

      \\sqrt{\\sum {(u_i-v_i)^2 / V[x_i]}}

   V is the variance vector; V[i] is the variance computed over all
   the i'th components of the points.  If not passed, it is
   automatically computed.

5. ``Y = pdist(X, 'sqeuclidean')``

   Computes the squared Euclidean distance :math:`||u-v||_2^2` between
   the vectors.

6. ``Y = pdist(X, 'cosine')``

   Computes the cosine distance between vectors u and v,

   .. math::

      1 - \\frac{u \\cdot v}
               {{||u||}_2 {||v||}_2}

   where :math:`||*||_2` is the 2-norm of its argument ``*``, and
   :math:`u \\cdot v` is the dot product of ``u`` and ``v``.

7. ``Y = pdist(X, 'correlation')``

   Computes the correlation distance between vectors u and v. This is

   .. math::

      1 - \\frac{(u - \\bar{u}) \\cdot (v - \\bar{v})}
               {{||(u - \\bar{u})||}_2 {||(v - \\bar{v})||}_2}

   where :math:`\\bar{v}` is the mean of the elements of vector v,
   and :math:`x \\cdot y` is the dot product of :math:`x` and :math:`y`.

8. ``Y = pdist(X, 'hamming')``

   Computes the normalized Hamming distance, or the proportion of
   those vector elements between two n-vectors ``u`` and ``v``
   which disagree. To save memory, the matrix ``X`` can be of type
   boolean.

9. ``Y = pdist(X, 'jaccard')``

   Computes the Jaccard distance between the points. Given two
   vectors, ``u`` and ``v``, the Jaccard distance is the
   proportion of those elements ``u[i]`` and ``v[i]`` that
   disagree where at least one of them is non-zero.

10. ``Y = pdist(X, 'chebyshev')``

   Computes the Chebyshev distance between the points. The
   Chebyshev distance between two n-vectors ``u`` and ``v`` is the
   maximum norm-1 distance between their respective elements. More
   precisely, the distance is given by

   .. math::

      d(u,v) = \\max_i {|u_i-v_i|}

11. ``Y = pdist(X, 'canberra')``

   Computes the Canberra distance between the points. The
   Canberra distance between two points ``u`` and ``v`` is

   .. math::

     d(u,v) = \\sum_i \\frac{|u_i-v_i|}
                          {|u_i|+|v_i|}

12. ``Y = pdist(X, 'braycurtis')``

   Computes the Bray-Curtis distance between the points. The
   Bray-Curtis distance between two points ``u`` and ``v`` is

   .. math::

        d(u,v) = \\frac{\\sum_i {u_i-v_i}}
                      {\\sum_i {u_i+v_i}}

13. ``Y = pdist(X, 'mahalanobis', VI=None)``

   Computes the Mahalanobis distance between the points. The
   Mahalanobis distance between two points ``u`` and ``v`` is
   :math:`(u-v)(1/V)(u-v)^T` where :math:`(1/V)` (the ``VI``
   variable) is the inverse covariance. If ``VI`` is not None,
   ``VI`` will be used as the inverse covariance matrix.

14. ``Y = pdist(X, 'yule')``

   Computes the Yule distance between each pair of boolean
   vectors. (see yule function documentation)

15. ``Y = pdist(X, 'matching')``

   Computes the matching distance between each pair of boolean
   vectors. (see matching function documentation)

16. ``Y = pdist(X, 'dice')``

   Computes the Dice distance between each pair of boolean
   vectors. (see dice function documentation)

17. ``Y = pdist(X, 'kulsinski')``

   Computes the Kulsinski distance between each pair of
   boolean vectors. (see kulsinski function documentation)

18. ``Y = pdist(X, 'rogerstanimoto')``

   Computes the Rogers-Tanimoto distance between each pair of
   boolean vectors. (see rogerstanimoto function documentation)

19. ``Y = pdist(X, 'russellrao')``

   Computes the Russell-Rao distance between each pair of
   boolean vectors. (see russellrao function documentation)

20. ``Y = pdist(X, 'sokalmichener')``

   Computes the Sokal-Michener distance between each pair of
   boolean vectors. (see sokalmichener function documentation)

21. ``Y = pdist(X, 'sokalsneath')``

   Computes the Sokal-Sneath distance between each pair of
   boolean vectors. (see sokalsneath function documentation)

22. ``Y = pdist(X, 'wminkowski')``

   Computes the weighted Minkowski distance between each pair of
   vectors. (see wminkowski function documentation)

23. ``Y = pdist(X, f)``

   Computes the distance between all pairs of vectors in X
   using the user supplied 2-arity function f. For example,
   Euclidean distance between the vectors could be computed
   as follows::

     dm = pdist(X, lambda u, v: np.sqrt(((u-v)**2).sum()))

   Note that you should avoid passing a reference to one of
   the distance functions defined in this library. For example,::

     dm = pdist(X, sokalsneath)

   would calculate the pair-wise distances between the vectors in
   X using the Python function sokalsneath. This would result in
   sokalsneath being called :math:`{n \\choose 2}` times, which
   is inefficient. Instead, the optimized C version is more
   efficient, and we call it using the following syntax.::

     dm = pdist(X, 'sokalsneath')

Parameters
----------
X : ndarray
    An m by n array of m original observations in an
    n-dimensional space.
metric : string or function
    The distance metric to use. The distance function can
    be 'braycurtis', 'canberra', 'chebyshev', 'cityblock',
    'correlation', 'cosine', 'dice', 'euclidean', 'hamming',
    'jaccard', 'kulsinski', 'mahalanobis', 'matching',
    'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean',
    'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule'.
w : ndarray
    The weight vector (for weighted Minkowski).
p : double
    The p-norm to apply (for Minkowski, weighted and unweighted)
V : ndarray
        The variance vector (for standardized Euclidean).
VI : ndarray
    The inverse of the covariance matrix (for Mahalanobis).

Returns
-------
Y : ndarray
    Returns a condensed distance matrix Y.  For
    each :math:`i` and :math:`j` (where :math:`i<j<n`), the
    metric ``dist(u=X[i], v=X[j])`` is computed and stored in entry ``ij``.

See Also
--------
squareform : converts between condensed distance matrices and
             square distance matrices.

Notes
-----
See ``squareform`` for information on how to calculate the index of
this entry or to convert the condensed distance matrix to a
redundant square matrix.