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.


def is_valid_dm(D, tol=<NUM_LIT:0.0>, throw=False, name="<STR_LIT:D>", warning=False):

D = np.asarray(D, order='<STR_LIT:c>')<EOL>valid = True<EOL>try:<EOL><INDENT>s = D.shape<EOL>if D.dtype != np.double:<EOL><INDENT>if name:<EOL><INDENT>raise TypeError(('<STR_LIT>'<EOL>'<STR_LIT>') % name)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>if len(D.shape) != <NUM_LIT:2>:<EOL><INDENT>if name:<EOL><INDENT>raise ValueError(('<STR_LIT>'<EOL>'<STR_LIT>') % name)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>if tol == <NUM_LIT:0.0>:<EOL><INDENT>if not (D == D.T).all():<EOL><INDENT>if name:<EOL><INDENT>raise ValueError(('<STR_LIT>'<EOL>'<STR_LIT>') % name)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT>if not (D[xrange(<NUM_LIT:0>, s[<NUM_LIT:0>]), xrange(<NUM_LIT:0>, s[<NUM_LIT:0>])] == <NUM_LIT:0>).all():<EOL><INDENT>if name:<EOL><INDENT>raise ValueError(('<STR_LIT>'<EOL>'<STR_LIT>') % name)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if not (D - D.T <= tol).all():<EOL><INDENT>if name:<EOL><INDENT>raise ValueError(('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>% (name, tol))<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>' % tol)<EOL><DEDENT><DEDENT>if not (D[xrange(<NUM_LIT:0>, s[<NUM_LIT:0>]), xrange(<NUM_LIT:0>, s[<NUM_LIT:0>])] <= tol).all():<EOL><INDENT>if name:<EOL><INDENT>raise ValueError(('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>% (name, tol))<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>% tol)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>except Exception as e:<EOL><INDENT>if throw:<EOL><INDENT>raise<EOL><DEDENT>if warning:<EOL><INDENT>warnings.warn(str(e))<EOL><DEDENT>valid = False<EOL><DEDENT>return valid<EOL>

Returns True if input array is a valid distance matrix.

Distance matrices must be 2-dimensional numpy arrays containing
doubles. They must have a zero-diagonal, and they must be symmetric.

Parameters
----------
D : ndarray
    The candidate object to test for validity.
tol : float, optional
    The distance matrix should be symmetric. `tol` is the maximum
    difference between entries ``ij`` and ``ji`` for the distance
    metric to be considered symmetric.
throw : bool, optional
    An exception is thrown if the distance matrix passed is not valid.
name : str, optional
    The name of the variable to checked. This is useful if
    throw is set to True so the offending variable can be identified
    in the exception message when an exception is thrown.
warning : bool, optional
    Instead of throwing an exception, a warning message is
    raised.

Returns
-------
valid : bool
    True if the variable `D` passed is a valid distance matrix.

Notes
-----
Small numerical differences in `D` and `D.T` and non-zeroness of
the diagonal are ignored if they are within the tolerance specified
by `tol`.


def is_valid_y(y, warning=False, throw=False, name=None):

y = np.asarray(y, order='<STR_LIT:c>')<EOL>valid = True<EOL>try:<EOL><INDENT>if type(y) != np.ndarray:<EOL><INDENT>if name:<EOL><INDENT>raise TypeError(('<STR_LIT>'<EOL>'<STR_LIT>') % name)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT><DEDENT>if y.dtype != np.double:<EOL><INDENT>if name:<EOL><INDENT>raise TypeError(('<STR_LIT>'<EOL>'<STR_LIT>') % name)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>if len(y.shape) != <NUM_LIT:1>:<EOL><INDENT>if name:<EOL><INDENT>raise ValueError(('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>% name)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>n = y.shape[<NUM_LIT:0>]<EOL>d = int(np.ceil(np.sqrt(n * <NUM_LIT:2>)))<EOL>if (d * (d - <NUM_LIT:1>) / <NUM_LIT:2>) != n:<EOL><INDENT>if name:<EOL><INDENT>raise ValueError(('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>') % name)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>except Exception as e:<EOL><INDENT>if throw:<EOL><INDENT>raise<EOL><DEDENT>if warning:<EOL><INDENT>warnings.warn(str(e))<EOL><DEDENT>valid = False<EOL><DEDENT>return valid<EOL>

Returns True if the input array is a valid condensed distance matrix.

Condensed distance matrices must be 1-dimensional
numpy arrays containing doubles. Their length must be a binomial
coefficient :math:`{n \\choose 2}` for some positive integer n.

Parameters
----------
y : ndarray
    The condensed distance matrix.
warning : bool, optional
    Invokes a warning if the variable passed is not a valid
    condensed distance matrix. The warning message explains why
    the distance matrix is not valid.  `name` is used when
    referencing the offending variable.
throws : throw, optional
    Throws an exception if the variable passed is not a valid
    condensed distance matrix.
name : bool, optional
    Used when referencing the offending variable in the
    warning or exception message.


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.


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


def cdist(XA, XB, metric='<STR_LIT>', p=<NUM_LIT:2>, V=None, VI=None, w=None):

<EOL><INDENT>XA = np.asarray(XA, order='<STR_LIT:c>')<EOL>XB = np.asarray(XB, order='<STR_LIT:c>')<EOL>[XA] = _copy_arrays_if_base_present([_convert_to_double(XA)])<EOL>[XB] = _copy_arrays_if_base_present([_convert_to_double(XB)])<EOL>s = XA.shape<EOL>sB = XB.shape<EOL>if len(s) != <NUM_LIT:2>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if len(sB) != <NUM_LIT:2>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if s[<NUM_LIT:1>] != sB[<NUM_LIT:1>]:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>mA = s[<NUM_LIT:0>]<EOL>mB = sB[<NUM_LIT:0>]<EOL>n = s[<NUM_LIT:1>]<EOL>dm = np.zeros((mA, mB), dtype=np.double)<EOL>if callable(metric):<EOL><INDENT>if metric == minkowski:<EOL><INDENT>for i in xrange(<NUM_LIT:0>, mA):<EOL><INDENT>for j in xrange(<NUM_LIT:0>, mB):<EOL><INDENT>dm[i, j] = minkowski(XA[i, :], XB[j, :], p)<EOL><DEDENT><DEDENT><DEDENT>elif metric == wminkowski:<EOL><INDENT>for i in xrange(<NUM_LIT:0>, mA):<EOL><INDENT>for j in xrange(<NUM_LIT:0>, mB):<EOL><INDENT>dm[i, j] = wminkowski(XA[i, :], XB[j, :], p, w)<EOL><DEDENT><DEDENT><DEDENT>elif metric == seuclidean:<EOL><INDENT>for i in xrange(<NUM_LIT:0>, mA):<EOL><INDENT>for j in xrange(<NUM_LIT:0>, mB):<EOL><INDENT>dm[i, j] = seuclidean(XA[i, :], XB[j, :], V)<EOL><DEDENT><DEDENT><DEDENT>elif metric == mahalanobis:<EOL><INDENT>for i in xrange(<NUM_LIT:0>, mA):<EOL><INDENT>for j in xrange(<NUM_LIT:0>, mB):<EOL><INDENT>dm[i, j] = mahalanobis(XA[i, :], XB[j, :], V)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>for i in xrange(<NUM_LIT:0>, mA):<EOL><INDENT>for j in xrange(<NUM_LIT:0>, mB):<EOL><INDENT>dm[i, j] = metric(XA[i, :], XB[j, :])<EOL><DEDENT><DEDENT><DEDENT><DEDENT>elif isinstance(metric, string_types):<EOL><INDENT>mstr = metric.lower()<EOL>if mstr in set(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:e>']):<EOL><INDENT>_distance_wrap.cdist_euclidean_wrap(_convert_to_double(XA),<EOL>_convert_to_double(XB), dm)<EOL><DEDENT>elif mstr in set(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']):<EOL><INDENT>_distance_wrap.cdist_sqeuclidean_wrap(_convert_to_double(XA),<EOL>_convert_to_double(XB), dm)<EOL><DEDENT>elif mstr in set(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:c>']):<EOL><INDENT>_distance_wrap.cdist_city_block_wrap(_convert_to_double(XA),<EOL>_convert_to_double(XB), dm)<EOL><DEDENT>elif mstr in set(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:h>']):<EOL><INDENT>if XA.dtype == np.bool:<EOL><INDENT>_distance_wrap.cdist_hamming_bool_wrap(_convert_to_bool(XA),<EOL>_convert_to_bool(XB),<EOL>dm)<EOL><DEDENT>else:<EOL><INDENT>_distance_wrap.cdist_hamming_wrap(_convert_to_double(XA),<EOL>_convert_to_double(XB), dm)<EOL><DEDENT><DEDENT>elif mstr in set(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']):<EOL><INDENT>if XA.dtype == np.bool:<EOL><INDENT>_distance_wrap.cdist_jaccard_bool_wrap(_convert_to_bool(XA),<EOL>_convert_to_bool(XB),<EOL>dm)<EOL><DEDENT>else:<EOL><INDENT>_distance_wrap.cdist_jaccard_wrap(_convert_to_double(XA),<EOL>_convert_to_double(XB), dm)<EOL><DEDENT><DEDENT>elif mstr in set(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']):<EOL><INDENT>_distance_wrap.cdist_chebyshev_wrap(_convert_to_double(XA),<EOL>_convert_to_double(XB), dm)<EOL><DEDENT>elif mstr in set(['<STR_LIT>', '<STR_LIT>', '<STR_LIT:m>', '<STR_LIT>']):<EOL><INDENT>_distance_wrap.cdist_minkowski_wrap(_convert_to_double(XA),<EOL>_convert_to_double(XB), dm, p)<EOL><DEDENT>elif mstr in set(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']):<EOL><INDENT>_distance_wrap.cdist_weighted_minkowski_wrap(_convert_to_double(XA),<EOL>_convert_to_double(XB),<EOL>dm, p,<EOL>_convert_to_double(w))<EOL><DEDENT>elif mstr in set(['<STR_LIT>', '<STR_LIT>', '<STR_LIT:s>']):<EOL><INDENT>if V is not None:<EOL><INDENT>V = np.asarray(V, order='<STR_LIT:c>')<EOL>if type(V) != np.ndarray:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if V.dtype != np.double:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if len(V.shape) != <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>if V.shape[<NUM_LIT:0>] != n:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>[VV] = _copy_arrays_if_base_present([_convert_to_double(V)])<EOL><DEDENT>else:<EOL><INDENT>X = np.vstack([XA, XB])<EOL>VV = np.var(X, axis=<NUM_LIT:0>, ddof=<NUM_LIT:1>)<EOL>X = None<EOL>del X<EOL><DEDENT>_distance_wrap.cdist_seuclidean_wrap(_convert_to_double(XA),<EOL>_convert_to_double(XB), VV, dm)<EOL><DEDENT>elif mstr in set(['<STR_LIT>', '<STR_LIT>']):<EOL><INDENT>normsA = np.sqrt(np.sum(XA * XA, axis=<NUM_LIT:1>))<EOL>normsB = np.sqrt(np.sum(XB * XB, axis=<NUM_LIT:1>))<EOL>_distance_wrap.cdist_cosine_wrap(_convert_to_double(XA),<EOL>_convert_to_double(XB), dm,<EOL>normsA,<EOL>normsB)<EOL><DEDENT>elif mstr in set(['<STR_LIT>', '<STR_LIT>']):<EOL><INDENT>XA2 = XA - XA.mean(<NUM_LIT:1>)[:, np.newaxis]<EOL>XB2 = XB - XB.mean(<NUM_LIT:1>)[:, np.newaxis]<EOL>normsA = np.sqrt(np.sum(XA2 * XA2, axis=<NUM_LIT:1>))<EOL>normsB = np.sqrt(np.sum(XB2 * XB2, axis=<NUM_LIT:1>))<EOL>_distance_wrap.cdist_cosine_wrap(_convert_to_double(XA2),<EOL>_convert_to_double(XB2),<EOL>_convert_to_double(dm),<EOL>_convert_to_double(normsA),<EOL>_convert_to_double(normsB))<EOL><DEDENT>elif mstr in set(['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']):<EOL><INDENT>if VI is not None:<EOL><INDENT>VI = _convert_to_double(np.asarray(VI, order='<STR_LIT:c>'))<EOL>if type(VI) != np.ndarray:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>if VI.dtype != np.double:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>[VI] = _copy_arrays_if_base_present([VI])<EOL><DEDENT>else:<EOL><INDENT>X = np.vstack([XA, XB])<EOL>V = np.cov(X.T)<EOL>X = None<EOL>del X<EOL>VI = _convert_to_double(np.linalg.inv(V).T.copy())<EOL><DEDENT>_distance_wrap.cdist_mahalanobis_wrap(_convert_to_double(XA),<EOL>_convert_to_double(XB),<EOL>VI, dm)<EOL><DEDENT>elif mstr == '<STR_LIT>':<EOL><INDENT>_distance_wrap.cdist_canberra_wrap(_convert_to_double(XA),<EOL>_convert_to_double(XB), dm)<EOL><DEDENT>elif mstr == '<STR_LIT>':<EOL><INDENT>_distance_wrap.cdist_bray_curtis_wrap(_convert_to_double(XA),<EOL>_convert_to_double(XB), dm)<EOL><DEDENT>elif mstr == '<STR_LIT>':<EOL><INDENT>_distance_wrap.cdist_yule_bool_wrap(_convert_to_bool(XA),<EOL>_convert_to_bool(XB), dm)<EOL><DEDENT>elif mstr == '<STR_LIT>':<EOL><INDENT>_distance_wrap.cdist_matching_bool_wrap(_convert_to_bool(XA),<EOL>_convert_to_bool(XB), dm)<EOL><DEDENT>elif mstr == '<STR_LIT>':<EOL><INDENT>_distance_wrap.cdist_kulsinski_bool_wrap(_convert_to_bool(XA),<EOL>_convert_to_bool(XB), dm)<EOL><DEDENT>elif mstr == '<STR_LIT>':<EOL><INDENT>_distance_wrap.cdist_dice_bool_wrap(_convert_to_bool(XA),<EOL>_convert_to_bool(XB), dm)<EOL><DEDENT>elif mstr == '<STR_LIT>':<EOL><INDENT>_distance_wrap.cdist_rogerstanimoto_bool_wrap(_convert_to_bool(XA),<EOL>_convert_to_bool(XB),<EOL>dm)<EOL><DEDENT>elif mstr == '<STR_LIT>':<EOL><INDENT>_distance_wrap.cdist_russellrao_bool_wrap(_convert_to_bool(XA),<EOL>_convert_to_bool(XB), dm)<EOL><DEDENT>elif mstr == '<STR_LIT>':<EOL><INDENT>_distance_wrap.cdist_sokalmichener_bool_wrap(_convert_to_bool(XA),<EOL>_convert_to_bool(XB),<EOL>dm)<EOL><DEDENT>elif mstr == '<STR_LIT>':<EOL><INDENT>_distance_wrap.cdist_sokalsneath_bool_wrap(_convert_to_bool(XA),<EOL>_convert_to_bool(XB),<EOL>dm)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = cdist(XA, XB, euclidean)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>if V is None:<EOL><INDENT>V = np.var(np.vstack([XA, XB]), axis=<NUM_LIT:0>, ddof=<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>V = np.asarray(V, order='<STR_LIT:c>')<EOL><DEDENT>dm = cdist(XA, XB, lambda u, v: seuclidean(u, v, V))<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = cdist(XA, XB, lambda u, v: sqeuclidean(u, v))<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = cdist(XA, XB, braycurtis)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>if VI is None:<EOL><INDENT>X = np.vstack([XA, XB])<EOL>V = np.cov(X.T)<EOL>VI = np.linalg.inv(V)<EOL>X = None<EOL>del X<EOL><DEDENT>else:<EOL><INDENT>VI = np.asarray(VI, order='<STR_LIT:c>')<EOL><DEDENT>[VI] = _copy_arrays_if_base_present([VI])<EOL>dm = cdist(XA, XB, (lambda u, v: mahalanobis(u, v, VI)))<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = cdist(XA, XB, canberra)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = cdist(XA, XB, cityblock)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = cdist(XA, XB, minkowski, p=p)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = cdist(XA, XB, wminkowski, p=p, w=w)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = cdist(XA, XB, cosine)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = cdist(XA, XB, correlation)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = cdist(XA, XB, hamming)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = cdist(XA, XB, jaccard)<EOL><DEDENT>elif metric == '<STR_LIT>' or metric == '<STR_LIT>':<EOL><INDENT>dm = cdist(XA, XB, chebyshev)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = cdist(XA, XB, yule)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = cdist(XA, XB, matching)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = cdist(XA, XB, dice)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = cdist(XA, XB, kulsinski)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = cdist(XA, XB, rogerstanimoto)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = cdist(XA, XB, russellrao)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = cdist(XA, XB, sokalsneath)<EOL><DEDENT>elif metric == '<STR_LIT>':<EOL><INDENT>dm = cdist(XA, XB, sokalmichener)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>' % mstr)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise TypeError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>return dm<EOL><DEDENT>

Computes distance between each pair of the two collections of inputs.

The following are common calling conventions:

1. ``Y = cdist(XA, XB, 'euclidean')``

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

2. ``Y = cdist(XA, XB, 'minkowski', p)``

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

3. ``Y = cdist(XA, XB, 'cityblock')``

   Computes the city block or Manhattan distance between the
   points.

4. ``Y = cdist(XA, XB, 'seuclidean', V=None)``

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

   .. math::

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

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

5. ``Y = cdist(XA, XB, 'sqeuclidean')``

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

6. ``Y = cdist(XA, XB, 'cosine')``

   Computes the cosine distance between vectors u and v,

   .. math::

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

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

7. ``Y = cdist(XA, XB, 'correlation')``

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

   .. math::

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

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

8. ``Y = cdist(XA, XB, 'hamming')``

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

9. ``Y = cdist(XA, XB, 'jaccard')``

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

10. ``Y = cdist(XA, XB, 'chebyshev')``

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

   .. math::

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

11. ``Y = cdist(XA, XB, 'canberra')``

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

   .. math::

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

12. ``Y = cdist(XA, XB, 'braycurtis')``

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

   .. math::

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

13. ``Y = cdist(XA, XB, 'mahalanobis', VI=None)``

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

14. ``Y = cdist(XA, XB, 'yule')``

   Computes the Yule distance between the boolean
   vectors. (see `yule` function documentation)

15. ``Y = cdist(XA, XB, 'matching')``

   Computes the matching distance between the boolean
   vectors. (see `matching` function documentation)

16. ``Y = cdist(XA, XB, 'dice')``

   Computes the Dice distance between the boolean vectors. (see
   `dice` function documentation)

17. ``Y = cdist(XA, XB, 'kulsinski')``

   Computes the Kulsinski distance between the boolean
   vectors. (see `kulsinski` function documentation)

18. ``Y = cdist(XA, XB, 'rogerstanimoto')``

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

19. ``Y = cdist(XA, XB, 'russellrao')``

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

20. ``Y = cdist(XA, XB, 'sokalmichener')``

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

21. ``Y = cdist(XA, XB, 'sokalsneath')``

   Computes the Sokal-Sneath distance between the vectors. (see
   `sokalsneath` function documentation)

22. ``Y = cdist(XA, XB, 'wminkowski')``

   Computes the weighted Minkowski distance between the
   vectors. (see `wminkowski` function documentation)

23. ``Y = cdist(XA, XB, f)``

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

     dm = cdist(XA, XB, lambda u, v: np.sqrt(((u-v)**2).sum()))

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

     dm = cdist(XA, XB, sokalsneath)

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

     dm = cdist(XA, XB, 'sokalsneath')

Parameters
----------
XA : ndarray
    An :math:`m_A` by :math:`n` array of :math:`m_A`
    original observations in an :math:`n`-dimensional space.
    Inputs are converted to float type.
XB : ndarray
    An :math:`m_B` by :math:`n` array of :math:`m_B`
    original observations in an :math:`n`-dimensional space.
    Inputs are converted to float type.
metric : str or callable, optional
    The distance metric to use.  If a string, the distance function can be
    'braycurtis', 'canberra', 'chebyshev', 'cityblock', 'correlation',
    'cosine', 'dice', 'euclidean', 'hamming', 'jaccard', 'kulsinski',
    'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto', 'russellrao',
    'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean',
    'wminkowski', 'yule'.
w : ndarray, optional
    The weight vector (for weighted Minkowski).
p : scalar, optional
    The p-norm to apply (for Minkowski, weighted and unweighted)
V : ndarray, optional
    The variance vector (for standardized Euclidean).
VI : ndarray, optional
    The inverse of the covariance matrix (for Mahalanobis).

Returns
-------
Y : ndarray
    A :math:`m_A` by :math:`m_B` distance matrix is returned.
    For each :math:`i` and :math:`j`, the metric
    ``dist(u=XA[i], v=XB[j])`` is computed and stored in the
    :math:`ij` th entry.

Raises
------
ValueError
    An exception is thrown if `XA` and `XB` do not have
    the same number of columns.

Examples
--------
Find the Euclidean distances between four 2-D coordinates:

>>> from scipy.spatial import distance
>>> coords = [(35.0456, -85.2672),
...           (35.1174, -89.9711),
...           (35.9728, -83.9422),
...           (36.1667, -86.7833)]
>>> distance.cdist(coords, coords, 'euclidean')
array([[ 0.    ,  4.7044,  1.6172,  1.8856],
       [ 4.7044,  0.    ,  6.0893,  3.3561],
       [ 1.6172,  6.0893,  0.    ,  2.8477],
       [ 1.8856,  3.3561,  2.8477,  0.    ]])

Find the Manhattan distance from a 3-D point to the corners of the unit
cube:

>>> a = np.array([[0, 0, 0],
                  [0, 0, 1],
                  [0, 1, 0],
                  [0, 1, 1],
                  [1, 0, 0],
                  [1, 0, 1],
                  [1, 1, 0],
                  [1, 1, 1]])
>>> b = np.array([[ 0.1,  0.2,  0.4]])
>>> distance.cdist(a, b, 'cityblock')
array([[ 0.7],
       [ 0.9],
       [ 1.3],
       [ 1.5],
       [ 1.5],
       [ 1.7],
       [ 2.1],
       [ 2.3]])


if tri.points.shape[<NUM_LIT:1>] != <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>ax.plot(tri.points[:,<NUM_LIT:0>], tri.points[:,<NUM_LIT:1>], '<STR_LIT:o>')<EOL>ax.triplot(tri.points[:,<NUM_LIT:0>], tri.points[:,<NUM_LIT:1>], tri.simplices.copy())<EOL>_adjust_bounds(ax, tri.points)<EOL>return ax.figure<EOL>

Plot the given Delaunay triangulation in 2-D

Parameters
----------
tri : scipy.spatial.Delaunay instance
    Triangulation to plot
ax : matplotlib.axes.Axes instance, optional
    Axes to plot on

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

See Also
--------
Delaunay
matplotlib.pyplot.triplot

Notes
-----
Requires Matplotlib.


if hull.points.shape[<NUM_LIT:1>] != <NUM_LIT:2>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>ax.plot(hull.points[:,<NUM_LIT:0>], hull.points[:,<NUM_LIT:1>], '<STR_LIT:o>')<EOL>for simplex in hull.simplices:<EOL><INDENT>ax.plot(hull.points[simplex,<NUM_LIT:0>], hull.points[simplex,<NUM_LIT:1>], '<STR_LIT>')<EOL><DEDENT>_adjust_bounds(ax, hull.points)<EOL>return ax.figure<EOL>

Plot the given convex hull diagram in 2-D

Parameters
----------
hull : scipy.spatial.ConvexHull instance
    Convex hull to plot
ax : matplotlib.axes.Axes instance, optional
    Axes to plot on

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

See Also
--------
ConvexHull

Notes
-----
Requires Matplotlib.


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 minkowski_distance_p(x, y, p=<NUM_LIT:2>):

x = np.asarray(x)<EOL>y = np.asarray(y)<EOL>if p == np.inf:<EOL><INDENT>return np.amax(np.abs(y-x), axis=-<NUM_LIT:1>)<EOL><DEDENT>elif p == <NUM_LIT:1>:<EOL><INDENT>return np.sum(np.abs(y-x), axis=-<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>return np.sum(np.abs(y-x)**p, axis=-<NUM_LIT:1>)<EOL><DEDENT>

Compute the p-th power of the L**p distance between two arrays.

For efficiency, this function computes the L**p distance but does
not extract the pth root. If `p` is 1 or infinity, this is equal to
the actual L**p distance.

Parameters
----------
x : (M, K) array_like
    Input array.
y : (N, K) array_like
    Input array.
p : float, 1 <= p <= infinity
    Which Minkowski p-norm to use.

Examples
--------
>>> minkowski_distance_p([[0,0],[0,0]], [[1,1],[0,1]])
array([2, 1])


def minkowski_distance(x, y, p=<NUM_LIT:2>):

x = np.asarray(x)<EOL>y = np.asarray(y)<EOL>if p == np.inf or p == <NUM_LIT:1>:<EOL><INDENT>return minkowski_distance_p(x, y, p)<EOL><DEDENT>else:<EOL><INDENT>return minkowski_distance_p(x, y, p)**(<NUM_LIT:1.>/p)<EOL><DEDENT>

Compute the L**p distance between two arrays.

Parameters
----------
x : (M, K) array_like
    Input array.
y : (N, K) array_like
    Input array.
p : float, 1 <= p <= infinity
    Which Minkowski p-norm to use.

Examples
--------
>>> minkowski_distance([[0,0],[0,0]], [[1,1],[0,1]])
array([ 1.41421356,  1.        ])


x = np.asarray(x)<EOL>m, k = x.shape<EOL>y = np.asarray(y)<EOL>n, kk = y.shape<EOL>if k != kk:<EOL><INDENT>raise ValueError("<STR_LIT>" % (k, kk))<EOL><DEDENT>if m*n*k <= threshold:<EOL><INDENT>return minkowski_distance(x[:,np.newaxis,:],y[np.newaxis,:,:],p)<EOL><DEDENT>else:<EOL><INDENT>result = np.empty((m,n),dtype=np.float)  <EOL>if m < n:<EOL><INDENT>for i in range(m):<EOL><INDENT>result[i,:] = minkowski_distance(x[i],y,p)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for j in range(n):<EOL><INDENT>result[:,j] = minkowski_distance(x,y[j],p)<EOL><DEDENT><DEDENT>return result<EOL><DEDENT>

Compute the distance matrix.

Returns the matrix of all pair-wise distances.

Parameters
----------
x : (M, K) array_like
    TODO: description needed
y : (N, K) array_like
    TODO: description needed
p : float, 1 <= p <= infinity
    Which Minkowski p-norm to use.
threshold : positive int
    If ``M * N * K`` > `threshold`, algorithm uses a Python loop instead
    of large temporary arrays.

Returns
-------
result : (M, N) ndarray
    Distance matrix.

Examples
--------
>>> distance_matrix([[0,0],[0,1]], [[1,0],[1,1]])
array([[ 1.        ,  1.41421356],
       [ 1.41421356,  1.        ]])


self.maxes = np.maximum(maxes,mins).astype(np.float)<EOL>self.mins = np.minimum(maxes,mins).astype(np.float)<EOL>self.m, = self.maxes.shape<EOL>


return np.prod(self.maxes-self.mins)<EOL>


mid = np.copy(self.maxes)<EOL>mid[d] = split<EOL>less = Rectangle(self.mins, mid)<EOL>mid = np.copy(self.mins)<EOL>mid[d] = split<EOL>greater = Rectangle(mid, self.maxes)<EOL>return less, greater<EOL>

Produce two hyperrectangles by splitting.

In general, if you need to compute maximum and minimum
distances to the children, it can be done more efficiently
by updating the maximum and minimum distances to the parent.

Parameters
----------
d : int
    Axis to split hyperrectangle along.
split :
    Input.


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 max_distance_point(self, x, p=<NUM_LIT>):

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

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

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


def min_distance_rectangle(self, other, p=<NUM_LIT>):

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

Compute the minimum distance between points in the two hyperrectangles.

Parameters
----------
other : hyperrectangle
    Input.
p : float
    Input.


def max_distance_rectangle(self, other, p=<NUM_LIT>):

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

Compute the maximum distance between points in the two hyperrectangles.

Parameters
----------
other : hyperrectangle
    Input.
p : float, optional
    Input.


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)


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_ball_tree(self, other, r, p=<NUM_LIT>, eps=<NUM_LIT:0>):

results = [[] for i in range(self.n)]<EOL>def traverse_checking(node1, rect1, node2, rect2):<EOL><INDENT>if rect1.min_distance_rectangle(rect2, p) > r/(<NUM_LIT:1.>+eps):<EOL><INDENT>return<EOL><DEDENT>elif rect1.max_distance_rectangle(rect2, p) < r*(<NUM_LIT:1.>+eps):<EOL><INDENT>traverse_no_checking(node1, node2)<EOL><DEDENT>elif isinstance(node1, KDTree.leafnode):<EOL><INDENT>if isinstance(node2, KDTree.leafnode):<EOL><INDENT>d = other.data[node2.idx]<EOL>for i in node1.idx:<EOL><INDENT>results[i] += node2.idx[minkowski_distance(d,self.data[i],p) <= r].tolist()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>less, greater = rect2.split(node2.split_dim, node2.split)<EOL>traverse_checking(node1,rect1,node2.less,less)<EOL>traverse_checking(node1,rect1,node2.greater,greater)<EOL><DEDENT><DEDENT>elif isinstance(node2, KDTree.leafnode):<EOL><INDENT>less, greater = rect1.split(node1.split_dim, node1.split)<EOL>traverse_checking(node1.less,less,node2,rect2)<EOL>traverse_checking(node1.greater,greater,node2,rect2)<EOL><DEDENT>else:<EOL><INDENT>less1, greater1 = rect1.split(node1.split_dim, node1.split)<EOL>less2, greater2 = rect2.split(node2.split_dim, node2.split)<EOL>traverse_checking(node1.less,less1,node2.less,less2)<EOL>traverse_checking(node1.less,less1,node2.greater,greater2)<EOL>traverse_checking(node1.greater,greater1,node2.less,less2)<EOL>traverse_checking(node1.greater,greater1,node2.greater,greater2)<EOL><DEDENT><DEDENT>def traverse_no_checking(node1, node2):<EOL><INDENT>if isinstance(node1, KDTree.leafnode):<EOL><INDENT>if isinstance(node2, KDTree.leafnode):<EOL><INDENT>for i in node1.idx:<EOL><INDENT>results[i] += node2.idx.tolist()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>traverse_no_checking(node1, node2.less)<EOL>traverse_no_checking(node1, node2.greater)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>traverse_no_checking(node1.less, node2)<EOL>traverse_no_checking(node1.greater, node2)<EOL><DEDENT><DEDENT>traverse_checking(self.tree, Rectangle(self.maxes, self.mins),<EOL>other.tree, Rectangle(other.maxes, other.mins))<EOL>return results<EOL>

Find all pairs of points whose distance is at most r

        Parameters
        ----------
        other : KDTree instance
            The tree containing points to search against.
        r : float
            The maximum distance, has to be positive.
        p : float, optional
            Which Minkowski norm to use.  `p` has to meet the condition
            ``1 <= p <= infinity``.
        eps : 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)``.  `eps` has to be non-negative.

        Returns
        -------
        results : list of lists
            For each element ``self.data[i]`` of this tree, ``results[i]`` is a
            list of the indices of its neighbors in ``other.data``.


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

results = set()<EOL>def traverse_checking(node1, rect1, node2, rect2):<EOL><INDENT>if rect1.min_distance_rectangle(rect2, p) > r/(<NUM_LIT:1.>+eps):<EOL><INDENT>return<EOL><DEDENT>elif rect1.max_distance_rectangle(rect2, p) < r*(<NUM_LIT:1.>+eps):<EOL><INDENT>traverse_no_checking(node1, node2)<EOL><DEDENT>elif isinstance(node1, KDTree.leafnode):<EOL><INDENT>if isinstance(node2, KDTree.leafnode):<EOL><INDENT>if id(node1) == id(node2):<EOL><INDENT>d = self.data[node2.idx]<EOL>for i in node1.idx:<EOL><INDENT>for j in node2.idx[minkowski_distance(d,self.data[i],p) <= r]:<EOL><INDENT>if i < j:<EOL><INDENT>results.add((i,j))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>d = self.data[node2.idx]<EOL>for i in node1.idx:<EOL><INDENT>for j in node2.idx[minkowski_distance(d,self.data[i],p) <= r]:<EOL><INDENT>if i < j:<EOL><INDENT>results.add((i,j))<EOL><DEDENT>elif j < i:<EOL><INDENT>results.add((j,i))<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>less, greater = rect2.split(node2.split_dim, node2.split)<EOL>traverse_checking(node1,rect1,node2.less,less)<EOL>traverse_checking(node1,rect1,node2.greater,greater)<EOL><DEDENT><DEDENT>elif isinstance(node2, KDTree.leafnode):<EOL><INDENT>less, greater = rect1.split(node1.split_dim, node1.split)<EOL>traverse_checking(node1.less,less,node2,rect2)<EOL>traverse_checking(node1.greater,greater,node2,rect2)<EOL><DEDENT>else:<EOL><INDENT>less1, greater1 = rect1.split(node1.split_dim, node1.split)<EOL>less2, greater2 = rect2.split(node2.split_dim, node2.split)<EOL>traverse_checking(node1.less,less1,node2.less,less2)<EOL>traverse_checking(node1.less,less1,node2.greater,greater2)<EOL>if id(node1) != id(node2):<EOL><INDENT>traverse_checking(node1.greater,greater1,node2.less,less2)<EOL><DEDENT>traverse_checking(node1.greater,greater1,node2.greater,greater2)<EOL><DEDENT><DEDENT>def traverse_no_checking(node1, node2):<EOL><INDENT>if isinstance(node1, KDTree.leafnode):<EOL><INDENT>if isinstance(node2, KDTree.leafnode):<EOL><INDENT>if id(node1) == id(node2):<EOL><INDENT>for i in node1.idx:<EOL><INDENT>for j in node2.idx:<EOL><INDENT>if i < j:<EOL><INDENT>results.add((i,j))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>for i in node1.idx:<EOL><INDENT>for j in node2.idx:<EOL><INDENT>if i < j:<EOL><INDENT>results.add((i,j))<EOL><DEDENT>elif j < i:<EOL><INDENT>results.add((j,i))<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>traverse_no_checking(node1, node2.less)<EOL>traverse_no_checking(node1, node2.greater)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if id(node1) == id(node2):<EOL><INDENT>traverse_no_checking(node1.less, node2.less)<EOL>traverse_no_checking(node1.less, node2.greater)<EOL>traverse_no_checking(node1.greater, node2.greater)<EOL><DEDENT>else:<EOL><INDENT>traverse_no_checking(node1.less, node2)<EOL>traverse_no_checking(node1.greater, node2)<EOL><DEDENT><DEDENT><DEDENT>traverse_checking(self.tree, Rectangle(self.maxes, self.mins),<EOL>self.tree, Rectangle(self.maxes, self.mins))<EOL>return results<EOL>

Find all pairs of points within a distance.

Parameters
----------
r : positive float
    The maximum distance.
p : float, optional
    Which Minkowski norm to use.  `p` has to meet the condition
    ``1 <= p <= infinity``.
eps : 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)``.  `eps` has to be non-negative.

