def nanvar(a, axis=None, dtype=None, out=None, ddof=<NUM_LIT:0>, keepdims=False):

arr, mask = _replace_nan(a, <NUM_LIT:0>)<EOL>if mask is None:<EOL><INDENT>return np.var(arr, axis=axis, dtype=dtype, out=out, ddof=ddof,<EOL>keepdims=keepdims)<EOL><DEDENT>if dtype is not None:<EOL><INDENT>dtype = np.dtype(dtype)<EOL><DEDENT>if dtype is not None and not issubclass(dtype.type, np.inexact):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if out is not None and not issubclass(out.dtype.type, np.inexact):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>with warnings.catch_warnings():<EOL><INDENT>warnings.simplefilter('<STR_LIT:ignore>')<EOL>cnt = np.sum(~mask, axis=axis, dtype=np.intp, keepdims=True)<EOL>avg = np.sum(arr, axis=axis, dtype=dtype, keepdims=True)<EOL>avg = _divide_by_count(avg, cnt)<EOL>arr -= avg<EOL>arr = _copyto(arr, <NUM_LIT:0>, mask)<EOL>if issubclass(arr.dtype.type, np.complexfloating):<EOL><INDENT>sqr = np.multiply(arr, arr.conj(), out=arr).real<EOL><DEDENT>else:<EOL><INDENT>sqr = np.multiply(arr, arr, out=arr)<EOL><DEDENT>var = np.sum(sqr, axis=axis, dtype=dtype, out=out, keepdims=keepdims)<EOL>if var.ndim < cnt.ndim:<EOL><INDENT>cnt = cnt.squeeze(axis)<EOL><DEDENT>dof = cnt - ddof<EOL>var = _divide_by_count(var, dof)<EOL><DEDENT>isbad = (dof <= <NUM_LIT:0>)<EOL>if np.any(isbad):<EOL><INDENT>warnings.warn("<STR_LIT>", RuntimeWarning)<EOL>var = _copyto(var, np.nan, isbad)<EOL><DEDENT>return var<EOL>

Compute the variance along the specified axis, while ignoring NaNs.

Returns the variance of the array elements, a measure of the spread of
a distribution.  The variance is computed for the flattened array by
default, otherwise over the specified axis.

For all-NaN slices or slices with zero degrees of freedom, NaN is
returned and a `RuntimeWarning` is raised.

.. versionadded:: 1.8.0

Parameters
----------
a : array_like
    Array containing numbers whose variance is desired.  If `a` is not an
    array, a conversion is attempted.
axis : int, optional
    Axis along which the variance is computed.  The default is to compute
    the variance of the flattened array.
dtype : data-type, optional
    Type to use in computing the variance.  For arrays of integer type
    the default is `float32`; for arrays of float types it is the same as
    the array type.
out : ndarray, optional
    Alternate output array in which to place the result.  It must have
    the same shape as the expected output, but the type is cast if
    necessary.
ddof : int, optional
    "Delta Degrees of Freedom": the divisor used in the calculation is
    ``N - ddof``, where ``N`` represents the number of non-NaN
    elements. By default `ddof` is zero.
keepdims : bool, optional
    If this is set to True, the axes which are reduced are left
    in the result as dimensions with size one. With this option,
    the result will broadcast correctly against the original `arr`.

Returns
-------
variance : ndarray, see dtype parameter above
    If `out` is None, return a new array containing the variance,
    otherwise return a reference to the output array. If ddof is >= the
    number of non-NaN elements in a slice or the slice contains only
    NaNs, then the result for that slice is NaN.

See Also
--------
std : Standard deviation
mean : Average
var : Variance while not ignoring NaNs
nanstd, nanmean
numpy.doc.ufuncs : Section "Output arguments"

Notes
-----
The variance is the average of the squared deviations from the mean,
i.e.,  ``var = mean(abs(x - x.mean())**2)``.

The mean is normally calculated as ``x.sum() / N``, where ``N = len(x)``.
If, however, `ddof` is specified, the divisor ``N - ddof`` is used
instead.  In standard statistical practice, ``ddof=1`` provides an
unbiased estimator of the variance of a hypothetical infinite
population.  ``ddof=0`` provides a maximum likelihood estimate of the
variance for normally distributed variables.

Note that for complex numbers, the absolute value is taken before
squaring, so that the result is always real and nonnegative.

For floating-point input, the variance is computed using the same
precision the input has.  Depending on the input data, this can cause
the results to be inaccurate, especially for `float32` (see example
below).  Specifying a higher-accuracy accumulator using the ``dtype``
keyword can alleviate this issue.

Examples
--------
>>> a = np.array([[1, np.nan], [3, 4]])
>>> np.var(a)
1.5555555555555554
>>> np.nanvar(a, axis=0)
array([ 1.,  0.])
>>> np.nanvar(a, axis=1)
array([ 0.,  0.25])


def _nanmedian_small(a, axis=None, out=None, overwrite_input=False):

a = np.ma.masked_array(a, np.isnan(a))<EOL>m = np.ma.median(a, axis=axis, overwrite_input=overwrite_input)<EOL>for i in range(np.count_nonzero(m.mask.ravel())):<EOL><INDENT>warnings.warn("<STR_LIT>", RuntimeWarning)<EOL><DEDENT>if out is not None:<EOL><INDENT>out[...] = m.filled(np.nan)<EOL>return out<EOL><DEDENT>return m.filled(np.nan)<EOL>

sort + indexing median, faster for small medians along multiple dimensions
due to the high overhead of apply_along_axis
see nanmedian for parameter usage


is_new = not isinstance(a, np.ndarray)<EOL>if is_new:<EOL><INDENT>a = np.array(a)<EOL><DEDENT>if not issubclass(a.dtype.type, np.inexact):<EOL><INDENT>return a, None<EOL><DEDENT>if not is_new:<EOL><INDENT>a = np.array(a, subok=True)<EOL><DEDENT>mask = np.isnan(a)<EOL>np.copyto(a, val, where=mask)<EOL>return a, mask<EOL>

If `a` is of inexact type, make a copy of `a`, replace NaNs with
the `val` value, and return the copy together with a boolean mask
marking the locations where NaNs were present. If `a` is not of
inexact type, do nothing and return `a` together with a mask of None.

Parameters
----------
a : array-like
    Input array.
val : float
    NaN values are set to val before doing the operation.

Returns
-------
y : ndarray
    If `a` is of inexact type, return a copy of `a` with the NaNs
    replaced by the fill value, otherwise return `a`.
mask: {bool, None}
    If `a` is of inexact type, return a boolean mask marking locations of
    NaNs, otherwise return None.


def nanmin(a, axis=None, out=None, keepdims=False):

if not isinstance(a, np.ndarray) or type(a) is np.ndarray:<EOL><INDENT>res = np.fmin.reduce(a, axis=axis, out=out, keepdims=keepdims)<EOL>if np.isnan(res).any():<EOL><INDENT>warnings.warn("<STR_LIT>", RuntimeWarning)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>a, mask = _replace_nan(a, +np.inf)<EOL>res = np.amin(a, axis=axis, out=out, keepdims=keepdims)<EOL>if mask is None:<EOL><INDENT>return res<EOL><DEDENT>mask = np.all(mask, axis=axis, keepdims=keepdims)<EOL>if np.any(mask):<EOL><INDENT>res = _copyto(res, np.nan, mask)<EOL>warnings.warn("<STR_LIT>", RuntimeWarning)<EOL><DEDENT><DEDENT>return res<EOL>

Return minimum of an array or minimum along an axis, ignoring any NaNs.
When all-NaN slices are encountered a ``RuntimeWarning`` is raised and
Nan is returned for that slice.

Parameters
----------
a : array_like
    Array containing numbers whose minimum is desired. If `a` is not an
    array, a conversion is attempted.
axis : int, optional
    Axis along which the minimum is computed. The default is to compute
    the minimum of the flattened array.
out : ndarray, optional
    Alternate output array in which to place the result.  The default
    is ``None``; if provided, it must have the same shape as the
    expected output, but the type will be cast if necessary.  See
    `doc.ufuncs` for details.

    .. versionadded:: 1.8.0
keepdims : bool, optional
    If this is set to True, the axes which are reduced are left in the
    result as dimensions with size one. With this option, the result
    will broadcast correctly against the original `a`.

    .. versionadded:: 1.8.0

Returns
-------
nanmin : ndarray
    An array with the same shape as `a`, with the specified axis
    removed.  If `a` is a 0-d array, or if axis is None, an ndarray
    scalar is returned.  The same dtype as `a` is returned.

See Also
--------
nanmax :
    The maximum value of an array along a given axis, ignoring any NaNs.
amin :
    The minimum value of an array along a given axis, propagating any NaNs.
fmin :
    Element-wise minimum of two arrays, ignoring any NaNs.
minimum :
    Element-wise minimum of two arrays, propagating any NaNs.
isnan :
    Shows which elements are Not a Number (NaN).
isfinite:
    Shows which elements are neither NaN nor infinity.

amax, fmax, maximum

Notes
-----
Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic
(IEEE 754). This means that Not a Number is not equivalent to infinity.
Positive infinity is treated as a very large number and negative
infinity is treated as a very small (i.e. negative) number.

If the input has a integer type the function is equivalent to np.min.

Examples
--------
>>> a = np.array([[1, 2], [3, np.nan]])
>>> np.nanmin(a)
1.0
>>> np.nanmin(a, axis=0)
array([ 1.,  2.])
>>> np.nanmin(a, axis=1)
array([ 1.,  3.])

When positive infinity and negative infinity are present:

>>> np.nanmin([1, 2, np.nan, np.inf])
1.0
>>> np.nanmin([1, 2, np.nan, np.NINF])
-inf


typecodes = [(isinstance(t, str) and t) or asarray(t).dtype.char<EOL>for t in typechars]<EOL>intersection = [t for t in typecodes if t in typeset]<EOL>if not intersection:<EOL><INDENT>return default<EOL><DEDENT>if '<STR_LIT:F>' in intersection and '<STR_LIT:d>' in intersection:<EOL><INDENT>return '<STR_LIT:D>'<EOL><DEDENT>l = []<EOL>for t in intersection:<EOL><INDENT>i = _typecodes_by_elsize.index(t)<EOL>l.append((i, t))<EOL><DEDENT>l.sort()<EOL>return l[<NUM_LIT:0>][<NUM_LIT:1>]<EOL>

Return the character for the minimum-size type to which given types can
be safely cast.

The returned type character must represent the smallest size dtype such
that an array of the returned type can handle the data from an array of
all types in `typechars` (or if `typechars` is an array, then its
dtype.char).

Parameters
----------
typechars : list of str or array_like
    If a list of strings, each string should represent a dtype.
    If array_like, the character representation of the array dtype is used.
typeset : str or list of str, optional
    The set of characters that the returned character is chosen from.
    The default set is 'GDFgdf'.
default : str, optional
    The default character, this is returned if none of the characters in
    `typechars` matches a character in `typeset`.

Returns
-------
typechar : str
    The character representing the minimum-size type that was found.

See Also
--------
dtype, sctype2char, maximum_sctype

Examples
--------
>>> np.mintypecode(['d', 'f', 'S'])
'd'
>>> x = np.array([1.1, 2-3.j])
>>> np.mintypecode(x)
'D'

>>> np.mintypecode('abceh', default='G')
'G'


return a.item()<EOL>

Convert an array of size 1 to its scalar equivalent.

Parameters
----------
a : ndarray
    Input array of size 1.

Returns
-------
out : scalar
    Scalar representation of `a`. The output data type is the same type
    returned by the input's `item` method.

Examples
--------
>>> np.asscalar(np.array([24]))
24


return asanyarray(val).imag<EOL>

Return the imaginary part of the elements of the array.

Parameters
----------
val : array_like
    Input array.

Returns
-------
out : ndarray
    Output array. If `val` is real, the type of `val` is used for the
    output.  If `val` has complex elements, the returned type is float.

See Also
--------
real, angle, real_if_close

Examples
--------
>>> a = np.array([1+2j, 3+4j, 5+6j])
>>> a.imag
array([ 2.,  4.,  6.])
>>> a.imag = np.array([8, 10, 12])
>>> a
array([ 1. +8.j,  3.+10.j,  5.+12.j])


def var(self, axis=None, dtype=None, out=None, ddof=<NUM_LIT:0>):

return N.ndarray.var(self, axis, dtype, out, ddof, keepdims=True)._collapse(axis)<EOL>

Returns the variance of the matrix elements, along the given axis.

Refer to `numpy.var` for full documentation.

See Also
--------
numpy.var

Notes
-----
This is the same as `ndarray.var`, except that where an `ndarray` would
be returned, a `matrix` object is returned instead.

Examples
--------
>>> x = np.matrix(np.arange(12).reshape((3, 4)))
>>> x
matrix([[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]])
>>> x.var()
11.916666666666666
>>> x.var(0)
matrix([[ 10.66666667,  10.66666667,  10.66666667,  10.66666667]])
>>> x.var(1)
matrix([[ 1.25],
        [ 1.25],
        [ 1.25]])


return self.transpose()<EOL>

Returns the transpose of the matrix.

Does *not* conjugate!  For the complex conjugate transpose, use ``.H``.

Parameters
----------
None

Returns
-------
ret : matrix object
    The (non-conjugated) transpose of the matrix.

See Also
--------
transpose, getH

Examples
--------
>>> m = np.matrix('[1, 2; 3, 4]')
>>> m
matrix([[1, 2],
        [3, 4]])
>>> m.getT()
matrix([[1, 3],
        [2, 4]])


