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


<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]))


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).


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

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


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>


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>',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


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


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.


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


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.


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

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>

See the docstring for `spmatrix.toarray`.


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).


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.


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.


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`.


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>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`.


def squareform(X, force="<STR_LIT>", checks=True):

X = _convert_to_double(np.asarray(X, order='<STR_LIT:c>'))<EOL>if not np.issubsctype(X, np.double):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>s = X.shape<EOL>if force.lower() == '<STR_LIT>':<EOL><INDENT>if len(s) != <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>elif force.lower() == '<STR_LIT>':<EOL><INDENT>if len(s) != <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>if len(s) == <NUM_LIT:1>:<EOL><INDENT>if X.shape[<NUM_LIT:0>] == <NUM_LIT:0>:<EOL><INDENT>return np.zeros((<NUM_LIT:1>, <NUM_LIT:1>), dtype=np.double)<EOL><DEDENT>d = int(np.ceil(np.sqrt(X.shape[<NUM_LIT:0>] * <NUM_LIT:2>)))<EOL>if d * (d - <NUM_LIT:1>) / <NUM_LIT:2> != int(s[<NUM_LIT:0>]):<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>M = np.zeros((d, d), dtype=np.double)<EOL>[X] = _copy_arrays_if_base_present([X])<EOL>_distance_wrap.to_squareform_from_vector_wrap(M, X)<EOL>M = M + M.transpose()<EOL>return M<EOL><DEDENT>elif len(s) == <NUM_LIT:2>:<EOL><INDENT>if s[<NUM_LIT:0>] != s[<NUM_LIT:1>]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if checks:<EOL><INDENT>is_valid_dm(X, throw=True, name='<STR_LIT:X>')<EOL><DEDENT>d = s[<NUM_LIT:0>]<EOL>if d <= <NUM_LIT:1>:<EOL><INDENT>return np.array([], dtype=np.double)<EOL><DEDENT>v = np.zeros((d * (d - <NUM_LIT:1>)) // <NUM_LIT:2>, dtype=np.double)<EOL>[X] = _copy_arrays_if_base_present([X])<EOL>_distance_wrap.to_vector_from_squareform_wrap(X, v)<EOL>return v<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>') % len(s))<EOL><DEDENT>

Converts a vector-form distance vector to a square-form distance
matrix, and vice-versa.

Parameters
----------
X : ndarray
    Either a condensed or redundant distance matrix.
force : str, optional
    As with MATLAB(TM), if force is equal to 'tovector' or 'tomatrix',
    the input will be treated as a distance matrix or distance vector
    respectively.
checks : bool, optional
    If `checks` is set to False, no checks will be made for matrix
    symmetry nor zero diagonals. This is useful if it is known that
    ``X - X.T1`` is small and ``diag(X)`` is close to zero.
    These values are ignored any way so they do not disrupt the
    squareform transformation.

Returns
-------
Y : ndarray
    If a condensed distance matrix is passed, a redundant one is
    returned, or if a redundant one is passed, a condensed distance
    matrix is returned.

Notes
-----

1. v = squareform(X)

   Given a square d-by-d symmetric distance matrix X,
   ``v=squareform(X)`` returns a ``d * (d-1) / 2`` (or
   `${n \\choose 2}$`) sized vector v.

  v[{n \\choose 2}-{n-i \\choose 2} + (j-i-1)] is the distance
  between points i and j. If X is non-square or asymmetric, an error
  is returned.

2. X = squareform(v)

  Given a d*d(-1)/2 sized v for some integer d>=2 encoding distances
  as described, X=squareform(v) returns a d by d distance matrix X. The
  X[i, j] and X[j, i] values are set to
  v[{n \\choose 2}-{n-i \\choose 2} + (j-u-1)] and all
  diagonal elements are zero.


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`.


Y = np.asarray(Y, order='<STR_LIT:c>')<EOL>is_valid_y(Y, throw=True, name='<STR_LIT:Y>')<EOL>k = Y.shape[<NUM_LIT:0>]<EOL>if k == <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>d = int(np.ceil(np.sqrt(k * <NUM_LIT:2>)))<EOL>if (d * (d - <NUM_LIT:1>) / <NUM_LIT:2>) != k:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>return d<EOL>

Returns the number of original observations that correspond to a
condensed distance matrix.

Parameters
----------
Y : ndarray
    Condensed distance matrix.

Returns
-------
n : int
    The number of observations in the condensed distance matrix `Y`.


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`.


d = np.asarray(d, order='<STR_LIT:c>')<EOL>is_valid_dm(d, tol=np.inf, throw=True, name='<STR_LIT:d>')<EOL>return d.shape[<NUM_LIT:0>]<EOL>

Returns the number of original observations that correspond to a
square, redundant distance matrix.

Parameters
----------
d : ndarray
    The target distance matrix.

Returns
-------
num_obs_dm : int
    The number of observations in the redundant distance matrix.


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.


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`.


if vor.points.shape[<NUM_LIT:1>] != <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>ax.plot(vor.points[:,<NUM_LIT:0>], vor.points[:,<NUM_LIT:1>], '<STR_LIT:.>')<EOL>ax.plot(vor.vertices[:,<NUM_LIT:0>], vor.vertices[:,<NUM_LIT:1>], '<STR_LIT:o>')<EOL>for simplex in vor.ridge_vertices:<EOL><INDENT>simplex = np.asarray(simplex)<EOL>if np.all(simplex >= <NUM_LIT:0>):<EOL><INDENT>ax.plot(vor.vertices[simplex,<NUM_LIT:0>], vor.vertices[simplex,<NUM_LIT:1>], '<STR_LIT>')<EOL><DEDENT><DEDENT>ptp_bound = vor.points.ptp(axis=<NUM_LIT:0>)<EOL>center = vor.points.mean(axis=<NUM_LIT:0>)<EOL>for pointidx, simplex in zip(vor.ridge_points, vor.ridge_vertices):<EOL><INDENT>simplex = np.asarray(simplex)<EOL>if np.any(simplex < <NUM_LIT:0>):<EOL><INDENT>i = simplex[simplex >= <NUM_LIT:0>][<NUM_LIT:0>]  <EOL>t = vor.points[pointidx[<NUM_LIT:1>]] - vor.points[pointidx[<NUM_LIT:0>]]  <EOL>t /= np.linalg.norm(t)<EOL>n = np.array([-t[<NUM_LIT:1>], t[<NUM_LIT:0>]])  <EOL>midpoint = vor.points[pointidx].mean(axis=<NUM_LIT:0>)<EOL>direction = np.sign(np.dot(midpoint - center, n)) * n<EOL>far_point = vor.vertices[i] + direction * ptp_bound.max()<EOL>ax.plot([vor.vertices[i,<NUM_LIT:0>], far_point[<NUM_LIT:0>]],<EOL>[vor.vertices[i,<NUM_LIT:1>], far_point[<NUM_LIT:1>]], '<STR_LIT>')<EOL><DEDENT><DEDENT>_adjust_bounds(ax, vor.points)<EOL>return ax.figure<EOL>

Plot the given Voronoi diagram in 2-D

Parameters
----------
vor : scipy.spatial.Voronoi instance
    Diagram to plot
ax : matplotlib.axes.Axes instance, optional
    Axes to plot on

Returns
-------
fig : matplotlib.figure.Figure instance
    Figure for the plot

See Also
--------
Voronoi

Notes
-----
Requires Matplotlib.


def min_distance_point(self, x, p=<NUM_LIT>):

return minkowski_distance(<NUM_LIT:0>, np.maximum(<NUM_LIT:0>,np.maximum(self.mins-x,x-self.maxes)),p)<EOL>

Return the minimum distance between input and points in the hyperrectangle.

Parameters
----------
x : array_like
    Input.
p : float, optional
    Input.


def query_ball_point(self, x, r, p=<NUM_LIT>, eps=<NUM_LIT:0>):

x = np.asarray(x)<EOL>if x.shape[-<NUM_LIT:1>] != self.m:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % (x.shape[-<NUM_LIT:1>], self.m))<EOL><DEDENT>if len(x.shape) == <NUM_LIT:1>:<EOL><INDENT>return self.__query_ball_point(x, r, p, eps)<EOL><DEDENT>else:<EOL><INDENT>retshape = x.shape[:-<NUM_LIT:1>]<EOL>result = np.empty(retshape, dtype=np.object)<EOL>for c in np.ndindex(retshape):<EOL><INDENT>result[c] = self.__query_ball_point(x[c], r, p=p, eps=eps)<EOL><DEDENT>return result<EOL><DEDENT>

Find all points within distance r of point(s) x.

        Parameters
        ----------
        x : array_like, shape tuple + (self.m,)
            The point or points to search for neighbors of.
        r : positive float
            The radius of points to return.
        p : float, optional
            Which Minkowski p-norm to use.  Should be in the range [1, inf].
        eps : nonnegative float, optional
            Approximate search. Branches of the tree are not explored if their
            nearest points are further than ``r / (1 + eps)``, and branches are
            added in bulk if their furthest points are nearer than
            ``r * (1 + eps)``.

        Returns
        -------
        results : list or array of lists
            If `x` is a single point, returns a list of the indices of the
            neighbors of `x`. If `x` is an array of points, returns an object
            array of shape tuple containing lists of neighbors.

        Notes
        -----
        If you have many points whose neighbors you want to find, you may save
        substantial amounts of time by putting them in a KDTree and using
        query_ball_tree.

        Examples
        --------
        >>> from scipy import spatial
        >>> x, y = np.mgrid[0:4, 0:4]
        >>> points = zip(x.ravel(), y.ravel())
        >>> tree = spatial.KDTree(points)
        >>> tree.query_ball_point([2, 0], 1)
        [4, 8, 9, 12]


def query(self, x, k=<NUM_LIT:1>, eps=<NUM_LIT:0>, p=<NUM_LIT:2>, distance_upper_bound=np.inf):

x = np.asarray(x)<EOL>if np.shape(x)[-<NUM_LIT:1>] != self.m:<EOL><INDENT>raise ValueError("<STR_LIT>" % (self.m, np.shape(x)))<EOL><DEDENT>if p < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>retshape = np.shape(x)[:-<NUM_LIT:1>]<EOL>if retshape != ():<EOL><INDENT>if k is None:<EOL><INDENT>dd = np.empty(retshape,dtype=np.object)<EOL>ii = np.empty(retshape,dtype=np.object)<EOL><DEDENT>elif k > <NUM_LIT:1>:<EOL><INDENT>dd = np.empty(retshape+(k,),dtype=np.float)<EOL>dd.fill(np.inf)<EOL>ii = np.empty(retshape+(k,),dtype=np.int)<EOL>ii.fill(self.n)<EOL><DEDENT>elif k == <NUM_LIT:1>:<EOL><INDENT>dd = np.empty(retshape,dtype=np.float)<EOL>dd.fill(np.inf)<EOL>ii = np.empty(retshape,dtype=np.int)<EOL>ii.fill(self.n)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>for c in np.ndindex(retshape):<EOL><INDENT>hits = self.__query(x[c], k=k, eps=eps, p=p, distance_upper_bound=distance_upper_bound)<EOL>if k is None:<EOL><INDENT>dd[c] = [d for (d,i) in hits]<EOL>ii[c] = [i for (d,i) in hits]<EOL><DEDENT>elif k > <NUM_LIT:1>:<EOL><INDENT>for j in range(len(hits)):<EOL><INDENT>dd[c+(j,)], ii[c+(j,)] = hits[j]<EOL><DEDENT><DEDENT>elif k == <NUM_LIT:1>:<EOL><INDENT>if len(hits) > <NUM_LIT:0>:<EOL><INDENT>dd[c], ii[c] = hits[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>dd[c] = np.inf<EOL>ii[c] = self.n<EOL><DEDENT><DEDENT><DEDENT>return dd, ii<EOL><DEDENT>else:<EOL><INDENT>hits = self.__query(x, k=k, eps=eps, p=p, distance_upper_bound=distance_upper_bound)<EOL>if k is None:<EOL><INDENT>return [d for (d,i) in hits], [i for (d,i) in hits]<EOL><DEDENT>elif k == <NUM_LIT:1>:<EOL><INDENT>if len(hits) > <NUM_LIT:0>:<EOL><INDENT>return hits[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>return np.inf, self.n<EOL><DEDENT><DEDENT>elif k > <NUM_LIT:1>:<EOL><INDENT>dd = np.empty(k,dtype=np.float)<EOL>dd.fill(np.inf)<EOL>ii = np.empty(k,dtype=np.int)<EOL>ii.fill(self.n)<EOL>for j in range(len(hits)):<EOL><INDENT>dd[j], ii[j] = hits[j]<EOL><DEDENT>return dd, ii<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>

Query the kd-tree for nearest neighbors

Parameters
----------
x : array_like, last dimension self.m
    An array of points to query.
k : integer
    The number of nearest neighbors to return.
eps : nonnegative float
    Return approximate nearest neighbors; the kth returned value
    is guaranteed to be no further than (1+eps) times the
    distance to the real kth nearest neighbor.
p : float, 1<=p<=infinity
    Which Minkowski p-norm to use.
    1 is the sum-of-absolute-values "Manhattan" distance
    2 is the usual Euclidean distance
    infinity is the maximum-coordinate-difference distance
distance_upper_bound : nonnegative float
    Return only neighbors within this distance. This is used to prune
    tree searches, so if you are doing a series of nearest-neighbor
    queries, it may help to supply the distance to the nearest neighbor
    of the most recent point.

Returns
-------
d : float or array of floats
    The distances to the nearest neighbors.
    If x has shape tuple+(self.m,), then d has shape tuple if
    k is one, or tuple+(k,) if k is larger than one. Missing
    neighbors (e.g. when k > n or distance_upper_bound is
    given) are indicated with infinite distances.  If k is None,
    then d is an object array of shape tuple, containing lists
    of distances. In either case the hits are sorted by distance
    (nearest first).
i : integer or array of integers
    The locations of the neighbors in self.data. i is the same
    shape as d.

Examples
--------
>>> from scipy import spatial
>>> x, y = np.mgrid[0:5, 2:8]
>>> tree = spatial.KDTree(zip(x.ravel(), y.ravel()))
>>> tree.data
array([[0, 2],
       [0, 3],
       [0, 4],
       [0, 5],
       [0, 6],
       [0, 7],
       [1, 2],
       [1, 3],
       [1, 4],
       [1, 5],
       [1, 6],
       [1, 7],
       [2, 2],
       [2, 3],
       [2, 4],
       [2, 5],
       [2, 6],
       [2, 7],
       [3, 2],
       [3, 3],
       [3, 4],
       [3, 5],
       [3, 6],
       [3, 7],
       [4, 2],
       [4, 3],
       [4, 4],
       [4, 5],
       [4, 6],
       [4, 7]])
>>> pts = np.array([[0, 0], [2.1, 2.9]])
>>> tree.query(pts)
(array([ 2.        ,  0.14142136]), array([ 0, 13]))
>>> tree.query(pts[0])
(2.0, 0)


expr = "<STR_LIT>""<STR_LIT>"<EOL>self.generic_2d(expr,complex64)<EOL>

Note: THIS TEST is KNOWN TO FAIL ON GCC 3.x.
            It will not adversely affect 99.99 percent of weave

        result[1:-1,1:-1] = (b[1:-1,1:-1] + b[2:,1:-1] + b[:-2,1:-1]
                             + b[1:-1,2:] + b[1:-1,:-2]) / 5.

        Note: THIS TEST is KNOWN TO FAIL ON GCC 3.x.  The reason is that
        5. is a double and b is a complex32.  blitz doesn't know
        how to handle complex32/double.  See:
        http://www.oonumerics.org/MailArchives/blitz-support/msg00541.php
        Unfortunately, the fix isn't trivial.  Instead of fixing it, I
        prefer to wait until we replace blitz++ with Pat Miller's code
        that doesn't rely on blitz..


backup_dir = tempfile.mkdtemp()<EOL>for file in temp_catalog_files():<EOL><INDENT>move_file(file,backup_dir)<EOL><DEDENT>return backup_dir<EOL>


result = <NUM_LIT:0><EOL>cmd = [str(name), '<STR_LIT>']<EOL>try:<EOL><INDENT>if sys.platform == '<STR_LIT:win32>':<EOL><INDENT>p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,<EOL>stderr=subprocess.STDOUT)<EOL><DEDENT>else:<EOL><INDENT>p = subprocess.Popen(cmd, stdout=subprocess.PIPE,<EOL>stderr=subprocess.STDOUT)<EOL><DEDENT>str_result = p.stdout.read()<EOL>if '<STR_LIT>' in str_result:<EOL><INDENT>result = <NUM_LIT:1><EOL><DEDENT><DEDENT>except:<EOL><INDENT>result = not os.system("<STR_LIT:U+0020>".join(cmd))<EOL><DEDENT>return result<EOL>


if sys.platform == '<STR_LIT:win32>':<EOL><INDENT>if not compiler_name:<EOL><INDENT>if msvc_exists():<EOL><INDENT>compiler_name = '<STR_LIT>'<EOL><DEDENT>elif gcc_exists():<EOL><INDENT>compiler_name = '<STR_LIT>'<EOL><DEDENT><DEDENT>elif compiler_name == '<STR_LIT>':<EOL><INDENT>compiler_name = '<STR_LIT>'<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if compiler_name == '<STR_LIT>':<EOL><INDENT>compiler_name = '<STR_LIT>'<EOL><DEDENT><DEDENT>return compiler_name<EOL>

Try and figure out which compiler is gonna be used on windows.
        On other platforms, it just returns whatever value it is given.

        converts 'gcc' to 'mingw32' on win32


if not compiler_name:<EOL><INDENT>compiler_name = '<STR_LIT>'<EOL><DEDENT>if sys.platform == '<STR_LIT:win32>':<EOL><INDENT>if not compiler_name:<EOL><INDENT>if msvc_exists():<EOL><INDENT>compiler_name = '<STR_LIT>'<EOL><DEDENT>elif gcc_exists():<EOL><INDENT>compiler_name = '<STR_LIT>'<EOL><DEDENT><DEDENT>elif compiler_name == '<STR_LIT>':<EOL><INDENT>compiler_name = '<STR_LIT>'<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if compiler_name == '<STR_LIT>':<EOL><INDENT>compiler_name = '<STR_LIT>'<EOL><DEDENT><DEDENT>return compiler_name<EOL>


def __init__(self, class_name="<STR_LIT>", pycobj=<NUM_LIT:0>, runtime_version=None):

self.class_name = class_name<EOL>self.pycobj = pycobj  <EOL>self.runtime_version = runtime_version<EOL>common_base_converter.__init__(self)<EOL>

Initializes the instance.

        Parameters
        ----------

        - class_name : `string`

          Name of class, this is set dynamically at build time by the
          `type_spec` method.

        - pycobj : `int`

          If `pycobj` is 0 then code is generated to deal with string
          representations of the SWIG wrapped pointer.  If it is 1,
          then code is generated to deal with a PyCObject.  If it is 2
          then code is generated to deal with a PySwigObject.

        - runtime_version : `int`

          Specifies the SWIG_RUNTIME_VERSION to use.  Defaults to
          `None`.  In this case the runtime is automatically
          determined.  This option is useful if you want to force the
          runtime_version to be a specific one and override the
          auto-detected one.


swig_typ = '<STR_LIT>'<EOL>if hasattr(value, '<STR_LIT>'):<EOL><INDENT>type_this = type(value.this)<EOL>type_str = str(type_this)<EOL>if isinstance(type_this, str):<EOL><INDENT>try:<EOL><INDENT>data = value.this.split('<STR_LIT:_>')<EOL>if data[<NUM_LIT:2>] == '<STR_LIT:p>':<EOL><INDENT>swig_typ = '<STR_LIT:str>'<EOL><DEDENT><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>elif type_str == "<STR_LIT>":<EOL><INDENT>swig_typ = '<STR_LIT>'<EOL><DEDENT>elif type_str.find('<STR_LIT>') > -<NUM_LIT:1>:<EOL><INDENT>swig_typ = '<STR_LIT>'<EOL><DEDENT><DEDENT>return swig_typ<EOL>

Given the object in the form of `value`, this method
        returns information on the SWIG internal object repesentation
        type.  Different versions of SWIG use different object
        representations.  This method provides information on the type
        of internal representation.

        Currently returns one of ['', 'str', 'pycobj', 'pyswig'].


if s is None:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>assert_(isinstance(s, str), msg="<STR_LIT>")<EOL>r = repr('<STR_LIT:">'+s)  <EOL>return '<STR_LIT:">'+r[<NUM_LIT:2>:-<NUM_LIT:1>]+'<STR_LIT:">'<EOL>

Hacky way to get legal C string from Python string


declare_return = '<STR_LIT>''<STR_LIT>''<STR_LIT>''<STR_LIT>'<EOL>py_objects = '<STR_LIT:U+002CU+0020>'.join(self.arg_specs.py_pointers())<EOL>if py_objects:<EOL><INDENT>declare_py_objects = '<STR_LIT>' + py_objects + '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>declare_py_objects = '<STR_LIT>'<EOL><DEDENT>py_vars = '<STR_LIT>'.join(self.arg_specs.py_variables())<EOL>if py_vars:<EOL><INDENT>init_values = py_vars + '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>init_values = '<STR_LIT>'<EOL><DEDENT>parse_tuple = '<STR_LIT>''<STR_LIT>''<STR_LIT>''<STR_LIT>'<EOL>return declare_return + declare_py_objects +init_values + parse_tuple<EOL>

Create code block for PyArg_ParseTuple.  Variable declarations
            for all PyObjects are done also.

            This code got a lot uglier when I added local_dict...


arg_strings = [arg.local_dict_code() for arg in self.arg_specs]<EOL>return "<STR_LIT>".join(arg_strings)<EOL>

Return the code to create the local dict as a string.


<EOL>global function_catalog<EOL>call_frame = sys._getframe().f_back<EOL>if local_dict is None:<EOL><INDENT>local_dict = call_frame.f_locals<EOL><DEDENT>if global_dict is None:<EOL><INDENT>global_dict = call_frame.f_globals<EOL><DEDENT>if force:<EOL><INDENT>module_dir = global_dict.get('<STR_LIT>',None)<EOL>func = compile_function(code,arg_names,local_dict,<EOL>global_dict,module_dir,<EOL>compiler=compiler,<EOL>verbose=verbose,<EOL>support_code=support_code,<EOL>headers=headers,<EOL>customize=customize,<EOL>type_converters=type_converters,<EOL>auto_downcast=auto_downcast,<EOL>**kw)<EOL>function_catalog.add_function(code,func,module_dir)<EOL>results = attempt_function_call(code,local_dict,global_dict)<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>results = apply(function_cache[code],(local_dict,global_dict))<EOL>return results<EOL><DEDENT>except TypeError as msg:<EOL><INDENT>msg = str(msg).strip()<EOL>if msg[:<NUM_LIT:16>] == "<STR_LIT>":<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>raise TypeError(msg)<EOL><DEDENT><DEDENT>except NameError as msg:<EOL><INDENT>msg = str(msg).strip()<EOL>if msg[:<NUM_LIT:16>] == "<STR_LIT>":<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>raise NameError(msg)<EOL><DEDENT><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>results = attempt_function_call(code,local_dict,global_dict)<EOL><DEDENT>except ValueError:<EOL><INDENT>module_dir = global_dict.get('<STR_LIT>',None)<EOL>func = compile_function(code,arg_names,local_dict,<EOL>global_dict,module_dir,<EOL>compiler=compiler,<EOL>verbose=verbose,<EOL>support_code=support_code,<EOL>headers=headers,<EOL>customize=customize,<EOL>type_converters=type_converters,<EOL>auto_downcast=auto_downcast,<EOL>**kw)<EOL>function_catalog.add_function(code,func,module_dir)<EOL>results = attempt_function_call(code,local_dict,global_dict)<EOL><DEDENT><DEDENT>return results<EOL>

Inline C/C++ code within Python scripts.

``inline()`` compiles and executes C/C++ code on the fly.  Variables
in the local and global Python scope are also available in the
C/C++ code.  Values are passed to the C/C++ code by assignment
much like variables passed are passed into a standard Python
function.  Values are returned from the C/C++ code through a
special argument called return_val.  Also, the contents of
mutable objects can be changed within the C/C++ code and the
changes remain after the C code exits and returns to Python.

inline has quite a few options as listed below.  Also, the keyword
arguments for distutils extension modules are accepted to
specify extra information needed for compiling.

Parameters
----------
code : string
    A string of valid C++ code.  It should not specify a return
    statement.  Instead it should assign results that need to be
    returned to Python in the `return_val`.
arg_names : [str], optional
    A list of Python variable names that should be transferred from
    Python into the C/C++ code.  It defaults to an empty string.
local_dict : dict, optional
    If specified, it is a dictionary of values that should be used as
    the local scope for the C/C++ code.  If local_dict is not
    specified the local dictionary of the calling function is used.
global_dict : dict, optional
    If specified, it is a dictionary of values that should be used as
    the global scope for the C/C++ code.  If `global_dict` is not
    specified, the global dictionary of the calling function is used.
force : {0, 1}, optional
    If 1, the C++ code is compiled every time inline is called.  This
    is really only useful for debugging, and probably only useful if
    your editing `support_code` a lot.
compiler : str, optional
    The name of compiler to use when compiling.  On windows, it
    understands 'msvc' and 'gcc' as well as all the compiler names
    understood by distutils.  On Unix, it'll only understand the
    values understood by distutils. (I should add 'gcc' though to
    this).

    On windows, the compiler defaults to the Microsoft C++ compiler.
    If this isn't available, it looks for mingw32 (the gcc compiler).

    On Unix, it'll probably use the same compiler that was used when
    compiling Python. Cygwin's behavior should be similar.
verbose : {0,1,2}, optional
    Specifies how much information is printed during the compile
    phase of inlining code.  0 is silent (except on windows with msvc
    where it still prints some garbage). 1 informs you when compiling
    starts, finishes, and how long it took.  2 prints out the command
    lines for the compilation process and can be useful if your having
    problems getting code to work.  Its handy for finding the name of
    the .cpp file if you need to examine it.  verbose has no effect if
    the compilation isn't necessary.
support_code : str, optional
    A string of valid C++ code declaring extra code that might be
    needed by your compiled function.  This could be declarations of
    functions, classes, or structures.
headers : [str], optional
    A list of strings specifying header files to use when compiling
    the code.  The list might look like ``["<vector>","'my_header'"]``.
    Note that the header strings need to be in a form than can be
    pasted at the end of a ``#include`` statement in the C++ code.
customize : base_info.custom_info, optional
    An alternative way to specify `support_code`, `headers`, etc. needed
    by the function.  See :mod:`scipy.weave.base_info` for more
    details. (not sure this'll be used much).
type_converters : [type converters], optional
    These guys are what convert Python data types to C/C++ data types.
    If you'd like to use a different set of type conversions than the
    default, specify them here. Look in the type conversions section
    of the main documentation for examples.
auto_downcast : {1,0}, optional
    This only affects functions that have numpy arrays as input
    variables.  Setting this to 1 will cause all floating point values
    to be cast as float instead of double if all the Numeric arrays
    are of type float.  If even one of the arrays has type double or
    double complex, all variables maintain their standard
    types.
newarr_converter : int, optional
    Unused.

Other Parameters
----------------
Relevant :mod:`distutils` keywords.  These are duplicated from Greg Ward's
:class:`distutils.extension.Extension` class for convenience:

sources : [string]
    List of source filenames, relative to the distribution root
    (where the setup script lives), in Unix form (slash-separated)
    for portability.  Source files may be C, C++, SWIG (.i),
    platform-specific resource files, or whatever else is recognized
    by the "build_ext" command as source for a Python extension.

    .. note:: The `module_path` file is always appended to the front of
       this list
include_dirs : [string]
    List of directories to search for C/C++ header files (in Unix
    form for portability).
define_macros : [(name : string, value : string|None)]
    List of macros to define; each macro is defined using a 2-tuple,
    where 'value' is either the string to define it to or None to
    define it without a particular value (equivalent of "#define
    FOO" in source or -DFOO on Unix C compiler command line).
undef_macros : [string]
    List of macros to undefine explicitly.
library_dirs : [string]
    List of directories to search for C/C++ libraries at link time.
libraries : [string]
    List of library names (not filenames or paths) to link against.
runtime_library_dirs : [string]
    List of directories to search for C/C++ libraries at run time
    (for shared extensions, this is when the extension is loaded).
extra_objects : [string]
    List of extra files to link with (e.g. object files not implied
    by 'sources', static libraries that must be explicitly specified,
    binary resource files, etc.)
extra_compile_args : [string]
    Any extra platform- and compiler-specific information to use
    when compiling the source files in 'sources'.  For platforms and
    compilers where "command line" makes sense, this is typically a
    list of command-line arguments, but for other platforms it could
    be anything.
extra_link_args : [string]
    Any extra platform- and compiler-specific information to use
    when linking object files together to create the extension (or
    to create a new static Python interpreter).  Similar
    interpretation as for 'extra_compile_args'.
export_symbols : [string]
    List of symbols to be exported from a shared extension.  Not
    used on all platforms, and not generally necessary for Python
    extensions, which typically export exactly one symbol: "init" +
    extension_name.
swig_opts : [string]
    Any extra options to pass to SWIG if a source file has the .i
    extension.
depends : [string]
    List of files that the extension depends on.
language : string
    Extension language (i.e. "c", "c++", "objc").  Will be detected
    from the source extensions if not provided.

See Also
--------
distutils.extension.Extension : Describes additional parameters.


arg_strings = [arg.declaration_code(inline=<NUM_LIT:1>)<EOL>for arg in self.arg_specs]<EOL>return "<STR_LIT>".join(arg_strings)<EOL>

Return the declaration code as a string.


import random<EOL>a = range(m)<EOL>d = {}<EOL>for i in range(m):<EOL><INDENT>key = random.choice(a)<EOL>a.remove(key)<EOL>d[key] = key<EOL><DEDENT>return d<EOL>


rows, cols, depth = <NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:4><EOL>arr = numpy.zeros((rows, cols, depth), '<STR_LIT:i>')<EOL>count = <NUM_LIT:0><EOL>for i in range(rows):<EOL><INDENT>for j in range(cols):<EOL><INDENT>for k in range(depth):<EOL><INDENT>arr[i,j,k] = count<EOL>count += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>return arr<EOL>

Creates a simple 3D numpy array with unique values at each
    location in the matrix.


code = """<STR_LIT>"""<EOL>weave.inline(code, ['<STR_LIT>'])<EOL>

Prints the given 3D array by accessing the raw numpy data and
    without using blitz converters.

    Notice the following:
      1. '\\n' to escape generating a newline in the C++ code.
      2. rows, cols = Narr[0], Narr[1].
      3. Array access using arr[(i*cols + j)*depth + k].


values = {}<EOL>for var,val in global_vars.items():<EOL><INDENT>if isinstance(val, ndarray):<EOL><INDENT>values[var] = dummy_array(val,name=var)<EOL><DEDENT>elif isnumeric(val):<EOL><INDENT>values[var] = val<EOL><DEDENT><DEDENT>for var,val in local_vars.items():<EOL><INDENT>if isinstance(val, ndarray):<EOL><INDENT>values[var] = dummy_array(val,name=var)<EOL><DEDENT>if isnumeric(val):<EOL><INDENT>values[var] = val<EOL><DEDENT><DEDENT>exec(expr,values)<EOL>try:<EOL><INDENT>exec(expr,values)<EOL><DEDENT>except:<EOL><INDENT>try:<EOL><INDENT>eval(expr,values)<EOL><DEDENT>except:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT><DEDENT>return <NUM_LIT:1><EOL>

Currently only checks expressions (not suites).
        Doesn't check that lhs = rhs. checked by compiled func though


x,y = make_same_length(xx,yy)<EOL>res = zeros(len(x))<EOL>for i in range(len(x)):<EOL><INDENT>if x[i] == y[i]:<EOL><INDENT>res[i] = x[i]<EOL><DEDENT>elif x[i] == <NUM_LIT:1>:<EOL><INDENT>res[i] = y[i]<EOL><DEDENT>elif y[i] == <NUM_LIT:1>:<EOL><INDENT>res[i] = x[i]<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>return res<EOL>

This returns the resulting size from operating on xx, and yy
        with a binary operator.  It accounts for broadcasting, and
        throws errors if the array sizes are incompatible.


try:<EOL><INDENT>return symbol.sym_name[i]<EOL><DEDENT>except KeyError:<EOL><INDENT>return token.tok_name[i]<EOL><DEDENT>

Convert numeric symbol or token to a desriptive name.


output = '<STR_LIT>'<EOL>for item in ast_seq:<EOL><INDENT>if isinstance(item, str):<EOL><INDENT>output = output + item<EOL><DEDENT>elif issequence(item):<EOL><INDENT>output = output + ast_to_string(item)<EOL><DEDENT><DEDENT>return output<EOL>

* Traverse an ast tree sequence, printing out all leaf nodes.

         This effectively rebuilds the expression the tree was built
         from.  I guess its probably missing whitespace.  How bout
         indent stuff and new lines?  Haven't checked this since we're
         currently only dealing with simple expressions.
    *


return self.module_dir<EOL>

Return the path used to replace the 'MODULE' in searches.


if isinstance(user_path_list, str):<EOL><INDENT>self.user_path_list = [user_path_list]<EOL><DEDENT>elif user_path_list:<EOL><INDENT>self.user_path_list = user_path_list<EOL><DEDENT>else:<EOL><INDENT>self.user_path_list = []<EOL><DEDENT>self.cache = {}<EOL>self.module_dir = None<EOL>self.paths_added = <NUM_LIT:0><EOL>sys.path.append(default_dir())<EOL>

Create a catalog for storing/searching for compiled functions.

            user_path_list contains directories that should be searched
            first for function catalogs.  They will come before the path
            entries in the PYTHONCOMPILED environment varilable.


matches = []<EOL>tmp_dir = tmp_dir or tempfile.gettempdir()<EOL>for tmp_file in os.listdir(tmp_dir):<EOL><INDENT>if tmp_file.startswith(prefix):<EOL><INDENT>matches.append(os.path.join(tmp_dir, tmp_file))<EOL><DEDENT><DEDENT>return matches<EOL>

Find temp dirs in 'tmp_dir' starting with 'prefix


if not os.path.isdir(dir):<EOL><INDENT>return False<EOL><DEDENT>prefix = '<STR_LIT>' % (socket.gethostname(),os.getpid())<EOL>try:<EOL><INDENT>tmp = tempfile.TemporaryFile(prefix=prefix,dir=dir)<EOL><DEDENT>except OSError:<EOL><INDENT>return False<EOL><DEDENT>tmp.close()<EOL>return True<EOL>

Determine whether a given directory is writable in a portable manner.

    Parameters
    ----------
    dir : str
        A string represeting a path to a directory on the filesystem.

    Returns
    -------
    res : bool
        True or False.


self.module_dir = None<EOL>

Reset 'MODULE' path to None so that it is ignored in searches.


sys.path = sys.path[self.paths_added:]<EOL>self.paths_added = <NUM_LIT:0><EOL>

Restores sys.path to normal after calls to configure_path()

            Remove the previously added paths from sys.path


try:<EOL><INDENT>os.makedirs(path, mode=<NUM_LIT>)<EOL><DEDENT>except OSError:<EOL><INDENT>pass<EOL><DEDENT>


return os.environ.get("<STR_LIT>") or os.environ.get("<STR_LIT>") or "<STR_LIT>"<EOL>


name = "<STR_LIT>" % tuple(sys.version_info[:<NUM_LIT:2>])<EOL>return name<EOL>

Name of intermediate dir for current python interpreter:
<temp dir>/<name>/pythonXY_intermediate/


return self.cache.get(code,[])<EOL>

Return list of functions for code from the cache.

            Return an empty list if the code entry is not found.


raise NotImplementedError<EOL>


raise NotImplementedError<EOL>

Pushes the value associated with co_names[namei] onto the stack.


raise NotImplementedError<EOL>

Pushes a try block from a try-except clause onto the block stack. delta points to the first except block.


raise NotImplementedError<EOL>

Stores TOS into the local co_varnames[var_num].


raise NotImplementedError<EOL>

Implements del name, where namei is the index into co_names attribute of the code object.


raise NotImplementedError<EOL>

Replaces TOS with getattr(TOS, co_names[namei].


raise NotImplementedError<EOL>

Loads the attribute co_names[namei] from the module found in TOS. The resulting object is pushed onto the stack, to be subsequently stored by a STORE_FAST instruction.


raise NotImplementedError<EOL>

Works as DELETE_NAME, but deletes a global name.


V = []<EOL>T = []<EOL>for i in range(count):<EOL><INDENT>v,t = self.pop()<EOL>V.append(v)<EOL>T.append(t)<EOL><DEDENT>V.reverse()<EOL>T.reverse()<EOL>self.pushTuple(tuple(V),tuple(T))<EOL>return<EOL>

Creates a tuple consuming count items from the stack, and pushes the resulting tuple onto the stack.


length = len(s)<EOL>i = <NUM_LIT:0><EOL>answer = []<EOL>while i < length:<EOL><INDENT>bytecode = ord(s[i])<EOL>name = byOpcode[bytecode]<EOL>if bytecode >= haveArgument:<EOL><INDENT>argument = <NUM_LIT>*ord(s[i+<NUM_LIT:2>])+ord(s[i+<NUM_LIT:1>])<EOL>i += <NUM_LIT:3><EOL><DEDENT>else:<EOL><INDENT>argument = None<EOL>i += <NUM_LIT:1><EOL><DEDENT>answer.append((bytecode,argument,name))<EOL><DEDENT>return answer<EOL>


raise NotImplementedError<EOL>

Prefixes any opcode which has an argument too big to fit into the default two bytes. ext holds two additional bytes which, taken together with the subsequent opcode's argument, comprise a four-byte argument, ext being the two most-significant bytes.


raise NotImplementedError<EOL>

Calls a function. argc is interpreted as in CALL_FUNCTION. The top element on the stack contains the variable argument list, followed by keyword and positional arguments.


raise NotImplementedError<EOL>

Implements del TOS.name, using namei as index into co_names.


file_changed = <NUM_LIT:1><EOL>if os.path.exists(module_file):<EOL><INDENT>f = open(module_file,'<STR_LIT:r>')<EOL>old_string = f.read()<EOL>f.close()<EOL>if old_string == module_string:<EOL><INDENT>file_changed = <NUM_LIT:0><EOL><DEDENT><DEDENT>if file_changed:<EOL><INDENT>f = open(module_file,'<STR_LIT:w>')<EOL>f.write(module_string)<EOL>f.close()<EOL><DEDENT>return module_file<EOL>

generate the source code file.  Only overwrite
        the existing file if the actual source has changed.


return [<NUM_LIT:1000>, <NUM_LIT:100>, <NUM_LIT:10>, <NUM_LIT:5>]<EOL>

Returns list of sample sizes to be used for comparison.


def expect(self, func=None, args=(), loc=<NUM_LIT:0>, scale=<NUM_LIT:1>, lb=None, ub=None,<EOL>conditional=False, **kwds):

lockwds = {'<STR_LIT>': loc,<EOL>'<STR_LIT>': scale}<EOL>self._argcheck(*args)<EOL>if func is None:<EOL><INDENT>def fun(x, *args):<EOL><INDENT>return x * self.pdf(x, *args, **lockwds)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>def fun(x, *args):<EOL><INDENT>return func(x) * self.pdf(x, *args, **lockwds)<EOL><DEDENT><DEDENT>if lb is None:<EOL><INDENT>lb = loc + self.a * scale<EOL><DEDENT>if ub is None:<EOL><INDENT>ub = loc + self.b * scale<EOL><DEDENT>if conditional:<EOL><INDENT>invfac = (self.sf(lb, *args, **lockwds)<EOL>- self.sf(ub, *args, **lockwds))<EOL><DEDENT>else:<EOL><INDENT>invfac = <NUM_LIT:1.0><EOL><DEDENT>kwds['<STR_LIT:args>'] = args<EOL>olderr = np.seterr(all='<STR_LIT:ignore>')<EOL>vals = integrate.quad(fun, lb, ub, **kwds)[<NUM_LIT:0>] / invfac<EOL>np.seterr(**olderr)<EOL>return vals<EOL>

Calculate expected value of a function with respect to the
        distribution.

        The expected value of a function ``f(x)`` with respect to a
        distribution ``dist`` is defined as::

                    ubound
            E[x] = Integral(f(x) * dist.pdf(x))
                    lbound

        Parameters
        ----------
        func : callable, optional
            Function for which integral is calculated. Takes only one argument.
            The default is the identity mapping f(x) = x.
        args : tuple, optional
            Argument (parameters) of the distribution.
        lb, ub : scalar, optional
            Lower and upper bound for integration. default is set to the
            support of the distribution.
        conditional : bool, optional
            If True, the integral is corrected by the conditional probability
            of the integration interval.  The return value is the expectation
            of the function, conditional on being in the given interval.
            Default is False.

        Additional keyword arguments are passed to the integration routine.

        Returns
        -------
        expect : float
            The calculated expected value.

        Notes
        -----
        The integration behavior of this function is inherited from
        `integrate.quad`.


def _construct_default_doc(self, longname=None, extradoc=None):

if longname is None:<EOL><INDENT>longname = '<STR_LIT:A>'<EOL><DEDENT>if extradoc is None:<EOL><INDENT>extradoc = '<STR_LIT>'<EOL><DEDENT>if extradoc.startswith('<STR_LIT>'):<EOL><INDENT>extradoc = extradoc[<NUM_LIT:2>:]<EOL><DEDENT>self.__doc__ = '<STR_LIT>'.join(['<STR_LIT>' % longname,<EOL>'<STR_LIT>', docheaders['<STR_LIT>'],<EOL>extradoc, '<STR_LIT>'])<EOL>self._construct_doc(docdict)<EOL>

Construct instance docstring from the default template.


Narg = len(args)<EOL>if Narg > self.numargs:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>start = [None]*<NUM_LIT:2><EOL>if (Narg < self.numargs) or not ('<STR_LIT>' in kwds and<EOL>'<STR_LIT>' in kwds):<EOL><INDENT>start = self._fitstart(data)<EOL>args += start[Narg:-<NUM_LIT:2>]<EOL><DEDENT>loc = kwds.get('<STR_LIT>', start[-<NUM_LIT:2>])<EOL>scale = kwds.get('<STR_LIT>', start[-<NUM_LIT:1>])<EOL>args += (loc, scale)<EOL>x0, func, restore, args = self._reduce_func(args, kwds)<EOL>optimizer = kwds.get('<STR_LIT>', optimize.fmin)<EOL>if not callable(optimizer) and isinstance(optimizer, string_types):<EOL><INDENT>if not optimizer.startswith('<STR_LIT>'):<EOL><INDENT>optimizer = "<STR_LIT>"+optimizer<EOL><DEDENT>if optimizer == '<STR_LIT>':<EOL><INDENT>optimizer = '<STR_LIT>'<EOL><DEDENT>try:<EOL><INDENT>optimizer = getattr(optimize, optimizer)<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise ValueError("<STR_LIT>" % optimizer)<EOL><DEDENT><DEDENT>vals = optimizer(func, x0, args=(ravel(data),), disp=<NUM_LIT:0>)<EOL>if restore is not None:<EOL><INDENT>vals = restore(args, vals)<EOL><DEDENT>vals = tuple(vals)<EOL>return vals<EOL>

Return MLEs for shape, location, and scale parameters from data.

MLE stands for Maximum Likelihood Estimate.  Starting estimates for
the fit are given by input arguments; for any arguments not provided
with starting estimates, ``self._fitstart(data)`` is called to generate
such.

One can hold some parameters fixed to specific values by passing in
keyword arguments ``f0``, ``f1``, ..., ``fn`` (for shape parameters)
and ``floc`` and ``fscale`` (for location and scale parameters,
respectively).

Parameters
----------
data : array_like
    Data to use in calculating the MLEs.
args : floats, optional
    Starting value(s) for any shape-characterizing arguments (those not
    provided will be determined by a call to ``_fitstart(data)``).
    No default value.
kwds : floats, optional
    Starting values for the location and scale parameters; no default.
    Special keyword arguments are recognized as holding certain
    parameters fixed:

    f0...fn : hold respective shape parameters fixed.

    floc : hold location parameter fixed to specified value.

    fscale : hold scale parameter fixed to specified value.

    optimizer : The optimizer to use.  The optimizer must take func,
                and starting position as the first two arguments,
                plus args (for extra arguments to pass to the
                function to be optimized) and disp=0 to suppress
                output as keyword arguments.

Returns
-------
shape, loc, scale : tuple of floats
    MLEs for any shape statistics, followed by those for location and
    scale.

Notes
-----
This fit is computed by maximizing a log-likelihood function, with
penalty applied for samples outside of range of the distribution. The
returned answer is not guaranteed to be the globally optimal MLE, it
may only be locally optimal, or the optimization may fail altogether.


args, loc, scale = self._parse_args(*args, **kwds)<EOL>x, loc, scale = map(asarray, (x, loc, scale))<EOL>args = tuple(map(asarray, args))<EOL>x = (x-loc)*<NUM_LIT:1.0>/scale<EOL>cond0 = self._argcheck(*args) & (scale > <NUM_LIT:0>)<EOL>cond1 = (scale > <NUM_LIT:0>) & (x > self.a) & (x < self.b)<EOL>cond2 = cond0 & (x <= self.a)<EOL>cond = cond0 & cond1<EOL>output = empty(shape(cond), '<STR_LIT:d>')<EOL>output.fill(NINF)<EOL>place(output, (<NUM_LIT:1>-cond0)+np.isnan(x), self.badvalue)<EOL>place(output, cond2, <NUM_LIT:0.0>)<EOL>if any(cond):<EOL><INDENT>goodargs = argsreduce(cond, *((x,)+args))<EOL>place(output, cond, self._logsf(*goodargs))<EOL><DEDENT>if output.ndim == <NUM_LIT:0>:<EOL><INDENT>return output[()]<EOL><DEDENT>return output<EOL>

Log of the survival function of the given RV.

Returns the log of the "survival function," defined as (1 - `cdf`),
evaluated at `x`.

Parameters
----------
x : array_like
    quantiles
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information)
loc : array_like, optional
    location parameter (default=0)
scale : array_like, optional
    scale parameter (default=1)

Returns
-------
logsf : ndarray
    Log of the survival function evaluated at `x`.


args, loc, _ = self._parse_args(*args, **kwds)<EOL>k, loc = map(asarray, (k, loc))<EOL>args = tuple(map(asarray, args))<EOL>k = asarray((k-loc))<EOL>cond0 = self._argcheck(*args)<EOL>cond1 = (k >= self.a) & (k < self.b)<EOL>cond2 = (k >= self.b)<EOL>cond = cond0 & cond1<EOL>output = empty(shape(cond), '<STR_LIT:d>')<EOL>output.fill(NINF)<EOL>place(output, (<NUM_LIT:1>-cond0) + np.isnan(k), self.badvalue)<EOL>place(output, cond2*(cond0 == cond0), <NUM_LIT:0.0>)<EOL>if any(cond):<EOL><INDENT>goodargs = argsreduce(cond, *((k,)+args))<EOL>place(output, cond, self._logcdf(*goodargs))<EOL><DEDENT>if output.ndim == <NUM_LIT:0>:<EOL><INDENT>return output[()]<EOL><DEDENT>return output<EOL>

Log of the cumulative distribution function at k of the given RV

Parameters
----------
k : array_like, int
    Quantiles.
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information).
loc : array_like, optional
    Location parameter (default=0).

Returns
-------
logcdf : array_like
    Log of the cumulative distribution function evaluated at k.


mu, mu2 = self.stats(*args, **{'<STR_LIT>': '<STR_LIT>'})<EOL>tmp = asarray(data)<EOL>muhat = tmp.mean()<EOL>mu2hat = tmp.var()<EOL>Shat = sqrt(mu2hat / mu2)<EOL>Lhat = muhat - Shat*mu<EOL>if not np.isfinite(Lhat):<EOL><INDENT>Lhat = <NUM_LIT:0><EOL><DEDENT>if not (np.isfinite(Shat) and (<NUM_LIT:0> < Shat)):<EOL><INDENT>Shat = <NUM_LIT:1><EOL><DEDENT>return Lhat, Shat<EOL>

Estimate loc and scale parameters from data using 1st and 2nd moments.

Parameters
----------
data : array_like
    Data to fit.
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information).

Returns
-------
Lhat : float
    Estimated location parameter for the data.
Shat : float
    Estimated scale parameter for the data.


newargs = np.atleast_1d(*args)<EOL>if not isinstance(newargs, list):<EOL><INDENT>newargs = [newargs, ]<EOL><DEDENT>expand_arr = (cond == cond)<EOL>return [np.extract(cond, arr1 * expand_arr) for arr1 in newargs]<EOL>

Return the sequence of ravel(args[i]) where ravel(condition) is
    True in 1D.

    Examples
    --------
    >>> import numpy as np
    >>> rand = np.random.random_sample
    >>> A = rand((4, 5))
    >>> B = 2
    >>> C = rand((1, 5))
    >>> cond = np.ones(A.shape)
    >>> [A1, B1, C1] = argsreduce(cond, A, B, C)
    >>> B1.shape
    (20,)
    >>> cond[2,:] = 0
    >>> [A2, B2, C2] = argsreduce(cond, A, B, C)
    >>> B2.shape
    (15,)


def _lazywhere(cond, arrays, f, fillvalue=None, f2=None):

if fillvalue is None:<EOL><INDENT>if f2 is None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>fillvalue = np.nan<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if f2 is not None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>arrays = np.broadcast_arrays(*arrays)<EOL>temp = tuple(np.extract(cond, arr) for arr in arrays)<EOL>out = valarray(shape(arrays[<NUM_LIT:0>]), value=fillvalue)<EOL>np.place(out, cond, f(*temp))<EOL>if f2 is not None:<EOL><INDENT>temp = tuple(np.extract(~cond, arr) for arr in arrays)<EOL>np.place(out, ~cond, f2(*temp))<EOL><DEDENT>return out<EOL>

np.where(cond, x, fillvalue) always evaluates x even where cond is False.
This one only evaluates f(arr1[cond], arr2[cond], ...).
For example,
>>> a, b = np.array([1, 2, 3, 4]), np.array([5, 6, 7, 8])
>>> def f(a, b):
    return a*b
>>> _lazywhere(a > 2, (a, b), f, np.nan)
array([ nan,  nan,  21.,  32.])

Notice it assumes that all `arrays` are of the same shape, or can be
broadcasted together.


args, loc, _ = self._parse_args(*args, **kwds)<EOL>q, loc = map(asarray, (q, loc))<EOL>args = tuple(map(asarray, args))<EOL>cond0 = self._argcheck(*args) & (loc == loc)<EOL>cond1 = (q > <NUM_LIT:0>) & (q < <NUM_LIT:1>)<EOL>cond2 = (q == <NUM_LIT:1>) & cond0<EOL>cond = cond0 & cond1<EOL>output = valarray(shape(cond), value=self.badvalue, typecode='<STR_LIT:d>')<EOL>place(output, (q == <NUM_LIT:0>)*(cond == cond), self.a-<NUM_LIT:1>)<EOL>place(output, cond2, self.b)<EOL>if any(cond):<EOL><INDENT>goodargs = argsreduce(cond, *((q,)+args+(loc,)))<EOL>loc, goodargs = goodargs[-<NUM_LIT:1>], goodargs[:-<NUM_LIT:1>]<EOL>place(output, cond, self._ppf(*goodargs) + loc)<EOL><DEDENT>if output.ndim == <NUM_LIT:0>:<EOL><INDENT>return output[()]<EOL><DEDENT>return output<EOL>

Percent point function (inverse of cdf) at q of the given RV

Parameters
----------
q : array_like
    Lower tail probability.
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information).
loc : array_like, optional
    Location parameter (default=0).
scale : array_like, optional
    Scale parameter (default=1).

Returns
-------
k : array_like
    Quantile corresponding to the lower tail probability, q.


kwds['<STR_LIT>'] = '<STR_LIT:v>'<EOL>res = self.stats(*args, **kwds)<EOL>if isinstance(res, ndarray) and res.ndim == <NUM_LIT:0>:<EOL><INDENT>return res[()]<EOL><DEDENT>return res<EOL>

Variance of the distribution

Parameters
----------
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information)
loc : array_like, optional
    location parameter (default=0)
scale : array_like, optional
    scale parameter (default=1)

Returns
-------
var : float
    the variance of the distribution


cond = <NUM_LIT:1><EOL>for arg in args:<EOL><INDENT>cond = logical_and(cond, (asarray(arg) > <NUM_LIT:0>))<EOL><DEDENT>return cond<EOL>

Default check for correct values on args and keywords.

        Returns condition array of 1's where arguments are correct and
         0's where they are not.


def _construct_argparser(<EOL>self, meths_to_inspect, locscale_in, locscale_out):

if self.shapes:<EOL><INDENT>if not isinstance(self.shapes, string_types):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>shapes = self.shapes.replace('<STR_LIT:U+002C>', '<STR_LIT:U+0020>').split()<EOL>for field in shapes:<EOL><INDENT>if keyword.iskeyword(field):<EOL><INDENT>raise SyntaxError('<STR_LIT>')<EOL><DEDENT>if not re.match('<STR_LIT>', field):<EOL><INDENT>raise SyntaxError(<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>shapes_list = []<EOL>for meth in meths_to_inspect:<EOL><INDENT>shapes_args = inspect.getargspec(meth)<EOL>shapes_list.append(shapes_args.args)<EOL>if len(shapes_args.args) > <NUM_LIT:2>:<EOL><INDENT>if shapes_args.varargs is not None:<EOL><INDENT>raise TypeError(<EOL>'<STR_LIT>')<EOL><DEDENT>if shapes_args.keywords is not None:<EOL><INDENT>raise TypeError(<EOL>'<STR_LIT>')<EOL><DEDENT>if shapes_args.defaults is not None:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>shapes = max(shapes_list, key=lambda x: len(x))<EOL>shapes = shapes[<NUM_LIT:2>:]  <EOL>for item in shapes_list:<EOL><INDENT>if len(item) > <NUM_LIT:2> and item[<NUM_LIT:2>:] != shapes:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>shapes_str = '<STR_LIT:U+002CU+0020>'.join(shapes) + '<STR_LIT:U+002CU+0020>' if shapes else '<STR_LIT>'  <EOL>dct = dict(shape_arg_str=shapes_str,<EOL>locscale_in=locscale_in,<EOL>locscale_out=locscale_out,<EOL>)<EOL>ns = {}<EOL>exec_(parse_arg_template % dct, ns)<EOL>for name in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>setattr(self, name,<EOL>instancemethod(ns[name], self, self.__class__)<EOL>)<EOL><DEDENT>self.shapes = '<STR_LIT:U+002CU+0020>'.join(shapes) if shapes else None<EOL>if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>self.numargs = len(shapes)<EOL><DEDENT>

Construct the parser for the shape arguments.

        Generates the argument-parsing functions dynamically and attaches
        them to the instance.
        Is supposed to be called in __init__ of a class for each distribution.

        If self.shapes is a non-empty string, interprets it as a
        comma-separated list of shape parameters.

        Otherwise inspects the call signatures of `meths_to_inspect`
        and constructs the argument-parsing functions from these.
        In this case also sets `shapes` and `numargs`.


if extradoc is None:<EOL><INDENT>extradoc = '<STR_LIT>'<EOL><DEDENT>if extradoc.startswith('<STR_LIT>'):<EOL><INDENT>extradoc = extradoc[<NUM_LIT:2>:]<EOL><DEDENT>self.__doc__ = '<STR_LIT>'.join(['<STR_LIT>' % longname,<EOL>'<STR_LIT>', docheaders['<STR_LIT>'],<EOL>extradoc, '<STR_LIT>'])<EOL>self._construct_doc(docdict_discrete)<EOL>

Construct instance docstring from the rv_discrete template.


def _construct_doc(self, docdict, shapes_vals=None):

tempdict = docdict.copy()<EOL>tempdict['<STR_LIT:name>'] = self.name or '<STR_LIT>'<EOL>tempdict['<STR_LIT>'] = self.shapes or '<STR_LIT>'<EOL>if shapes_vals is None:<EOL><INDENT>shapes_vals = ()<EOL><DEDENT>vals = '<STR_LIT:U+002CU+0020>'.join(str(_) for _ in shapes_vals)<EOL>tempdict['<STR_LIT>'] = vals<EOL>if self.shapes:<EOL><INDENT>tempdict['<STR_LIT>'] = '<STR_LIT>' % (self.shapes, vals)<EOL><DEDENT>else:<EOL><INDENT>tempdict['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>if self.shapes is None:<EOL><INDENT>for item in ['<STR_LIT>', '<STR_LIT:default>', '<STR_LIT>']:<EOL><INDENT>tempdict[item] = tempdict[item].replace(<EOL>"<STR_LIT>", "<STR_LIT>")<EOL><DEDENT><DEDENT>for i in range(<NUM_LIT:2>):<EOL><INDENT>if self.shapes is None:<EOL><INDENT>self.__doc__ = self.__doc__.replace("<STR_LIT>", "<STR_LIT>")<EOL><DEDENT>self.__doc__ = doccer.docformat(self.__doc__, tempdict)<EOL><DEDENT>self.__doc__ = self.__doc__.replace('<STR_LIT>', '<STR_LIT:(>').replace('<STR_LIT>', '<STR_LIT:)>')<EOL>

Construct the instance docstring with string substitutions.


pk = asarray(pk)<EOL>pk = <NUM_LIT:1.0>*pk / sum(pk, axis=<NUM_LIT:0>)<EOL>if qk is None:<EOL><INDENT>vec = entr(pk)<EOL><DEDENT>else:<EOL><INDENT>qk = asarray(qk)<EOL>if len(qk) != len(pk):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>qk = <NUM_LIT:1.0>*qk / sum(qk, axis=<NUM_LIT:0>)<EOL>vec = kl_div(pk, qk)<EOL><DEDENT>S = sum(vec, axis=<NUM_LIT:0>)<EOL>if base is not None:<EOL><INDENT>S /= log(base)<EOL><DEDENT>return S<EOL>

Calculate the entropy of a distribution for given probability values.

    If only probabilities `pk` are given, the entropy is calculated as
    ``S = -sum(pk * log(pk), axis=0)``.

    If `qk` is not None, then compute the Kullback-Leibler divergence
    ``S = sum(pk * log(pk / qk), axis=0)``.

    This routine will normalize `pk` and `qk` if they don't sum to 1.

    Parameters
    ----------
    pk : sequence
        Defines the (discrete) distribution. ``pk[i]`` is the (possibly
        unnormalized) probability of event ``i``.
    qk : sequence, optional
        Sequence against which the relative entropy is computed. Should be in
        the same format as `pk`.
    base : float, optional
        The logarithmic base to use, defaults to ``e`` (natural logarithm).

    Returns
    -------
    S : float
        The calculated entropy.


args, loc, _ = self._parse_args(*args, **kwds)<EOL>k, loc = map(asarray, (k, loc))<EOL>args = tuple(map(asarray, args))<EOL>k = asarray(k-loc)<EOL>cond0 = self._argcheck(*args)<EOL>cond1 = (k >= self.a) & (k <= self.b)<EOL>cond2 = (k < self.a) & cond0<EOL>cond = cond0 & cond1<EOL>output = zeros(shape(cond), '<STR_LIT:d>')<EOL>place(output, (<NUM_LIT:1>-cond0) + np.isnan(k), self.badvalue)<EOL>place(output, cond2, <NUM_LIT:1.0>)<EOL>if any(cond):<EOL><INDENT>goodargs = argsreduce(cond, *((k,)+args))<EOL>place(output, cond, np.clip(self._sf(*goodargs), <NUM_LIT:0>, <NUM_LIT:1>))<EOL><DEDENT>if output.ndim == <NUM_LIT:0>:<EOL><INDENT>return output[()]<EOL><DEDENT>return output<EOL>

Survival function (1-cdf) at k of the given RV.

Parameters
----------
k : array_like
    Quantiles.
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information).
loc : array_like, optional
    Location parameter (default=0).

Returns
-------
sf : array_like
    Survival function evaluated at k.


@np.deprecate<EOL><INDENT>def est_loc_scale(self, data, *args):<DEDENT>

return self.fit_loc_scale(data, *args)<EOL>

This function is deprecated, use self.fit_loc_scale(data) instead.


args, loc, _ = self._parse_args(*args, **kwds)<EOL>k, loc = map(asarray, (k, loc))<EOL>args = tuple(map(asarray, args))<EOL>k = asarray((k-loc))<EOL>cond0 = self._argcheck(*args)<EOL>cond1 = (k >= self.a) & (k <= self.b) & self._nonzero(k, *args)<EOL>cond = cond0 & cond1<EOL>output = empty(shape(cond), '<STR_LIT:d>')<EOL>output.fill(NINF)<EOL>place(output, (<NUM_LIT:1>-cond0) + np.isnan(k), self.badvalue)<EOL>if any(cond):<EOL><INDENT>goodargs = argsreduce(cond, *((k,)+args))<EOL>place(output, cond, self._logpmf(*goodargs))<EOL><DEDENT>if output.ndim == <NUM_LIT:0>:<EOL><INDENT>return output[()]<EOL><DEDENT>return output<EOL>

Log of the probability mass function at k of the given RV.

Parameters
----------
k : array_like
    Quantiles.
arg1, arg2, arg3,... : array_like
    The shape parameter(s) for the distribution (see docstring of the
    instance object for more information).
loc : array_like, optional
    Location parameter. Default is 0.

Returns
-------
logpmf : array_like
    Log of the probability mass function evaluated at k.


alpha = _dirichlet_check_parameters(alpha)<EOL>out = alpha / (np.sum(alpha))<EOL>return _squeeze_output(out)<EOL>

Compute the mean of the dirichlet distribution.

Parameters
----------
%(_dirichlet_doc_default_callparams)s

Returns
-------
mu : scalar
    Mean of the Dirichlet distribution


x = np.asarray(x, dtype=float)<EOL>if x.ndim == <NUM_LIT:0>:<EOL><INDENT>x = x[np.newaxis]<EOL><DEDENT>elif x.ndim == <NUM_LIT:1>:<EOL><INDENT>if dim == <NUM_LIT:1>:<EOL><INDENT>x = x[:, np.newaxis]<EOL><DEDENT>else:<EOL><INDENT>x = x[np.newaxis, :]<EOL><DEDENT><DEDENT>return x<EOL>

Adjust quantiles array so that last axis labels the components of
each data point.


return np.sum(gammaln(alpha)) - gammaln(np.sum(alpha))<EOL>

r"""
    Internal helper function to compute the log of the useful quotient

    .. math::
        B(\alpha) = \frac{\prod_{i=1}{K}\Gamma(\alpha_i)}{\Gamma\left(\sum_{i=1}^{K}\alpha_i\right)}

    Parameters
    ----------
    %(_dirichlet_doc_default_callparams)s

    Returns
    -------
    B : scalar
        Helper quotient, internal use only


alpha = _dirichlet_check_parameters(alpha)<EOL>return np.random.dirichlet(alpha, size=size)<EOL>

Draw random samples from a Dirichlet distribution.

Parameters
----------
%(_dirichlet_doc_default_callparams)s
size : integer, optional
    Number of samples to draw (default 1).

Returns
-------
rvs : ndarray or scalar
    Random variates of size (`size`, `N`), where `N` is the
    dimension of the random variable.


def _logpdf(self, x, mean, prec_U, log_det_cov, rank):

dev = x - mean<EOL>maha = np.sum(np.square(np.dot(dev, prec_U)), axis=-<NUM_LIT:1>)<EOL>return -<NUM_LIT:0.5> * (rank * _LOG_2PI + log_det_cov + maha)<EOL>

Parameters
----------
x : ndarray
    Points at which to evaluate the log of the probability
    density function
mean : ndarray
    Mean of the distribution
prec_U : ndarray
    A decomposition such that np.dot(prec_U, prec_U.T)
    is the precision matrix, i.e. inverse of the covariance matrix.
log_det_cov : float
    Logarithm of the determinant of the covariance matrix
rank : int
    Rank of the covariance matrix.

Notes
-----
As this function does no argument checking, it should not be
called directly; use 'logpdf' instead.


def rvs(self, mean=None, cov=<NUM_LIT:1>, size=<NUM_LIT:1>):

dim, mean, cov = _process_parameters(None, mean, cov)<EOL>out = np.random.multivariate_normal(mean, cov, size)<EOL>return _squeeze_output(out)<EOL>

Draw random samples from a multivariate normal distribution.

Parameters
----------
%(_doc_default_callparams)s
size : integer, optional
    Number of samples to draw (default 1).

Notes
-----
%(_doc_callparams_note)s

Returns
-------
rvs : ndarray or scalar
    Random variates of size (`size`, `N`), where `N` is the
    dimension of the random variable.


x = ravel(data)<EOL>n = len(x)<EOL>if (n < <NUM_LIT:2>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>xbar = x.mean()<EOL>C = x.var()<EOL>if (n > <NUM_LIT:1000>):  <EOL><INDENT>mdist = distributions.norm(loc=xbar, scale=math.sqrt(C/n))<EOL>sdist = distributions.norm(loc=math.sqrt(C), scale=math.sqrt(C/(<NUM_LIT>*n)))<EOL>vdist = distributions.norm(loc=C, scale=math.sqrt(<NUM_LIT>/n)*C)<EOL><DEDENT>else:<EOL><INDENT>nm1 = n-<NUM_LIT:1><EOL>fac = n*C/<NUM_LIT><EOL>val = nm1/<NUM_LIT><EOL>mdist = distributions.t(nm1,loc=xbar,scale=math.sqrt(C/nm1))<EOL>sdist = distributions.gengamma(val,-<NUM_LIT:2>,scale=math.sqrt(fac))<EOL>vdist = distributions.invgamma(val,scale=fac)<EOL><DEDENT>return mdist, vdist, sdist<EOL>

'Frozen' distributions for mean, variance, and standard deviation of data.

Parameters
----------
data : array_like
    Input array. Converted to 1-D using ravel.
    Requires 2 or more data-points.

Returns
-------
mdist : "frozen" distribution object
    Distribution object representing the mean of the data
vdist : "frozen" distribution object
    Distribution object representing the variance of the data
sdist : "frozen" distribution object
    Distribution object representing the standard deviation of the data

Notes
-----
The return values from bayes_mvs(data) is equivalent to
``tuple((x.mean(), x.interval(0.90)) for x in mvsdist(data))``.

In other words, calling ``<dist>.mean()`` and ``<dist>.interval(0.90)``
on the three distribution objects returned from this function will give
the same results that are returned from `bayes_mvs`.

Examples
--------
>>> from scipy.stats import mvsdist
>>> data = [6, 9, 12, 7, 8, 8, 13]
>>> mean, var, std = mvsdist(data)

We now have frozen distribution objects "mean", "var" and "std" that we can
examine:

>>> mean.mean()
9.0
>>> mean.interval(0.95)
(6.6120585482655692, 11.387941451734431)
>>> mean.std()
1.1952286093343936


def ppcc_max(x, brack=(<NUM_LIT:0.0>,<NUM_LIT:1.0>), dist='<STR_LIT>'):

dist = _parse_dist_kw(dist)<EOL>osm_uniform = _calc_uniform_order_statistic_medians(x)<EOL>osr = sort(x)<EOL>def tempfunc(shape, mi, yvals, func):<EOL><INDENT>xvals = func(mi, shape)<EOL>r, prob = stats.pearsonr(xvals, yvals)<EOL>return <NUM_LIT:1>-r<EOL><DEDENT>return optimize.brent(tempfunc, brack=brack, args=(osm_uniform, osr, dist.ppf))<EOL>

Returns the shape parameter that maximizes the probability plot
    correlation coefficient for the given data to a one-parameter
    family of distributions.

    See also ppcc_plot


def wilcoxon(x, y=None, zero_method="<STR_LIT>", correction=False):

if zero_method not in ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if y is None:<EOL><INDENT>d = x<EOL><DEDENT>else:<EOL><INDENT>x, y = map(asarray, (x, y))<EOL>if len(x) != len(y):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>d = x-y<EOL><DEDENT>if zero_method == "<STR_LIT>":<EOL><INDENT>d = compress(not_equal(d, <NUM_LIT:0>), d, axis=-<NUM_LIT:1>)  <EOL><DEDENT>count = len(d)<EOL>if (count < <NUM_LIT:10>):<EOL><INDENT>warnings.warn("<STR_LIT>")<EOL><DEDENT>r = stats.rankdata(abs(d))<EOL>r_plus = sum((d > <NUM_LIT:0>) * r, axis=<NUM_LIT:0>)<EOL>r_minus = sum((d < <NUM_LIT:0>) * r, axis=<NUM_LIT:0>)<EOL>if zero_method == "<STR_LIT>":<EOL><INDENT>r_zero = sum((d == <NUM_LIT:0>) * r, axis=<NUM_LIT:0>)<EOL>r_plus += r_zero / <NUM_LIT><EOL>r_minus += r_zero / <NUM_LIT><EOL><DEDENT>T = min(r_plus, r_minus)<EOL>mn = count*(count + <NUM_LIT:1.>) * <NUM_LIT><EOL>se = count*(count + <NUM_LIT:1.>) * (<NUM_LIT> * count + <NUM_LIT:1.>)<EOL>if zero_method == "<STR_LIT>":<EOL><INDENT>r = r[d != <NUM_LIT:0>]<EOL><DEDENT>replist, repnum = find_repeats(r)<EOL>if repnum.size != <NUM_LIT:0>:<EOL><INDENT>se -= <NUM_LIT:0.5> * (repnum * (repnum * repnum - <NUM_LIT:1>)).sum()<EOL><DEDENT>se = sqrt(se / <NUM_LIT>)<EOL>correction = <NUM_LIT:0.5> * int(bool(correction)) * np.sign(T - mn)<EOL>z = (T - mn - correction) / se<EOL>prob = <NUM_LIT> * distributions.norm.sf(abs(z))<EOL>return T, prob<EOL>

Calculate the Wilcoxon signed-rank test.

The Wilcoxon signed-rank test tests the null hypothesis that two
related paired samples come from the same distribution. In particular,
it tests whether the distribution of the differences x - y is symmetric
about zero. It is a non-parametric version of the paired T-test.

Parameters
----------
x : array_like
    The first set of measurements.
y : array_like, optional
    The second set of measurements.  If `y` is not given, then the `x`
    array is considered to be the differences between the two sets of
    measurements.
zero_method : string, {"pratt", "wilcox", "zsplit"}, optional
    "pratt":
        Pratt treatment: includes zero-differences in the ranking process
        (more conservative)
    "wilcox":
        Wilcox treatment: discards all zero-differences
    "zsplit":
        Zero rank split: just like Pratt, but spliting the zero rank
        between positive and negative ones
correction : bool, optional
    If True, apply continuity correction by adjusting the Wilcoxon rank
    statistic by 0.5 towards the mean value when computing the
    z-statistic.  Default is False.

Returns
-------
T : float
    The sum of the ranks of the differences above or below zero, whichever
    is smaller.
p-value : float
    The two-sided p-value for the test.

Notes
-----
Because the normal approximation is used for the calculations, the
samples used should be large.  A typical rule is to require that
n > 20.

References
----------
.. [1] http://en.wikipedia.org/wiki/Wilcoxon_signed-rank_test


def _anderson_ksamp_right(samples, Z, Zstar, k, n, N):

A2kN = <NUM_LIT:0.><EOL>lj = Z.searchsorted(Zstar[:-<NUM_LIT:1>], '<STR_LIT:right>') - Z.searchsorted(Zstar[:-<NUM_LIT:1>],<EOL>'<STR_LIT:left>')<EOL>Bj = lj.cumsum()<EOL>for i in arange(<NUM_LIT:0>, k):<EOL><INDENT>s = np.sort(samples[i])<EOL>Mij = s.searchsorted(Zstar[:-<NUM_LIT:1>], side='<STR_LIT:right>')<EOL>inner = lj / float(N) * (N * Mij - Bj * n[i])**<NUM_LIT:2> / (Bj * (N - Bj))<EOL>A2kN += inner.sum() / n[i]<EOL><DEDENT>return A2kN<EOL>

Compute A2akN equation 6 of Scholz & Stephens.

Parameters
----------
samples : sequence of 1-D array_like
    Array of sample arrays.
Z : array_like
    Sorted array of all observations.
Zstar : array_like
    Sorted array of unique observations.
k : int
    Number of samples.
n : array_like
    Number of observations in each sample.
N : int
    Total number of observations.

Returns
-------
A2KN : float
    The A2KN statistics of Scholz and Stephens 1987.


def circvar(samples, high=<NUM_LIT:2>*pi, low=<NUM_LIT:0>, axis=None):

samples, ang = _circfuncs_common(samples, high, low)<EOL>res = np.mean(exp(<NUM_LIT>*ang), axis=axis)<EOL>R = abs(res)<EOL>return ((high-low)/<NUM_LIT>/pi)**<NUM_LIT:2> * <NUM_LIT:2> * log(<NUM_LIT:1>/R)<EOL>

Compute the circular variance for samples assumed to be in a range

Parameters
----------
samples : array_like
    Input array.
low : float or int, optional
    Low boundary for circular variance range.  Default is 0.
high : float or int, optional
    High boundary for circular variance range.  Default is ``2*pi``.
axis : int, optional
    Axis along which variances are computed.  The default is to compute
    the variance of the flattened array.

Returns
-------
circvar : float
    Circular variance.

Notes
-----
This uses a definition of circular variance that in the limit of small
angles returns a number close to the 'linear' variance.


k = len(args)<EOL>if k < <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>Ni = zeros(k)<EOL>ssq = zeros(k,'<STR_LIT:d>')<EOL>for j in range(k):<EOL><INDENT>Ni[j] = len(args[j])<EOL>ssq[j] = np.var(args[j], ddof=<NUM_LIT:1>)<EOL><DEDENT>Ntot = sum(Ni,axis=<NUM_LIT:0>)<EOL>spsq = sum((Ni-<NUM_LIT:1>)*ssq,axis=<NUM_LIT:0>)/(<NUM_LIT:1.0>*(Ntot-k))<EOL>numer = (Ntot*<NUM_LIT:1.0>-k)*log(spsq) - sum((Ni-<NUM_LIT:1.0>)*log(ssq),axis=<NUM_LIT:0>)<EOL>denom = <NUM_LIT:1.0> + (<NUM_LIT:1.0>/(<NUM_LIT:3>*(k-<NUM_LIT:1>)))*((sum(<NUM_LIT:1.0>/(Ni-<NUM_LIT:1.0>),axis=<NUM_LIT:0>))-<NUM_LIT:1.0>/(Ntot-k))<EOL>T = numer / denom<EOL>pval = distributions.chi2.sf(T,k-<NUM_LIT:1>)  <EOL>return T, pval<EOL>

Perform Bartlett's test for equal variances

Bartlett's test tests the null hypothesis that all input samples
are from populations with equal variances.  For samples
from significantly non-normal populations, Levene's test
`levene` is more robust.

Parameters
----------
sample1, sample2,... : array_like
    arrays of sample data.  May be different lengths.

Returns
-------
T : float
    The test statistic.
p-value : float
    The p-value of the test.

References
----------
.. [1]  http://www.itl.nist.gov/div898/handbook/eda/section3/eda357.htm

.. [2]  Snedecor, George W. and Cochran, William G. (1989), Statistical
          Methods, Eighth Edition, Iowa State University Press.


if self.d != <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>stdev = ravel(sqrt(self.covariance))[<NUM_LIT:0>]<EOL>normalized_low = ravel((low - self.dataset) / stdev)<EOL>normalized_high = ravel((high - self.dataset) / stdev)<EOL>value = np.mean(special.ndtr(normalized_high) -<EOL>special.ndtr(normalized_low))<EOL>return value<EOL>

Computes the integral of a 1D pdf between two bounds.

Parameters
----------
low : scalar
    Lower bound of integration.
high : scalar
    Upper bound of integration.

Returns
-------
value : scalar
    The result of the integral.

Raises
------
ValueError
    If the KDE is over more than one dimension.


if bw_method is None:<EOL><INDENT>pass<EOL><DEDENT>elif bw_method == '<STR_LIT>':<EOL><INDENT>self.covariance_factor = self.scotts_factor<EOL><DEDENT>elif bw_method == '<STR_LIT>':<EOL><INDENT>self.covariance_factor = self.silverman_factor<EOL><DEDENT>elif np.isscalar(bw_method) and not isinstance(bw_method, string_types):<EOL><INDENT>self._bw_method = '<STR_LIT>'<EOL>self.covariance_factor = lambda: bw_method<EOL><DEDENT>elif callable(bw_method):<EOL><INDENT>self._bw_method = bw_method<EOL>self.covariance_factor = lambda: self._bw_method(self)<EOL><DEDENT>else:<EOL><INDENT>msg = "<STR_LIT>""<STR_LIT>"<EOL>raise ValueError(msg)<EOL><DEDENT>self._compute_covariance()<EOL>

Compute the estimator bandwidth with given method.

        The new bandwidth calculated after a call to `set_bandwidth` is used
        for subsequent evaluations of the estimated density.

        Parameters
        ----------
        bw_method : str, scalar or callable, optional
            The method used to calculate the estimator bandwidth.  This can be
            'scott', 'silverman', a scalar constant or a callable.  If a
            scalar, this will be used directly as `kde.factor`.  If a callable,
            it should take a `gaussian_kde` instance as only parameter and
            return a scalar.  If None (default), nothing happens; the current
            `kde.covariance_factor` method is kept.

        Notes
        -----
        .. versionadded:: 0.11

        Examples
        --------
        >>> x1 = np.array([-7, -5, 1, 4, 5.])
        >>> kde = stats.gaussian_kde(x1)
        >>> xs = np.linspace(-10, 10, num=50)
        >>> y1 = kde(xs)
        >>> kde.set_bandwidth(bw_method='silverman')
        >>> y2 = kde(xs)
        >>> kde.set_bandwidth(bw_method=kde.factor / 3.)
        >>> y3 = kde(xs)

        >>> fig = plt.figure()
        >>> ax = fig.add_subplot(111)
        >>> ax.plot(x1, np.ones(x1.shape) / (4. * x1.size), 'bo',
        ...         label='Data points (rescaled)')
        >>> ax.plot(xs, y1, label='Scott (default)')
        >>> ax.plot(xs, y2, label='Silverman')
        >>> ax.plot(xs, y3, label='Const (1/3 * Silverman)')
        >>> ax.legend()
        >>> plt.show()


if other.d != self.d:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if other.n < self.n:<EOL><INDENT>small = other<EOL>large = self<EOL><DEDENT>else:<EOL><INDENT>small = self<EOL>large = other<EOL><DEDENT>sum_cov = small.covariance + large.covariance<EOL>sum_cov_chol = linalg.cho_factor(sum_cov)<EOL>result = <NUM_LIT:0.0><EOL>for i in range(small.n):<EOL><INDENT>mean = small.dataset[:, i, newaxis]<EOL>diff = large.dataset - mean<EOL>tdiff = linalg.cho_solve(sum_cov_chol, diff)<EOL>energies = sum(diff * tdiff, axis=<NUM_LIT:0>) / <NUM_LIT><EOL>result += sum(exp(-energies), axis=<NUM_LIT:0>)<EOL><DEDENT>result /= sqrt(linalg.det(<NUM_LIT:2> * pi * sum_cov)) * large.n * small.n<EOL>return result<EOL>

Computes the integral of the product of this  kernel density estimate
with another.

Parameters
----------
other : gaussian_kde instance
    The other kde.

Returns
-------
value : scalar
    The result of the integral.

Raises
------
ValueError
    If the KDEs have different dimensionality.


if size is None:<EOL><INDENT>size = self.n<EOL><DEDENT>norm = transpose(multivariate_normal(zeros((self.d,), float),<EOL>self.covariance, size=size))<EOL>indices = randint(<NUM_LIT:0>, self.n, size=size)<EOL>means = self.dataset[:, indices]<EOL>return means + norm<EOL>

Randomly sample a dataset from the estimated pdf.

Parameters
----------
size : int, optional
    The number of samples to draw.  If not provided, then the size is
    the same as the underlying dataset.

Returns
-------
resample : (self.d, `size`) ndarray
    The sampled dataset.


def f_value_multivariate(ER, EF, dfnum, dfden):

if isinstance(ER, (int, float)):<EOL><INDENT>ER = array([[ER]])<EOL><DEDENT>if isinstance(EF, (int, float)):<EOL><INDENT>EF = array([[EF]])<EOL><DEDENT>n_um = (linalg.det(ER) - linalg.det(EF)) / float(dfnum)<EOL>d_en = linalg.det(EF) / float(dfden)<EOL>return n_um / d_en<EOL>

Returns a multivariate F-statistic.

Parameters
----------
ER : ndarray
    Error associated with the null hypothesis (the Restricted model).
    From a multivariate F calculation.
EF : ndarray
    Error associated with the alternate hypothesis (the Full model)
    From a multivariate F calculation.
dfnum : int
    Degrees of freedom the Restricted model.
dfden : int
    Degrees of freedom associated with the Restricted model.

Returns
-------
fstat : float
    The computed F-statistic.


items, inv = np.unique(a, return_inverse=True)<EOL>freq = np.bincount(inv)<EOL>return np.array([items, freq]).T<EOL>

Returns a 2-D array of item frequencies.

Parameters
----------
a : (N,) array_like
    Input array.

Returns
-------
itemfreq : (K, 2) ndarray
    A 2-D frequency table.  Column 1 contains sorted, unique values from
    `a`, column 2 contains their respective counts.

Examples
--------
>>> a = np.array([1, 1, 5, 0, 1, 2, 2, 0, 1, 4])
>>> stats.itemfreq(a)
array([[ 0.,  2.],
       [ 1.,  4.],
       [ 2.,  2.],
       [ 4.,  1.],
       [ 5.,  1.]])
>>> np.bincount(a)
array([2, 4, 2, 0, 1, 1])

>>> stats.itemfreq(a/10.)
array([[ 0. ,  2. ],
       [ 0.1,  4. ],
       [ 0.2,  2. ],
       [ 0.4,  1. ],
       [ 0.5,  1. ]])


def zmap(scores, compare, axis=<NUM_LIT:0>, ddof=<NUM_LIT:0>):

scores, compare = map(np.asanyarray, [scores, compare])<EOL>mns = compare.mean(axis=axis)<EOL>sstd = compare.std(axis=axis, ddof=ddof)<EOL>if axis and mns.ndim < compare.ndim:<EOL><INDENT>return ((scores - np.expand_dims(mns, axis=axis)) /<EOL>np.expand_dims(sstd,axis=axis))<EOL><DEDENT>else:<EOL><INDENT>return (scores - mns) / sstd<EOL><DEDENT>

Calculates the relative z-scores.

Returns an array of z-scores, i.e., scores that are standardized to zero
mean and unit variance, where mean and variance are calculated from the
comparison array.

Parameters
----------
scores : array_like
    The input for which z-scores are calculated.
compare : array_like
    The input from which the mean and standard deviation of the
    normalization are taken; assumed to have the same dimension as
    `scores`.
axis : int or None, optional
    Axis over which mean and variance of `compare` are calculated.
    Default is 0.
ddof : int, optional
    Degrees of freedom correction in the calculation of the
    standard deviation. Default is 0.

Returns
-------
zscore : array_like
    Z-scores, in the same shape as `scores`.

Notes
-----
This function preserves ndarray subclasses, and works also with
matrices and masked arrays (it uses `asanyarray` instead of `asarray`
for parameters).

Examples
--------
>>> a = [0.5, 2.0, 2.5, 3]
>>> b = [0, 1, 2, 3, 4]
>>> zmap(a, b)
array([-1.06066017,  0.        ,  0.35355339,  0.70710678])


def tvar(a, limits=None, inclusive=(True, True)):

a = asarray(a)<EOL>a = a.astype(float).ravel()<EOL>if limits is None:<EOL><INDENT>n = len(a)<EOL>return a.var()*(n/(n-<NUM_LIT:1.>))<EOL><DEDENT>am = mask_to_limits(a, limits, inclusive)<EOL>return masked_var(am)<EOL>

Compute the trimmed variance

This function computes the sample variance of an array of values,
while ignoring values which are outside of given `limits`.

Parameters
----------
a : array_like
    Array of values.
limits : None or (lower limit, upper limit), optional
    Values in the input array less than the lower limit or greater than the
    upper limit will be ignored. When limits is None, then all values are
    used. Either of the limit values in the tuple can also be None
    representing a half-open interval.  The default value is None.
inclusive : (bool, bool), optional
    A tuple consisting of the (lower flag, upper flag).  These flags
    determine whether values exactly equal to the lower or upper limits
    are included.  The default value is (True, True).

Returns
-------
tvar : float
    Trimmed variance.

Notes
-----
`tvar` computes the unbiased sample variance, i.e. it uses a correction
factor ``n / (n - 1)``.


a, axis = _chk_asarray(a, axis)<EOL>return np.sum(a*a, axis)<EOL>

Squares each element of the input array, and returns the sum(s) of that.

Parameters
----------
a : array_like
    Input array.
axis : int or None, optional
    The axis along which to calculate. If None, use whole array.
    Default is 0, i.e. along the first axis.

Returns
-------
ss : ndarray
    The sum along the given axis for (a**2).

See also
--------
square_of_sums : The square(s) of the sum(s) (the opposite of `ss`).

Examples
--------
>>> from scipy import stats
>>> a = np.array([1., 2., 5.])
>>> stats.ss(a)
30.0

And calculating along an axis:

>>> b = np.array([[1., 2., 5.], [2., 5., 6.]])
>>> stats.ss(b, axis=1)
array([ 30., 65.])


def trimboth(a, proportiontocut, axis=<NUM_LIT:0>):

a = np.asarray(a)<EOL>if axis is None:<EOL><INDENT>a = a.ravel()<EOL>axis = <NUM_LIT:0><EOL><DEDENT>nobs = a.shape[axis]<EOL>lowercut = int(proportiontocut * nobs)<EOL>uppercut = nobs - lowercut<EOL>if (lowercut >= uppercut):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>sl = [slice(None)] * a.ndim<EOL>sl[axis] = slice(lowercut, uppercut)<EOL>return a[sl]<EOL>

Slices off a proportion of items from both ends of an array.

Slices off the passed proportion of items from both ends of the passed
array (i.e., with `proportiontocut` = 0.1, slices leftmost 10% **and**
rightmost 10% of scores).  You must pre-sort the array if you want
'proper' trimming.  Slices off less if proportion results in a
non-integer slice index (i.e., conservatively slices off
`proportiontocut`).

Parameters
----------
a : array_like
    Data to trim.
proportiontocut : float
    Proportion (in range 0-1) of total data set to trim of each end.
axis : int or None, optional
    Axis along which the observations are trimmed. The default is to trim
    along axis=0. If axis is None then the array will be flattened before
    trimming.

Returns
-------
out : ndarray
    Trimmed version of array `a`.

See Also
--------
trim_mean

Examples
--------
>>> from scipy import stats
>>> a = np.arange(20)
>>> b = stats.trimboth(a, 0.1)
>>> b.shape
(16,)


def mask_to_limits(a, limits, inclusive):

lower_limit, upper_limit = limits<EOL>lower_include, upper_include = inclusive<EOL>am = ma.MaskedArray(a)<EOL>if lower_limit is not None:<EOL><INDENT>if lower_include:<EOL><INDENT>am = ma.masked_less(am, lower_limit)<EOL><DEDENT>else:<EOL><INDENT>am = ma.masked_less_equal(am, lower_limit)<EOL><DEDENT><DEDENT>if upper_limit is not None:<EOL><INDENT>if upper_include:<EOL><INDENT>am = ma.masked_greater(am, upper_limit)<EOL><DEDENT>else:<EOL><INDENT>am = ma.masked_greater_equal(am, upper_limit)<EOL><DEDENT><DEDENT>if am.count() == <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return am<EOL>

Mask an array for values outside of given limits.

    This is primarily a utility function.

    Parameters
    ----------
    a : array
    limits : (float or None, float or None)
        A tuple consisting of the (lower limit, upper limit).  Values in the
        input array less than the lower limit or greater than the upper limit
        will be masked out. None implies no limit.
    inclusive : (bool, bool)
        A tuple consisting of the (lower flag, upper flag).  These flags
        determine whether values exactly equal to lower or upper are allowed.

    Returns
    -------
    A MaskedArray.

    Raises
    ------
    A ValueError if there are no values within the given limits.