Returns
-------
results : set
    Set of pairs ``(i,j)``, with ``i < j``, for which the corresponding
    positions are close.


def count_neighbors(self, other, r, p=<NUM_LIT>):

def traverse(node1, rect1, node2, rect2, idx):<EOL><INDENT>min_r = rect1.min_distance_rectangle(rect2,p)<EOL>max_r = rect1.max_distance_rectangle(rect2,p)<EOL>c_greater = r[idx] > max_r<EOL>result[idx[c_greater]] += node1.children*node2.children<EOL>idx = idx[(min_r <= r[idx]) & (r[idx] <= max_r)]<EOL>if len(idx) == <NUM_LIT:0>:<EOL><INDENT>return<EOL><DEDENT>if isinstance(node1,KDTree.leafnode):<EOL><INDENT>if isinstance(node2,KDTree.leafnode):<EOL><INDENT>ds = minkowski_distance(self.data[node1.idx][:,np.newaxis,:],<EOL>other.data[node2.idx][np.newaxis,:,:],<EOL>p).ravel()<EOL>ds.sort()<EOL>result[idx] += np.searchsorted(ds,r[idx],side='<STR_LIT:right>')<EOL><DEDENT>else:<EOL><INDENT>less, greater = rect2.split(node2.split_dim, node2.split)<EOL>traverse(node1, rect1, node2.less, less, idx)<EOL>traverse(node1, rect1, node2.greater, greater, idx)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if isinstance(node2,KDTree.leafnode):<EOL><INDENT>less, greater = rect1.split(node1.split_dim, node1.split)<EOL>traverse(node1.less, less, node2, rect2, idx)<EOL>traverse(node1.greater, greater, node2, rect2, idx)<EOL><DEDENT>else:<EOL><INDENT>less1, greater1 = rect1.split(node1.split_dim, node1.split)<EOL>less2, greater2 = rect2.split(node2.split_dim, node2.split)<EOL>traverse(node1.less,less1,node2.less,less2,idx)<EOL>traverse(node1.less,less1,node2.greater,greater2,idx)<EOL>traverse(node1.greater,greater1,node2.less,less2,idx)<EOL>traverse(node1.greater,greater1,node2.greater,greater2,idx)<EOL><DEDENT><DEDENT><DEDENT>R1 = Rectangle(self.maxes, self.mins)<EOL>R2 = Rectangle(other.maxes, other.mins)<EOL>if np.shape(r) == ():<EOL><INDENT>r = np.array([r])<EOL>result = np.zeros(<NUM_LIT:1>,dtype=int)<EOL>traverse(self.tree, R1, other.tree, R2, np.arange(<NUM_LIT:1>))<EOL>return result[<NUM_LIT:0>]<EOL><DEDENT>elif len(np.shape(r)) == <NUM_LIT:1>:<EOL><INDENT>r = np.asarray(r)<EOL>n, = r.shape<EOL>result = np.zeros(n,dtype=int)<EOL>traverse(self.tree, R1, other.tree, R2, np.arange(n))<EOL>return result<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>