M = asanyarray(M)<EOL>if len(M.shape) != <NUM_LIT:2> or M.shape[<NUM_LIT:0>] != M.shape[<NUM_LIT:1>]:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not issubdtype(type(n), int):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>from numpy.linalg import inv<EOL>if n==<NUM_LIT:0>:<EOL><INDENT>M = M.copy()<EOL>M[:] = identity(M.shape[<NUM_LIT:0>])<EOL>return M<EOL><DEDENT>elif n<<NUM_LIT:0>:<EOL><INDENT>M = inv(M)<EOL>n *= -<NUM_LIT:1><EOL><DEDENT>result = M<EOL>if n <= <NUM_LIT:3>:<EOL><INDENT>for _ in range(n-<NUM_LIT:1>):<EOL><INDENT>result=N.dot(result, M)<EOL><DEDENT>return result<EOL><DEDENT>beta = binary_repr(n)<EOL>Z, q, t = M, <NUM_LIT:0>, len(beta)<EOL>while beta[t-q-<NUM_LIT:1>] == '<STR_LIT:0>':<EOL><INDENT>Z = N.dot(Z, Z)<EOL>q += <NUM_LIT:1><EOL><DEDENT>result = Z<EOL>for k in range(q+<NUM_LIT:1>, t):<EOL><INDENT>Z = N.dot(Z, Z)<EOL>if beta[t-k-<NUM_LIT:1>] == '<STR_LIT:1>':<EOL><INDENT>result = N.dot(result, Z)<EOL><DEDENT><DEDENT>return result<EOL>

Raise a square matrix to the (integer) power `n`.

For positive integers `n`, the power is computed by repeated matrix
squarings and matrix multiplications. If ``n == 0``, the identity matrix
of the same shape as M is returned. If ``n < 0``, the inverse
is computed and then raised to the ``abs(n)``.

Parameters
----------
M : ndarray or matrix object
    Matrix to be "powered."  Must be square, i.e. ``M.shape == (m, m)``,
    with `m` a positive integer.
n : int
    The exponent can be any integer or long integer, positive,
    negative, or zero.

Returns
-------
M**n : ndarray or matrix object
    The return value is the same shape and type as `M`;
    if the exponent is positive or zero then the type of the
    elements is the same as those of `M`. If the exponent is
    negative the elements are floating-point.

Raises
------
LinAlgError
    If the matrix is not numerically invertible.

See Also
--------
matrix
    Provides an equivalent function as the exponentiation operator
    (``**``, not ``^``).

Examples
--------
>>> from numpy import linalg as LA
>>> i = np.array([[0, 1], [-1, 0]]) # matrix equiv. of the imaginary unit
>>> LA.matrix_power(i, 3) # should = -i
array([[ 0, -1],
       [ 1,  0]])
>>> LA.matrix_power(np.matrix(i), 3) # matrix arg returns matrix
matrix([[ 0, -1],
        [ 1,  0]])
>>> LA.matrix_power(i, 0)
array([[1, 0],
       [0, 1]])
>>> LA.matrix_power(i, -3) # should = 1/(-i) = i, but w/ f.p. elements
array([[ 0.,  1.],
       [-1.,  0.]])

Somewhat more sophisticated example

>>> q = np.zeros((4, 4))
>>> q[0:2, 0:2] = -i
>>> q[2:4, 2:4] = i
>>> q # one of the three quarternion units not equal to 1
array([[ 0., -1.,  0.,  0.],
       [ 1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  1.],
       [ 0.,  0., -1.,  0.]])
>>> LA.matrix_power(q, 2) # = -np.eye(4)
array([[-1.,  0.,  0.,  0.],
       [ 0., -1.,  0.,  0.],
       [ 0.,  0., -1.,  0.],
       [ 0.,  0.,  0., -1.]])


return self.__array__()<EOL>

Return `self` as an `ndarray` object.

Equivalent to ``np.asarray(self)``.

Parameters
----------
None

Returns
-------
ret : ndarray
    `self` as an `ndarray`

Examples
--------
>>> x = np.matrix(np.arange(12).reshape((3,4))); x
matrix([[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]])
>>> x.getA()
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])


def mean(self, axis=None, dtype=None, out=None):

return N.ndarray.mean(self, axis, dtype, out, keepdims=True)._collapse(axis)<EOL>

Returns the average of the matrix elements along the given axis.

Refer to `numpy.mean` for full documentation.

See Also
--------
numpy.mean

Notes
-----
Same as `ndarray.mean` except that, where that returns an `ndarray`,
this returns a `matrix` object.

Examples
--------
>>> x = np.matrix(np.arange(12).reshape((3, 4)))
>>> x
matrix([[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]])
>>> x.mean()
5.5
>>> x.mean(0)
matrix([[ 4.,  5.,  6.,  7.]])
>>> x.mean(1)
matrix([[ 1.5],
        [ 5.5],
        [ 9.5]])


if axis is None:<EOL><INDENT>return self[<NUM_LIT:0>, <NUM_LIT:0>]<EOL><DEDENT>elif axis==<NUM_LIT:0>:<EOL><INDENT>return self<EOL><DEDENT>elif axis==<NUM_LIT:1>:<EOL><INDENT>return self.transpose()<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>

A convenience function for operations that need to preserve axis
        orientation.


def sum(self, axis=None, dtype=None, out=None):

return N.ndarray.sum(self, axis, dtype, out, keepdims=True)._collapse(axis)<EOL>

Returns the sum of the matrix elements, along the given axis.

Refer to `numpy.sum` for full documentation.

See Also
--------
numpy.sum

Notes
-----
This is the same as `ndarray.sum`, except that where an `ndarray` would
be returned, a `matrix` object is returned instead.

Examples
--------
>>> x = np.matrix([[1, 2], [4, 3]])
>>> x.sum()
10
>>> x.sum(axis=1)
matrix([[3],
        [7]])
>>> x.sum(axis=1, dtype='float')
matrix([[ 3.],
        [ 7.]])
>>> out = np.zeros((1, 2), dtype='float')
>>> x.sum(axis=1, dtype='float', out=out)
matrix([[ 3.],
        [ 7.]])


if isinstance(obj, str):<EOL><INDENT>if gdict is None:<EOL><INDENT>frame = sys._getframe().f_back<EOL>glob_dict = frame.f_globals<EOL>loc_dict = frame.f_locals<EOL><DEDENT>else:<EOL><INDENT>glob_dict = gdict<EOL>loc_dict = ldict<EOL><DEDENT>return matrix(_from_string(obj, glob_dict, loc_dict))<EOL><DEDENT>if isinstance(obj, (tuple, list)):<EOL><INDENT>arr_rows = []<EOL>for row in obj:<EOL><INDENT>if isinstance(row, N.ndarray):  <EOL><INDENT>return matrix(concatenate(obj, axis=-<NUM_LIT:1>))<EOL><DEDENT>else:<EOL><INDENT>arr_rows.append(concatenate(row, axis=-<NUM_LIT:1>))<EOL><DEDENT><DEDENT>return matrix(concatenate(arr_rows, axis=<NUM_LIT:0>))<EOL><DEDENT>if isinstance(obj, N.ndarray):<EOL><INDENT>return matrix(obj)<EOL><DEDENT>

Build a matrix object from a string, nested sequence, or array.

Parameters
----------
obj : str or array_like
    Input data.  Names of variables in the current scope may be
    referenced, even if `obj` is a string.

Returns
-------
out : matrix
    Returns a matrix object, which is a specialized 2-D array.

See Also
--------
matrix

Examples
--------
>>> A = np.mat('1 1; 1 1')
>>> B = np.mat('2 2; 2 2')
>>> C = np.mat('3 4; 5 6')
>>> D = np.mat('7 8; 9 0')

All the following expressions construct the same block matrix:

>>> np.bmat([[A, B], [C, D]])
matrix([[1, 1, 2, 2],
        [1, 1, 2, 2],
        [3, 4, 7, 8],
        [5, 6, 9, 0]])
>>> np.bmat(np.r_[np.c_[A, B], np.c_[C, D]])
matrix([[1, 1, 2, 2],
        [1, 1, 2, 2],
        [3, 4, 7, 8],
        [5, 6, 9, 0]])
>>> np.bmat('A,B; C,D')
matrix([[1, 1, 2, 2],
        [1, 1, 2, 2],
        [3, 4, 7, 8],
        [5, 6, 9, 0]])


return list(self._raw_data.keys())<EOL>

Return the list of variable names.

Parameters
----------
None

Returns
-------
names : list of str
    The names of all variables in the `VariableSet` instance.


def CCompiler_object_filenames(self, source_filenames, strip_dir=<NUM_LIT:0>, output_dir='<STR_LIT>'):

if output_dir is None:<EOL><INDENT>output_dir = '<STR_LIT>'<EOL><DEDENT>obj_names = []<EOL>for src_name in source_filenames:<EOL><INDENT>base, ext = os.path.splitext(os.path.normpath(src_name))<EOL>base = os.path.splitdrive(base)[<NUM_LIT:1>] <EOL>base = base[os.path.isabs(base):]  <EOL>if base.startswith('<STR_LIT:..>'):<EOL><INDENT>i = base.rfind('<STR_LIT:..>')+<NUM_LIT:2><EOL>d = base[:i]<EOL>d = os.path.basename(os.path.abspath(d))<EOL>base = d + base[i:]<EOL><DEDENT>if ext not in self.src_extensions:<EOL><INDENT>raise UnknownFileError("<STR_LIT>" % (ext, src_name))<EOL><DEDENT>if strip_dir:<EOL><INDENT>base = os.path.basename(base)<EOL><DEDENT>obj_name = os.path.join(output_dir, base + self.obj_extension)<EOL>obj_names.append(obj_name)<EOL><DEDENT>return obj_names<EOL>

Return the name of the object files for the given source files.

Parameters
----------
source_filenames : list of str
    The list of paths to source files. Paths can be either relative or
    absolute, this is handled transparently.
strip_dir : bool, optional
    Whether to strip the directory from the returned paths. If True,
    the file name prepended by `output_dir` is returned. Default is False.
output_dir : str, optional
    If given, this path is prepended to the returned paths to the
    object files.

Returns
-------
obj_names : list of str
    The list of paths to the object files corresponding to the source
    files in `source_filenames`.


def CCompiler_get_version(self, force=False, ok_status=[<NUM_LIT:0>]):

if not force and hasattr(self, '<STR_LIT:version>'):<EOL><INDENT>return self.version<EOL><DEDENT>self.find_executables()<EOL>try:<EOL><INDENT>version_cmd = self.version_cmd<EOL><DEDENT>except AttributeError:<EOL><INDENT>return None<EOL><DEDENT>if not version_cmd or not version_cmd[<NUM_LIT:0>]:<EOL><INDENT>return None<EOL><DEDENT>try:<EOL><INDENT>matcher = self.version_match<EOL><DEDENT>except AttributeError:<EOL><INDENT>try:<EOL><INDENT>pat = self.version_pattern<EOL><DEDENT>except AttributeError:<EOL><INDENT>return None<EOL><DEDENT>def matcher(version_string):<EOL><INDENT>m = re.match(pat, version_string)<EOL>if not m:<EOL><INDENT>return None<EOL><DEDENT>version = m.group('<STR_LIT:version>')<EOL>return version<EOL><DEDENT><DEDENT>status, output = exec_command(version_cmd, use_tee=<NUM_LIT:0>)<EOL>version = None<EOL>if status in ok_status:<EOL><INDENT>version = matcher(output)<EOL>if version:<EOL><INDENT>version = LooseVersion(version)<EOL><DEDENT><DEDENT>self.version = version<EOL>return version<EOL>

Return compiler version, or None if compiler is not available.

Parameters
----------
force : bool, optional
    If True, force a new determination of the version, even if the
    compiler already has a version attribute. Default is False.
ok_status : list of int, optional
    The list of status values returned by the version look-up process
    for which a version string is returned. If the status value is not
    in `ok_status`, None is returned. Default is ``[0]``.

Returns
-------
version : str or None
    Version string, in the format of `distutils.version.LooseVersion`.


def CCompiler_customize_cmd(self, cmd, ignore=()):

log.info('<STR_LIT>' % (self.__class__.__name__,<EOL>cmd.__class__.__name__))<EOL>def allow(attr):<EOL><INDENT>return getattr(cmd, attr, None) is not None and attr not in ignore<EOL><DEDENT>if allow('<STR_LIT>'):<EOL><INDENT>self.set_include_dirs(cmd.include_dirs)<EOL><DEDENT>if allow('<STR_LIT>'):<EOL><INDENT>for (name, value) in cmd.define:<EOL><INDENT>self.define_macro(name, value)<EOL><DEDENT><DEDENT>if allow('<STR_LIT>'):<EOL><INDENT>for macro in cmd.undef:<EOL><INDENT>self.undefine_macro(macro)<EOL><DEDENT><DEDENT>if allow('<STR_LIT>'):<EOL><INDENT>self.set_libraries(self.libraries + cmd.libraries)<EOL><DEDENT>if allow('<STR_LIT>'):<EOL><INDENT>self.set_library_dirs(self.library_dirs + cmd.library_dirs)<EOL><DEDENT>if allow('<STR_LIT>'):<EOL><INDENT>self.set_runtime_library_dirs(cmd.rpath)<EOL><DEDENT>if allow('<STR_LIT>'):<EOL><INDENT>self.set_link_objects(cmd.link_objects)<EOL><DEDENT>

Customize compiler using distutils command.

Parameters
----------
cmd : class instance
    An instance inheriting from `distutils.cmd.Command`.
ignore : sequence of str, optional
    List of `CCompiler` commands (without ``'set_'``) that should not be
    altered. Strings that are checked for are:
    ``('include_dirs', 'define', 'undef', 'libraries', 'library_dirs',
    'rpath', 'link_objects')``.

Returns
-------
None


if self.compiler_type=='<STR_LIT>': return self<EOL>cxx = copy(self)<EOL>cxx.compiler_so = [cxx.compiler_cxx[<NUM_LIT:0>]] + cxx.compiler_so[<NUM_LIT:1>:]<EOL>if sys.platform.startswith('<STR_LIT>') and '<STR_LIT>' in cxx.linker_so[<NUM_LIT:0>]:<EOL><INDENT>cxx.linker_so = [cxx.linker_so[<NUM_LIT:0>], cxx.compiler_cxx[<NUM_LIT:0>]]+ cxx.linker_so[<NUM_LIT:2>:]<EOL><DEDENT>else:<EOL><INDENT>cxx.linker_so = [cxx.compiler_cxx[<NUM_LIT:0>]] + cxx.linker_so[<NUM_LIT:1>:]<EOL><DEDENT>return cxx<EOL>