Count how many nearby pairs can be formed.

Count the number of pairs (x1,x2) can be formed, with x1 drawn
from self and x2 drawn from `other`, and where
``distance(x1, x2, p) <= r``.
This is the "two-point correlation" described in Gray and Moore 2000,
"N-body problems in statistical learning", and the code here is based
on their algorithm.

Parameters
----------
other : KDTree instance
    The other tree to draw points from.
r : float or one-dimensional array of floats
    The radius to produce a count for. Multiple radii are searched with
    a single tree traversal.
p : float, 1<=p<=infinity
    Which Minkowski p-norm to use

Returns
-------
result : int or 1-D array of ints
    The number of pairs. Note that this is internally stored in a numpy
    int, and so may overflow if very large (2e9).


def sparse_distance_matrix(self, other, max_distance, p=<NUM_LIT>):

result = scipy.sparse.dok_matrix((self.n,other.n))<EOL>def traverse(node1, rect1, node2, rect2):<EOL><INDENT>if rect1.min_distance_rectangle(rect2, p) > max_distance:<EOL><INDENT>return<EOL><DEDENT>elif isinstance(node1, KDTree.leafnode):<EOL><INDENT>if isinstance(node2, KDTree.leafnode):<EOL><INDENT>for i in node1.idx:<EOL><INDENT>for j in node2.idx:<EOL><INDENT>d = minkowski_distance(self.data[i],other.data[j],p)<EOL>if d <= max_distance:<EOL><INDENT>result[i,j] = d<EOL><DEDENT><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>less, greater = rect2.split(node2.split_dim, node2.split)<EOL>traverse(node1,rect1,node2.less,less)<EOL>traverse(node1,rect1,node2.greater,greater)<EOL><DEDENT><DEDENT>elif isinstance(node2, KDTree.leafnode):<EOL><INDENT>less, greater = rect1.split(node1.split_dim, node1.split)<EOL>traverse(node1.less,less,node2,rect2)<EOL>traverse(node1.greater,greater,node2,rect2)<EOL><DEDENT>else:<EOL><INDENT>less1, greater1 = rect1.split(node1.split_dim, node1.split)<EOL>less2, greater2 = rect2.split(node2.split_dim, node2.split)<EOL>traverse(node1.less,less1,node2.less,less2)<EOL>traverse(node1.less,less1,node2.greater,greater2)<EOL>traverse(node1.greater,greater1,node2.less,less2)<EOL>traverse(node1.greater,greater1,node2.greater,greater2)<EOL><DEDENT><DEDENT>traverse(self.tree, Rectangle(self.maxes, self.mins),<EOL>other.tree, Rectangle(other.maxes, other.mins))<EOL>return result<EOL>

Compute a sparse distance matrix

Computes a distance matrix between two KDTrees, leaving as zero
any distance greater than max_distance.

Parameters
----------
other : KDTree

max_distance : positive float

p : float, optional

Returns
-------
result : dok_matrix
    Sparse matrix representing the results in "dictionary of keys" format.


return DbfilenameShelf(filename, flag)<EOL>

Open a persistent dictionary for reading and writing.

    Argument is the filename for the dbm database.
    See the module's __doc__ string for an overview of the interface.


print('<STR_LIT>', end='<STR_LIT:U+0020>')<EOL>a = []<EOL>t1 = time.time()<EOL>list_append_c(a,Na)<EOL>t2 = time.time()<EOL>print('<STR_LIT>', t2 - t1, '<STR_LIT>')<EOL>a = []<EOL>t1 = time.time()<EOL>list_append_c(a,Na)<EOL>t2 = time.time()<EOL>print('<STR_LIT>', t2 - t1)<EOL>a = []<EOL>t1 = time.time()<EOL>list_append_scxx(a,Na)<EOL>t2 = time.time()<EOL>print('<STR_LIT>', t2 - t1)<EOL>a = []<EOL>t1 = time.time()<EOL>list_append_c(a,Na)<EOL>t2 = time.time()<EOL>print('<STR_LIT>', t2 - t1)<EOL>