Return the C++ compiler.

Parameters
----------
None

Returns
-------
cxx : class instance
    The C++ compiler, as a `CCompiler` instance.


def simple_version_match(pat=r'<STR_LIT>', ignore='<STR_LIT>', start='<STR_LIT>'):

def matcher(self, version_string):<EOL><INDENT>version_string = version_string.replace('<STR_LIT:\n>', '<STR_LIT:U+0020>')<EOL>pos = <NUM_LIT:0><EOL>if start:<EOL><INDENT>m = re.match(start, version_string)<EOL>if not m:<EOL><INDENT>return None<EOL><DEDENT>pos = m.end()<EOL><DEDENT>while True:<EOL><INDENT>m = re.search(pat, version_string[pos:])<EOL>if not m:<EOL><INDENT>return None<EOL><DEDENT>if ignore and re.match(ignore, m.group(<NUM_LIT:0>)):<EOL><INDENT>pos = m.end()<EOL>continue<EOL><DEDENT>break<EOL><DEDENT>return m.group(<NUM_LIT:0>)<EOL><DEDENT>return matcher<EOL>

Simple matching of version numbers, for use in CCompiler and FCompiler.

Parameters
----------
pat : str, optional
    A regular expression matching version numbers.
    Default is ``r'[-.\\d]+'``.
ignore : str, optional
    A regular expression matching patterns to skip.
    Default is ``''``, in which case nothing is skipped.
start : str, optional
    A regular expression matching the start of where to start looking
    for version numbers.
    Default is ``''``, in which case searching is started at the
    beginning of the version string given to `matcher`.

Returns
-------
matcher : callable
    A function that is appropriate to use as the ``.version_match``
    attribute of a `CCompiler` class. `matcher` takes a single parameter,
    a version string.


if WARN >= self.threshold:<EOL><INDENT>if args:<EOL><INDENT>print(green_text(msg % _fix_args(args)))<EOL><DEDENT>else:<EOL><INDENT>print(green_text(msg))<EOL><DEDENT>sys.stdout.flush()<EOL><DEDENT>

If we log WARN messages, log this message as a 'nice' anti-warn
message.


flags = {}<EOL>f = open_latin1(src, '<STR_LIT:r>')<EOL>i = <NUM_LIT:0><EOL>for line in f:<EOL><INDENT>i += <NUM_LIT:1><EOL>if i><NUM_LIT:20>: break<EOL>m = _f77flags_re.match(line)<EOL>if not m: continue<EOL>fcname = m.group('<STR_LIT>').strip()<EOL>fflags = m.group('<STR_LIT>').strip()<EOL>flags[fcname] = split_quoted(fflags)<EOL><DEDENT>f.close()<EOL>return flags<EOL>

Search the first 20 lines of fortran 77 code for line pattern
  `CF77FLAGS(<fcompiler type>)=<f77 flags>`
Return a dictionary {<fcompiler type>:<f77 flags>}.


return self._get_command_flags('<STR_LIT>')<EOL>


pass<EOL>

Called at the beginning of customisation. Subclasses should
        override this if they need to set up the executables dictionary.

        Note that self.find_executables() is run afterwards, so the
        self.executables dictionary values can contain <F77> or <F90> as
        the command, which will be replaced by the found F77 or F90
        compiler.


def get_default_fcompiler(osname=None, platform=None, requiref90=False,<EOL>c_compiler=None):

matching_compiler_types = available_fcompilers_for_platform(osname,<EOL>platform)<EOL>compiler_type =  _find_existing_fcompiler(matching_compiler_types,<EOL>osname=osname,<EOL>platform=platform,<EOL>requiref90=requiref90,<EOL>c_compiler=c_compiler)<EOL>return compiler_type<EOL>

Determine the default Fortran compiler to use for the given
    platform.


assert self._is_customised<EOL>exe_cache = self._exe_cache<EOL>def cached_find_executable(exe):<EOL><INDENT>if exe in exe_cache:<EOL><INDENT>return exe_cache[exe]<EOL><DEDENT>fc_exe = find_executable(exe)<EOL>exe_cache[exe] = exe_cache[fc_exe] = fc_exe<EOL>return fc_exe<EOL><DEDENT>def verify_command_form(name, value):<EOL><INDENT>if value is not None and not is_sequence_of_strings(value):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" %<EOL>(name, value, self.__class__.__name__))<EOL><DEDENT><DEDENT>def set_exe(exe_key, f77=None, f90=None):<EOL><INDENT>cmd = self.executables.get(exe_key, None)<EOL>if not cmd:<EOL><INDENT>return None<EOL><DEDENT>exe_from_environ = getattr(self.command_vars, exe_key)<EOL>if not exe_from_environ:<EOL><INDENT>possibles = [f90, f77] + self.possible_executables<EOL><DEDENT>else:<EOL><INDENT>possibles = [exe_from_environ] + self.possible_executables<EOL><DEDENT>seen = set()<EOL>unique_possibles = []<EOL>for e in possibles:<EOL><INDENT>if e == '<STR_LIT>':<EOL><INDENT>e = f77<EOL><DEDENT>elif e == '<STR_LIT>':<EOL><INDENT>e = f90<EOL><DEDENT>if not e or e in seen:<EOL><INDENT>continue<EOL><DEDENT>seen.add(e)<EOL>unique_possibles.append(e)<EOL><DEDENT>for exe in unique_possibles:<EOL><INDENT>fc_exe = cached_find_executable(exe)<EOL>if fc_exe:<EOL><INDENT>cmd[<NUM_LIT:0>] = fc_exe<EOL>return fc_exe<EOL><DEDENT><DEDENT>self.set_command(exe_key, None)<EOL>return None<EOL><DEDENT>ctype = self.compiler_type<EOL>f90 = set_exe('<STR_LIT>')<EOL>if not f90:<EOL><INDENT>f77 = set_exe('<STR_LIT>')<EOL>if f77:<EOL><INDENT>log.warn('<STR_LIT>' % ctype)<EOL><DEDENT>else:<EOL><INDENT>raise CompilerNotFound('<STR_LIT>' % ctype)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>f77 = set_exe('<STR_LIT>', f90=f90)<EOL>if not f77:<EOL><INDENT>log.warn('<STR_LIT>' % ctype)<EOL><DEDENT>set_exe('<STR_LIT>', f90=f90)<EOL><DEDENT>set_exe('<STR_LIT>', f77=f77, f90=f90)<EOL>set_exe('<STR_LIT>', f77=f77, f90=f90)<EOL>set_exe('<STR_LIT>', f77=f77, f90=f90)<EOL>set_exe('<STR_LIT>')<EOL>set_exe('<STR_LIT>')<EOL>

Go through the self.executables dictionary, and attempt to
        find and assign appropiate executables.

        Executable names are looked for in the environment (environment
        variables, the distutils.cfg, and command line), the 0th-element of
        the command list, and the self.possible_executables list.

        Also, if the 0th element is "<F77>" or "<F90>", the Fortran 77
        or the Fortran 90 compiler executable is used, unless overridden
        by an environment setting.

        Subclasses should call this if overriden.


def check_libs2(self, lib_dirs, libs, opt_libs=[]):

exts = self.library_extensions()<EOL>info = self._check_libs(lib_dirs, libs, opt_libs, exts)<EOL>if not info:<EOL><INDENT>log.info('<STR_LIT>', '<STR_LIT:U+002C>'.join(libs),<EOL>lib_dirs)<EOL><DEDENT>return info<EOL>

If static or shared libraries are available then return
        their info dictionary.

        Checks each library for shared or static.


flag = <NUM_LIT:0><EOL>if not self.has_info():<EOL><INDENT>flag = <NUM_LIT:1><EOL>log.info(self.__class__.__name__ + '<STR_LIT::>')<EOL>if hasattr(self, '<STR_LIT>'):<EOL><INDENT>self.calc_info()<EOL><DEDENT>if notfound_action:<EOL><INDENT>if not self.has_info():<EOL><INDENT>if notfound_action == <NUM_LIT:1>:<EOL><INDENT>warnings.warn(self.notfounderror.__doc__)<EOL><DEDENT>elif notfound_action == <NUM_LIT:2>:<EOL><INDENT>raise self.notfounderror(self.notfounderror.__doc__)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(repr(notfound_action))<EOL><DEDENT><DEDENT><DEDENT>if not self.has_info():<EOL><INDENT>log.info('<STR_LIT>')<EOL>self.set_info()<EOL><DEDENT>else:<EOL><INDENT>log.info('<STR_LIT>')<EOL><DEDENT><DEDENT>res = self.saved_results.get(self.__class__.__name__)<EOL>if self.verbosity > <NUM_LIT:0> and flag:<EOL><INDENT>for k, v in res.items():<EOL><INDENT>v = str(v)<EOL>if k in ['<STR_LIT>', '<STR_LIT>'] and len(v) > <NUM_LIT>:<EOL><INDENT>v = v[:<NUM_LIT>] + '<STR_LIT>' + v[-<NUM_LIT>:]<EOL><DEDENT>log.info('<STR_LIT>', k, v)<EOL><DEDENT>log.info('<STR_LIT>')<EOL><DEDENT>return copy.deepcopy(res)<EOL>

Return a dictonary with items that are compatible
            with numpy.distutils.setup keyword arguments.


r = []<EOL>for a in args:<EOL><INDENT>if not a:<EOL><INDENT>continue<EOL><DEDENT>if is_string(a):<EOL><INDENT>a = [a]<EOL><DEDENT>r.append(a)<EOL><DEDENT>args = r<EOL>if not args:<EOL><INDENT>return []<EOL><DEDENT>if len(args) == <NUM_LIT:1>:<EOL><INDENT>result = reduce(lambda a, b: a + b, map(glob, args[<NUM_LIT:0>]), [])<EOL><DEDENT>elif len(args) == <NUM_LIT:2>:<EOL><INDENT>result = []<EOL>for a0 in args[<NUM_LIT:0>]:<EOL><INDENT>for a1 in args[<NUM_LIT:1>]:<EOL><INDENT>result.extend(glob(os.path.join(a0, a1)))<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>result = combine_paths(*(combine_paths(args[<NUM_LIT:0>], args[<NUM_LIT:1>]) + args[<NUM_LIT:2>:]))<EOL><DEDENT>verbosity = kws.get('<STR_LIT>', <NUM_LIT:1>)<EOL>log.debug('<STR_LIT>', '<STR_LIT:U+002C>'.join(result))<EOL>return result<EOL>

Return a list of existing paths composed by all combinations of
        items from arguments.


return check_compiler_gcc4(self)<EOL>

Return True if the C compiler is gcc >= 4.


return check_inline(self)<EOL>

Return the inline keyword recognized by the compiler, empty string
        otherwise.


var = re.compile('<STR_LIT>')<EOL>fs = open(source, '<STR_LIT:r>')<EOL>try:<EOL><INDENT>ft = open(target, '<STR_LIT:w>')<EOL>try:<EOL><INDENT>for l in fs:<EOL><INDENT>m = var.search(l)<EOL>if m:<EOL><INDENT>ft.write(l.replace('<STR_LIT>' % m.group(<NUM_LIT:1>), d[m.group(<NUM_LIT:1>)]))<EOL><DEDENT>else:<EOL><INDENT>ft.write(l)<EOL><DEDENT><DEDENT><DEDENT>finally:<EOL><INDENT>ft.close()<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>fs.close()<EOL><DEDENT>

Substitute any occurence of @foo@ by d['foo'] from source file into
    target.


lib_name = "<STR_LIT>" % tuple(sys.version_info[:<NUM_LIT:2>])<EOL>lib_file = os.path.join(sys.prefix, '<STR_LIT>', lib_name)<EOL>out_name = "<STR_LIT>" % tuple(sys.version_info[:<NUM_LIT:2>])<EOL>out_file = os.path.join(sys.prefix, '<STR_LIT>', out_name)<EOL>if not os.path.isfile(lib_file):<EOL><INDENT>log.warn('<STR_LIT>' % (lib_file))<EOL>return<EOL><DEDENT>if os.path.isfile(out_file):<EOL><INDENT>log.debug('<STR_LIT>' % (out_file))<EOL>return<EOL><DEDENT>log.info('<STR_LIT>' % (out_file))<EOL>from numpy.distutils import lib2def<EOL>def_name = "<STR_LIT>" % tuple(sys.version_info[:<NUM_LIT:2>])<EOL>def_file = os.path.join(sys.prefix, '<STR_LIT>', def_name)<EOL>nm_cmd = '<STR_LIT>' % (lib2def.DEFAULT_NM, lib_file)<EOL>nm_output = lib2def.getnm(nm_cmd)<EOL>dlist, flist = lib2def.parse_nm(nm_output)<EOL>lib2def.output_def(dlist, flist, lib2def.DEF_HEADER, open(def_file, '<STR_LIT:w>'))<EOL>dll_name = "<STR_LIT>" % tuple(sys.version_info[:<NUM_LIT:2>])<EOL>args = (dll_name, def_file, out_file)<EOL>cmd = '<STR_LIT>' % args<EOL>status = os.system(cmd)<EOL>if status:<EOL><INDENT>log.warn('<STR_LIT>')<EOL><DEDENT>return<EOL>

Build the import libraries for Mingw32-gcc on Windows


if _cache:<EOL><INDENT>return _cache[<NUM_LIT:0>]<EOL><DEDENT>ok = True<EOL>display_opts = ['<STR_LIT>'+n for n in Distribution.display_option_names]<EOL>for o in Distribution.display_options:<EOL><INDENT>if o[<NUM_LIT:1>]:<EOL><INDENT>display_opts.append('<STR_LIT:->'+o[<NUM_LIT:1>])<EOL><DEDENT><DEDENT>for arg in sys.argv:<EOL><INDENT>if arg.startswith('<STR_LIT>') or arg=='<STR_LIT>' or arg in display_opts:<EOL><INDENT>ok = False<EOL>break<EOL><DEDENT><DEDENT>_cache.append(ok)<EOL>return ok<EOL>

Return True if command line does not contain any
    help or display requests.