Compare the list append method from scxx to using the Python API
        directly.


print('<STR_LIT>', end='<STR_LIT:U+0020>')<EOL>a = [<NUM_LIT:0>] * N<EOL>b = [<NUM_LIT:1>] * N<EOL>t1 = time.time()<EOL>list_copy_c(a,b)<EOL>t2 = time.time()<EOL>print('<STR_LIT>', t2 - t1, '<STR_LIT>')<EOL>a = [<NUM_LIT:0>] * N<EOL>b = [<NUM_LIT:1>] * N<EOL>t1 = time.time()<EOL>list_copy_c(a,b)<EOL>t2 = time.time()<EOL>print('<STR_LIT>', t2 - t1)<EOL>a = [<NUM_LIT:0>] * N<EOL>b = [<NUM_LIT:1>] * N<EOL>t1 = time.time()<EOL>list_copy_scxx(a,b)<EOL>t2 = time.time()<EOL>print('<STR_LIT>', t2 - t1)<EOL>a = [<NUM_LIT:0>] * N<EOL>b = [<NUM_LIT:1>] * N<EOL>t1 = time.time()<EOL>list_copy_c(a,b)<EOL>t2 = time.time()<EOL>print('<STR_LIT>', t2 - t1)<EOL>


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


t.slow = True<EOL>if ('<STR_LIT>' in os.environ and<EOL>bool(os.environ['<STR_LIT>'])):<EOL><INDENT>t.__test__ = True<EOL><DEDENT>else:<EOL><INDENT>t.__test__ = False<EOL><DEDENT>return t<EOL>

Replacement for numpy.testing.dec.slow for weave.


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


cat_dir = catalog.default_dir()<EOL>for file in os.listdir(backup_dir):<EOL><INDENT>file = os.path.join(backup_dir,file)<EOL>d,f = os.path.split(file)<EOL>dst_file = os.path.join(cat_dir, f)<EOL>if os.path.exists(dst_file):<EOL><INDENT>os.remove(dst_file)<EOL><DEDENT>move_file(file,dst_file)<EOL><DEDENT>os.rmdir(backup_dir)<EOL>


d = catalog.default_dir()<EOL>for i in range(<NUM_LIT>):<EOL><INDENT>new_d = os.path.join(d,tempfile.gettempprefix()[<NUM_LIT:1>:-<NUM_LIT:1>]+repr(i))<EOL>if not os.path.exists(new_d):<EOL><INDENT>os.mkdir(new_d)<EOL>break<EOL><DEDENT><DEDENT>return new_d<EOL>

Create a sub directory in the temp directory for use in tests


files = map(lambda x,d=d: os.path.join(d,x),os.listdir(d))<EOL>for i in files:<EOL><INDENT>try:<EOL><INDENT>if os.path.isdir(i):<EOL><INDENT>cleanup_temp_dir(i)<EOL><DEDENT>else:<EOL><INDENT>os.remove(i)<EOL><DEDENT><DEDENT>except OSError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>try:<EOL><INDENT>os.rmdir(d)<EOL><DEDENT>except OSError:<EOL><INDENT>pass<EOL><DEDENT>

Remove a directory created by empty_temp_dir().

    This should probably catch some errors.


from os.path import exists, isfile, isdir, basename, dirname<EOL>import errno<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % (src, dst))<EOL><DEDENT>if dry_run:<EOL><INDENT>return dst<EOL><DEDENT>if not isfile(src):<EOL><INDENT>raise DistutilsFileError("<STR_LIT>" % src)<EOL><DEDENT>if isdir(dst):<EOL><INDENT>dst = os.path.join(dst, basename(src))<EOL><DEDENT>elif exists(dst):<EOL><INDENT>raise DistutilsFileError("<STR_LIT>"<EOL>"<STR_LIT>" % (src, dst))<EOL><DEDENT>if not isdir(dirname(dst)):<EOL><INDENT>raise DistutilsFileError("<STR_LIT>"<EOL>"<STR_LIT>" % (src, dst))<EOL><DEDENT>copy_it = <NUM_LIT:0><EOL>try:<EOL><INDENT>os.rename(src, dst)<EOL><DEDENT>except os.error as xxx_todo_changeme1:<EOL><INDENT>(num, msg) = xxx_todo_changeme1.args<EOL>if num == errno.EXDEV:<EOL><INDENT>copy_it = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>raise DistutilsFileError("<STR_LIT>" %<EOL>(src, dst, msg))<EOL><DEDENT><DEDENT>if copy_it:<EOL><INDENT>distutils.file_util.copy_file(src, dst)<EOL>try:<EOL><INDENT>os.unlink(src)<EOL><DEDENT>except os.error as xxx_todo_changeme:<EOL><INDENT>(num, msg) = xxx_todo_changeme.args<EOL>try:<EOL><INDENT>os.unlink(dst)<EOL><DEDENT>except os.error:<EOL><INDENT>pass<EOL><DEDENT>raise DistutilsFileError("<STR_LIT>"<EOL>"<STR_LIT>" % (src, dst, src, msg))<EOL><DEDENT><DEDENT>return dst<EOL>

Move a file 'src' to 'dst'.  If 'dst' is a directory, the file will
    be moved into it with the same name; otherwise, 'src' is just renamed
    to 'dst'.  Return the new full name of the file.

    Handles cross-device moves on Unix using 'copy_file()'.  What about
    other systems???


<EOL>distutils.sysconfig.get_config_vars()<EOL>if '<STR_LIT>' in distutils.sysconfig._config_vars:<EOL><INDENT>flags = distutils.sysconfig._config_vars['<STR_LIT>']<EOL>flags = flags.replace('<STR_LIT>','<STR_LIT>')<EOL>distutils.sysconfig._config_vars['<STR_LIT>'] = flags<EOL><DEDENT>module_dir,cpp_name = os.path.split(os.path.abspath(module_path))<EOL>module_name,ext = os.path.splitext(cpp_name)<EOL>sources = kw.get('<STR_LIT>',[])<EOL>kw['<STR_LIT>'] = [module_path] + sources<EOL>if '<STR_LIT>' in os.environ:<EOL><INDENT>path_string = os.environ['<STR_LIT>']<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>extra_include_dirs = path_string.split('<STR_LIT:;>')<EOL><DEDENT>else:<EOL><INDENT>extra_include_dirs = path_string.split('<STR_LIT::>')<EOL><DEDENT>include_dirs = kw.get('<STR_LIT>',[])<EOL>kw['<STR_LIT>'] = include_dirs + extra_include_dirs<EOL><DEDENT>platform = sys.platform<EOL>version = sys.version.lower()<EOL>if platform[:<NUM_LIT:5>] == '<STR_LIT>' and '<STR_LIT>' in version:<EOL><INDENT>extra_link_args = kw.get('<STR_LIT>',[])<EOL>kw['<STR_LIT>'] = ['<STR_LIT>'] + extra_link_args<EOL><DEDENT>ext = Extension(module_name, **kw)<EOL>return ext<EOL>

Create an Extension that can be buil by setup.py

        See build_extension for information on keyword arguments.


def build_extension(module_path,compiler_name='<STR_LIT>',build_dir=None,<EOL>temp_dir=None, verbose=<NUM_LIT:0>, **kw):

success = <NUM_LIT:0><EOL>from numpy.distutils.core import setup<EOL>from numpy.distutils.log import set_verbosity<EOL>set_verbosity(-<NUM_LIT:1>)<EOL>import distutils.sysconfig<EOL>distutils.sysconfig.get_config_vars()<EOL>if '<STR_LIT>' in distutils.sysconfig._config_vars:<EOL><INDENT>flags = distutils.sysconfig._config_vars['<STR_LIT>']<EOL>flags = flags.replace('<STR_LIT>','<STR_LIT>')<EOL>distutils.sysconfig._config_vars['<STR_LIT>'] = flags<EOL><DEDENT>module_dir,cpp_name = os.path.split(os.path.abspath(module_path))<EOL>module_name,ext = os.path.splitext(cpp_name)<EOL>temp_dir = configure_temp_dir(temp_dir)<EOL>build_dir = configure_build_dir(build_dir or module_dir)<EOL>compiler_dir = platform_info.get_compiler_dir(compiler_name)<EOL>temp_dir = os.path.join(temp_dir,compiler_dir)<EOL>distutils.dir_util.mkpath(temp_dir)<EOL>compiler_name = choose_compiler(compiler_name)<EOL>configure_sys_argv(compiler_name,temp_dir,build_dir)<EOL>try:<EOL><INDENT>if verbose == <NUM_LIT:1>:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>if verbose > <NUM_LIT:1>:<EOL><INDENT>verb = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>verb = <NUM_LIT:0><EOL><DEDENT>t1 = time.time()<EOL>ext = create_extension(module_path,**kw)<EOL>builtin = sys.modules['<STR_LIT>']<EOL>old_SysExit = builtin.__dict__['<STR_LIT>']<EOL>builtin.__dict__['<STR_LIT>'] = CompileError<EOL>oldcwd = os.path.abspath(os.getcwd())<EOL>os.chdir(build_dir)<EOL>import copy<EOL>environ = copy.deepcopy(os.environ)<EOL>try:<EOL><INDENT>setup(name=module_name, ext_modules=[ext],verbose=verb)<EOL><DEDENT>finally:<EOL><INDENT>os.environ = environ<EOL>builtin.__dict__['<STR_LIT>'] = old_SysExit<EOL>os.chdir(oldcwd)<EOL><DEDENT>t2 = time.time()<EOL>if verbose == <NUM_LIT:1>:<EOL><INDENT>print('<STR_LIT>', t2 - t1)<EOL><DEDENT>success = <NUM_LIT:1><EOL>configure_python_path(build_dir)<EOL><DEDENT>except SyntaxError:  <EOL><INDENT>success = <NUM_LIT:0><EOL><DEDENT>restore_sys_argv()<EOL>return success<EOL>