from numpy.distutils.npy_pkg_config import parse_flags<EOL>pkg_info = get_pkg_info(pkgname, dirs)<EOL>info = parse_flags(pkg_info.cflags())<EOL>for k, v in parse_flags(pkg_info.libs()).items():<EOL><INDENT>info[k].extend(v)<EOL><DEDENT>info['<STR_LIT>'] = info['<STR_LIT>']<EOL>del info['<STR_LIT>']<EOL>del info['<STR_LIT>']<EOL>return info<EOL>

Return an info dict for a given C library.

The info dict contains the necessary options to use the C library.

Parameters
----------
pkgname : str
    Name of the package (should match the name of the .ini file, without
    the extension, e.g. foo for the file foo.ini).
dirs : sequence, optional
    If given, should be a sequence of additional directories where to look
    for npy-pkg-config files. Those directories are searched prior to the
    NumPy directory.

Returns
-------
info : dict
    The dictionary with build information.

Raises
------
PkgNotFound
    If the package is not found.

See Also
--------
Configuration.add_npy_pkg_config, Configuration.add_installed_library,
get_pkg_info

Examples
--------
To get the necessary information for the npymath library from NumPy:

>>> npymath_info = np.distutils.misc_util.get_info('npymath')
>>> npymath_info                                    #doctest: +SKIP
{'define_macros': [], 'libraries': ['npymath'], 'library_dirs':
['.../numpy/core/lib'], 'include_dirs': ['.../numpy/core/include']}

This info dict can then be used as input to a `Configuration` instance::

  config.add_extension('foo', sources=['foo.c'], extra_info=npymath_info)


target = njoin(self.local_path, '<STR_LIT>')<EOL>revision = self._get_svn_revision(self.local_path)<EOL>if os.path.isfile(target) or revision is None:<EOL><INDENT>return<EOL><DEDENT>else:<EOL><INDENT>def generate_svn_version_py():<EOL><INDENT>if not os.path.isfile(target):<EOL><INDENT>version = str(revision)<EOL>self.info('<STR_LIT>' % (target, version))<EOL>f = open(target, '<STR_LIT:w>')<EOL>f.write('<STR_LIT>' % (version))<EOL>f.close()<EOL><DEDENT>import atexit<EOL>def rm_file(f=target,p=self.info):<EOL><INDENT>if delete:<EOL><INDENT>try: os.remove(f); p('<STR_LIT>'+f)<EOL>except OSError: pass<EOL>try: os.remove(f+'<STR_LIT:c>'); p('<STR_LIT>'+f+'<STR_LIT:c>')<EOL>except OSError: pass<EOL><DEDENT><DEDENT>atexit.register(rm_file)<EOL>return target<EOL><DEDENT>self.add_data_files(('<STR_LIT>', generate_svn_version_py()))<EOL><DEDENT>

Appends a data function to the data_files list that will generate
        __svn_version__.py file to the current package directory.

        Generate package __svn_version__.py file from SVN revision number,
        it will be removed after python exits but will be available
        when sdist, etc commands are executed.

        Notes
        -----
        If __svn_version__.py existed before, nothing is done.

        This is
        intended for working with source directories that are in an SVN
        repository.


if sys.platform=='<STR_LIT:win32>':<EOL><INDENT>if os.environ.get('<STR_LIT>', '<STR_LIT>')=='<STR_LIT>':<EOL><INDENT>return True<EOL><DEDENT>if os.environ.get('<STR_LIT>', '<STR_LIT>')=='<STR_LIT>':<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>

Return true when using mingw32 environment.


if subpackage_name is None:<EOL><INDENT>if subpackage_path is None:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>")<EOL><DEDENT>subpackage_name = os.path.basename(subpackage_path)<EOL><DEDENT>l = subpackage_name.split('<STR_LIT:.>')<EOL>if subpackage_path is None and '<STR_LIT:*>' in subpackage_name:<EOL><INDENT>return self._wildcard_get_subpackage(subpackage_name,<EOL>parent_name,<EOL>caller_level = caller_level+<NUM_LIT:1>)<EOL><DEDENT>assert '<STR_LIT:*>' not in subpackage_name, repr((subpackage_name, subpackage_path, parent_name))<EOL>if subpackage_path is None:<EOL><INDENT>subpackage_path = njoin([self.local_path] + l)<EOL><DEDENT>else:<EOL><INDENT>subpackage_path = njoin([subpackage_path] + l[:-<NUM_LIT:1>])<EOL>subpackage_path = self.paths([subpackage_path])[<NUM_LIT:0>]<EOL><DEDENT>setup_py = njoin(subpackage_path, self.setup_name)<EOL>if not self.options['<STR_LIT>']:<EOL><INDENT>if not os.path.isfile(setup_py):<EOL><INDENT>setup_py = njoin(subpackage_path,<EOL>'<STR_LIT>' % (subpackage_name))<EOL><DEDENT><DEDENT>if not os.path.isfile(setup_py):<EOL><INDENT>if not self.options['<STR_LIT>']:<EOL><INDENT>self.warn('<STR_LIT>''<STR_LIT>'% (os.path.dirname(setup_py), subpackage_name))<EOL><DEDENT>config = Configuration(subpackage_name, parent_name,<EOL>self.top_path, subpackage_path,<EOL>caller_level = caller_level+<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>config = self._get_configuration_from_setup_py(<EOL>setup_py,<EOL>subpackage_name,<EOL>subpackage_path,<EOL>parent_name,<EOL>caller_level = caller_level + <NUM_LIT:1>)<EOL><DEDENT>if config:<EOL><INDENT>return [config]<EOL><DEDENT>else:<EOL><INDENT>return []<EOL><DEDENT>

Return list of subpackage configurations.

        Parameters
        ----------
        subpackage_name : str or None
            Name of the subpackage to get the configuration. '*' in
            subpackage_name is handled as a wildcard.
        subpackage_path : str
            If None, then the path is assumed to be the local path plus the
            subpackage_name. If a setup.py file is not found in the
            subpackage_path, then a default configuration is used.
        parent_name : str
            Parent name.


if not is_string(path):<EOL><INDENT>return path<EOL><DEDENT>if '<STR_LIT:.>' not in path:<EOL><INDENT>return path<EOL><DEDENT>l = path.split(os.sep)<EOL>while l:<EOL><INDENT>try:<EOL><INDENT>i = l.index('<STR_LIT:.>', <NUM_LIT:1>)<EOL><DEDENT>except ValueError:<EOL><INDENT>break<EOL><DEDENT>del l[i]<EOL><DEDENT>j = <NUM_LIT:1><EOL>while l:<EOL><INDENT>try:<EOL><INDENT>i = l.index('<STR_LIT:..>', j)<EOL><DEDENT>except ValueError:<EOL><INDENT>break<EOL><DEDENT>if l[i-<NUM_LIT:1>]=='<STR_LIT:..>':<EOL><INDENT>j += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>del l[i], l[i-<NUM_LIT:1>]<EOL>j = <NUM_LIT:1><EOL><DEDENT><DEDENT>if not l:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>return os.sep.join(l)<EOL>


<EOL>try:<EOL><INDENT>caller_file = eval('<STR_LIT>', frame.f_globals, frame.f_locals)<EOL>d = os.path.dirname(os.path.abspath(caller_file))<EOL><DEDENT>except NameError:<EOL><INDENT>caller_name = eval('<STR_LIT>', frame.f_globals, frame.f_locals)<EOL>__import__(caller_name)<EOL>mod = sys.modules[caller_name]<EOL>if hasattr(mod, '<STR_LIT>'):<EOL><INDENT>d = os.path.dirname(os.path.abspath(mod.__file__))<EOL><DEDENT>else:<EOL><INDENT>d = os.path.abspath('<STR_LIT:.>')<EOL><DEDENT><DEDENT>if parent_path is not None:<EOL><INDENT>d = rel_path(d, parent_path)<EOL><DEDENT>return d or '<STR_LIT:.>'<EOL>

Return path of the module given a frame object from the call stack.

    Returned path is relative to parent_path when given,
    otherwise it is absolute path.


def add_npy_pkg_config(self, template, install_dir, subst_dict=None):

if subst_dict is None:<EOL><INDENT>subst_dict = {}<EOL><DEDENT>basename = os.path.splitext(template)[<NUM_LIT:0>]<EOL>template = os.path.join(self.package_path, template)<EOL>if self.name in self.installed_pkg_config:<EOL><INDENT>self.installed_pkg_config[self.name].append((template, install_dir,<EOL>subst_dict))<EOL><DEDENT>else:<EOL><INDENT>self.installed_pkg_config[self.name] = [(template, install_dir,<EOL>subst_dict)]<EOL><DEDENT>

Generate and install a npy-pkg config file from a template.

The config file generated from `template` is installed in the
given install directory, using `subst_dict` for variable substitution.

Parameters
----------
template : str
    The path of the template, relatively to the current package path.
install_dir : str
    Where to install the npy-pkg config file, relatively to the current
    package path.
subst_dict : dict, optional
    If given, any string of the form ``@key@`` will be replaced by
    ``subst_dict[key]`` in the template file when installed. The install
    prefix is always available through the variable ``@prefix@``, since the
    install prefix is not easy to get reliably from setup.py.

See also
--------
add_installed_library, get_info

Notes
-----
This works for both standard installs and in-place builds, i.e. the
``@prefix@`` refer to the source directory for in-place builds.

Examples
--------
::

    config.add_npy_pkg_config('foo.ini.in', 'lib', {'foo': bar})

Assuming the foo.ini.in file has the following content::

    [meta]
    Name=@foo@
    Version=1.0
    Description=dummy description

    [default]
    Cflags=-I@prefix@/include
    Libs=

The generated file will have the following content::

    [meta]
    Name=bar
    Version=1.0
    Description=dummy description

    [default]
    Cflags=-Iprefix_dir/include
    Libs=

and will be installed as foo.ini in the 'lib' subpath.


def gpaths(paths, local_path='<STR_LIT>', include_non_existing=True):

if is_string(paths):<EOL><INDENT>paths = (paths,)<EOL><DEDENT>return _fix_paths(paths, local_path, include_non_existing)<EOL>

Apply glob to paths and prepend local_path if needed.


def get_version(self, version_file=None, version_variable=None):

version = getattr(self, '<STR_LIT:version>', None)<EOL>if version is not None:<EOL><INDENT>return version<EOL><DEDENT>if version_file is None:<EOL><INDENT>files = ['<STR_LIT>',<EOL>self.name.split('<STR_LIT:.>')[-<NUM_LIT:1>]+'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>files = [version_file]<EOL><DEDENT>if version_variable is None:<EOL><INDENT>version_vars = ['<STR_LIT:version>',<EOL>'<STR_LIT>',<EOL>self.name.split('<STR_LIT:.>')[-<NUM_LIT:1>]+'<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>version_vars = [version_variable]<EOL><DEDENT>for f in files:<EOL><INDENT>fn = njoin(self.local_path, f)<EOL>if os.path.isfile(fn):<EOL><INDENT>info = (open(fn), fn, ('<STR_LIT>', '<STR_LIT>', <NUM_LIT:1>))<EOL>name = os.path.splitext(os.path.basename(fn))[<NUM_LIT:0>]<EOL>n = dot_join(self.name, name)<EOL>try:<EOL><INDENT>version_module = imp.load_module('<STR_LIT:_>'.join(n.split('<STR_LIT:.>')),*info)<EOL><DEDENT>except ImportError:<EOL><INDENT>msg = get_exception()<EOL>self.warn(str(msg))<EOL>version_module = None<EOL><DEDENT>if version_module is None:<EOL><INDENT>continue<EOL><DEDENT>for a in version_vars:<EOL><INDENT>version = getattr(version_module, a, None)<EOL>if version is not None:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if version is not None:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>if version is not None:<EOL><INDENT>self.version = version<EOL>return version<EOL><DEDENT>revision = self._get_svn_revision(self.local_path)<EOL>if revision is None:<EOL><INDENT>revision = self._get_hg_revision(self.local_path)<EOL><DEDENT>if revision is not None:<EOL><INDENT>version = str(revision)<EOL>self.version = version<EOL><DEDENT>return version<EOL>

Try to get version string of a package.

        Return a version string of the current package or None if the version
        information could not be detected.

        Notes
        -----
        This method scans files named
        __version__.py, <packagename>_version.py, version.py, and
        __svn_version__.py for string variables version, __version\__, and
        <packagename>_version, until a version number is found.


<EOL>import numpy<EOL>d = os.path.join(os.path.dirname(numpy.__file__),<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>return d<EOL>

Return the path where to find the npy-pkg-config directory.


revision = None<EOL>m = None<EOL>cwd =  os.getcwd()<EOL>try:<EOL><INDENT>os.chdir(path or '<STR_LIT:.>')<EOL>p = subprocess.Popen(['<STR_LIT>'], shell=True,<EOL>stdout=subprocess.PIPE, stderr=None,<EOL>close_fds=True)<EOL>sout = p.stdout<EOL>m = re.match(r'<STR_LIT>', sout.read())<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>os.chdir(cwd)<EOL>if m:<EOL><INDENT>revision = int(m.group('<STR_LIT>'))<EOL>return revision<EOL><DEDENT>branch_fn = njoin(path, '<STR_LIT>', '<STR_LIT>')<EOL>branch_cache_fn = njoin(path, '<STR_LIT>', '<STR_LIT>')<EOL>if os.path.isfile(branch_fn):<EOL><INDENT>branch0 = None<EOL>f = open(branch_fn)<EOL>revision0 = f.read().strip()<EOL>f.close()<EOL>branch_map = {}<EOL>for line in file(branch_cache_fn, '<STR_LIT:r>'):<EOL><INDENT>branch1, revision1  = line.split()[:<NUM_LIT:2>]<EOL>if revision1==revision0:<EOL><INDENT>branch0 = branch1<EOL><DEDENT>try:<EOL><INDENT>revision1 = int(revision1)<EOL><DEDENT>except ValueError:<EOL><INDENT>continue<EOL><DEDENT>branch_map[branch1] = revision1<EOL><DEDENT>revision = branch_map.get(branch0)<EOL><DEDENT>return revision<EOL>

Return path's Mercurial revision number.


if not compiler.compiler_type == "<STR_LIT>":<EOL><INDENT>raise ValueError("<STR_LIT>"% compiler.compiler_type)<EOL><DEDENT>return compiler._MSVCCompiler__version<EOL>

Return version major and minor of compiler instance if it is
    MSVC, raise an exception otherwise.


from numpy.distutils.core import get_distribution<EOL>return get_distribution()<EOL>

Return the distutils distribution object for self.


for key, value in options.items():<EOL><INDENT>if key in self.options:<EOL><INDENT>self.options[key] = value<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>'+key)<EOL><DEDENT><DEDENT>

Configure Configuration instance.

The following options are available:
 - ignore_setup_xxx_py
 - assume_default_configuration
 - delegate_options_to_subpackages
 - quiet


if not is_string(directory):<EOL><INDENT>return False<EOL><DEDENT>abs_dir = os.path.abspath(directory)<EOL>c = os.path.commonprefix([os.getcwd(), abs_dir])<EOL>new_dir = abs_dir[len(c):].split(os.sep)<EOL>if new_dir and not new_dir[<NUM_LIT:0>]:<EOL><INDENT>new_dir = new_dir[<NUM_LIT:1>:]<EOL><DEDENT>if new_dir and new_dir[<NUM_LIT:0>]=='<STR_LIT>':<EOL><INDENT>return False<EOL><DEDENT>new_dir = os.sep.join(new_dir)<EOL>return os.path.isdir(new_dir)<EOL>

Return true if directory is local directory.


for item in lst:<EOL><INDENT>if not is_string(item):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL>

Return True if all items in lst are string objects.


self.py_modules.append((self.name, name, generate_config_py))<EOL>

Generate package __config__.py file containing system_info
        information used during building the package.

        This file is installed to the
        package installation directory.


if not f90_ext_match(source):<EOL><INDENT>return []<EOL><DEDENT>modules = []<EOL>f = open(source, '<STR_LIT:r>')<EOL>for line in f:<EOL><INDENT>m = f90_module_name_match(line)<EOL>if m:<EOL><INDENT>name = m.group('<STR_LIT:name>')<EOL>modules.append(name)<EOL><DEDENT><DEDENT>f.close()<EOL>return modules<EOL>

Return a list of Fortran f90 module names that
    given source file defines.


target = njoin(self.local_path, '<STR_LIT>')<EOL>revision = self._get_hg_revision(self.local_path)<EOL>if os.path.isfile(target) or revision is None:<EOL><INDENT>return<EOL><DEDENT>else:<EOL><INDENT>def generate_hg_version_py():<EOL><INDENT>if not os.path.isfile(target):<EOL><INDENT>version = str(revision)<EOL>self.info('<STR_LIT>' % (target, version))<EOL>f = open(target, '<STR_LIT:w>')<EOL>f.write('<STR_LIT>' % (version))<EOL>f.close()<EOL><DEDENT>import atexit<EOL>def rm_file(f=target,p=self.info):<EOL><INDENT>if delete:<EOL><INDENT>try: os.remove(f); p('<STR_LIT>'+f)<EOL>except OSError: pass<EOL>try: os.remove(f+'<STR_LIT:c>'); p('<STR_LIT>'+f+'<STR_LIT:c>')<EOL>except OSError: pass<EOL><DEDENT><DEDENT>atexit.register(rm_file)<EOL>return target<EOL><DEDENT>self.add_data_files(('<STR_LIT>', generate_hg_version_py()))<EOL><DEDENT>

Appends a data function to the data_files list that will generate
        __hg_version__.py file to the current package directory.

        Generate package __hg_version__.py file from Mercurial revision,
        it will be removed after python exits but will be available
        when sdist, etc commands are executed.

        Notes
        -----
        If __hg_version__.py existed before, nothing is done.

        This is intended for working with source directories that are
        in an Mercurial repository.


def UnixCCompiler_create_static_lib(self, objects, output_libname,<EOL>output_dir=None, debug=<NUM_LIT:0>, target_lang=None):

objects, output_dir = self._fix_object_args(objects, output_dir)<EOL>output_filename =self.library_filename(output_libname, output_dir=output_dir)<EOL>if self._need_link(objects, output_filename):<EOL><INDENT>try:<EOL><INDENT>os.unlink(output_filename)<EOL><DEDENT>except (IOError, OSError):<EOL><INDENT>pass<EOL><DEDENT>self.mkpath(os.path.dirname(output_filename))<EOL>tmp_objects = objects + self.objects<EOL>while tmp_objects:<EOL><INDENT>objects = tmp_objects[:<NUM_LIT:50>]<EOL>tmp_objects = tmp_objects[<NUM_LIT:50>:]<EOL>display = '<STR_LIT>' % (<EOL>os.path.basename(self.archiver[<NUM_LIT:0>]),<EOL>len(objects), output_filename)<EOL>self.spawn(self.archiver + [output_filename] + objects,<EOL>display = display)<EOL><DEDENT>if self.ranlib:<EOL><INDENT>display = '<STR_LIT>' % (os.path.basename(self.ranlib[<NUM_LIT:0>]),<EOL>output_filename)<EOL>try:<EOL><INDENT>self.spawn(self.ranlib + [output_filename],<EOL>display = display)<EOL><DEDENT>except DistutilsExecError:<EOL><INDENT>msg = str(get_exception())<EOL>raise LibError(msg)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>log.debug("<STR_LIT>", output_filename)<EOL><DEDENT>return<EOL>

Build a static library in a separate sub-process.

Parameters
----------
objects : list or tuple of str
    List of paths to object files used to build the static library.
output_libname : str
    The library name as an absolute or relative (if `output_dir` is used)
    path.
output_dir : str, optional
    The path to the output directory. Default is None, in which case
    the ``output_dir`` attribute of the UnixCCompiler instance.
debug : bool, optional
    This parameter is not used.
target_lang : str, optional
    This parameter is not used.

Returns
-------
None


if hasattr(stream, '<STR_LIT>'):<EOL><INDENT>try:<EOL><INDENT>r = stream.fileno()<EOL>return True<EOL><DEDENT>except IOError:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT>

Returns True if 'stream' supports the file descriptor and allows fileno().


if isinstance(args[<NUM_LIT:0>], tuple):<EOL><INDENT>args = args[<NUM_LIT:0>]<EOL><DEDENT>return asmatrix(np.random.randn(*args))<EOL>

Return a random matrix with data from the "standard normal" distribution.

`randn` generates a matrix filled with random floats sampled from a
univariate "normal" (Gaussian) distribution of mean 0 and variance 1.

Parameters
----------
\\*args : Arguments
    Shape of the output.
    If given as N integers, each integer specifies the size of one
    dimension. If given as a tuple, this tuple gives the complete shape.

Returns
-------
Z : matrix of floats
    A matrix of floating-point samples drawn from the standard normal
    distribution.

See Also
--------
rand, random.randn

Notes
-----
For random samples from :math:`N(\\mu, \\sigma^2)`, use:

``sigma * np.matlib.randn(...) + mu``

Examples
--------
>>> import numpy.matlib
>>> np.matlib.randn(1)
matrix([[-0.09542833]])                                 #random
>>> np.matlib.randn(1, 2, 3)
matrix([[ 0.16198284,  0.0194571 ,  0.18312985],
        [-0.7509172 ,  1.61055   ,  0.45298599]])       #random

Two-by-four matrix of samples from :math:`N(3, 6.25)`:

>>> 2.5 * np.matlib.randn((2, 4)) + 3
matrix([[ 4.74085004,  8.89381862,  4.09042411,  4.83721922],
        [ 7.52373709,  5.07933944, -2.64043543,  0.45610557]])  #random


a = asanyarray(a)<EOL>ndim = a.ndim<EOL>if ndim == <NUM_LIT:0>:<EOL><INDENT>origrows, origcols = (<NUM_LIT:1>, <NUM_LIT:1>)<EOL><DEDENT>elif ndim == <NUM_LIT:1>:<EOL><INDENT>origrows, origcols = (<NUM_LIT:1>, a.shape[<NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>origrows, origcols = a.shape<EOL><DEDENT>rows = origrows * m<EOL>cols = origcols * n<EOL>c = a.reshape(<NUM_LIT:1>, a.size).repeat(m, <NUM_LIT:0>).reshape(rows, origcols).repeat(n, <NUM_LIT:0>)<EOL>return c.reshape(rows, cols)<EOL>

Repeat a 0-D to 2-D array or matrix MxN times.

Parameters
----------
a : array_like
    The array or matrix to be repeated.
m, n : int
    The number of times `a` is repeated along the first and second axes.

Returns
-------
out : ndarray
    The result of repeating `a`.

Examples
--------
>>> import numpy.matlib
>>> a0 = np.array(1)
>>> np.matlib.repmat(a0, 2, 3)
array([[1, 1, 1],
       [1, 1, 1]])

>>> a1 = np.arange(4)
>>> np.matlib.repmat(a1, 2, 2)
array([[0, 1, 2, 3, 0, 1, 2, 3],
       [0, 1, 2, 3, 0, 1, 2, 3]])

>>> a2 = np.asmatrix(np.arange(6).reshape(2, 3))
>>> np.matlib.repmat(a2, 2, 3)
matrix([[0, 1, 2, 0, 1, 2, 0, 1, 2],
        [3, 4, 5, 3, 4, 5, 3, 4, 5],
        [0, 1, 2, 0, 1, 2, 0, 1, 2],
        [3, 4, 5, 3, 4, 5, 3, 4, 5]])


def set_initial_value(self, y, t=<NUM_LIT:0.0>):

if isscalar(y):<EOL><INDENT>y = [y]<EOL><DEDENT>n_prev = len(self._y)<EOL>if not n_prev:<EOL><INDENT>self.set_integrator('<STR_LIT>')  <EOL><DEDENT>self._y = asarray(y, self._integrator.scalar)<EOL>self.t = t<EOL>self._integrator.reset(len(self._y), self.jac is not None)<EOL>return self<EOL>


if self._integrator.supports_solout:<EOL><INDENT>self._integrator.set_solout(solout)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>+ "<STR_LIT>")<EOL><DEDENT>

Set callable to be called at every successful integration step.

Parameters
----------
solout : callable
    ``solout(t, y)`` is called at each internal integrator step,
    t is a scalar providing the current independent position
    y is the current soloution ``y.shape == (n,)``
    solout should return -1 to stop integration
    otherwise it should return None or 0


def run_relax(self, f, jac, y0, t0, t1, f_params, jac_params):

raise NotImplementedError('<STR_LIT>' %<EOL>self.__class__.__name__)<EOL>

Integrate from t=t0 to t>=t1 and return (y1,t).


def romberg(function, a, b, args=(), tol=<NUM_LIT>, rtol=<NUM_LIT>, show=False,<EOL>divmax=<NUM_LIT:10>, vec_func=False):

if isinf(a) or isinf(b):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>vfunc = vectorize1(function, args, vec_func=vec_func)<EOL>n = <NUM_LIT:1><EOL>interval = [a,b]<EOL>intrange = b-a<EOL>ordsum = _difftrap(vfunc, interval, n)<EOL>result = intrange * ordsum<EOL>resmat = [[result]]<EOL>err = np.inf<EOL>for i in xrange(<NUM_LIT:1>, divmax+<NUM_LIT:1>):<EOL><INDENT>n = n * <NUM_LIT:2><EOL>ordsum = ordsum + _difftrap(vfunc, interval, n)<EOL>resmat.append([])<EOL>resmat[i].append(intrange * ordsum / n)<EOL>for k in range(i):<EOL><INDENT>resmat[i].append(_romberg_diff(resmat[i-<NUM_LIT:1>][k], resmat[i][k], k+<NUM_LIT:1>))<EOL><DEDENT>result = resmat[i][i]<EOL>lastresult = resmat[i-<NUM_LIT:1>][i-<NUM_LIT:1>]<EOL>err = abs(result - lastresult)<EOL>if err < tol or err < rtol*abs(result):<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>warnings.warn(<EOL>"<STR_LIT>" % (divmax, err),<EOL>AccuracyWarning)<EOL><DEDENT>if show:<EOL><INDENT>_printresmat(vfunc, interval, resmat)<EOL><DEDENT>return result<EOL>

Romberg integration of a callable function or method.

Returns the integral of `function` (a function of one variable)
over the interval (`a`, `b`).

If `show` is 1, the triangular array of the intermediate results
will be printed.  If `vec_func` is True (default is False), then
`function` is assumed to support vector arguments.

Parameters
----------
function : callable
    Function to be integrated.
a : float
    Lower limit of integration.
b : float
    Upper limit of integration.

Returns
-------
results  : float
    Result of the integration.

Other Parameters
----------------
args : tuple, optional
    Extra arguments to pass to function. Each element of `args` will
    be passed as a single argument to `func`. Default is to pass no
    extra arguments.
tol, rtol : float, optional
    The desired absolute and relative tolerances. Defaults are 1.48e-8.
show : bool, optional
    Whether to print the results. Default is False.
divmax : int, optional
    Maximum order of extrapolation. Default is 10.
vec_func : bool, optional
    Whether `func` handles arrays as arguments (i.e whether it is a
    "vector" function). Default is False.

See Also
--------
fixed_quad : Fixed-order Gaussian quadrature.
quad : Adaptive quadrature using QUADPACK.
dblquad : Double integrals.
tplquad : Triple integrals.
romb : Integrators for sampled data.
simps : Integrators for sampled data.
cumtrapz : Cumulative integration for sampled data.
ode : ODE integrator.
odeint : ODE integrator.

References
----------
.. [1] 'Romberg's method' http://en.wikipedia.org/wiki/Romberg%27s_method

Examples
--------
Integrate a gaussian from 0 to 1 and compare to the error function.

>>> from scipy import integrate
>>> from scipy.special import erf
>>> gaussian = lambda x: 1/np.sqrt(np.pi) * np.exp(-x**2)
>>> result = integrate.romberg(gaussian, 0, 1, show=True)
Romberg integration of <function vfunc at ...> from [0, 1]

::

   Steps  StepSize  Results
       1  1.000000  0.385872
       2  0.500000  0.412631  0.421551
       4  0.250000  0.419184  0.421368  0.421356
       8  0.125000  0.420810  0.421352  0.421350  0.421350
      16  0.062500  0.421215  0.421350  0.421350  0.421350  0.421350
      32  0.031250  0.421317  0.421350  0.421350  0.421350  0.421350  0.421350

The final result is 0.421350396475 after 33 function evaluations.

>>> print("%g %g" % (2*result, erf(1)))
0.842701 0.842701


if n in _cached_p_roots.cache:<EOL><INDENT>return _cached_p_roots.cache[n]<EOL><DEDENT>_cached_p_roots.cache[n] = p_roots(n)<EOL>return _cached_p_roots.cache[n]<EOL>

Cache p_roots results for speeding up multiple calls of the fixed_quad function.


try:<EOL><INDENT>N = len(rn)-<NUM_LIT:1><EOL>if equal:<EOL><INDENT>rn = np.arange(N+<NUM_LIT:1>)<EOL><DEDENT>elif np.all(np.diff(rn) == <NUM_LIT:1>):<EOL><INDENT>equal = <NUM_LIT:1><EOL><DEDENT><DEDENT>except:<EOL><INDENT>N = rn<EOL>rn = np.arange(N+<NUM_LIT:1>)<EOL>equal = <NUM_LIT:1><EOL><DEDENT>if equal and N in _builtincoeffs:<EOL><INDENT>na, da, vi, nb, db = _builtincoeffs[N]<EOL>return na*np.array(vi,float)/da, float(nb)/db<EOL><DEDENT>if (rn[<NUM_LIT:0>] != <NUM_LIT:0>) or (rn[-<NUM_LIT:1>] != N):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>yi = rn / float(N)<EOL>ti = <NUM_LIT>*yi - <NUM_LIT:1><EOL>nvec = np.arange(<NUM_LIT:0>,N+<NUM_LIT:1>)<EOL>C = ti**nvec[:,np.newaxis]<EOL>Cinv = np.linalg.inv(C)<EOL>for i in range(<NUM_LIT:2>):<EOL><INDENT>Cinv = <NUM_LIT:2>*Cinv - Cinv.dot(C).dot(Cinv)<EOL><DEDENT>vec = <NUM_LIT> / (nvec[::<NUM_LIT:2>]+<NUM_LIT:1>)<EOL>ai = np.dot(Cinv[:,::<NUM_LIT:2>],vec) * N/<NUM_LIT:2><EOL>if (N % <NUM_LIT:2> == <NUM_LIT:0>) and equal:<EOL><INDENT>BN = N/(N+<NUM_LIT>)<EOL>power = N+<NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>BN = N/(N+<NUM_LIT>)<EOL>power = N+<NUM_LIT:1><EOL><DEDENT>BN = BN - np.dot(yi**power, ai)<EOL>p1 = power+<NUM_LIT:1><EOL>fac = power*math.log(N) - gammaln(p1)<EOL>fac = math.exp(fac)<EOL>return ai, BN*fac<EOL>

Return weights and error coefficient for Newton-Cotes integration.

Suppose we have (N+1) samples of f at the positions
x_0, x_1, ..., x_N.  Then an N-point Newton-Cotes formula for the
integral between x_0 and x_N is:

:math:`\\int_{x_0}^{x_N} f(x)dx = \\Delta x \\sum_{i=0}^{N} a_i f(x_i)
+ B_N (\\Delta x)^{N+2} f^{N+1} (\\xi)`

where :math:`\\xi \\in [x_0,x_N]` and :math:`\\Delta x = \\frac{x_N-x_0}{N}`
is the averages samples spacing.

If the samples are equally-spaced and N is even, then the error
term is :math:`B_N (\\Delta x)^{N+3} f^{N+2}(\\xi)`.

Parameters
----------
rn : int
    The integer order for equally-spaced data or the relative positions of
    the samples with the first sample at 0 and the last at N, where N+1 is
    the length of `rn`.  N is the order of the Newton-Cotes integration.
equal : int, optional
    Set to 1 to enforce equally spaced data.

Returns
-------
an : ndarray
    1-D array of weights to apply to the function at the provided sample
    positions.
B : float
    Error coefficient.

Notes
-----
Normally, the Newton-Cotes rules are used on smaller integration
regions and a composite rule is used to return the total integral.


[x,w] = _cached_p_roots(n)<EOL>x = real(x)<EOL>ainf, binf = map(isinf,(a,b))<EOL>if ainf or binf:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>y = (b-a)*(x+<NUM_LIT:1>)/<NUM_LIT> + a<EOL>return (b-a)/<NUM_LIT>*sum(w*func(y,*args),<NUM_LIT:0>), None<EOL>

Compute a definite integral using fixed-order Gaussian quadrature.

Integrate `func` from `a` to `b` using Gaussian quadrature of
order `n`.

Parameters
----------
func : callable
    A Python function or method to integrate (must accept vector inputs).
a : float
    Lower limit of integration.
b : float
    Upper limit of integration.
args : tuple, optional
    Extra arguments to pass to function, if any.
n : int, optional
    Order of quadrature integration. Default is 5.

Returns
-------
val : float
    Gaussian quadrature approximation to the integral

See Also
--------
quad : adaptive quadrature using QUADPACK
dblquad : double integrals
tplquad : triple integrals
romberg : adaptive Romberg quadrature
quadrature : adaptive Gaussian quadrature
romb : integrators for sampled data
simps : integrators for sampled data
cumtrapz : cumulative integration for sampled data
ode : ODE integrator
odeint : ODE integrator


def nquad(func, ranges, args=None, opts=None):

depth = len(ranges)<EOL>ranges = [rng if callable(rng) else _RangeFunc(rng) for rng in ranges]<EOL>if args is None:<EOL><INDENT>args = ()<EOL><DEDENT>if opts is None:<EOL><INDENT>opts = [dict([])] * depth<EOL><DEDENT>if isinstance(opts, dict):<EOL><INDENT>opts = [opts] * depth<EOL><DEDENT>else:<EOL><INDENT>opts = [opt if callable(opt) else _OptFunc(opt) for opt in opts]<EOL><DEDENT>return _NQuad(func, ranges, opts).integrate(*args)<EOL>

Integration over multiple variables.

Wraps `quad` to enable integration over multiple variables.
Various options allow improved integration of discontinuous functions, as
well as the use of weighted integration, and generally finer control of the
integration process.

Parameters
----------
func : callable
    The function to be integrated. Has arguments of ``x0, ... xn``,
    ``t0, tm``, where integration is carried out over ``x0, ... xn``, which
    must be floats.  Function signature should be
    ``func(x0, x1, ..., xn, t0, t1, ..., tm)``.  Integration is carried out
    in order.  That is, integration over ``x0`` is the innermost integral,
    and ``xn`` is the outermost.
    If performance is a concern, this function may be a ctypes function of
    the form::

        f(int n, double args[n])

    where ``n`` is the number of extra parameters and args is an array
    of doubles of the additional parameters.  This function may then
    be compiled to a dynamic/shared library then imported through
    ``ctypes``, setting the function's argtypes to ``(c_int, c_double)``,
    and the function's restype to ``(c_double)``.  Its pointer may then be
    passed into `nquad` normally.
    This allows the underlying Fortran library to evaluate the function in
    the innermost integration calls without callbacks to Python, and also
    speeds up the evaluation of the function itself.
ranges : iterable object
    Each element of ranges may be either a sequence  of 2 numbers, or else
    a callable that returns such a sequence.  ``ranges[0]`` corresponds to
    integration over x0, and so on.  If an element of ranges is a callable,
    then it will be called with all of the integration arguments available.
    e.g. if ``func = f(x0, x1, x2)``, then ``ranges[0]`` may be defined as
    either ``(a, b)`` or else as ``(a, b) = range0(x1, x2)``.
args : iterable object, optional
    Additional arguments ``t0, ..., tn``, required by `func`.
opts : iterable object or dict, optional
    Options to be passed to `quad`.  May be empty, a dict, or
    a sequence of dicts or functions that return a dict.  If empty, the
    default options from scipy.integrate.quadare used.  If a dict, the same
    options are used for all levels of integraion.  If a sequence, then each
    element of the sequence corresponds to a particular integration. e.g.
    opts[0] corresponds to integration over x0, and so on. The available
    options together with their default values are:

      - epsabs = 1.49e-08
      - epsrel = 1.49e-08
      - limit  = 50
      - points = None
      - weight = None
      - wvar   = None
      - wopts  = None

    The ``full_output`` option from `quad` is unavailable, due to the
    complexity of handling the large amount of data such an option would
    return for this kind of nested integration.  For more information on
    these options, see `quad` and `quad_explain`.

Returns
-------
result : float
    The result of the integration.
abserr : float
    The maximum of the estimates of the absolute error in the various
    integration results.

See Also
--------
quad : 1-dimensional numerical integration
dblquad, tplquad : double and triple integrals
fixed_quad : fixed-order Gaussian quadrature
quadrature : adaptive Gaussian quadrature

Examples
--------
>>> from scipy import integrate
>>> func = lambda x0,x1,x2,x3 : x0**2 + x1*x2 - x3**3 + np.sin(x0) + (
...                                 1 if (x0-.2*x3-.5-.25*x1>0) else 0)
>>> points = [[lambda (x1,x2,x3) : 0.2*x3 + 0.5 + 0.25*x1], [], [], []]
>>> def opts0(*args, **kwargs):
...     return {'points':[0.2*args[2] + 0.5 + 0.25*args[0]]}
>>> integrate.nquad(func, [[0,1], [-1,1], [.13,.8], [-.15,1]],
...                 opts=[opts0,{},{},{}])
(1.5267454070738633, 2.9437360001402324e-14)

>>> scale = .1
>>> def func2(x0, x1, x2, x3, t0, t1):
...     return x0*x1*x3**2 + np.sin(x2) + 1 + (1 if x0+t1*x1-t0>0 else 0)
>>> def lim0(x1, x2, x3, t0, t1):
...     return [scale * (x1**2 + x2 + np.cos(x3)*t0*t1 + 1) - 1,
...             scale * (x1**2 + x2 + np.cos(x3)*t0*t1 + 1) + 1]
>>> def lim1(x2, x3, t0, t1):
...     return [scale * (t0*x2 + t1*x3) - 1,
...             scale * (t0*x2 + t1*x3) + 1]
>>> def lim2(x3, t0, t1):
...     return [scale * (x3 + t0**2*t1**3) - 1,
...             scale * (x3 + t0**2*t1**3) + 1]
>>> def lim3(t0, t1):
...     return [scale * (t0+t1) - 1, scale * (t0+t1) + 1]
>>> def opts0(x1, x2, x3, t0, t1):
...     return {'points' : [t0 - t1*x1]}
>>> def opts1(x2, x3, t0, t1):
...     return {}
>>> def opts2(x3, t0, t1):
...     return {}
>>> def opts3(t0, t1):
...     return {}
>>> integrate.nquad(func2, [lim0, lim1, lim2, lim3], args=(0,0),
                    opts=[opts0, opts1, opts2, opts3])
(25.066666666666666, 2.7829590483937256e-13)


def dblquad(func, a, b, gfun, hfun, args=(), epsabs=<NUM_LIT>, epsrel=<NUM_LIT>):

return quad(_infunc, a, b, (func, gfun, hfun, args),<EOL>epsabs=epsabs, epsrel=epsrel)<EOL>

Compute a double integral.

Return the double (definite) integral of ``func(y, x)`` from ``x = a..b``
and ``y = gfun(x)..hfun(x)``.

Parameters
----------
func : callable
    A Python function or method of at least two variables: y must be the
    first argument and x the second argument.
(a,b) : tuple
    The limits of integration in x: `a` < `b`
gfun : callable
    The lower boundary curve in y which is a function taking a single
    floating point argument (x) and returning a floating point result: a
    lambda function can be useful here.
hfun : callable
    The upper boundary curve in y (same requirements as `gfun`).
args : sequence, optional
    Extra arguments to pass to `func`.
epsabs : float, optional
    Absolute tolerance passed directly to the inner 1-D quadrature
    integration. Default is 1.49e-8.
epsrel : float
    Relative tolerance of the inner 1-D integrals. Default is 1.49e-8.

Returns
-------
y : float
    The resultant integral.
abserr : float
    An estimate of the error.

See also
--------
quad : single integral
tplquad : triple integral
nquad : N-dimensional integrals
fixed_quad : fixed-order Gaussian quadrature
quadrature : adaptive Gaussian quadrature
odeint : ODE integrator
ode : ODE integrator
simps : integrator for sampled data
romb : integrator for sampled data
scipy.special : for coefficients and roots of orthogonal polynomials


def quad(func, a, b, args=(), full_output=<NUM_LIT:0>, epsabs=<NUM_LIT>, epsrel=<NUM_LIT>,<EOL>limit=<NUM_LIT:50>, points=None, weight=None, wvar=None, wopts=None, maxp1=<NUM_LIT:50>,<EOL>limlst=<NUM_LIT:50>):

if not isinstance(args, tuple):<EOL><INDENT>args = (args,)<EOL><DEDENT>if (weight is None):<EOL><INDENT>retval = _quad(func, a, b, args, full_output, epsabs, epsrel, limit,<EOL>points)<EOL><DEDENT>else:<EOL><INDENT>retval = _quad_weight(func, a, b, args, full_output, epsabs, epsrel,<EOL>limlst, limit, maxp1, weight, wvar, wopts)<EOL><DEDENT>ier = retval[-<NUM_LIT:1>]<EOL>if ier == <NUM_LIT:0>:<EOL><INDENT>return retval[:-<NUM_LIT:1>]<EOL><DEDENT>msgs = {<NUM_LIT>: "<STR_LIT>",<EOL><NUM_LIT:1>: "<STR_LIT>" % limit,<EOL><NUM_LIT:2>: "<STR_LIT>",<EOL><NUM_LIT:3>: "<STR_LIT>",<EOL><NUM_LIT:4>: "<STR_LIT>",<EOL><NUM_LIT:5>: "<STR_LIT>",<EOL><NUM_LIT:6>: "<STR_LIT>",<EOL><NUM_LIT:7>: "<STR_LIT>",<EOL>'<STR_LIT>': "<STR_LIT>"}<EOL>if weight in ['<STR_LIT>','<STR_LIT>'] and (b == Inf or a == -Inf):<EOL><INDENT>msgs[<NUM_LIT:1>] = "<STR_LIT>"<EOL>msgs[<NUM_LIT:4>] = "<STR_LIT>"<EOL>msgs[<NUM_LIT:7>] = "<STR_LIT>"<EOL>explain = {<NUM_LIT:1>: "<STR_LIT>",<EOL><NUM_LIT:2>: "<STR_LIT>",<EOL><NUM_LIT:3>: "<STR_LIT>",<EOL><NUM_LIT:4>: "<STR_LIT>",<EOL><NUM_LIT:5>: "<STR_LIT>"}<EOL><DEDENT>try:<EOL><INDENT>msg = msgs[ier]<EOL><DEDENT>except KeyError:<EOL><INDENT>msg = msgs['<STR_LIT>']<EOL><DEDENT>if ier in [<NUM_LIT:1>,<NUM_LIT:2>,<NUM_LIT:3>,<NUM_LIT:4>,<NUM_LIT:5>,<NUM_LIT:7>]:<EOL><INDENT>if full_output:<EOL><INDENT>if weight in ['<STR_LIT>','<STR_LIT>'] and (b == Inf or a == Inf):<EOL><INDENT>return retval[:-<NUM_LIT:1>] + (msg, explain)<EOL><DEDENT>else:<EOL><INDENT>return retval[:-<NUM_LIT:1>] + (msg,)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>warnings.warn(msg, IntegrationWarning)<EOL>return retval[:-<NUM_LIT:1>]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError(msg)<EOL><DEDENT>

Compute a definite integral.

Integrate func from `a` to `b` (possibly infinite interval) using a
technique from the Fortran library QUADPACK.

Parameters
----------
func : function
    A Python function or method to integrate.  If `func` takes many
    arguments, it is integrated along the axis corresponding to the
    first argument.
    If the user desires improved integration performance, then f may
    instead be a ``ctypes`` function of the form:

        f(int n, double args[n]),

    where ``args`` is an array of function arguments and ``n`` is the
    length of ``args``. ``f.argtypes`` should be set to
    ``(c_int, c_double)``, and ``f.restype`` should be ``(c_double,)``.
a : float
    Lower limit of integration (use -numpy.inf for -infinity).
b : float
    Upper limit of integration (use numpy.inf for +infinity).
args : tuple, optional
    Extra arguments to pass to `func`.
full_output : int, optional
    Non-zero to return a dictionary of integration information.
    If non-zero, warning messages are also suppressed and the
    message is appended to the output tuple.

Returns
-------
y : float
    The integral of func from `a` to `b`.
abserr : float
    An estimate of the absolute error in the result.
infodict : dict
    A dictionary containing additional information.
    Run scipy.integrate.quad_explain() for more information.
message :
    A convergence message.
explain :
    Appended only with 'cos' or 'sin' weighting and infinite
    integration limits, it contains an explanation of the codes in
    infodict['ierlst']

Other Parameters
----------------
epsabs : float or int, optional
    Absolute error tolerance.
epsrel : float or int, optional
    Relative error tolerance.
limit : float or int, optional
    An upper bound on the number of subintervals used in the adaptive
    algorithm.
points : (sequence of floats,ints), optional
    A sequence of break points in the bounded integration interval
    where local difficulties of the integrand may occur (e.g.,
    singularities, discontinuities). The sequence does not have
    to be sorted.
weight : float or int, optional
    String indicating weighting function. Full explanation for this
    and the remaining arguments can be found below.
wvar : optional
    Variables for use with weighting functions.
wopts : optional
    Optional input for reusing Chebyshev moments.
maxp1 : float or int, optional
    An upper bound on the number of Chebyshev moments.
limlst : int, optional
    Upper bound on the number of cycles (>=3) for use with a sinusoidal
    weighting and an infinite end-point.

See Also
--------
dblquad : double integral
tplquad : triple integral
nquad : n-dimensional integrals (uses `quad` recursively)
fixed_quad : fixed-order Gaussian quadrature
quadrature : adaptive Gaussian quadrature
odeint : ODE integrator
ode : ODE integrator
simps : integrator for sampled data
romb : integrator for sampled data
scipy.special : for coefficients and roots of orthogonal polynomials

Notes
-----

**Extra information for quad() inputs and outputs**

If full_output is non-zero, then the third output argument
(infodict) is a dictionary with entries as tabulated below.  For
infinite limits, the range is transformed to (0,1) and the
optional outputs are given with respect to this transformed range.
Let M be the input argument limit and let K be infodict['last'].
The entries are:

'neval'
    The number of function evaluations.
'last'
    The number, K, of subintervals produced in the subdivision process.
'alist'
    A rank-1 array of length M, the first K elements of which are the
    left end points of the subintervals in the partition of the
    integration range.
'blist'
    A rank-1 array of length M, the first K elements of which are the
    right end points of the subintervals.
'rlist'
    A rank-1 array of length M, the first K elements of which are the
    integral approximations on the subintervals.
'elist'
    A rank-1 array of length M, the first K elements of which are the
    moduli of the absolute error estimates on the subintervals.
'iord'
    A rank-1 integer array of length M, the first L elements of
    which are pointers to the error estimates over the subintervals
    with ``L=K`` if ``K<=M/2+2`` or ``L=M+1-K`` otherwise. Let I be the
    sequence ``infodict['iord']`` and let E be the sequence
    ``infodict['elist']``.  Then ``E[I[1]], ..., E[I[L]]`` forms a
    decreasing sequence.

If the input argument points is provided (i.e. it is not None),
the following additional outputs are placed in the output
dictionary.  Assume the points sequence is of length P.

'pts'
    A rank-1 array of length P+2 containing the integration limits
    and the break points of the intervals in ascending order.
    This is an array giving the subintervals over which integration
    will occur.
'level'
    A rank-1 integer array of length M (=limit), containing the
    subdivision levels of the subintervals, i.e., if (aa,bb) is a
    subinterval of ``(pts[1], pts[2])`` where ``pts[0]`` and ``pts[2]``
    are adjacent elements of ``infodict['pts']``, then (aa,bb) has level l
    if ``|bb-aa| = |pts[2]-pts[1]| * 2**(-l)``.
'ndin'
    A rank-1 integer array of length P+2.  After the first integration
    over the intervals (pts[1], pts[2]), the error estimates over some
    of the intervals may have been increased artificially in order to
    put their subdivision forward.  This array has ones in slots
    corresponding to the subintervals for which this happens.

**Weighting the integrand**

The input variables, *weight* and *wvar*, are used to weight the
integrand by a select list of functions.  Different integration
methods are used to compute the integral with these weighting
functions.  The possible values of weight and the corresponding
weighting functions are.

==========  ===================================   =====================
``weight``  Weight function used                  ``wvar``
==========  ===================================   =====================
'cos'       cos(w*x)                              wvar = w
'sin'       sin(w*x)                              wvar = w
'alg'       g(x) = ((x-a)**alpha)*((b-x)**beta)   wvar = (alpha, beta)
'alg-loga'  g(x)*log(x-a)                         wvar = (alpha, beta)
'alg-logb'  g(x)*log(b-x)                         wvar = (alpha, beta)
'alg-log'   g(x)*log(x-a)*log(b-x)                wvar = (alpha, beta)
'cauchy'    1/(x-c)                               wvar = c
==========  ===================================   =====================

wvar holds the parameter w, (alpha, beta), or c depending on the weight
selected.  In these expressions, a and b are the integration limits.

For the 'cos' and 'sin' weighting, additional inputs and outputs are
available.

For finite integration limits, the integration is performed using a
Clenshaw-Curtis method which uses Chebyshev moments.  For repeated
calculations, these moments are saved in the output dictionary:

'momcom'
    The maximum level of Chebyshev moments that have been computed,
    i.e., if ``M_c`` is ``infodict['momcom']`` then the moments have been
    computed for intervals of length ``|b-a| * 2**(-l)``,
    ``l=0,1,...,M_c``.
'nnlog'
    A rank-1 integer array of length M(=limit), containing the
    subdivision levels of the subintervals, i.e., an element of this
    array is equal to l if the corresponding subinterval is
    ``|b-a|* 2**(-l)``.
'chebmo'
    A rank-2 array of shape (25, maxp1) containing the computed
    Chebyshev moments.  These can be passed on to an integration
    over the same interval by passing this array as the second
    element of the sequence wopts and passing infodict['momcom'] as
    the first element.

If one of the integration limits is infinite, then a Fourier integral is
computed (assuming w neq 0).  If full_output is 1 and a numerical error
is encountered, besides the error message attached to the output tuple,
a dictionary is also appended to the output tuple which translates the
error codes in the array ``info['ierlst']`` to English messages.  The
output information dictionary contains the following entries instead of
'last', 'alist', 'blist', 'rlist', and 'elist':

'lst'
    The number of subintervals needed for the integration (call it ``K_f``).
'rslst'
    A rank-1 array of length M_f=limlst, whose first ``K_f`` elements
    contain the integral contribution over the interval
    ``(a+(k-1)c, a+kc)`` where ``c = (2*floor(|w|) + 1) * pi / |w|``
    and ``k=1,2,...,K_f``.
'erlst'
    A rank-1 array of length ``M_f`` containing the error estimate
    corresponding to the interval in the same position in
    ``infodict['rslist']``.
'ierlst'
    A rank-1 integer array of length ``M_f`` containing an error flag
    corresponding to the interval in the same position in
    ``infodict['rslist']``.  See the explanation dictionary (last entry
    in the output tuple) for the meaning of the codes.

Examples
--------
Calculate :math:`\\int^4_0 x^2 dx` and compare with an analytic result

>>> from scipy import integrate
>>> x2 = lambda x: x**2
>>> integrate.quad(x2, 0, 4)
(21.333333333333332, 2.3684757858670003e-13)
>>> print(4**3 / 3.)  # analytical result
21.3333333333

Calculate :math:`\\int^\\infty_0 e^{-x} dx`

>>> invexp = lambda x: np.exp(-x)
>>> integrate.quad(invexp, 0, np.inf)
(1.0, 5.842605999138044e-11)

>>> f = lambda x,a : a*x
>>> y, err = integrate.quad(f, 0, 1, args=(1,))
>>> y
0.5
>>> y, err = integrate.quad(f, 0, 1, args=(3,))
>>> y
1.5

Calculate :math:`\\int^1_0 x^2 + y^2 dx` with ctypes, holding
y parameter as 1::

    testlib.c =>
        double func(int n, double args[n]){
            return args[0]*args[0] + args[1]*args[1];}
    compile to library testlib.*

>>> from scipy import integrate
>>> import ctypes
>>> lib = ctypes.CDLL('/home/.../testlib.*') #use absolute path
>>> lib.func.restype = ctypes.c_double
>>> lib.func.argtypes = (ctypes.c_int,ctypes.c_double)
>>> integrate.quad(lib.func,0,1,(1))
(1.3333333333333333, 1.4802973661668752e-14)
>>> print((1.0**3/3.0 + 1.0) - (0.0**3/3.0 + 0.0)) #Analytic result
1.3333333333333333


def alt_sg_coeffs(window_length, polyorder, pos):

if pos is None:<EOL><INDENT>pos = window_length // <NUM_LIT:2><EOL><DEDENT>t = np.arange(window_length)<EOL>unit = (t == pos).astype(int)<EOL>h = np.polyval(np.polyfit(t, unit, polyorder), t)<EOL>return h<EOL>

This is an alternative implementation of the SG coefficients.

    It uses numpy.polyfit and numpy.polyval.  The results should be
    equivalent to those of savgol_coeffs(), but this implementation
    is slower.

    window_length should be odd.


N = len(args)<EOL>if N == <NUM_LIT:2>:  <EOL><INDENT>self._num, self._den = normalize(*args)<EOL>self._update(N)<EOL>self.inputs = <NUM_LIT:1><EOL>if len(self.num.shape) > <NUM_LIT:1>:<EOL><INDENT>self.outputs = self.num.shape[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>self.outputs = <NUM_LIT:1><EOL><DEDENT><DEDENT>elif N == <NUM_LIT:3>:      <EOL><INDENT>self._zeros, self._poles, self._gain = args<EOL>self._update(N)<EOL>self.zeros = numpy.asarray(self.zeros)<EOL>self.poles = numpy.asarray(self.poles)<EOL>self.inputs = <NUM_LIT:1><EOL>if len(self.zeros.shape) > <NUM_LIT:1>:<EOL><INDENT>self.outputs = self.zeros.shape[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>self.outputs = <NUM_LIT:1><EOL><DEDENT><DEDENT>elif N == <NUM_LIT:4>:       <EOL><INDENT>self._A, self._B, self._C, self._D = abcd_normalize(*args)<EOL>self._update(N)<EOL>self.inputs = self.B.shape[-<NUM_LIT:1>]<EOL>self.outputs = self.C.shape[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>

Initialize the LTI system using either:

    - (numerator, denominator)
    - (zeros, poles, gain)
    - (A, B, C, D) : state-space.


return lsim(self, U, T, X0=X0)<EOL>

Return the response of a continuous-time system to input `U`.
See `scipy.signal.lsim` for details.


def impulse(system, X0=None, T=None, N=None):

if isinstance(system, lti):<EOL><INDENT>sys = system<EOL><DEDENT>else:<EOL><INDENT>sys = lti(*system)<EOL><DEDENT>if X0 is None:<EOL><INDENT>B = sys.B<EOL><DEDENT>else:<EOL><INDENT>B = sys.B + X0<EOL><DEDENT>if N is None:<EOL><INDENT>N = <NUM_LIT:100><EOL><DEDENT>if T is None:<EOL><INDENT>T = _default_response_times(sys.A, N)<EOL><DEDENT>else:<EOL><INDENT>T = asarray(T)<EOL><DEDENT>h = zeros(T.shape, sys.A.dtype)<EOL>s, v = linalg.eig(sys.A)<EOL>vi = linalg.inv(v)<EOL>C = sys.C<EOL>for k in range(len(h)):<EOL><INDENT>es = diag(numpy.exp(s * T[k]))<EOL>eA = dot(dot(v, es), vi)<EOL>eA = _cast_to_array_dtype(eA, h)<EOL>h[k] = squeeze(dot(dot(C, eA), B))<EOL><DEDENT>return T, h<EOL>

Impulse response of continuous-time system.

    Parameters
    ----------
    system : an instance of the LTI class or a tuple of array_like
        describing the system.
        The following gives the number of elements in the tuple and
        the interpretation:

            * 2 (num, den)
            * 3 (zeros, poles, gain)
            * 4 (A, B, C, D)

    X0 : array_like, optional
        Initial state-vector.  Defaults to zero.
    T : array_like, optional
        Time points.  Computed if not given.
    N : int, optional
        The number of time points to compute (if `T` is not given).

    Returns
    -------
    T : ndarray
        A 1-D array of time points.
    yout : ndarray
        A 1-D array containing the impulse response of the system (except for
        singularities at zero).


return tf2ss(*zpk2tf(z, p, k))<EOL>

Zero-pole-gain representation to state-space representation

    Parameters
    ----------
    z, p : sequence
        Zeros and poles.
    k : float
        System gain.

    Returns
    -------
    A, B, C, D : ndarray
        State space representation of the system, in controller canonical
        form.


return '<STR_LIT>'.format(<EOL>self.__class__.__name__,<EOL>repr(self.A),<EOL>repr(self.B),<EOL>repr(self.C),<EOL>repr(self.D),<EOL>)<EOL>

Canonical representation using state-space to preserve numerical
precision and any MIMO information


def dstep(system, x0=None, t=None, n=None):

<EOL>if len(system) == <NUM_LIT:3>:<EOL><INDENT>n_inputs = <NUM_LIT:1><EOL>dt = system[<NUM_LIT:2>]<EOL><DEDENT>elif len(system) == <NUM_LIT:4>:<EOL><INDENT>n_inputs = <NUM_LIT:1><EOL>dt = system[<NUM_LIT:3>]<EOL><DEDENT>elif len(system) == <NUM_LIT:5>:<EOL><INDENT>n_inputs = system[<NUM_LIT:1>].shape[<NUM_LIT:1>]<EOL>dt = system[<NUM_LIT:4>]<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" +<EOL>"<STR_LIT>" +<EOL>"<STR_LIT>")<EOL><DEDENT>if n is None:<EOL><INDENT>n = <NUM_LIT:100><EOL><DEDENT>if t is None:<EOL><INDENT>t = np.linspace(<NUM_LIT:0>, n * dt, n, endpoint=False)<EOL><DEDENT>yout = None<EOL>for i in range(<NUM_LIT:0>, n_inputs):<EOL><INDENT>u = np.zeros((t.shape[<NUM_LIT:0>], n_inputs))<EOL>u[:,i] = np.ones((t.shape[<NUM_LIT:0>],))<EOL>one_output = dlsim(system, u, t=t, x0=x0)<EOL>if yout is None:<EOL><INDENT>yout = (one_output[<NUM_LIT:1>],)<EOL><DEDENT>else:<EOL><INDENT>yout = yout + (one_output[<NUM_LIT:1>],)<EOL><DEDENT>tout = one_output[<NUM_LIT:0>]<EOL><DEDENT>return tout, yout<EOL>

Step response of discrete-time system.

    Parameters
    ----------
    system : a tuple describing the system.
        The following gives the number of elements in the tuple and
        the interpretation:

          * 3: (num, den, dt)
          * 4: (zeros, poles, gain, dt)
          * 5: (A, B, C, D, dt)

    x0 : array_like, optional
        Initial state-vector (default is zero).
    t : array_like, optional
        Time points (computed if not given).
    n : int, optional
        Number of time points to compute if `t` is not given.

    Returns
    -------
    t : ndarray
        Output time points, as a 1-D array.
    yout : tuple of array_like
        Step response of system.  Each element of the tuple represents
        the output of the system based on a step response to each input.

    See Also
    --------
    step, dimpulse, dlsim, cont2discrete


def dimpulse(system, x0=None, t=None, n=None):

<EOL>if len(system) == <NUM_LIT:3>:<EOL><INDENT>n_inputs = <NUM_LIT:1><EOL>dt = system[<NUM_LIT:2>]<EOL><DEDENT>elif len(system) == <NUM_LIT:4>:<EOL><INDENT>n_inputs = <NUM_LIT:1><EOL>dt = system[<NUM_LIT:3>]<EOL><DEDENT>elif len(system) == <NUM_LIT:5>:<EOL><INDENT>n_inputs = system[<NUM_LIT:1>].shape[<NUM_LIT:1>]<EOL>dt = system[<NUM_LIT:4>]<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" +<EOL>"<STR_LIT>" +<EOL>"<STR_LIT>")<EOL><DEDENT>if n is None:<EOL><INDENT>n = <NUM_LIT:100><EOL><DEDENT>if t is None:<EOL><INDENT>t = np.linspace(<NUM_LIT:0>, n * dt, n, endpoint=False)<EOL><DEDENT>yout = None<EOL>for i in range(<NUM_LIT:0>, n_inputs):<EOL><INDENT>u = np.zeros((t.shape[<NUM_LIT:0>], n_inputs))<EOL>u[<NUM_LIT:0>,i] = <NUM_LIT:1.0><EOL>one_output = dlsim(system, u, t=t, x0=x0)<EOL>if yout is None:<EOL><INDENT>yout = (one_output[<NUM_LIT:1>],)<EOL><DEDENT>else:<EOL><INDENT>yout = yout + (one_output[<NUM_LIT:1>],)<EOL><DEDENT>tout = one_output[<NUM_LIT:0>]<EOL><DEDENT>return tout, yout<EOL>

Impulse response of discrete-time system.

    Parameters
    ----------
    system : tuple
        The following gives the number of elements in the tuple and
        the interpretation:

          * 3: (num, den, dt)
          * 4: (zeros, poles, gain, dt)
          * 5: (A, B, C, D, dt)

    x0 : array_like, optional
        Initial state-vector.  Defaults to zero.
    t : array_like, optional
        Time points.  Computed if not given.
    n : int, optional
        The number of time points to compute (if `t` is not given).

    Returns
    -------
    t : ndarray
        A 1-D array of time points.
    yout : tuple of array_like
        Impulse response of system.  Each element of the tuple represents
        the output of the system based on an impulse in each input.

    See Also
    --------
    impulse, dstep, dlsim, cont2discrete


def correlate2d(in1, in2, mode='<STR_LIT>', boundary='<STR_LIT>', fillvalue=<NUM_LIT:0>):

in1 = asarray(in1)<EOL>in2 = asarray(in2)<EOL>if mode == '<STR_LIT>':<EOL><INDENT>_check_valid_mode_shapes(in1.shape, in2.shape)<EOL><DEDENT>val = _valfrommode(mode)<EOL>bval = _bvalfromboundary(boundary)<EOL>with warnings.catch_warnings():<EOL><INDENT>warnings.simplefilter('<STR_LIT:ignore>', np.ComplexWarning)<EOL>out = sigtools._convolve2d(in1, in2, <NUM_LIT:0>, val, bval, fillvalue)<EOL><DEDENT>return out<EOL>

Cross-correlate two 2-dimensional arrays.

Cross correlate `in1` and `in2` with output size determined by `mode`, and
boundary conditions determined by `boundary` and `fillvalue`.

Parameters
----------
in1, in2 : array_like
    Two-dimensional input arrays to be convolved.
mode : str {'full', 'valid', 'same'}, optional
    A string indicating the size of the output:

    ``full``
       The output is the full discrete linear cross-correlation
       of the inputs. (Default)
    ``valid``
       The output consists only of those elements that do not
       rely on the zero-padding.
    ``same``
       The output is the same size as `in1`, centered
       with respect to the 'full' output.

boundary : str {'fill', 'wrap', 'symm'}, optional
    A flag indicating how to handle boundaries:

    ``fill``
       pad input arrays with fillvalue. (default)
    ``wrap``
       circular boundary conditions.
    ``symm``
       symmetrical boundary conditions.

fillvalue : scalar, optional
    Value to fill pad input arrays with. Default is 0.

Returns
-------
correlate2d : ndarray
    A 2-dimensional array containing a subset of the discrete linear
    cross-correlation of `in1` with `in2`.

Examples
--------
Use 2D cross-correlation to find the location of a template in a noisy
image:

>>> from scipy import signal
>>> from scipy import misc
>>> lena = misc.lena() - misc.lena().mean()
>>> template = np.copy(lena[235:295, 310:370]) # right eye
>>> template -= template.mean()
>>> lena = lena + np.random.randn(*lena.shape) * 50 # add noise
>>> corr = signal.correlate2d(lena, template, boundary='symm', mode='same')
>>> y, x = np.unravel_index(np.argmax(corr), corr.shape) # find the match

>>> import matplotlib.pyplot as plt
>>> fig, (ax_orig, ax_template, ax_corr) = plt.subplots(1, 3)
>>> ax_orig.imshow(lena, cmap='gray')
>>> ax_orig.set_title('Original')
>>> ax_orig.set_axis_off()
>>> ax_template.imshow(template, cmap='gray')
>>> ax_template.set_title('Template')
>>> ax_template.set_axis_off()
>>> ax_corr.imshow(corr, cmap='gray')
>>> ax_corr.set_title('Cross-correlation')
>>> ax_corr.set_axis_off()
>>> ax_orig.plot(x, y, 'ro')
>>> fig.show()


events = asarray(events)<EOL>period = asarray(period)<EOL>if events.ndim > <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if period.ndim > <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>scalarperiod = not period.ndim<EOL>events = atleast_2d(events)<EOL>period = atleast_2d(period)<EOL>if (period <= <NUM_LIT:0>).any():<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>vectors = exp(dot(<NUM_LIT>*pi/period.T, events))<EOL>vectormean = mean(vectors, axis=<NUM_LIT:1>)<EOL>strength = abs(vectormean)<EOL>phase = angle(vectormean)<EOL>if scalarperiod:<EOL><INDENT>strength = strength[<NUM_LIT:0>]<EOL>phase = phase[<NUM_LIT:0>]<EOL><DEDENT>return strength, phase<EOL>

Determine the vector strength of the events corresponding to the given
period.

The vector strength is a measure of phase synchrony, how well the
timing of the events is synchronized to a single period of a periodic
signal.

If multiple periods are used, calculate the vector strength of each.
This is called the "resonating vector strength".

Parameters
----------
events : 1D array_like
    An array of time points containing the timing of the events.
period : float or array_like
    The period of the signal that the events should synchronize to.
    The period is in the same units as `events`.  It can also be an array
    of periods, in which case the outputs are arrays of the same length.

Returns
-------
strength : float or 1D array
    The strength of the synchronization.  1.0 is perfect synchronization
    and 0.0 is no synchronization.  If `period` is an array, this is also
    an array with each element containing the vector strength at the
    corresponding period.
phase : float or array
    The phase that the events are most strongly synchronized to in radians.
    If `period` is an array, this is also an array with each element
    containing the phase for the corresponding period.

References
----------
van Hemmen, JL, Longtin, A, and Vollmayr, AN. Testing resonating vector
    strength: Auditory system, electric fish, and noise.
    Chaos 21, 047508 (2011);
    doi: 10.1063/1.3670512
van Hemmen, JL.  Vector strength after Goldberg, Brown, and von Mises:
    biological and mathematical perspectives.  Biol Cybern.
    2013 Aug;107(4):385-96. doi: 10.1007/s00422-013-0561-7.
van Hemmen, JL and Vollmayr, AN.  Resonating vector strength: what happens
    when we vary the "probing" frequency while keeping the spike times
    fixed.  Biol Cybern. 2013 Aug;107(4):491-94.
    doi: 10.1007/s00422-013-0560-8


def hilbert(x, N=None, axis=-<NUM_LIT:1>):

x = asarray(x)<EOL>if iscomplexobj(x):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if N is None:<EOL><INDENT>N = x.shape[axis]<EOL><DEDENT>if N <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>Xf = fft(x, N, axis=axis)<EOL>h = zeros(N)<EOL>if N % <NUM_LIT:2> == <NUM_LIT:0>:<EOL><INDENT>h[<NUM_LIT:0>] = h[N // <NUM_LIT:2>] = <NUM_LIT:1><EOL>h[<NUM_LIT:1>:N // <NUM_LIT:2>] = <NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>h[<NUM_LIT:0>] = <NUM_LIT:1><EOL>h[<NUM_LIT:1>:(N + <NUM_LIT:1>) // <NUM_LIT:2>] = <NUM_LIT:2><EOL><DEDENT>if len(x.shape) > <NUM_LIT:1>:<EOL><INDENT>ind = [newaxis] * x.ndim<EOL>ind[axis] = slice(None)<EOL>h = h[ind]<EOL><DEDENT>x = ifft(Xf * h, axis=axis)<EOL>return x<EOL>

Compute the analytic signal, using the Hilbert transform.

The transformation is done along the last axis by default.

Parameters
----------
x : array_like
    Signal data.  Must be real.
N : int, optional
    Number of Fourier components.  Default: ``x.shape[axis]``
axis : int, optional
    Axis along which to do the transformation.  Default: -1.

Returns
-------
xa : ndarray
    Analytic signal of `x`, of each 1-D array along `axis`

Notes
-----
The analytic signal ``x_a(t)`` of signal ``x(t)`` is:

.. math:: x_a = F^{-1}(F(x) 2U) = x + i y

where `F` is the Fourier transform, `U` the unit step function,
and `y` the Hilbert transform of `x`. [1]_

In other words, the negative half of the frequency spectrum is zeroed
out, turning the real-valued signal into a complex signal.  The Hilbert
transformed signal can be obtained from ``np.imag(hilbert(x))``, and the
original signal from ``np.real(hilbert(x))``.

References
----------
.. [1] Wikipedia, "Analytic signal".
       http://en.wikipedia.org/wiki/Analytic_signal