Build the file given by module_path into a Python extension module.

        build_extensions uses distutils to build Python extension modules.
        kw arguments not used are passed on to the distutils extension
        module.  Directory settings can handle absoulte settings, but don't
        currently expand '~' or environment variables.

        module_path   -- the full path name to the c file to compile.
                         Something like:  /full/path/name/module_name.c
                         The name of the c/c++ file should be the same as the
                         name of the module (i.e. the initmodule() routine)
        compiler_name -- The name of the compiler to use.  On Windows if it
                         isn't given, MSVC is used if it exists (is found).
                         gcc is used as a second choice. If neither are found,
                         the default distutils compiler is used. Acceptable
                         names are 'gcc', 'msvc' or any of the compiler names
                         shown by distutils.ccompiler.show_compilers()
        build_dir     -- The location where the resulting extension module
                         should be placed. This location must be writable.  If
                         it isn't, several default locations are tried.  If the
                         build_dir is not in the current python path, a warning
                         is emitted, and it is added to the end of the path.
                         build_dir defaults to the current directory.
        temp_dir      -- The location where temporary files (*.o or *.obj)
                         from the build are placed. This location must be
                         writable.  If it isn't, several default locations are
                         tried.  It defaults to tempfile.gettempdir()
        verbose       -- 0, 1, or 2.  0 is as quiet as possible. 1 prints
                         minimal information.  2 is noisy.
        **kw          -- keyword arguments. These are passed on to the
                         distutils extension module.  Most of the keywords
                         are listed below.

        Distutils keywords.  These are cut and pasted from Greg Ward's
        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 (eg. object files not implied
          by 'sources', static library 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.


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


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>


result = <NUM_LIT:0><EOL>try:<EOL><INDENT>p = subprocess.Popen(['<STR_LIT>'], shell=True, stdout=subprocess.PIPE,<EOL>stderr=subprocess.STDOUT)<EOL>str_result = p.stdout.read()<EOL>if '<STR_LIT>' in str_result:<EOL><INDENT>result = <NUM_LIT:1><EOL><DEDENT><DEDENT>except:<EOL><INDENT>import distutils.msvccompiler<EOL>try:<EOL><INDENT>cc = distutils.msvccompiler.MSVCCompiler()<EOL>cc.initialize()<EOL>p = subprocess.Popen([cc.cc])<EOL>result = <NUM_LIT:1><EOL><DEDENT>except distutils.errors.DistutilsPlatformError:<EOL><INDENT>pass<EOL><DEDENT>except WindowsError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>return result<EOL>

Determine whether MSVC is available on the machine.


subscript_lists = []<EOL>if isinstance(ast_list, list):<EOL><INDENT>found,data = match(indexed_array_pattern,ast_list)<EOL>if found:<EOL><INDENT>subscript_lists.append(data)<EOL><DEDENT>for item in ast_list:<EOL><INDENT>if isinstance(item, list):<EOL><INDENT>subscript_lists.extend(harvest_subscript_dicts(item))<EOL><DEDENT><DEDENT><DEDENT>return subscript_lists<EOL>


all_dicts = harvest_subscript_dicts(ast_list)<EOL>for subscript_dict in all_dicts:<EOL><INDENT>transform_subscript_list(subscript_dict)<EOL><DEDENT>

Walk through an ast_list converting all x:y:z subscripts
        to slice(x,y,z) subscripts.


compiler_type = choose_compiler(compiler_name)<EOL>configure_sys_argv(compiler_type)<EOL>dist = dummy_dist()<EOL>compiler_obj = create_compiler_instance(dist)<EOL>exe_name = compiler_exe_name(compiler_obj)<EOL>exe_path = compiler_exe_path(exe_name)<EOL>if not exe_path:<EOL><INDENT>raise ValueError("<STR_LIT>" % compiler_name)<EOL><DEDENT>chk_sum = check_sum(exe_path)<EOL>restore_sys_argv()<EOL>return '<STR_LIT>'+chk_sum<EOL>

Try to figure out the compiler directory based on the
        input compiler name.  This is fragile and really should
        be done at the distutils level inside the compiler.  I
        think it is only useful on windows at the moment.


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>


result = <NUM_LIT:0><EOL>cmd = '<STR_LIT>' % name<EOL>try:<EOL><INDENT>p = subprocess.Popen([str(name), '<STR_LIT>'], shell=True,<EOL>stdout=subprocess.PIPE, stderr=subprocess.STDOUT)<EOL>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(cmd)<EOL><DEDENT>return result<EOL>

Test to make sure gcc is found

        Does this return correct value on win98???


result = <NUM_LIT:0><EOL>try:<EOL><INDENT>p = subprocess.Popen(['<STR_LIT>'], shell=True,<EOL>stdout=subprocess.PIPE, stderr=subprocess.STDOUT)<EOL>str_result = p.stdout.read()<EOL>if '<STR_LIT>' in str_result:<EOL><INDENT>result = <NUM_LIT:1><EOL><DEDENT><DEDENT>except:<EOL><INDENT>import distutils.msvccompiler<EOL>try:<EOL><INDENT>version = distutils.msvccompiler.get_devstudio_versions()<EOL><DEDENT>except:<EOL><INDENT>version = distutils.msvccompiler.get_build_version()<EOL><DEDENT>if version:<EOL><INDENT>result = <NUM_LIT:1><EOL><DEDENT><DEDENT>return result<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.


versions = []<EOL>for key in sys.modules:<EOL><INDENT>idx = key.find('<STR_LIT>')<EOL>if idx > -<NUM_LIT:1>:<EOL><INDENT>ver = int(key[idx+<NUM_LIT>:])<EOL>if ver not in versions:<EOL><INDENT>versions.append(ver)<EOL><DEDENT><DEDENT><DEDENT>nver = len(versions)<EOL>if nver == <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>elif nver == <NUM_LIT:1>:<EOL><INDENT>return versions[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>")<EOL>print("<STR_LIT>")<EOL>return max(versions)<EOL><DEDENT>

This method tries to deduce the SWIG runtime version.  If
        the SWIG runtime layout changes, the `SWIG_TypeQuery` function
        will not work properly.


common_base_converter.init_info(self)<EOL>self.type_name = self.class_name<EOL>self.c_type = self.class_name + "<STR_LIT:*>"<EOL>self.return_type = self.class_name + "<STR_LIT:*>"<EOL>self.to_c_return = None  <EOL>self.check_func = None  <EOL>if self.pycobj == <NUM_LIT:1>:<EOL><INDENT>self.define_macros.append(("<STR_LIT>", None))<EOL>self.define_macros.append(("<STR_LIT>", None))<EOL><DEDENT>elif self.pycobj == <NUM_LIT:2>:<EOL><INDENT>self.define_macros.append(("<STR_LIT>", None))<EOL><DEDENT>if self.runtime_version is None:<EOL><INDENT>self.runtime_version = self._get_swig_runtime_version()<EOL><DEDENT>rv = self.runtime_version<EOL>if rv == <NUM_LIT:0>:<EOL><INDENT>if runtime:<EOL><INDENT>self.define_macros.append(("<STR_LIT>", None))<EOL><DEDENT>self.support_code.append(swigptr2.swigptr2_code_v0)<EOL><DEDENT>elif rv == <NUM_LIT:1>:<EOL><INDENT>self.support_code.append(swigptr2.swigptr2_code_v1)<EOL><DEDENT>elif rv == <NUM_LIT:2>:<EOL><INDENT>self.support_code.append(swigptr2.swigptr2_code_v2)<EOL><DEDENT>elif rv == <NUM_LIT:3>:<EOL><INDENT>self.support_code.append(swigptr2.swigptr2_code_v3)<EOL><DEDENT>else:<EOL><INDENT>raise AssertionError("<STR_LIT>" % rv)<EOL><DEDENT>self.support_code.append(swig2_common_code)<EOL>

Keyword arguments:

          runtime -- If false (default), the user does not need to
          link to the swig runtime (libswipy).  Newer versions of SWIG
          (>=1.3.23) do not need to build a SWIG runtime library at
          all.  In these versions of SWIG the swig_type_info is stored
          in a common module.  swig_type_info stores the type
          information and the type converters to cast pointers
          correctly.

          With earlier versions of SWIG (<1.3.22) one has to either
          link the weave module with a SWIG runtime library
          (libswigpy) in order to get the swig_type_info.  Thus, if
          `runtime` is True, the user must link to the swipy runtime
          library and in this case type checking will be performed.
          With these versions of SWIG, if runtime is `False`, no type
          checking is done.


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 self._get_swig_type(value):<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>

This is a generic type matcher for SWIG-1.3 objects.  For
        specific instances, override this method.  The method also
        handles cases where SWIG uses a PyCObject for the `this`
        attribute and not a string.


<EOL>swig_ob_type = self._get_swig_type(value)<EOL>pycobj = <NUM_LIT:0><EOL>if swig_ob_type == '<STR_LIT:str>':<EOL><INDENT>class_name = value.this.split('<STR_LIT:_>')[-<NUM_LIT:1>]<EOL><DEDENT>elif swig_ob_type == '<STR_LIT>':<EOL><INDENT>pycobj = <NUM_LIT:1><EOL><DEDENT>elif swig_ob_type == '<STR_LIT>':<EOL><INDENT>pycobj = <NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>raise AssertionError("<STR_LIT>" % value)<EOL><DEDENT>if pycobj:<EOL><INDENT>class_name = value.__class__.__name__<EOL>if class_name[-<NUM_LIT:3>:] == '<STR_LIT>':<EOL><INDENT>class_name = class_name[:-<NUM_LIT:3>]<EOL><DEDENT><DEDENT>new_spec = self.__class__(class_name, pycobj, self.runtime_version)<EOL>new_spec.name = name<EOL>return new_spec<EOL>

This returns a generic type converter for SWIG-1.3
        objects.  For specific instances, override this function if
        necessary.


<EOL>ast_seq = copy.deepcopy(ast_seq)<EOL>slice_handler.transform_slices(ast_seq)<EOL>expr = ast_tools.ast_to_string(ast_seq)<EOL>expr = expr.replace('<STR_LIT>', '<STR_LIT>')<EOL>expr = expr.replace('<STR_LIT>', '<STR_LIT>')<EOL>expr = expr.replace('<STR_LIT:[>','<STR_LIT:(>')<EOL>expr = expr.replace('<STR_LIT:]>', '<STR_LIT:)>')<EOL>expr = expr.replace('<STR_LIT>', '<STR_LIT:1>')<EOL>return expr + '<STR_LIT>'<EOL>

Convert an ast_sequence to a blitz expression.


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


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


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


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


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.


mod = ext_tools.ext_module('<STR_LIT>')<EOL>a = <NUM_LIT:1>  <EOL>fib_code = """<STR_LIT>"""<EOL>ext_code = """<STR_LIT>"""<EOL>fib = ext_tools.ext_function('<STR_LIT>',ext_code,['<STR_LIT:a>'])<EOL>fib.customize.add_support_code(fib_code)<EOL>mod.add_function(fib)<EOL>fib_code = """<STR_LIT>"""<EOL>ext_code = """<STR_LIT>"""<EOL>fib = ext_tools.ext_function('<STR_LIT>',ext_code,['<STR_LIT:a>'])<EOL>fib.customize.add_support_code(fib_code)<EOL>mod.add_function(fib)<EOL>mod.compile()<EOL>

Builds an extension module with fibonacci calculators.


<EOL>obs = asarray(obs)<EOL>code_book = asarray(code_book)<EOL>obs_sh = shape(obs)<EOL>code_book_sh = shape(code_book)<EOL>assert(len(obs_sh) == <NUM_LIT:2> and len(code_book_sh) == <NUM_LIT:2>)<EOL>assert(obs_sh[<NUM_LIT:1>] == code_book_sh[<NUM_LIT:1>])<EOL>assert(obs.typecode() == code_book.typecode())<EOL>type = c_spec.num_to_c_types[obs.typecode()]<EOL>ar_type = '<STR_LIT>'<EOL>code = """<STR_LIT>""" % locals()<EOL>code, distortion = inline_tools.inline(code,['<STR_LIT>','<STR_LIT>'],<EOL>type_converters=blitz_type_converters,<EOL>compiler='<STR_LIT>',<EOL>verbose=<NUM_LIT:1>)<EOL>return code, distortion<EOL>

doesn't use blitz (except in conversion)
        ALSO DOES NOT HANDLE STRIDED ARRAYS CORRECTLY


<EOL>obs = asarray(obs)<EOL>code_book = asarray(code_book)<EOL>obs_sh = shape(obs)<EOL>code_book_sh = shape(code_book)<EOL>assert(len(obs_sh) == <NUM_LIT:2> and len(code_book_sh) == <NUM_LIT:2>)<EOL>assert(obs_sh[<NUM_LIT:1>] == code_book_sh[<NUM_LIT:1>])<EOL>assert(obs.typecode() == code_book.typecode())<EOL>type = c_spec.num_to_c_types[obs.typecode()]<EOL>code = """<STR_LIT>""" % locals()<EOL>import ext_tools<EOL>code, distortion = inline_tools.inline(code,['<STR_LIT>','<STR_LIT>'])<EOL>return code, distortion<EOL>

Uses standard array conversion completely bi-passing blitz.
        THIS DOES NOT HANDLE STRIDED ARRAYS CORRECTLY


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>


mod = ext_tools.ext_module('<STR_LIT>')<EOL>a = <NUM_LIT:1><EOL>ext_code = "<STR_LIT>"<EOL>func = ext_tools.ext_function('<STR_LIT>',ext_code,['<STR_LIT:a>'])<EOL>mod.add_function(func)<EOL>ext_code = "<STR_LIT>"<EOL>func = ext_tools.ext_function('<STR_LIT>',ext_code,['<STR_LIT:a>'])<EOL>mod.add_function(func)<EOL>mod.compile()<EOL>

Build a simple extension with functions that increment numbers.
        The extension will be built in the local directory.


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


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

Prints the given 3D array by using blitz converters which
    provides a numpy-like syntax for accessing the numpy data.

    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, j, k).


assert(type(func) in [FunctionType,MethodType,type(len)])<EOL>code = """<STR_LIT>"""<EOL>return inline_tools.inline(code,['<STR_LIT>','<STR_LIT>'])<EOL>

Uses CXX C code to implement a simple map-like function.
        It does not provide any error checking.


Uses Python API more than CXX to implement a simple map-like function.
        It does not provide any error checking.


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.


new_list = []<EOL>for item in ast_tuple:<EOL><INDENT>if isinstance(item, int):<EOL><INDENT>new_list.append(int_to_symbol(item))<EOL><DEDENT>elif issequence(item):<EOL><INDENT>new_list.append(translate_symbols(item))<EOL><DEDENT>else:<EOL><INDENT>new_list.append(item)<EOL><DEDENT><DEDENT>if isinstance(ast_tuple, tuple):<EOL><INDENT>return tuple(new_list)<EOL><DEDENT>else:<EOL><INDENT>return new_list<EOL><DEDENT>

Translate numeric grammar symbols in an ast_tuple descriptive names.

        This simply traverses the tree converting any integer value to values
        found in symbol.sym_name or token.tok_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.
    *


<EOL>if isinstance(expr_string, str):<EOL><INDENT>ast = parser.expr(expr_string).totuple()[<NUM_LIT:1>][<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>ast = parser.expr(repr(expr_string)).totuple()[<NUM_LIT:1>][<NUM_LIT:1>]<EOL><DEDENT>return ast<EOL>

Build an ast for an atom from the given expr string.

        If expr_string is not a string, it is converted to a string
        before parsing to an ast_tuple.


found,data = <NUM_LIT:0>,{}<EOL>if not isinstance(pattern_list, list):<EOL><INDENT>pattern_list = [pattern_list]<EOL><DEDENT>for pattern in pattern_list:<EOL><INDENT>found,data = match(pattern,ast_tuple)<EOL>if found:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if not found:<EOL><INDENT>for item in ast_tuple:<EOL><INDENT>if issequence(item):<EOL><INDENT>found, data = find_first_pattern(item,pattern_list)<EOL><DEDENT>if found:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>return found,data<EOL>

* Find the first occurrence of a pattern one of a list of patterns
        in ast_tuple.

        Used for testing at the moment.

        ast_tuple    -- tuple or list created by ast.totuple() or ast.tolist().
        pattern_list -- A single pattern or list of patterns to search
                        for in the ast_tuple.  If a single pattern is
                        used, it MUST BE A IN A TUPLE format.
        Returns:
            found -- true/false indicating whether pattern was found
            data  -- dictionary of data from first matching pattern in tree.
                     (see match function by Jeremy Hylton).
    *


output = []<EOL>for item in lst:<EOL><INDENT>if item not in reserved_names:<EOL><INDENT>output.append(item)<EOL><DEDENT><DEDENT>return output<EOL>

These are functions names -- don't create variables for them
        There is a more reobust approach, but this ought to work pretty
        well.


variables = []<EOL>if issequence(ast_list):<EOL><INDENT>found,data = match(name_pattern,ast_list)<EOL>if found:<EOL><INDENT>variables.append(data['<STR_LIT>'])<EOL><DEDENT>for item in ast_list:<EOL><INDENT>if issequence(item):<EOL><INDENT>variables.extend(harvest_variables(item))<EOL><DEDENT><DEDENT><DEDENT>variables = remove_duplicates(variables)<EOL>variables = remove_reserved_names(variables)<EOL>return variables<EOL>

Retrieve all the variables that need to be defined.


if vars is None:<EOL><INDENT>vars = {}<EOL><DEDENT>if isinstance(pattern, list):       <EOL><INDENT>vars[pattern[<NUM_LIT:0>]] = data<EOL>return <NUM_LIT:1>, vars<EOL><DEDENT>if not isinstance(pattern, tuple):<EOL><INDENT>return (pattern == data), vars<EOL><DEDENT>if len(data) != len(pattern):<EOL><INDENT>return <NUM_LIT:0>, vars<EOL><DEDENT>for pattern, data in zip(pattern, data):<EOL><INDENT>same, vars = match(pattern, data, vars)<EOL>if not same:<EOL><INDENT>break<EOL><DEDENT><DEDENT>return same, vars<EOL>

match `data' to `pattern', with variable extraction.

    pattern
        Pattern to match against, possibly containing variables.

    data
        Data to be checked and against which variables are extracted.

    vars
        Dictionary of variables which have already been found.  If not
        provided, an empty dictionary is created.

    The `pattern' value may contain variables of the form ['varname'] which
    are allowed to match anything.  The value that is matched is returned as
    part of a dictionary which maps 'varname' to the matched value.  'varname'
    is not required to be a string object, but using strings makes patterns
    and the code which uses them more readable.

    This function returns two values: a boolean indicating whether a match
    was found and a dictionary mapping variable names to their associated
    values.

    From the Demo/Parser/example.py file


if not issequence(ast_tuple):<EOL><INDENT>return ast_tuple<EOL><DEDENT>new_list = []<EOL>for item in ast_tuple:<EOL><INDENT>new_list.append(tuples_to_lists(item))<EOL><DEDENT>return new_list<EOL>

Convert an ast object tree in tuple form to list form.


import inspect<EOL>value = inspect.getmodule(object)<EOL>if value is None:<EOL><INDENT>for name,mod in sys.modules.items():<EOL><INDENT>try:<EOL><INDENT>if mod and object in mod.__dict__.values():<EOL><INDENT>value = mod<EOL>if str(mod) not in '<STR_LIT>':<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>except (TypeError, KeyError, ImportError):<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>return value<EOL>

Discover the name of the module where object was defined.

        This is an augmented version of inspect.getmodule that can discover
        the parent module for extension functions.