from numpy.core import ndarray<EOL>from numpy.lib import iscomplexobj, real, imag<EOL>try:<EOL><INDENT>usecomplex = iscomplexobj(actual) or iscomplexobj(desired)<EOL><DEDENT>except ValueError:<EOL><INDENT>usecomplex = False<EOL><DEDENT>def _build_err_msg():<EOL><INDENT>header = ('<STR_LIT>' % decimal)<EOL>return build_err_msg([actual, desired], err_msg, verbose=verbose,<EOL>header=header)<EOL><DEDENT>if usecomplex:<EOL><INDENT>if iscomplexobj(actual):<EOL><INDENT>actualr = real(actual)<EOL>actuali = imag(actual)<EOL><DEDENT>else:<EOL><INDENT>actualr = actual<EOL>actuali = <NUM_LIT:0><EOL><DEDENT>if iscomplexobj(desired):<EOL><INDENT>desiredr = real(desired)<EOL>desiredi = imag(desired)<EOL><DEDENT>else:<EOL><INDENT>desiredr = desired<EOL>desiredi = <NUM_LIT:0><EOL><DEDENT>try:<EOL><INDENT>assert_almost_equal(actualr, desiredr, decimal=decimal)<EOL>assert_almost_equal(actuali, desiredi, decimal=decimal)<EOL><DEDENT>except AssertionError:<EOL><INDENT>raise AssertionError(_build_err_msg())<EOL><DEDENT><DEDENT>if isinstance(actual, (ndarray, tuple, list))or isinstance(desired, (ndarray, tuple, list)):<EOL><INDENT>return assert_array_almost_equal(actual, desired, decimal, err_msg)<EOL><DEDENT>try:<EOL><INDENT>if not (gisfinite(desired) and gisfinite(actual)):<EOL><INDENT>if gisnan(desired) or gisnan(actual):<EOL><INDENT>if not (gisnan(desired) and gisnan(actual)):<EOL><INDENT>raise AssertionError(_build_err_msg())<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if not desired == actual:<EOL><INDENT>raise AssertionError(_build_err_msg())<EOL><DEDENT><DEDENT>return<EOL><DEDENT><DEDENT>except (NotImplementedError, TypeError):<EOL><INDENT>pass<EOL><DEDENT>if round(abs(desired - actual), decimal) != <NUM_LIT:0> :<EOL><INDENT>raise AssertionError(_build_err_msg())<EOL><DEDENT>

Raises an AssertionError if two items are not equal up to desired
precision.

.. note:: It is recommended to use one of `assert_allclose`,
          `assert_array_almost_equal_nulp` or `assert_array_max_ulp`
          instead of this function for more consistent floating point
          comparisons.

The test is equivalent to ``abs(desired-actual) < 0.5 * 10**(-decimal)``.

Given two objects (numbers or ndarrays), check that all elements of these
objects are almost equal. An exception is raised at conflicting values.
For ndarrays this delegates to assert_array_almost_equal

Parameters
----------
actual : array_like
    The object to check.
desired : array_like
    The expected object.
decimal : int, optional
    Desired precision, default is 7.
err_msg : str, optional
    The error message to be printed in case of failure.
verbose : bool, optional
    If True, the conflicting values are appended to the error message.

Raises
------
AssertionError
  If actual and desired are not equal up to specified precision.

See Also
--------
assert_allclose: Compare two array_like objects for equality with desired
                 relative and/or absolute precision.
assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal

Examples
--------
>>> import numpy.testing as npt
>>> npt.assert_almost_equal(2.3333333333333, 2.33333334)
>>> npt.assert_almost_equal(2.3333333333333, 2.33333334, decimal=10)
...
<type 'exceptions.AssertionError'>:
Items are not equal:
 ACTUAL: 2.3333333333333002
 DESIRED: 2.3333333399999998

>>> npt.assert_almost_equal(np.array([1.0,2.3333333333333]),
...                         np.array([1.0,2.33333334]), decimal=9)
...
<type 'exceptions.AssertionError'>:
Arrays are not almost equal
<BLANKLINE>
(mismatch 50.0%)
 x: array([ 1.        ,  2.33333333])
 y: array([ 1.        ,  2.33333334])


import numpy as np<EOL>(actual, desired) = map(float, (actual, desired))<EOL>if desired==actual:<EOL><INDENT>return<EOL><DEDENT>with np.errstate(invalid='<STR_LIT:ignore>'):<EOL><INDENT>scale = <NUM_LIT:0.5>*(np.abs(desired) + np.abs(actual))<EOL>scale = np.power(<NUM_LIT:10>, np.floor(np.log10(scale)))<EOL><DEDENT>try:<EOL><INDENT>sc_desired = desired/scale<EOL><DEDENT>except ZeroDivisionError:<EOL><INDENT>sc_desired = <NUM_LIT:0.0><EOL><DEDENT>try:<EOL><INDENT>sc_actual = actual/scale<EOL><DEDENT>except ZeroDivisionError:<EOL><INDENT>sc_actual = <NUM_LIT:0.0><EOL><DEDENT>msg = build_err_msg([actual, desired], err_msg,<EOL>header='<STR_LIT>' %<EOL>significant,<EOL>verbose=verbose)<EOL>try:<EOL><INDENT>if not (gisfinite(desired) and gisfinite(actual)):<EOL><INDENT>if gisnan(desired) or gisnan(actual):<EOL><INDENT>if not (gisnan(desired) and gisnan(actual)):<EOL><INDENT>raise AssertionError(msg)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if not desired == actual:<EOL><INDENT>raise AssertionError(msg)<EOL><DEDENT><DEDENT>return<EOL><DEDENT><DEDENT>except (TypeError, NotImplementedError):<EOL><INDENT>pass<EOL><DEDENT>if np.abs(sc_desired - sc_actual) >= np.power(<NUM_LIT>, -(significant-<NUM_LIT:1>)) :<EOL><INDENT>raise AssertionError(msg)<EOL><DEDENT>

Raises an AssertionError if two items are not equal up to significant
digits.

.. note:: It is recommended to use one of `assert_allclose`,
          `assert_array_almost_equal_nulp` or `assert_array_max_ulp`
          instead of this function for more consistent floating point
          comparisons.

Given two numbers, check that they are approximately equal.
Approximately equal is defined as the number of significant digits
that agree.

Parameters
----------
actual : scalar
    The object to check.
desired : scalar
    The expected object.
significant : int, optional
    Desired precision, default is 7.
err_msg : str, optional
    The error message to be printed in case of failure.
verbose : bool, optional
    If True, the conflicting values are appended to the error message.

Raises
------
AssertionError
  If actual and desired are not equal up to specified precision.

See Also
--------
assert_allclose: Compare two array_like objects for equality with desired
                 relative and/or absolute precision.
assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal

Examples
--------
>>> np.testing.assert_approx_equal(0.12345677777777e-20, 0.1234567e-20)
>>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345671e-20,
                                   significant=8)
>>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345672e-20,
                                   significant=8)
...
<type 'exceptions.AssertionError'>:
Items are not equal to 8 significant digits:
 ACTUAL: 1.234567e-021
 DESIRED: 1.2345672000000001e-021

the evaluated condition that raises the exception is

>>> abs(0.12345670e-20/1e-21 - 0.12345672e-20/1e-21) >= 10**-(8-1)
True


def assert_array_equal(x, y, err_msg='<STR_LIT>', verbose=True):

assert_array_compare(operator.__eq__, x, y, err_msg=err_msg,<EOL>verbose=verbose, header='<STR_LIT>')<EOL>

Raises an AssertionError if two array_like objects are not equal.

Given two array_like objects, check that the shape is equal and all
elements of these objects are equal. An exception is raised at
shape mismatch or conflicting values. In contrast to the standard usage
in numpy, NaNs are compared like numbers, no assertion is raised if
both objects have NaNs in the same positions.

The usual caution for verifying equality with floating point numbers is
advised.

Parameters
----------
x : array_like
    The actual object to check.
y : array_like
    The desired, expected object.
err_msg : str, optional
    The error message to be printed in case of failure.
verbose : bool, optional
    If True, the conflicting values are appended to the error message.

Raises
------
AssertionError
    If actual and desired objects are not equal.

See Also
--------
assert_allclose: Compare two array_like objects for equality with desired
                 relative and/or absolute precision.
assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal

Examples
--------
The first assert does not raise an exception:

>>> np.testing.assert_array_equal([1.0,2.33333,np.nan],
...                               [np.exp(0),2.33333, np.nan])

Assert fails with numerical inprecision with floats:

>>> np.testing.assert_array_equal([1.0,np.pi,np.nan],
...                               [1, np.sqrt(np.pi)**2, np.nan])
...
<type 'exceptions.ValueError'>:
AssertionError:
Arrays are not equal
<BLANKLINE>
(mismatch 50.0%)
 x: array([ 1.        ,  3.14159265,         NaN])
 y: array([ 1.        ,  3.14159265,         NaN])

Use `assert_allclose` or one of the nulp (number of floating point values)
functions for these cases instead:

>>> np.testing.assert_allclose([1.0,np.pi,np.nan],
...                            [1, np.sqrt(np.pi)**2, np.nan],
...                            rtol=1e-10, atol=0)


def assert_array_almost_equal(x, y, decimal=<NUM_LIT:6>, err_msg='<STR_LIT>', verbose=True):

from numpy.core import around, number, float_, result_type, array<EOL>from numpy.core.numerictypes import issubdtype<EOL>from numpy.core.fromnumeric import any as npany<EOL>def compare(x, y):<EOL><INDENT>try:<EOL><INDENT>if npany(gisinf(x)) or npany( gisinf(y)):<EOL><INDENT>xinfid = gisinf(x)<EOL>yinfid = gisinf(y)<EOL>if not xinfid == yinfid:<EOL><INDENT>return False<EOL><DEDENT>if x.size == y.size == <NUM_LIT:1>:<EOL><INDENT>return x == y<EOL><DEDENT>x = x[~xinfid]<EOL>y = y[~yinfid]<EOL><DEDENT><DEDENT>except (TypeError, NotImplementedError):<EOL><INDENT>pass<EOL><DEDENT>dtype = result_type(y, <NUM_LIT:1.>)<EOL>y = array(y, dtype=dtype, copy=False, subok=True)<EOL>z = abs(x-y)<EOL>if not issubdtype(z.dtype, number):<EOL><INDENT>z = z.astype(float_) <EOL><DEDENT>return around(z, decimal) <= <NUM_LIT>**(-decimal)<EOL><DEDENT>assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose,<EOL>header=('<STR_LIT>' % decimal),<EOL>precision=decimal)<EOL>

Raises an AssertionError if two objects are not equal up to desired
precision.

.. note:: It is recommended to use one of `assert_allclose`,
          `assert_array_almost_equal_nulp` or `assert_array_max_ulp`
          instead of this function for more consistent floating point
          comparisons.

The test verifies identical shapes and verifies values with
``abs(desired-actual) < 0.5 * 10**(-decimal)``.

Given two array_like objects, check that the shape is equal and all
elements of these objects are almost equal. An exception is raised at
shape mismatch or conflicting values. In contrast to the standard usage
in numpy, NaNs are compared like numbers, no assertion is raised if
both objects have NaNs in the same positions.

Parameters
----------
x : array_like
    The actual object to check.
y : array_like
    The desired, expected object.
decimal : int, optional
    Desired precision, default is 6.
err_msg : str, optional
  The error message to be printed in case of failure.
verbose : bool, optional
    If True, the conflicting values are appended to the error message.

Raises
------
AssertionError
    If actual and desired are not equal up to specified precision.

See Also
--------
assert_allclose: Compare two array_like objects for equality with desired
                 relative and/or absolute precision.
assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal

Examples
--------
the first assert does not raise an exception

>>> np.testing.assert_array_almost_equal([1.0,2.333,np.nan],
                                         [1.0,2.333,np.nan])

>>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan],
...                                      [1.0,2.33339,np.nan], decimal=5)
...
<type 'exceptions.AssertionError'>:
AssertionError:
Arrays are not almost equal
<BLANKLINE>
(mismatch 50.0%)
 x: array([ 1.     ,  2.33333,      NaN])
 y: array([ 1.     ,  2.33339,      NaN])

>>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan],
...                                      [1.0,2.33333, 5], decimal=5)
<type 'exceptions.ValueError'>:
ValueError:
Arrays are not almost equal
 x: array([ 1.     ,  2.33333,      NaN])
 y: array([ 1.     ,  2.33333,  5.     ])


def assert_array_less(x, y, err_msg='<STR_LIT>', verbose=True):

assert_array_compare(operator.__lt__, x, y, err_msg=err_msg,<EOL>verbose=verbose,<EOL>header='<STR_LIT>')<EOL>

Raises an AssertionError if two array_like objects are not ordered by less
than.

Given two array_like objects, check that the shape is equal and all
elements of the first object are strictly smaller than those of the
second object. An exception is raised at shape mismatch or incorrectly
ordered values. Shape mismatch does not raise if an object has zero
dimension. In contrast to the standard usage in numpy, NaNs are
compared, no assertion is raised if both objects have NaNs in the same
positions.

Parameters
----------
x : array_like
  The smaller object to check.
y : array_like
  The larger object to compare.
err_msg : string
  The error message to be printed in case of failure.
verbose : bool
    If True, the conflicting values are appended to the error message.

Raises
------
AssertionError
  If actual and desired objects are not equal.

See Also
--------
assert_array_equal: tests objects for equality
assert_array_almost_equal: test objects for equality up to precision

Examples
--------
>>> np.testing.assert_array_less([1.0, 1.0, np.nan], [1.1, 2.0, np.nan])
>>> np.testing.assert_array_less([1.0, 1.0, np.nan], [1, 2.0, np.nan])
...
<type 'exceptions.ValueError'>:
Arrays are not less-ordered
(mismatch 50.0%)
 x: array([  1.,   1.,  NaN])
 y: array([  1.,   2.,  NaN])

>>> np.testing.assert_array_less([1.0, 4.0], 3)
...
<type 'exceptions.ValueError'>:
Arrays are not less-ordered
(mismatch 50.0%)
 x: array([ 1.,  4.])
 y: array(3)

>>> np.testing.assert_array_less([1.0, 2.0, 3.0], [4])
...
<type 'exceptions.ValueError'>:
Arrays are not less-ordered
(shapes (3,), (1,) mismatch)
 x: array([ 1.,  2.,  3.])
 y: array([4])


<EOL>import difflib<EOL>if not isinstance(actual, str) :<EOL><INDENT>raise AssertionError(repr(type(actual)))<EOL><DEDENT>if not isinstance(desired, str):<EOL><INDENT>raise AssertionError(repr(type(desired)))<EOL><DEDENT>if re.match(r'<STR_LIT>'+desired+r'<STR_LIT>', actual, re.M):<EOL><INDENT>return<EOL><DEDENT>diff = list(difflib.Differ().compare(actual.splitlines(<NUM_LIT:1>), desired.splitlines(<NUM_LIT:1>)))<EOL>diff_list = []<EOL>while diff:<EOL><INDENT>d1 = diff.pop(<NUM_LIT:0>)<EOL>if d1.startswith('<STR_LIT:U+0020>'):<EOL><INDENT>continue<EOL><DEDENT>if d1.startswith('<STR_LIT>'):<EOL><INDENT>l = [d1]<EOL>d2 = diff.pop(<NUM_LIT:0>)<EOL>if d2.startswith('<STR_LIT>'):<EOL><INDENT>l.append(d2)<EOL>d2 = diff.pop(<NUM_LIT:0>)<EOL><DEDENT>if not d2.startswith('<STR_LIT>') :<EOL><INDENT>raise AssertionError(repr(d2))<EOL><DEDENT>l.append(d2)<EOL>d3 = diff.pop(<NUM_LIT:0>)<EOL>if d3.startswith('<STR_LIT>'):<EOL><INDENT>l.append(d3)<EOL><DEDENT>else:<EOL><INDENT>diff.insert(<NUM_LIT:0>, d3)<EOL><DEDENT>if re.match(r'<STR_LIT>'+d2[<NUM_LIT:2>:]+r'<STR_LIT>', d1[<NUM_LIT:2>:]):<EOL><INDENT>continue<EOL><DEDENT>diff_list.extend(l)<EOL>continue<EOL><DEDENT>raise AssertionError(repr(d1))<EOL><DEDENT>if not diff_list:<EOL><INDENT>return<EOL><DEDENT>msg = '<STR_LIT>' % ('<STR_LIT>'.join(diff_list)).rstrip()<EOL>if actual != desired :<EOL><INDENT>raise AssertionError(msg)<EOL><DEDENT>

Test if two strings are equal.

If the given strings are equal, `assert_string_equal` does nothing.
If they are not equal, an AssertionError is raised, and the diff
between the strings is shown.

Parameters
----------
actual : str
    The string to test for equality against the expected string.
desired : str
    The expected string.

Examples
--------
>>> np.testing.assert_string_equal('abc', 'abc')
>>> np.testing.assert_string_equal('abc', 'abcd')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
...
AssertionError: Differences in strings:
- abc+ abcd?    +


import doctest, imp<EOL>if filename is None:<EOL><INDENT>f = sys._getframe(<NUM_LIT:1>)<EOL>filename = f.f_globals['<STR_LIT>']<EOL><DEDENT>name = os.path.splitext(os.path.basename(filename))[<NUM_LIT:0>]<EOL>path = [os.path.dirname(filename)]<EOL>file, pathname, description = imp.find_module(name, path)<EOL>try:<EOL><INDENT>m = imp.load_module(name, file, pathname, description)<EOL><DEDENT>finally:<EOL><INDENT>file.close()<EOL><DEDENT>tests = doctest.DocTestFinder().find(m)<EOL>runner = doctest.DocTestRunner(verbose=False)<EOL>msg = []<EOL>if raise_on_error:<EOL><INDENT>out = lambda s: msg.append(s)<EOL><DEDENT>else:<EOL><INDENT>out = None<EOL><DEDENT>for test in tests:<EOL><INDENT>runner.run(test, out=out)<EOL><DEDENT>if runner.failures > <NUM_LIT:0> and raise_on_error:<EOL><INDENT>raise AssertionError("<STR_LIT>" % "<STR_LIT:\n>".join(msg))<EOL><DEDENT>

Run doctests found in the given file.

By default `rundocs` raises an AssertionError on failure.

Parameters
----------
filename : str
    The path to the file for which the doctests are run.
raise_on_error : bool
    Whether to raise an AssertionError when a doctest fails. Default is
    True.

Notes
-----
The doctests can be run by the user/developer by adding the ``doctests``
argument to the ``test()`` call. For example, to run all tests (including
doctests) for `numpy.lib`:

>>> np.lib.test(doctests=True) #doctest: +SKIP


nose = import_nose()<EOL>return nose.tools.assert_raises(*args,**kwargs)<EOL>

assert_raises(exception_class, callable, *args, **kwargs)

Fail unless an exception of class exception_class is thrown
by callable when invoked with arguments args and keyword
arguments kwargs. If a different type of exception is
thrown, it will not be caught, and the test case will be
deemed to have suffered an error, exactly as for an
unexpected exception.


def assert_raises_regex(exception_class, expected_regexp,<EOL>callable_obj=None, *args, **kwargs):

nose = import_nose()<EOL>global assert_raises_regex_impl<EOL>if assert_raises_regex_impl is None:<EOL><INDENT>try:<EOL><INDENT>assert_raises_regex_impl = nose.tools.assert_raises_regex<EOL><DEDENT>except AttributeError:<EOL><INDENT>try:<EOL><INDENT>assert_raises_regex_impl = nose.tools.assert_raises_regexp<EOL><DEDENT>except AttributeError:<EOL><INDENT>class _AssertRaisesContext(object):<EOL><INDENT>"""<STR_LIT>"""<EOL>def __init__(self, expected, expected_regexp=None):<EOL><INDENT>self.expected = expected<EOL>self.expected_regexp = expected_regexp<EOL><DEDENT>def failureException(self, msg):<EOL><INDENT>return AssertionError(msg)<EOL><DEDENT>def __enter__(self):<EOL><INDENT>return self<EOL><DEDENT>def __exit__(self, exc_type, exc_value, tb):<EOL><INDENT>if exc_type is None:<EOL><INDENT>try:<EOL><INDENT>exc_name = self.expected.__name__<EOL><DEDENT>except AttributeError:<EOL><INDENT>exc_name = str(self.expected)<EOL><DEDENT>raise self.failureException(<EOL>"<STR_LIT>".format(exc_name))<EOL><DEDENT>if not issubclass(exc_type, self.expected):<EOL><INDENT>return False<EOL><DEDENT>self.exception = exc_value  <EOL>if self.expected_regexp is None:<EOL><INDENT>return True<EOL><DEDENT>expected_regexp = self.expected_regexp<EOL>if isinstance(expected_regexp, basestring):<EOL><INDENT>expected_regexp = re.compile(expected_regexp)<EOL><DEDENT>if not expected_regexp.search(str(exc_value)):<EOL><INDENT>raise self.failureException(<EOL>'<STR_LIT>' %<EOL>(expected_regexp.pattern, str(exc_value)))<EOL><DEDENT>return True<EOL><DEDENT><DEDENT>def impl(cls, regex, callable_obj, *a, **kw):<EOL><INDENT>mgr = _AssertRaisesContext(cls, regex)<EOL>if callable_obj is None:<EOL><INDENT>return mgr<EOL><DEDENT>with mgr:<EOL><INDENT>callable_obj(*a, **kw)<EOL><DEDENT><DEDENT>assert_raises_regex_impl = impl<EOL><DEDENT><DEDENT><DEDENT>return assert_raises_regex_impl(exception_class, expected_regexp,<EOL>callable_obj, *args, **kwargs)<EOL>

Fail unless an exception of class exception_class and with message that
matches expected_regexp is thrown by callable when invoked with arguments
args and keyword arguments kwargs.

Name of this function adheres to Python 3.2+ reference, but should work in
all versions down to 2.6.


frame = sys._getframe(<NUM_LIT:1>)<EOL>locs, globs = frame.f_locals, frame.f_globals<EOL>code = compile(code_str,<EOL>'<STR_LIT>' % label,<EOL>'<STR_LIT>')<EOL>i = <NUM_LIT:0><EOL>elapsed = jiffies()<EOL>while i < times:<EOL><INDENT>i += <NUM_LIT:1><EOL>exec(code, globs, locs)<EOL><DEDENT>elapsed = jiffies() - elapsed<EOL>return <NUM_LIT>*elapsed<EOL>

Return elapsed time for executing code in the namespace of the caller.

The supplied code string is compiled with the Python builtin ``compile``.
The precision of the timing is 10 milli-seconds. If the code will execute
fast on this timescale, it can be executed many times to get reasonable
timing accuracy.

Parameters
----------
code_str : str
    The code to be timed.
times : int, optional
    The number of times the code is executed. Default is 1. The code is
    only compiled once.
label : str, optional
    A label to identify `code_str` with. This is passed into ``compile``
    as the second argument (for run-time error messages).

Returns
-------
elapsed : float
    Total elapsed time in seconds for executing `code_str` `times` times.

Examples
--------
>>> etime = np.testing.measure('for i in range(1000): np.sqrt(i**2)',
...                            times=times)
>>> print "Time for a single execution : ", etime / times, "s"
Time for a single execution :  0.005 s


import numpy as np<EOL>a = np.arange(<NUM_LIT:100> * <NUM_LIT:100>)<EOL>b = np.arange(<NUM_LIT:100>*<NUM_LIT:100>).reshape(<NUM_LIT:100>, <NUM_LIT:100>)<EOL>c = b<EOL>i = <NUM_LIT:1><EOL>rc = sys.getrefcount(i)<EOL>for j in range(<NUM_LIT:15>):<EOL><INDENT>d = op(b, c)<EOL><DEDENT>assert_(sys.getrefcount(i) >= rc)<EOL>

Check that ufuncs don't mishandle refcount of object `1`.
Used in a few regression tests.


def assert_allclose(actual, desired, rtol=<NUM_LIT>, atol=<NUM_LIT:0>,<EOL>err_msg='<STR_LIT>', verbose=True):

import numpy as np<EOL>def compare(x, y):<EOL><INDENT>return np.allclose(x, y, rtol=rtol, atol=atol)<EOL><DEDENT>actual, desired = np.asanyarray(actual), np.asanyarray(desired)<EOL>header = '<STR_LIT>' % (rtol, atol)<EOL>assert_array_compare(compare, actual, desired, err_msg=str(err_msg),<EOL>verbose=verbose, header=header)<EOL>

Raises an AssertionError if two objects are not equal up to desired
tolerance.

The test is equivalent to ``allclose(actual, desired, rtol, atol)``.
It compares the difference between `actual` and `desired` to
``atol + rtol * abs(desired)``.

.. versionadded:: 1.5.0

Parameters
----------
actual : array_like
    Array obtained.
desired : array_like
    Array desired.
rtol : float, optional
    Relative tolerance.
atol : float, optional
    Absolute tolerance.
err_msg : str, optional
    The error message to be printed in case of failure.
verbose : bool, optional
    If True, the conflicting values are appended to the error message.

Raises
------
AssertionError
    If actual and desired are not equal up to specified precision.

See Also
--------
assert_array_almost_equal_nulp, assert_array_max_ulp

Examples
--------
>>> x = [1e-5, 1e-3, 1e-1]
>>> y = np.arccos(np.cos(x))
>>> assert_allclose(x, y, rtol=1e-5, atol=0)


def assert_array_almost_equal_nulp(x, y, nulp=<NUM_LIT:1>):

import numpy as np<EOL>ax = np.abs(x)<EOL>ay = np.abs(y)<EOL>ref = nulp * np.spacing(np.where(ax > ay, ax, ay))<EOL>if not np.all(np.abs(x-y) <= ref):<EOL><INDENT>if np.iscomplexobj(x) or np.iscomplexobj(y):<EOL><INDENT>msg = "<STR_LIT>" % nulp<EOL><DEDENT>else:<EOL><INDENT>max_nulp = np.max(nulp_diff(x, y))<EOL>msg = "<STR_LIT>" % (nulp, max_nulp)<EOL><DEDENT>raise AssertionError(msg)<EOL><DEDENT>

Compare two arrays relatively to their spacing.

This is a relatively robust method to compare two arrays whose amplitude
is variable.

Parameters
----------
x, y : array_like
    Input arrays.
nulp : int, optional
    The maximum number of unit in the last place for tolerance (see Notes).
    Default is 1.

Returns
-------
None

Raises
------
AssertionError
    If the spacing between `x` and `y` for one or more elements is larger
    than `nulp`.

See Also
--------
assert_array_max_ulp : Check that all items of arrays differ in at most
    N Units in the Last Place.
spacing : Return the distance between x and the nearest adjacent number.

Notes
-----
An assertion is raised if the following condition is not met::

    abs(x - y) <= nulps * spacing(maximum(abs(x), abs(y)))

Examples
--------
>>> x = np.array([1., 1e-10, 1e-20])
>>> eps = np.finfo(x.dtype).eps
>>> np.testing.assert_array_almost_equal_nulp(x, x*eps/2 + x)

>>> np.testing.assert_array_almost_equal_nulp(x, x*eps + x)
Traceback (most recent call last):
  ...
AssertionError: X and Y are not equal to 1 ULP (max is 2)


def assert_array_max_ulp(a, b, maxulp=<NUM_LIT:1>, dtype=None):

import numpy as np<EOL>ret = nulp_diff(a, b, dtype)<EOL>if not np.all(ret <= maxulp):<EOL><INDENT>raise AssertionError("<STR_LIT>" %maxulp)<EOL><DEDENT>return ret<EOL>

Check that all items of arrays differ in at most N Units in the Last Place.

Parameters
----------
a, b : array_like
    Input arrays to be compared.
maxulp : int, optional
    The maximum number of units in the last place that elements of `a` and
    `b` can differ. Default is 1.
dtype : dtype, optional
    Data-type to convert `a` and `b` to if given. Default is None.

Returns
-------
ret : ndarray
    Array containing number of representable floating point numbers between
    items in `a` and `b`.

Raises
------
AssertionError
    If one or more elements differ by more than `maxulp`.

See Also
--------
assert_array_almost_equal_nulp : Compare two arrays relatively to their
    spacing.

Examples
--------
>>> a = np.linspace(0., 1., 100)
>>> res = np.testing.assert_array_max_ulp(a, np.arcsin(np.sin(a)))


import numpy as np<EOL>if dtype:<EOL><INDENT>x = np.array(x, dtype=dtype)<EOL>y = np.array(y, dtype=dtype)<EOL><DEDENT>else:<EOL><INDENT>x = np.array(x)<EOL>y = np.array(y)<EOL><DEDENT>t = np.common_type(x, y)<EOL>if np.iscomplexobj(x) or np.iscomplexobj(y):<EOL><INDENT>raise NotImplementedError("<STR_LIT>")<EOL><DEDENT>x = np.array(x, dtype=t)<EOL>y = np.array(y, dtype=t)<EOL>if not x.shape == y.shape:<EOL><INDENT>raise ValueError("<STR_LIT>" %(x.shape, y.shape))<EOL><DEDENT>def _diff(rx, ry, vdt):<EOL><INDENT>diff = np.array(rx-ry, dtype=vdt)<EOL>return np.abs(diff)<EOL><DEDENT>rx = integer_repr(x)<EOL>ry = integer_repr(y)<EOL>return _diff(rx, ry, t)<EOL>

For each item in x and y, return the number of representable floating
    points between them.

    Parameters
    ----------
    x : array_like
        first input array
    y : array_like
        second input array

    Returns
    -------
    nulp : array_like
        number of representable floating point numbers between each item in x
        and y.

    Examples
    --------
    # By definition, epsilon is the smallest number such as 1 + eps != 1, so
    # there should be exactly one ULP between 1 and 1 + eps
    >>> nulp_diff(1, 1 + np.finfo(x.dtype).eps)
    1.0


import numpy as np<EOL>if x.dtype == np.float32:<EOL><INDENT>return _integer_repr(x, np.int32, np.int32(-<NUM_LIT:2>**<NUM_LIT>))<EOL><DEDENT>elif x.dtype == np.float64:<EOL><INDENT>return _integer_repr(x, np.int64, np.int64(-<NUM_LIT:2>**<NUM_LIT>))<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % x.dtype)<EOL><DEDENT>

Return the signed-magnitude interpretation of the binary representation of
    x.


def assert_warns(warning_class, func, *args, **kw):

with warnings.catch_warnings(record=True) as l:<EOL><INDENT>warnings.simplefilter('<STR_LIT>')<EOL>result = func(*args, **kw)<EOL>if not len(l) > <NUM_LIT:0>:<EOL><INDENT>raise AssertionError("<STR_LIT>"<EOL>% func.__name__)<EOL><DEDENT>if not l[<NUM_LIT:0>].category is warning_class:<EOL><INDENT>raise AssertionError("<STR_LIT>""<STR_LIT>" % (func.__name__, warning_class, l[<NUM_LIT:0>]))<EOL><DEDENT><DEDENT>return result<EOL>

Fail unless the given callable throws the specified warning.

A warning of class warning_class should be thrown by the callable when
invoked with arguments args and keyword arguments kwargs.
If a different type of warning is thrown, it will not be caught, and the
test case will be deemed to have suffered an error.

.. versionadded:: 1.4.0

Parameters
----------
warning_class : class
    The class defining the warning that `func` is expected to throw.
func : callable
    The callable to test.
\\*args : Arguments
    Arguments passed to `func`.
\\*\\*kwargs : Kwargs
    Keyword arguments passed to `func`.

Returns
-------
The value returned by `func`.


def assert_no_warnings(func, *args, **kw):

with warnings.catch_warnings(record=True) as l:<EOL><INDENT>warnings.simplefilter('<STR_LIT>')<EOL>result = func(*args, **kw)<EOL>if len(l) > <NUM_LIT:0>:<EOL><INDENT>raise AssertionError("<STR_LIT>"<EOL>% (func.__name__, l))<EOL><DEDENT><DEDENT>return result<EOL>

Fail if the given callable produces any warnings.

.. versionadded:: 1.7.0

Parameters
----------
func : callable
    The callable to test.
\\*args : Arguments
    Arguments passed to `func`.
\\*\\*kwargs : Kwargs
    Keyword arguments passed to `func`.

Returns
-------
The value returned by `func`.


def _gen_alignment_data(dtype=float32, type='<STR_LIT>', max_size=<NUM_LIT>):

ufmt = '<STR_LIT>'<EOL>bfmt = '<STR_LIT>'<EOL>for o in range(<NUM_LIT:3>):<EOL><INDENT>for s in range(o + <NUM_LIT:2>, max(o + <NUM_LIT:3>, max_size)):<EOL><INDENT>if type == '<STR_LIT>':<EOL><INDENT>inp = lambda : arange(s, dtype=dtype)[o:]<EOL>out = empty((s,), dtype=dtype)[o:]<EOL>yield out, inp(), ufmt % (o, o, s, dtype, '<STR_LIT>')<EOL>yield inp(), inp(), ufmt % (o, o, s, dtype, '<STR_LIT>')<EOL>yield out[<NUM_LIT:1>:], inp()[:-<NUM_LIT:1>], ufmt %(o + <NUM_LIT:1>, o, s - <NUM_LIT:1>, dtype, '<STR_LIT>')<EOL>yield out[:-<NUM_LIT:1>], inp()[<NUM_LIT:1>:], ufmt %(o, o + <NUM_LIT:1>, s - <NUM_LIT:1>, dtype, '<STR_LIT>')<EOL>yield inp()[:-<NUM_LIT:1>], inp()[<NUM_LIT:1>:], ufmt %(o, o + <NUM_LIT:1>, s - <NUM_LIT:1>, dtype, '<STR_LIT>')<EOL>yield inp()[<NUM_LIT:1>:], inp()[:-<NUM_LIT:1>], ufmt %(o + <NUM_LIT:1>, o, s - <NUM_LIT:1>, dtype, '<STR_LIT>')<EOL><DEDENT>if type == '<STR_LIT>':<EOL><INDENT>inp1 = lambda :arange(s, dtype=dtype)[o:]<EOL>inp2 = lambda :arange(s, dtype=dtype)[o:]<EOL>out = empty((s,), dtype=dtype)[o:]<EOL>yield out, inp1(), inp2(),  bfmt %(o, o, o, s, dtype, '<STR_LIT>')<EOL>yield inp1(), inp1(), inp2(), bfmt %(o, o, o, s, dtype, '<STR_LIT>')<EOL>yield inp2(), inp1(), inp2(), bfmt %(o, o, o, s, dtype, '<STR_LIT>')<EOL>yield out[<NUM_LIT:1>:], inp1()[:-<NUM_LIT:1>], inp2()[:-<NUM_LIT:1>], bfmt %(o + <NUM_LIT:1>, o, o, s - <NUM_LIT:1>, dtype, '<STR_LIT>')<EOL>yield out[:-<NUM_LIT:1>], inp1()[<NUM_LIT:1>:], inp2()[:-<NUM_LIT:1>], bfmt %(o, o + <NUM_LIT:1>, o, s - <NUM_LIT:1>, dtype, '<STR_LIT>')<EOL>yield out[:-<NUM_LIT:1>], inp1()[:-<NUM_LIT:1>], inp2()[<NUM_LIT:1>:], bfmt %(o, o, o + <NUM_LIT:1>, s - <NUM_LIT:1>, dtype, '<STR_LIT>')<EOL>yield inp1()[<NUM_LIT:1>:], inp1()[:-<NUM_LIT:1>], inp2()[:-<NUM_LIT:1>], bfmt %(o + <NUM_LIT:1>, o, o, s - <NUM_LIT:1>, dtype, '<STR_LIT>')<EOL>yield inp1()[:-<NUM_LIT:1>], inp1()[<NUM_LIT:1>:], inp2()[:-<NUM_LIT:1>], bfmt %(o, o + <NUM_LIT:1>, o, s - <NUM_LIT:1>, dtype, '<STR_LIT>')<EOL>yield inp1()[:-<NUM_LIT:1>], inp1()[:-<NUM_LIT:1>], inp2()[<NUM_LIT:1>:], bfmt %(o, o, o + <NUM_LIT:1>, s - <NUM_LIT:1>, dtype, '<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>

generator producing data with different alignment and offsets
to test simd vectorization

Parameters
----------
dtype : dtype
    data type to produce
type : string
    'unary': create data for unary operations, creates one input
             and output array
    'binary': create data for unary operations, creates two input
             and output array
max_size : integer
    maximum size of data to produce

Returns
-------
if type is 'unary' yields one output, one input array and a message
containing information on the data
if type is 'binary' yields one output array, two input array and a message
containing information on the data


tmpdir = mkdtemp(*args, **kwargs)<EOL>yield tmpdir<EOL>shutil.rmtree(tmpdir)<EOL>

Context manager to provide a temporary test folder.

    All arguments are passed as this to the underlying tempfile.mkdtemp
    function.


t.slow = True<EOL>return t<EOL>

Label a test as 'slow'.

The exact definition of a slow test is obviously both subjective and
hardware-dependent, but in general any individual test that requires more
than a second or two should be labeled as slow (the whole suite consits of
thousands of tests, so even a second is significant).

Parameters
----------
t : callable
    The test to label as slow.

Returns
-------
t : callable
    The decorated test `t`.

Examples
--------
The `numpy.testing` module includes ``import decorators as dec``.
A test can be decorated as slow like this::

  from numpy.testing import *

  @dec.slow
  def test_big(self):
      print 'Big, slow test'


def skip_decorator(f):<EOL><INDENT>import nose<EOL>if isinstance(skip_condition, collections.Callable):<EOL><INDENT>skip_val = lambda : skip_condition()<EOL><DEDENT>else:<EOL><INDENT>skip_val = lambda : skip_condition<EOL><DEDENT>def get_msg(func,msg=None):<EOL><INDENT>"""<STR_LIT>"""<EOL>if msg is None:<EOL><INDENT>out = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>out = msg<EOL><DEDENT>return "<STR_LIT>" % (func.__name__, out)<EOL><DEDENT>def skipper_func(*args, **kwargs):<EOL><INDENT>"""<STR_LIT>"""<EOL>if skip_val():<EOL><INDENT>raise nose.SkipTest(get_msg(f, msg))<EOL><DEDENT>else:<EOL><INDENT>return f(*args, **kwargs)<EOL><DEDENT><DEDENT>def skipper_gen(*args, **kwargs):<EOL><INDENT>"""<STR_LIT>"""<EOL>if skip_val():<EOL><INDENT>raise nose.SkipTest(get_msg(f, msg))<EOL><DEDENT>else:<EOL><INDENT>for x in f(*args, **kwargs):<EOL><INDENT>yield x<EOL><DEDENT><DEDENT><DEDENT>if nose.util.isgenerator(f):<EOL><INDENT>skipper = skipper_gen<EOL><DEDENT>else:<EOL><INDENT>skipper = skipper_func<EOL><DEDENT>return nose.tools.make_decorator(f)(skipper)<EOL><DEDENT>return skip_decorator<EOL>

Make function raise SkipTest exception if a given condition is true.

If the condition is a callable, it is used at runtime to dynamically
make the decision. This is useful for tests that may require costly
imports, to delay the cost until the test suite is actually executed.

Parameters
----------
skip_condition : bool or callable
    Flag to determine whether to skip the decorated test.
msg : str, optional
    Message to give on raising a SkipTest exception. Default is None.

Returns
-------
decorator : function
    Decorator which, when applied to a function, causes SkipTest
    to be raised when `skip_condition` is True, and the function
    to be called normally otherwise.

Notes
-----
The decorator itself is decorated with the ``nose.tools.make_decorator``
function in order to transmit function name, and various other metadata.


if msg is None:<EOL><INDENT>msg = '<STR_LIT>'<EOL><DEDENT>if isinstance(fail_condition, collections.Callable):<EOL><INDENT>fail_val = lambda : fail_condition()<EOL><DEDENT>else:<EOL><INDENT>fail_val = lambda : fail_condition<EOL><DEDENT>def knownfail_decorator(f):<EOL><INDENT>import nose<EOL>from .noseclasses import KnownFailureTest<EOL>def knownfailer(*args, **kwargs):<EOL><INDENT>if fail_val():<EOL><INDENT>raise KnownFailureTest(msg)<EOL><DEDENT>else:<EOL><INDENT>return f(*args, **kwargs)<EOL><DEDENT><DEDENT>return nose.tools.make_decorator(f)(knownfailer)<EOL><DEDENT>return knownfail_decorator<EOL>

Make function raise KnownFailureTest exception if given condition is true.

If the condition is a callable, it is used at runtime to dynamically
make the decision. This is useful for tests that may require costly
imports, to delay the cost until the test suite is actually executed.

Parameters
----------
fail_condition : bool or callable
    Flag to determine whether to mark the decorated test as a known
    failure (if True) or not (if False).
msg : str, optional
    Message to give on raising a KnownFailureTest exception.
    Default is None.

Returns
-------
decorator : function
    Decorator, which, when applied to a function, causes SkipTest
    to be raised when `skip_condition` is True, and the function
    to be called normally otherwise.

Notes
-----
The decorator itself is decorated with the ``nose.tools.make_decorator``
function in order to transmit function name, and various other metadata.


def deprecate_decorator(f):<EOL><INDENT>import nose<EOL>from .noseclasses import KnownFailureTest<EOL>def _deprecated_imp(*args, **kwargs):<EOL><INDENT>with warnings.catch_warnings(record=True) as l:<EOL><INDENT>warnings.simplefilter('<STR_LIT>')<EOL>f(*args, **kwargs)<EOL>if not len(l) > <NUM_LIT:0>:<EOL><INDENT>raise AssertionError("<STR_LIT>"<EOL>% f.__name__)<EOL><DEDENT>if not l[<NUM_LIT:0>].category is DeprecationWarning:<EOL><INDENT>raise AssertionError("<STR_LIT>""<STR_LIT>" % (f.__name__, l[<NUM_LIT:0>]))<EOL><DEDENT><DEDENT><DEDENT>if isinstance(conditional, collections.Callable):<EOL><INDENT>cond = conditional()<EOL><DEDENT>else:<EOL><INDENT>cond = conditional<EOL><DEDENT>if cond:<EOL><INDENT>return nose.tools.make_decorator(f)(_deprecated_imp)<EOL><DEDENT>else:<EOL><INDENT>return f<EOL><DEDENT><DEDENT>return deprecate_decorator<EOL>

Filter deprecation warnings while running the test suite.

This decorator can be used to filter DeprecationWarning's, to avoid
printing them during the test suite run, while checking that the test
actually raises a DeprecationWarning.

Parameters
----------
conditional : bool or callable, optional
    Flag to determine whether to mark test as deprecated or not. If the
    condition is a callable, it is used at runtime to dynamically make the
    decision. Default is True.

Returns
-------
decorator : function
    The `deprecated` decorator itself.

Notes
-----
.. versionadded:: 1.4.0


if sys.platform == '<STR_LIT:win32>':<EOL><INDENT>locales = ['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>locales = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL><DEDENT>def wrapper(*args, **kwargs):<EOL><INDENT>curloc = locale.getlocale(locale.LC_NUMERIC)<EOL>try:<EOL><INDENT>for loc in locales:<EOL><INDENT>try:<EOL><INDENT>locale.setlocale(locale.LC_NUMERIC, loc)<EOL>break<EOL><DEDENT>except locale.Error:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise nose.SkipTest("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>return func(*args, **kwargs)<EOL><DEDENT>finally:<EOL><INDENT>locale.setlocale(locale.LC_NUMERIC, locale=curloc)<EOL><DEDENT><DEDENT>return nose.tools.make_decorator(func)(wrapper)<EOL>

Swap LC_NUMERIC locale to one in which the decimal point is ',' and not '.'
If not possible, raise nose.SkipTest


out = []<EOL>for item in descr:<EOL><INDENT>dtype = item[<NUM_LIT:1>]<EOL>if isinstance(dtype, str):<EOL><INDENT>if dtype[<NUM_LIT:0>] not in ['<STR_LIT:|>', '<STR_LIT:<>', '<STR_LIT:>>']:<EOL><INDENT>onebyte = dtype[<NUM_LIT:1>:] == "<STR_LIT:1>"<EOL>if onebyte or dtype[<NUM_LIT:0>] in ['<STR_LIT:S>', '<STR_LIT>', '<STR_LIT:b>']:<EOL><INDENT>dtype = "<STR_LIT:|>" + dtype<EOL><DEDENT>else:<EOL><INDENT>dtype = byteorder + dtype<EOL><DEDENT><DEDENT>if len(item) > <NUM_LIT:2> and np.prod(item[<NUM_LIT:2>]) > <NUM_LIT:1>:<EOL><INDENT>nitem = (item[<NUM_LIT:0>], dtype, item[<NUM_LIT:2>])<EOL><DEDENT>else:<EOL><INDENT>nitem = (item[<NUM_LIT:0>], dtype)<EOL><DEDENT>out.append(nitem)<EOL><DEDENT>elif isinstance(item[<NUM_LIT:1>], list):<EOL><INDENT>l = []<EOL>for j in normalize_descr(item[<NUM_LIT:1>]):<EOL><INDENT>l.append(j)<EOL><DEDENT>out.append((item[<NUM_LIT:0>], l))<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" %(type(item)))<EOL><DEDENT><DEDENT>return out<EOL>

Normalize a description adding the platform byteorder.


def _get_multi_index(self, arr, indices):

in_indices = list(indices)<EOL>indices = []<EOL>no_copy = True<EOL>num_fancy = <NUM_LIT:0><EOL>fancy_dim = <NUM_LIT:0><EOL>error_unless_broadcast_to_empty = False<EOL>ndim = <NUM_LIT:0><EOL>ellipsis_pos = None <EOL>for i, indx in enumerate(in_indices):<EOL><INDENT>if indx is None:<EOL><INDENT>continue<EOL><DEDENT>if isinstance(indx, np.ndarray) and indx.dtype == bool:<EOL><INDENT>no_copy = False<EOL>if indx.ndim == <NUM_LIT:0>:<EOL><INDENT>raise IndexError<EOL><DEDENT>ndim += indx.ndim<EOL>fancy_dim += indx.ndim<EOL>continue<EOL><DEDENT>if indx is Ellipsis:<EOL><INDENT>if ellipsis_pos is None:<EOL><INDENT>ellipsis_pos = i<EOL>continue <EOL><DEDENT>raise IndexError<EOL><DEDENT>if isinstance(indx, slice):<EOL><INDENT>ndim += <NUM_LIT:1><EOL>continue<EOL><DEDENT>if not isinstance(indx, np.ndarray):<EOL><INDENT>indx = np.array(indx, dtype=np.intp)<EOL>in_indices[i] = indx<EOL><DEDENT>elif indx.dtype.kind != '<STR_LIT:b>' and indx.dtype.kind != '<STR_LIT:i>':<EOL><INDENT>raise IndexError('<STR_LIT>')<EOL><DEDENT>if indx.ndim != <NUM_LIT:0>:<EOL><INDENT>no_copy = False<EOL><DEDENT>ndim += <NUM_LIT:1><EOL>fancy_dim += <NUM_LIT:1><EOL><DEDENT>if arr.ndim - ndim < <NUM_LIT:0>:<EOL><INDENT>raise IndexError<EOL><DEDENT>if ndim == <NUM_LIT:0> and not None in in_indices:<EOL><INDENT>return arr.copy(), no_copy<EOL><DEDENT>if ellipsis_pos is not None:<EOL><INDENT>in_indices[ellipsis_pos:ellipsis_pos+<NUM_LIT:1>] = [slice(None, None)] * (arr.ndim - ndim)<EOL><DEDENT>for ax, indx in enumerate(in_indices):<EOL><INDENT>if isinstance(indx, slice):<EOL><INDENT>indx = np.arange(*indx.indices(arr.shape[ax]))<EOL>indices.append(['<STR_LIT:s>', indx])<EOL>continue<EOL><DEDENT>elif indx is None:<EOL><INDENT>indices.append(['<STR_LIT:n>', np.array([<NUM_LIT:0>], dtype=np.intp)])<EOL>arr = arr.reshape((arr.shape[:ax] + (<NUM_LIT:1>,) + arr.shape[ax:]))<EOL>continue<EOL><DEDENT>if isinstance(indx, np.ndarray) and indx.dtype == bool:<EOL><INDENT>try:<EOL><INDENT>flat_indx = np.ravel_multi_index(np.nonzero(indx),<EOL>arr.shape[ax:ax+indx.ndim], mode='<STR_LIT>')<EOL><DEDENT>except:<EOL><INDENT>error_unless_broadcast_to_empty = True<EOL>flat_indx = np.array([<NUM_LIT:0>]*indx.sum(), dtype=np.intp)<EOL><DEDENT>if indx.ndim != <NUM_LIT:0>:<EOL><INDENT>arr = arr.reshape((arr.shape[:ax]<EOL>+ (np.prod(arr.shape[ax:ax+indx.ndim]),)<EOL>+ arr.shape[ax+indx.ndim:]))<EOL>indx = flat_indx<EOL><DEDENT>else:<EOL><INDENT>raise IndexError<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if indx.ndim == <NUM_LIT:0>:<EOL><INDENT>if indx >= arr.shape[ax] or indx < -arr.shape[ax]:<EOL><INDENT>raise IndexError<EOL><DEDENT><DEDENT><DEDENT>if indx.ndim == <NUM_LIT:0>:<EOL><INDENT>if indx >= arr.shape[ax] or indx < - arr.shape[ax]:<EOL><INDENT>raise IndexError<EOL><DEDENT><DEDENT>if len(indices) > <NUM_LIT:0> and indices[-<NUM_LIT:1>][<NUM_LIT:0>] == '<STR_LIT:f>' and ax != ellipsis_pos:<EOL><INDENT>indices[-<NUM_LIT:1>].append(indx)<EOL><DEDENT>else:<EOL><INDENT>num_fancy += <NUM_LIT:1><EOL>indices.append(['<STR_LIT:f>', indx])<EOL><DEDENT><DEDENT>if num_fancy > <NUM_LIT:1> and not no_copy:<EOL><INDENT>new_indices = indices[:]<EOL>axes = list(range(arr.ndim))<EOL>fancy_axes = []<EOL>new_indices.insert(<NUM_LIT:0>, ['<STR_LIT:f>'])<EOL>ni = <NUM_LIT:0><EOL>ai = <NUM_LIT:0><EOL>for indx in indices:<EOL><INDENT>ni += <NUM_LIT:1><EOL>if indx[<NUM_LIT:0>] == '<STR_LIT:f>':<EOL><INDENT>new_indices[<NUM_LIT:0>].extend(indx[<NUM_LIT:1>:])<EOL>del new_indices[ni]<EOL>ni -= <NUM_LIT:1><EOL>for ax in range(ai, ai + len(indx[<NUM_LIT:1>:])):<EOL><INDENT>fancy_axes.append(ax)<EOL>axes.remove(ax)<EOL><DEDENT><DEDENT>ai += len(indx) - <NUM_LIT:1> <EOL><DEDENT>indices = new_indices<EOL>arr = arr.transpose(*(fancy_axes + axes))<EOL><DEDENT>ax = <NUM_LIT:0><EOL>for indx in indices:<EOL><INDENT>if indx[<NUM_LIT:0>] == '<STR_LIT:f>':<EOL><INDENT>if len(indx) == <NUM_LIT:1>:<EOL><INDENT>continue<EOL><DEDENT>orig_shape = arr.shape<EOL>orig_slice = orig_shape[ax:ax + len(indx[<NUM_LIT:1>:])]<EOL>arr = arr.reshape((arr.shape[:ax]<EOL>+ (np.prod(orig_slice).astype(int),)<EOL>+ arr.shape[ax + len(indx[<NUM_LIT:1>:]):]))<EOL>if len(indx[<NUM_LIT:1>:]) != <NUM_LIT:1>:<EOL><INDENT>res = np.broadcast(*indx[<NUM_LIT:1>:]) <EOL><DEDENT>else:<EOL><INDENT>res = indx[<NUM_LIT:1>]<EOL><DEDENT>if res.size != <NUM_LIT:0>:<EOL><INDENT>if error_unless_broadcast_to_empty:<EOL><INDENT>raise IndexError<EOL><DEDENT>for _indx, _size in zip(indx[<NUM_LIT:1>:], orig_slice):<EOL><INDENT>if _indx.size == <NUM_LIT:0>:<EOL><INDENT>continue<EOL><DEDENT>if np.any(_indx >= _size) or np.any(_indx < -_size):<EOL><INDENT>raise IndexError<EOL><DEDENT><DEDENT><DEDENT>if len(indx[<NUM_LIT:1>:]) == len(orig_slice):<EOL><INDENT>if np.product(orig_slice) == <NUM_LIT:0>:<EOL><INDENT>try:<EOL><INDENT>mi = np.ravel_multi_index(indx[<NUM_LIT:1>:], orig_slice, mode='<STR_LIT>')<EOL><DEDENT>except:<EOL><INDENT>raise IndexError('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>mi = np.ravel_multi_index(indx[<NUM_LIT:1>:], orig_slice, mode='<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError<EOL><DEDENT>arr = arr.take(mi.ravel(), axis=ax)<EOL>arr = arr.reshape((arr.shape[:ax]<EOL>+ mi.shape<EOL>+ arr.shape[ax+<NUM_LIT:1>:]))<EOL>ax += mi.ndim<EOL>continue<EOL><DEDENT>arr = arr.take(indx[<NUM_LIT:1>], axis=ax)<EOL>ax += <NUM_LIT:1><EOL><DEDENT>return arr, no_copy<EOL>

Mimic multi dimensional indexing.

        Parameters
        ----------
        arr : ndarray
            Array to be indexed.
        indices : tuple of index objects

        Returns
        -------
        out : ndarray
            An array equivalent to the indexing operation (but always a copy).
            `arr[indices]` should be identical.
        no_copy : bool
            Whether the indexing operation requires a copy. If this is `True`,
            `np.may_share_memory(arr, arr[indicies])` should be `True` (with
            some exceptions for scalars and possibly 0-d arrays).

        Notes
        -----
        While the function may mostly match the errors of normal indexing this
        is generally not the case.


def _check_multi_index(self, arr, index):

<EOL>try:<EOL><INDENT>mimic_get, no_copy = self._get_multi_index(arr, index)<EOL><DEDENT>except Exception as e:<EOL><INDENT>prev_refcount = sys.getrefcount(arr)<EOL>assert_raises(Exception, arr.__getitem__, index)<EOL>assert_raises(Exception, arr.__setitem__, index, <NUM_LIT:0>)<EOL>assert_equal(prev_refcount, sys.getrefcount(arr))<EOL>return<EOL><DEDENT>self._compare_index_result(arr, index, mimic_get, no_copy)<EOL>

Check a multi index item getting and simple setting.

        Parameters
        ----------
        arr : ndarray
            Array to be indexed, must be a reshaped arange.
        index : tuple of indexing objects
            Index being tested.


def _check_single_index(self, arr, index):

try:<EOL><INDENT>mimic_get, no_copy = self._get_multi_index(arr, (index,))<EOL><DEDENT>except Exception as e:<EOL><INDENT>prev_refcount = sys.getrefcount(arr)<EOL>assert_raises(Exception, arr.__getitem__, index)<EOL>assert_raises(Exception, arr.__setitem__, index, <NUM_LIT:0>)<EOL>assert_equal(prev_refcount, sys.getrefcount(arr))<EOL>return<EOL><DEDENT>self._compare_index_result(arr, index, mimic_get, no_copy)<EOL>

Check a single index item getting and simple setting.

        Parameters
        ----------
        arr : ndarray
            Array to be indexed, must be an arange.
        index : indexing object
            Index being tested. Must be a single index and not a tuple
            of indexing objects (see also `_check_multi_index`).


def _compare_index_result(self, arr, index, mimic_get, no_copy):

arr = arr.copy()<EOL>indexed_arr = arr[index]<EOL>assert_array_equal(indexed_arr, mimic_get)<EOL>if indexed_arr.size != <NUM_LIT:0> and indexed_arr.ndim != <NUM_LIT:0>:<EOL><INDENT>assert_(np.may_share_memory(indexed_arr, arr) == no_copy)<EOL>if no_copy:<EOL><INDENT>assert_equal(sys.getrefcount(arr), <NUM_LIT:3>)<EOL><DEDENT>else:<EOL><INDENT>assert_equal(sys.getrefcount(arr), <NUM_LIT:2>)<EOL><DEDENT><DEDENT>b = arr.copy()<EOL>b[index] = mimic_get + <NUM_LIT:1000><EOL>if b.size == <NUM_LIT:0>:<EOL><INDENT>return <EOL><DEDENT>if no_copy and indexed_arr.ndim != <NUM_LIT:0>:<EOL><INDENT>indexed_arr += <NUM_LIT:1000><EOL>assert_array_equal(arr, b)<EOL>return<EOL><DEDENT>arr.flat[indexed_arr.ravel()] += <NUM_LIT:1000><EOL>assert_array_equal(arr, b)<EOL>

Compare mimicked result to indexing result.


return platform.processor() == '<STR_LIT>' orplatform.machine().startswith('<STR_LIT>')<EOL>

True if we are running on a Power PC platform.


def _check_branch_cut(f, x0, dx, re_sign=<NUM_LIT:1>, im_sign=-<NUM_LIT:1>, sig_zero_ok=False,<EOL>dtype=np.complex):

x0 = np.atleast_1d(x0).astype(dtype)<EOL>dx = np.atleast_1d(dx).astype(dtype)<EOL>scale = np.finfo(dtype).eps * <NUM_LIT><EOL>atol  = <NUM_LIT><EOL>y0 = f(x0)<EOL>yp = f(x0 + dx*scale*np.absolute(x0)/np.absolute(dx))<EOL>ym = f(x0 - dx*scale*np.absolute(x0)/np.absolute(dx))<EOL>assert_(np.all(np.absolute(y0.real - yp.real) < atol), (y0, yp))<EOL>assert_(np.all(np.absolute(y0.imag - yp.imag) < atol), (y0, yp))<EOL>assert_(np.all(np.absolute(y0.real - ym.real*re_sign) < atol), (y0, ym))<EOL>assert_(np.all(np.absolute(y0.imag - ym.imag*im_sign) < atol), (y0, ym))<EOL>if sig_zero_ok:<EOL><INDENT>jr = (x0.real == <NUM_LIT:0>) & (dx.real != <NUM_LIT:0>)<EOL>ji = (x0.imag == <NUM_LIT:0>) & (dx.imag != <NUM_LIT:0>)<EOL>x = -x0<EOL>x.real[jr] = <NUM_LIT:0.>*dx.real<EOL>x.imag[ji] = <NUM_LIT:0.>*dx.imag<EOL>x = -x<EOL>ym = f(x)<EOL>ym = ym[jr | ji]<EOL>y0 = y0[jr | ji]<EOL>assert_(np.all(np.absolute(y0.real - ym.real*re_sign) < atol), (y0, ym))<EOL>assert_(np.all(np.absolute(y0.imag - ym.imag*im_sign) < atol), (y0, ym))<EOL><DEDENT>

Check for a branch cut in a function.

Assert that `x0` lies on a branch cut of function `f` and `f` is
continuous from the direction `dx`.

Parameters
----------
f : func
    Function to check
x0 : array-like
    Point on branch cut
dx : array-like
    Direction to check continuity in
re_sign, im_sign : {1, -1}
    Change of sign of the real or imaginary part expected
sig_zero_ok : bool
    Whether to check if the branch cut respects signed zero (if applicable)
dtype : dtype
    Dtype to check (should be complex)


<EOL>info = np.finfo(dtype)<EOL>real_dtype = dtype(<NUM_LIT:0.>).real.dtype<EOL>eps = info.eps<EOL>def check(x, rtol):<EOL><INDENT>x = x.astype(real_dtype)<EOL>z = x.astype(dtype)<EOL>d = np.absolute(np.arcsinh(x)/np.arcsinh(z).real - <NUM_LIT:1>)<EOL>assert_(np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(),<EOL>'<STR_LIT>'))<EOL>z = (<NUM_LIT>*x).astype(dtype)<EOL>d = np.absolute(np.arcsinh(x)/np.arcsin(z).imag - <NUM_LIT:1>)<EOL>assert_(np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(),<EOL>'<STR_LIT>'))<EOL>z = x.astype(dtype)<EOL>d = np.absolute(np.arctanh(x)/np.arctanh(z).real - <NUM_LIT:1>)<EOL>assert_(np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(),<EOL>'<STR_LIT>'))<EOL>z = (<NUM_LIT>*x).astype(dtype)<EOL>d = np.absolute(np.arctanh(x)/np.arctan(z).imag - <NUM_LIT:1>)<EOL>assert_(np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(),<EOL>'<STR_LIT>'))<EOL><DEDENT>x_series = np.logspace(-<NUM_LIT:20>, -<NUM_LIT>, <NUM_LIT:200>)<EOL>x_basic = np.logspace(-<NUM_LIT>, <NUM_LIT:0>, <NUM_LIT:10>, endpoint=False)<EOL>if dtype is np.longcomplex:<EOL><INDENT>check(x_series, <NUM_LIT:50>*eps)<EOL><DEDENT>else:<EOL><INDENT>check(x_series, <NUM_LIT:2>*eps)<EOL><DEDENT>check(x_basic, <NUM_LIT:2>*eps/<NUM_LIT>)<EOL>z = np.array([<NUM_LIT>*(<NUM_LIT:1>+<NUM_LIT>)], dtype=dtype)<EOL>p = <NUM_LIT> + <NUM_LIT><EOL>d = np.absolute(<NUM_LIT:1>-np.arctanh(z)/p)<EOL>assert_(np.all(d < <NUM_LIT>))<EOL>p = <NUM_LIT> + <NUM_LIT><EOL>d = np.absolute(<NUM_LIT:1>-np.arcsinh(z)/p)<EOL>assert_(np.all(d < <NUM_LIT>))<EOL>p = <NUM_LIT> + <NUM_LIT><EOL>d = np.absolute(<NUM_LIT:1>-np.arctan(z)/p)<EOL>assert_(np.all(d < <NUM_LIT>))<EOL>p = <NUM_LIT> + <NUM_LIT><EOL>d = np.absolute(<NUM_LIT:1>-np.arcsin(z)/p)<EOL>assert_(np.all(d < <NUM_LIT>))<EOL>def check(func, z0, d=<NUM_LIT:1>):<EOL><INDENT>z0 = np.asarray(z0, dtype=dtype)<EOL>zp = z0 + abs(z0) * d * eps * <NUM_LIT:2><EOL>zm = z0 - abs(z0) * d * eps * <NUM_LIT:2><EOL>assert_(np.all(zp != zm), (zp, zm))<EOL>good = (abs(func(zp) - func(zm)) < <NUM_LIT:2>*eps)<EOL>assert_(np.all(good), (func, z0[~good]))<EOL><DEDENT>for func in (np.arcsinh, np.arcsinh, np.arcsin, np.arctanh, np.arctan):<EOL><INDENT>pts = [rp+<NUM_LIT>*ip for rp in (-<NUM_LIT>, <NUM_LIT:0>, <NUM_LIT>) for ip in(-<NUM_LIT>, <NUM_LIT:0>, <NUM_LIT>)<EOL>if rp != <NUM_LIT:0> or ip != <NUM_LIT:0>]<EOL>check(func, pts, <NUM_LIT:1>)<EOL>check(func, pts, <NUM_LIT>)<EOL>check(func, pts, <NUM_LIT:1>+<NUM_LIT>)<EOL><DEDENT>

Check loss of precision in complex arc* functions


if nelems == <NUM_LIT:0>:<EOL><INDENT>return [size // <NUM_LIT:2>]  <EOL><DEDENT>res = []<EOL>for step in (<NUM_LIT:1>, <NUM_LIT:2>):<EOL><INDENT>for sign in (-<NUM_LIT:1>, <NUM_LIT:1>):<EOL><INDENT>start = size // <NUM_LIT:2> - nelems * step * sign // <NUM_LIT:2><EOL>stop = start + nelems * step * sign<EOL>res.append(slice(start, stop, step * sign))<EOL><DEDENT><DEDENT>return res<EOL>

Returns slices of length nelems, from start onwards, in direction sign.


res = []<EOL>for nelems in (<NUM_LIT:0>, <NUM_LIT:2>, <NUM_LIT:3>):<EOL><INDENT>ind = _indices_for_nelems(nelems)<EOL>res.extend([(a, b) for a in ind for b in ind])  <EOL><DEDENT>return res<EOL>


ind = _indices_for_axis()<EOL>res = [[]]<EOL>for i in range(ndims):<EOL><INDENT>newres = []<EOL>for elem in ind:<EOL><INDENT>for others in res:<EOL><INDENT>newres.append([elem] + others)<EOL><DEDENT><DEDENT>res = newres<EOL><DEDENT>return res<EOL>

Returns ((axis0_src, axis0_dst), (axis1_src, axis1_dst), ... ) index pairs.


arr = np.arange(np.product(shape)).reshape(shape)<EOL>cpy = arr.copy()<EOL>cpy[dstidx] = arr[srcidx]<EOL>arr[dstidx] = arr[srcidx]<EOL>assert np.all(arr == cpy), '<STR_LIT>' % (dstidx, srcidx)<EOL>

Check assignment arr[dstidx] = arr[srcidx] works.


def assert_deprecated(self, function, num=<NUM_LIT:1>, ignore_others=False,<EOL>function_fails=False,<EOL>exceptions=(DeprecationWarning,), args=(), kwargs={}):

<EOL>self.log[:] = []<EOL>try:<EOL><INDENT>function(*args, **kwargs)<EOL><DEDENT>except (Exception if function_fails else tuple()):<EOL><INDENT>pass<EOL><DEDENT>num_found = <NUM_LIT:0><EOL>for warning in self.log:<EOL><INDENT>if warning.category is DeprecationWarning:<EOL><INDENT>num_found += <NUM_LIT:1><EOL><DEDENT>elif not ignore_others:<EOL><INDENT>raise AssertionError("<STR_LIT>"<EOL>% warning.category)<EOL><DEDENT><DEDENT>if num is not None and num_found != num:<EOL><INDENT>raise AssertionError("<STR_LIT>"<EOL>% (len(self.log), num))<EOL><DEDENT>with warnings.catch_warnings():<EOL><INDENT>warnings.filterwarnings("<STR_LIT:error>", message=self.message,<EOL>category=DeprecationWarning)<EOL>try:<EOL><INDENT>function(*args, **kwargs)<EOL>if exceptions != tuple():<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT><DEDENT>except exceptions:<EOL><INDENT>if exceptions == tuple():<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT>

Test if DeprecationWarnings are given and raised.

        This first checks if the function when called gives `num`
        DeprecationWarnings, after that it tries to raise these
        DeprecationWarnings and compares them with `exceptions`.
        The exceptions can be different for cases where this code path
        is simply not anticipated and the exception is replaced.

        Parameters
        ----------
        f : callable
            The function to test
        num : int
            Number of DeprecationWarnings to expect. This should normally be 1.
        ignore_other : bool
            Whether warnings of the wrong type should be ignored (note that
            the message is not checked)
        function_fails : bool
            If the function would normally fail, setting this will check for
            warnings inside a try/except block.
        exceptions : Exception or tuple of Exceptions
            Exception to expect when turning the warnings into an error.
            The default checks for DeprecationWarnings. If exceptions is
            empty the function is expected to run successfull.
        args : tuple
            Arguments for `f`
        kwargs : dict
            Keyword arguments for `f`


def assert_not_deprecated(self, function, args=(), kwargs={}):

self.assert_deprecated(function, num=<NUM_LIT:0>, ignore_others=True,<EOL>exceptions=tuple(), args=args, kwargs=kwargs)<EOL>

Test if DeprecationWarnings are given and raised.

        This is just a shorthand for:

        self.assert_deprecated(function, num=0, ignore_others=True,
                        exceptions=tuple(), args=args, kwargs=kwargs)


if self.base is not None and hasattr(self.base, '<STR_LIT>'):<EOL><INDENT>self.base.flush()<EOL><DEDENT>

Write any changes in the array to the file on disk.

For further information, see `memmap`.

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

See Also
--------
memmap


def set_printoptions(precision=None, threshold=None, edgeitems=None,<EOL>linewidth=None, suppress=None,<EOL>nanstr=None, infstr=None,<EOL>formatter=None):

global _summaryThreshold, _summaryEdgeItems, _float_output_precision,_line_width, _float_output_suppress_small, _nan_str, _inf_str,_formatter<EOL>if linewidth is not None:<EOL><INDENT>_line_width = linewidth<EOL><DEDENT>if threshold is not None:<EOL><INDENT>_summaryThreshold = threshold<EOL><DEDENT>if edgeitems is not None:<EOL><INDENT>_summaryEdgeItems = edgeitems<EOL><DEDENT>if precision is not None:<EOL><INDENT>_float_output_precision = precision<EOL><DEDENT>if suppress is not None:<EOL><INDENT>_float_output_suppress_small = not not suppress<EOL><DEDENT>if nanstr is not None:<EOL><INDENT>_nan_str = nanstr<EOL><DEDENT>if infstr is not None:<EOL><INDENT>_inf_str = infstr<EOL><DEDENT>_formatter = formatter<EOL>

Set printing options.

These options determine the way floating point numbers, arrays and
other NumPy objects are displayed.

Parameters
----------
precision : int, optional
    Number of digits of precision for floating point output (default 8).
threshold : int, optional
    Total number of array elements which trigger summarization
    rather than full repr (default 1000).
edgeitems : int, optional
    Number of array items in summary at beginning and end of
    each dimension (default 3).
linewidth : int, optional
    The number of characters per line for the purpose of inserting
    line breaks (default 75).
suppress : bool, optional
    Whether or not suppress printing of small floating point values
    using scientific notation (default False).
nanstr : str, optional
    String representation of floating point not-a-number (default nan).
infstr : str, optional
    String representation of floating point infinity (default inf).
formatter : dict of callables, optional
    If not None, the keys should indicate the type(s) that the respective
    formatting function applies to.  Callables should return a string.
    Types that are not specified (by their corresponding keys) are handled
    by the default formatters.  Individual types for which a formatter
    can be set are::

        - 'bool'
        - 'int'
        - 'timedelta' : a `numpy.timedelta64`
        - 'datetime' : a `numpy.datetime64`
        - 'float'
        - 'longfloat' : 128-bit floats
        - 'complexfloat'
        - 'longcomplexfloat' : composed of two 128-bit floats
        - 'numpy_str' : types `numpy.string_` and `numpy.unicode_`
        - 'str' : all other strings

    Other keys that can be used to set a group of types at once are::

        - 'all' : sets all types
        - 'int_kind' : sets 'int'
        - 'float_kind' : sets 'float' and 'longfloat'
        - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat'
        - 'str_kind' : sets 'str' and 'numpystr'

See Also
--------
get_printoptions, set_string_function, array2string

Notes
-----
`formatter` is always reset with a call to `set_printoptions`.

Examples
--------
Floating point precision can be set:

>>> np.set_printoptions(precision=4)
>>> print np.array([1.123456789])
[ 1.1235]

Long arrays can be summarised:

>>> np.set_printoptions(threshold=5)
>>> print np.arange(10)
[0 1 2 ..., 7 8 9]

Small results can be suppressed:

>>> eps = np.finfo(float).eps
>>> x = np.arange(4.)
>>> x**2 - (x + eps)**2
array([ -4.9304e-32,  -4.4409e-16,   0.0000e+00,   0.0000e+00])
>>> np.set_printoptions(suppress=True)
>>> x**2 - (x + eps)**2
array([-0., -0.,  0.,  0.])

A custom formatter can be used to display array elements as desired:

>>> np.set_printoptions(formatter={'all':lambda x: 'int: '+str(-x)})
>>> x = np.arange(3)
>>> x
array([int: 0, int: -1, int: -2])
>>> np.set_printoptions()  # formatter gets reset
>>> x
array([0, 1, 2])

To put back the default options, you can use:

>>> np.set_printoptions(edgeitems=3,infstr='inf',
... linewidth=75, nanstr='nan', precision=8,
... suppress=False, threshold=1000, formatter=None)


Return the current print options.

Returns
-------
print_opts : dict
    Dictionary of current print options with keys

      - precision : int
      - threshold : int
      - edgeitems : int
      - linewidth : int
      - suppress : bool
      - nanstr : str
      - infstr : str
      - formatter : dict of callables

    For a full description of these options, see `set_printoptions`.

See Also
--------
set_printoptions, set_string_function


def array2string(a, max_line_width=None, precision=None,<EOL>suppress_small=None, separator='<STR_LIT:U+0020>', prefix="<STR_LIT>",<EOL>style=repr, formatter=None):

if a.shape == ():<EOL><INDENT>x = a.item()<EOL>try:<EOL><INDENT>lst = a._format(x)<EOL>msg = "<STR_LIT>""<STR_LIT>""<STR_LIT>"<EOL>import warnings<EOL>warnings.warn(msg, DeprecationWarning)<EOL><DEDENT>except AttributeError:<EOL><INDENT>if isinstance(x, tuple):<EOL><INDENT>x = _convert_arrays(x)<EOL><DEDENT>lst = style(x)<EOL><DEDENT><DEDENT>elif reduce(product, a.shape) == <NUM_LIT:0>:<EOL><INDENT>lst = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>lst = _array2string(a, max_line_width, precision, suppress_small,<EOL>separator, prefix, formatter=formatter)<EOL><DEDENT>return lst<EOL>

Return a string representation of an array.

Parameters
----------
a : ndarray
    Input array.
max_line_width : int, optional
    The maximum number of columns the string should span. Newline
    characters splits the string appropriately after array elements.
precision : int, optional
    Floating point precision. Default is the current printing
    precision (usually 8), which can be altered using `set_printoptions`.
suppress_small : bool, optional
    Represent very small numbers as zero. A number is "very small" if it
    is smaller than the current printing precision.
separator : str, optional
    Inserted between elements.
prefix : str, optional
    An array is typically printed as::

      'prefix(' + array2string(a) + ')'

    The length of the prefix string is used to align the
    output correctly.
style : function, optional
    A function that accepts an ndarray and returns a string.  Used only
    when the shape of `a` is equal to ``()``, i.e. for 0-D arrays.
formatter : dict of callables, optional
    If not None, the keys should indicate the type(s) that the respective
    formatting function applies to.  Callables should return a string.
    Types that are not specified (by their corresponding keys) are handled
    by the default formatters.  Individual types for which a formatter
    can be set are::

        - 'bool'
        - 'int'
        - 'timedelta' : a `numpy.timedelta64`
        - 'datetime' : a `numpy.datetime64`
        - 'float'
        - 'longfloat' : 128-bit floats
        - 'complexfloat'
        - 'longcomplexfloat' : composed of two 128-bit floats
        - 'numpy_str' : types `numpy.string_` and `numpy.unicode_`
        - 'str' : all other strings

    Other keys that can be used to set a group of types at once are::

        - 'all' : sets all types
        - 'int_kind' : sets 'int'
        - 'float_kind' : sets 'float' and 'longfloat'
        - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat'
        - 'str_kind' : sets 'str' and 'numpystr'

Returns
-------
array_str : str
    String representation of the array.

Raises
------
TypeError
    if a callable in `formatter` does not return a string.

See Also
--------
array_str, array_repr, set_printoptions, get_printoptions

Notes
-----
If a formatter is specified for a certain type, the `precision` keyword is
ignored for that type.

Examples
--------
>>> x = np.array([1e-16,1,2,3])
>>> print np.array2string(x, precision=2, separator=',',
...                       suppress_small=True)
[ 0., 1., 2., 3.]

>>> x  = np.arange(3.)
>>> np.array2string(x, formatter={'float_kind':lambda x: "%.2f" % x})
'[0.00 1.00 2.00]'

>>> x  = np.arange(3)
>>> np.array2string(x, formatter={'int':lambda x: hex(x)})
'[0x0L 0x1L 0x2L]'


def _formatArray(a, format_function, rank, max_line_len,<EOL>next_line_prefix, separator, edge_items, summary_insert):

if rank == <NUM_LIT:0>:<EOL><INDENT>obj = a.item()<EOL>if isinstance(obj, tuple):<EOL><INDENT>obj = _convert_arrays(obj)<EOL><DEDENT>return str(obj)<EOL><DEDENT>if summary_insert and <NUM_LIT:2>*edge_items < len(a):<EOL><INDENT>leading_items, trailing_items, summary_insert1 =edge_items, edge_items, summary_insert<EOL><DEDENT>else:<EOL><INDENT>leading_items, trailing_items, summary_insert1 = <NUM_LIT:0>, len(a), "<STR_LIT>"<EOL><DEDENT>if rank == <NUM_LIT:1>:<EOL><INDENT>s = "<STR_LIT>"<EOL>line = next_line_prefix<EOL>for i in range(leading_items):<EOL><INDENT>word = format_function(a[i]) + separator<EOL>s, line = _extendLine(s, line, word, max_line_len, next_line_prefix)<EOL><DEDENT>if summary_insert1:<EOL><INDENT>s, line = _extendLine(s, line, summary_insert1, max_line_len, next_line_prefix)<EOL><DEDENT>for i in range(trailing_items, <NUM_LIT:1>, -<NUM_LIT:1>):<EOL><INDENT>word = format_function(a[-i]) + separator<EOL>s, line = _extendLine(s, line, word, max_line_len, next_line_prefix)<EOL><DEDENT>word = format_function(a[-<NUM_LIT:1>])<EOL>s, line = _extendLine(s, line, word, max_line_len, next_line_prefix)<EOL>s += line + "<STR_LIT>"<EOL>s = '<STR_LIT:[>' + s[len(next_line_prefix):]<EOL><DEDENT>else:<EOL><INDENT>s = '<STR_LIT:[>'<EOL>sep = separator.rstrip()<EOL>for i in range(leading_items):<EOL><INDENT>if i > <NUM_LIT:0>:<EOL><INDENT>s += next_line_prefix<EOL><DEDENT>s += _formatArray(a[i], format_function, rank-<NUM_LIT:1>, max_line_len,<EOL>"<STR_LIT:U+0020>" + next_line_prefix, separator, edge_items,<EOL>summary_insert)<EOL>s = s.rstrip() + sep.rstrip() + '<STR_LIT:\n>'*max(rank-<NUM_LIT:1>, <NUM_LIT:1>)<EOL><DEDENT>if summary_insert1:<EOL><INDENT>s += next_line_prefix + summary_insert1 + "<STR_LIT:\n>"<EOL><DEDENT>for i in range(trailing_items, <NUM_LIT:1>, -<NUM_LIT:1>):<EOL><INDENT>if leading_items or i != trailing_items:<EOL><INDENT>s += next_line_prefix<EOL><DEDENT>s += _formatArray(a[-i], format_function, rank-<NUM_LIT:1>, max_line_len,<EOL>"<STR_LIT:U+0020>" + next_line_prefix, separator, edge_items,<EOL>summary_insert)<EOL>s = s.rstrip() + sep.rstrip() + '<STR_LIT:\n>'*max(rank-<NUM_LIT:1>, <NUM_LIT:1>)<EOL><DEDENT>if leading_items or trailing_items > <NUM_LIT:1>:<EOL><INDENT>s += next_line_prefix<EOL><DEDENT>s += _formatArray(a[-<NUM_LIT:1>], format_function, rank-<NUM_LIT:1>, max_line_len,<EOL>"<STR_LIT:U+0020>" + next_line_prefix, separator, edge_items,<EOL>summary_insert).rstrip()+'<STR_LIT>'<EOL><DEDENT>return s<EOL>

formatArray is designed for two modes of operation:

    1. Full output

    2. Summarized output


def take(a, indices, axis=None, out=None, mode='<STR_LIT>'):

try:<EOL><INDENT>take = a.take<EOL><DEDENT>except AttributeError:<EOL><INDENT>return _wrapit(a, '<STR_LIT>', indices, axis, out, mode)<EOL><DEDENT>return take(indices, axis, out, mode)<EOL>

Take elements from an array along an axis.

This function does the same thing as "fancy" indexing (indexing arrays
using arrays); however, it can be easier to use if you need elements
along a given axis.

Parameters
----------
a : array_like
    The source array.
indices : array_like
    The indices of the values to extract.

    .. versionadded:: 1.8.0

    Also allow scalars for indices.
axis : int, optional
    The axis over which to select values. By default, the flattened
    input array is used.
out : ndarray, optional
    If provided, the result will be placed in this array. It should
    be of the appropriate shape and dtype.
mode : {'raise', 'wrap', 'clip'}, optional
    Specifies how out-of-bounds indices will behave.

    * 'raise' -- raise an error (default)
    * 'wrap' -- wrap around
    * 'clip' -- clip to the range

    'clip' mode means that all indices that are too large are replaced
    by the index that addresses the last element along that axis. Note
    that this disables indexing with negative numbers.

Returns
-------
subarray : ndarray
    The returned array has the same type as `a`.

See Also
--------
compress : Take elements using a boolean mask
ndarray.take : equivalent method

Examples
--------
>>> a = [4, 3, 5, 7, 6, 8]
>>> indices = [0, 1, 4]
>>> np.take(a, indices)
array([4, 3, 6])

In this example if `a` is an ndarray, "fancy" indexing can be used.

>>> a = np.array(a)
>>> a[indices]
array([4, 3, 6])

If `indices` is not one dimensional, the output also has these dimensions.

>>> np.take(a, [[0, 1], [2, 3]])
array([[4, 3],
       [5, 7]])


def reshape(a, newshape, order='<STR_LIT:C>'):

try:<EOL><INDENT>reshape = a.reshape<EOL><DEDENT>except AttributeError:<EOL><INDENT>return _wrapit(a, '<STR_LIT>', newshape, order=order)<EOL><DEDENT>return reshape(newshape, order=order)<EOL>

Gives a new shape to an array without changing its data.

Parameters
----------
a : array_like
    Array to be reshaped.
newshape : int or tuple of ints
    The new shape should be compatible with the original shape. If
    an integer, then the result will be a 1-D array of that length.
    One shape dimension can be -1. In this case, the value is inferred
    from the length of the array and remaining dimensions.
order : {'C', 'F', 'A'}, optional
    Read the elements of `a` using this index order, and place the elements
    into the reshaped array using this index order.  'C' means to
    read / write the elements using C-like index order, with the last axis index
    changing fastest, back to the first axis index changing slowest.  'F'
    means to read / write the elements using Fortran-like index order, with
    the first index changing fastest, and the last index changing slowest.
    Note that the 'C' and 'F' options take no account of the memory layout
    of the underlying array, and only refer to the order of indexing.  'A'
    means to read / write the elements in Fortran-like index order if `a` is
    Fortran *contiguous* in memory, C-like order otherwise.

Returns
-------
reshaped_array : ndarray
    This will be a new view object if possible; otherwise, it will
    be a copy.  Note there is no guarantee of the *memory layout* (C- or
    Fortran- contiguous) of the returned array.

See Also
--------
ndarray.reshape : Equivalent method.

Notes
-----
It is not always possible to change the shape of an array without
copying the data. If you want an error to be raise if the data is copied,
you should assign the new shape to the shape attribute of the array::

 >>> a = np.zeros((10, 2))
 # A transpose make the array non-contiguous
 >>> b = a.T
 # Taking a view makes it possible to modify the shape without modifying the
 # initial object.
 >>> c = b.view()
 >>> c.shape = (20)
 AttributeError: incompatible shape for a non-contiguous array

The `order` keyword gives the index ordering both for *fetching* the values
from `a`, and then *placing* the values into the output array.  For example,
let's say you have an array:

>>> a = np.arange(6).reshape((3, 2))
>>> a
array([[0, 1],
       [2, 3],
       [4, 5]])

You can think of reshaping as first raveling the array (using the given
index order), then inserting the elements from the raveled array into the
new array using the same kind of index ordering as was used for the
raveling.

>>> np.reshape(a, (2, 3)) # C-like index ordering
array([[0, 1, 2],
       [3, 4, 5]])
>>> np.reshape(np.ravel(a), (2, 3)) # equivalent to C ravel then C reshape
array([[0, 1, 2],
       [3, 4, 5]])
>>> np.reshape(a, (2, 3), order='F') # Fortran-like index ordering
array([[0, 4, 3],
       [2, 1, 5]])
>>> np.reshape(np.ravel(a, order='F'), (2, 3), order='F')
array([[0, 4, 3],
       [2, 1, 5]])

Examples
--------
>>> a = np.array([[1,2,3], [4,5,6]])
>>> np.reshape(a, 6)
array([1, 2, 3, 4, 5, 6])
>>> np.reshape(a, 6, order='F')
array([1, 4, 2, 5, 3, 6])

>>> np.reshape(a, (3,-1))       # the unspecified value is inferred to be 2
array([[1, 2],
       [3, 4],
       [5, 6]])


def choose(a, choices, out=None, mode='<STR_LIT>'):

try:<EOL><INDENT>choose = a.choose<EOL><DEDENT>except AttributeError:<EOL><INDENT>return _wrapit(a, '<STR_LIT>', choices, out=out, mode=mode)<EOL><DEDENT>return choose(choices, out=out, mode=mode)<EOL>

Construct an array from an index array and a set of arrays to choose from.

First of all, if confused or uncertain, definitely look at the Examples -
in its full generality, this function is less simple than it might
seem from the following code description (below ndi =
`numpy.lib.index_tricks`):

``np.choose(a,c) == np.array([c[a[I]][I] for I in ndi.ndindex(a.shape)])``.

But this omits some subtleties.  Here is a fully general summary:

Given an "index" array (`a`) of integers and a sequence of `n` arrays
(`choices`), `a` and each choice array are first broadcast, as necessary,
to arrays of a common shape; calling these *Ba* and *Bchoices[i], i =
0,...,n-1* we have that, necessarily, ``Ba.shape == Bchoices[i].shape``
for each `i`.  Then, a new array with shape ``Ba.shape`` is created as
follows:

* if ``mode=raise`` (the default), then, first of all, each element of
  `a` (and thus `Ba`) must be in the range `[0, n-1]`; now, suppose that
  `i` (in that range) is the value at the `(j0, j1, ..., jm)` position
  in `Ba` - then the value at the same position in the new array is the
  value in `Bchoices[i]` at that same position;

* if ``mode=wrap``, values in `a` (and thus `Ba`) may be any (signed)
  integer; modular arithmetic is used to map integers outside the range
  `[0, n-1]` back into that range; and then the new array is constructed
  as above;

* if ``mode=clip``, values in `a` (and thus `Ba`) may be any (signed)
  integer; negative integers are mapped to 0; values greater than `n-1`
  are mapped to `n-1`; and then the new array is constructed as above.

Parameters
----------
a : int array
    This array must contain integers in `[0, n-1]`, where `n` is the number
    of choices, unless ``mode=wrap`` or ``mode=clip``, in which cases any
    integers are permissible.
choices : sequence of arrays
    Choice arrays. `a` and all of the choices must be broadcastable to the
    same shape.  If `choices` is itself an array (not recommended), then
    its outermost dimension (i.e., the one corresponding to
    ``choices.shape[0]``) is taken as defining the "sequence".
out : array, optional
    If provided, the result will be inserted into this array. It should
    be of the appropriate shape and dtype.
mode : {'raise' (default), 'wrap', 'clip'}, optional
    Specifies how indices outside `[0, n-1]` will be treated:

      * 'raise' : an exception is raised
      * 'wrap' : value becomes value mod `n`
      * 'clip' : values < 0 are mapped to 0, values > n-1 are mapped to n-1

Returns
-------
merged_array : array
    The merged result.

Raises
------
ValueError: shape mismatch
    If `a` and each choice array are not all broadcastable to the same
    shape.

See Also
--------
ndarray.choose : equivalent method

Notes
-----
To reduce the chance of misinterpretation, even though the following
"abuse" is nominally supported, `choices` should neither be, nor be
thought of as, a single array, i.e., the outermost sequence-like container
should be either a list or a tuple.

Examples
--------

>>> choices = [[0, 1, 2, 3], [10, 11, 12, 13],
...   [20, 21, 22, 23], [30, 31, 32, 33]]
>>> np.choose([2, 3, 1, 0], choices
... # the first element of the result will be the first element of the
... # third (2+1) "array" in choices, namely, 20; the second element
... # will be the second element of the fourth (3+1) choice array, i.e.,
... # 31, etc.
... )
array([20, 31, 12,  3])
>>> np.choose([2, 4, 1, 0], choices, mode='clip') # 4 goes to 3 (4-1)
array([20, 31, 12,  3])
>>> # because there are 4 choice arrays
>>> np.choose([2, 4, 1, 0], choices, mode='wrap') # 4 goes to (4 mod 4)
array([20,  1, 12,  3])
>>> # i.e., 0

A couple examples illustrating how choose broadcasts:

>>> a = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
>>> choices = [-10, 10]
>>> np.choose(a, choices)
array([[ 10, -10,  10],
       [-10,  10, -10],
       [ 10, -10,  10]])

>>> # With thanks to Anne Archibald
>>> a = np.array([0, 1]).reshape((2,1,1))
>>> c1 = np.array([1, 2, 3]).reshape((1,3,1))
>>> c2 = np.array([-1, -2, -3, -4, -5]).reshape((1,1,5))
>>> np.choose(a, (c1, c2)) # result is 2x3x5, res[0,:,:]=c1, res[1,:,:]=c2
array([[[ 1,  1,  1,  1,  1],
        [ 2,  2,  2,  2,  2],
        [ 3,  3,  3,  3,  3]],
       [[-1, -2, -3, -4, -5],
        [-1, -2, -3, -4, -5],
        [-1, -2, -3, -4, -5]]])


try:<EOL><INDENT>repeat = a.repeat<EOL><DEDENT>except AttributeError:<EOL><INDENT>return _wrapit(a, '<STR_LIT>', repeats, axis)<EOL><DEDENT>return repeat(repeats, axis)<EOL>

Repeat elements of an array.

Parameters
----------
a : array_like
    Input array.
repeats : {int, array of ints}
    The number of repetitions for each element.  `repeats` is broadcasted
    to fit the shape of the given axis.
axis : int, optional
    The axis along which to repeat values.  By default, use the
    flattened input array, and return a flat output array.

Returns
-------
repeated_array : ndarray
    Output array which has the same shape as `a`, except along
    the given axis.

See Also
--------
tile : Tile an array.

Examples
--------
>>> x = np.array([[1,2],[3,4]])
>>> np.repeat(x, 2)
array([1, 1, 2, 2, 3, 3, 4, 4])
>>> np.repeat(x, 3, axis=1)
array([[1, 1, 1, 2, 2, 2],
       [3, 3, 3, 4, 4, 4]])
>>> np.repeat(x, [1, 2], axis=0)
array([[1, 2],
       [3, 4],
       [3, 4]])


return a.put(ind, v, mode)<EOL>

Replaces specified elements of an array with given values.

The indexing works on the flattened target array. `put` is roughly
equivalent to:

::

    a.flat[ind] = v

Parameters
----------
a : ndarray
    Target array.
ind : array_like
    Target indices, interpreted as integers.
v : array_like
    Values to place in `a` at target indices. If `v` is shorter than
    `ind` it will be repeated as necessary.
mode : {'raise', 'wrap', 'clip'}, optional
    Specifies how out-of-bounds indices will behave.

    * 'raise' -- raise an error (default)
    * 'wrap' -- wrap around
    * 'clip' -- clip to the range

    'clip' mode means that all indices that are too large are replaced
    by the index that addresses the last element along that axis. Note
    that this disables indexing with negative numbers.

See Also
--------
putmask, place

Examples
--------
>>> a = np.arange(5)
>>> np.put(a, [0, 2], [-44, -55])
>>> a
array([-44,   1, -55,   3,   4])

>>> a = np.arange(5)
>>> np.put(a, 22, -5, mode='clip')
>>> a
array([ 0,  1,  2,  3, -5])


try:<EOL><INDENT>swapaxes = a.swapaxes<EOL><DEDENT>except AttributeError:<EOL><INDENT>return _wrapit(a, '<STR_LIT>', axis1, axis2)<EOL><DEDENT>return swapaxes(axis1, axis2)<EOL>

Interchange two axes of an array.

Parameters
----------
a : array_like
    Input array.
axis1 : int
    First axis.
axis2 : int
    Second axis.

Returns
-------
a_swapped : ndarray
    If `a` is an ndarray, then a view of `a` is returned; otherwise
    a new array is created.

Examples
--------
>>> x = np.array([[1,2,3]])
>>> np.swapaxes(x,0,1)
array([[1],
       [2],
       [3]])

>>> x = np.array([[[0,1],[2,3]],[[4,5],[6,7]]])
>>> x
array([[[0, 1],
        [2, 3]],
       [[4, 5],
        [6, 7]]])

>>> np.swapaxes(x,0,2)
array([[[0, 4],
        [2, 6]],
       [[1, 5],
        [3, 7]]])


try:<EOL><INDENT>transpose = a.transpose<EOL><DEDENT>except AttributeError:<EOL><INDENT>return _wrapit(a, '<STR_LIT>', axes)<EOL><DEDENT>return transpose(axes)<EOL>

Permute the dimensions of an array.

Parameters
----------
a : array_like
    Input array.
axes : list of ints, optional
    By default, reverse the dimensions, otherwise permute the axes
    according to the values given.

Returns
-------
p : ndarray
    `a` with its axes permuted.  A view is returned whenever
    possible.

See Also
--------
rollaxis

Examples
--------
>>> x = np.arange(4).reshape((2,2))
>>> x
array([[0, 1],
       [2, 3]])

>>> np.transpose(x)
array([[0, 2],
       [1, 3]])

>>> x = np.ones((1, 2, 3))
>>> np.transpose(x, (1, 0, 2)).shape
(2, 1, 3)


def partition(a, kth, axis=-<NUM_LIT:1>, kind='<STR_LIT>', order=None):

if axis is None:<EOL><INDENT>a = asanyarray(a).flatten()<EOL>axis = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>a = asanyarray(a).copy(order="<STR_LIT>")<EOL><DEDENT>a.partition(kth, axis=axis, kind=kind, order=order)<EOL>return a<EOL>

Return a partitioned copy of an array.

Creates a copy of the array with its elements rearranged in such a way that
the value of the element in kth position is in the position it would be in
a sorted array. All elements smaller than the kth element are moved before
this element and all equal or greater are moved behind it. The ordering of
the elements in the two partitions is undefined.

.. versionadded:: 1.8.0

Parameters
----------
a : array_like
    Array to be sorted.
kth : int or sequence of ints
    Element index to partition by. The kth value of the element will be in
    its final sorted position and all smaller elements will be moved before
    it and all equal or greater elements behind it.
    The order all elements in the partitions is undefined.
    If provided with a sequence of kth it will partition all elements
    indexed by kth  of them into their sorted position at once.
axis : int or None, optional
    Axis along which to sort. If None, the array is flattened before
    sorting. The default is -1, which sorts along the last axis.
kind : {'introselect'}, optional
    Selection algorithm. Default is 'introselect'.
order : list, optional
    When `a` is a structured array, this argument specifies which fields
    to compare first, second, and so on.  This list does not need to
    include all of the fields.

Returns
-------
partitioned_array : ndarray
    Array of the same type and shape as `a`.

See Also
--------
ndarray.partition : Method to sort an array in-place.
argpartition : Indirect partition.
sort : Full sorting

Notes
-----
The various selection algorithms are characterized by their average speed,
worst case performance, work space size, and whether they are stable. A
stable sort keeps items with the same key in the same relative order. The
available algorithms have the following properties:

================= ======= ============= ============ =======
   kind            speed   worst case    work space  stable
================= ======= ============= ============ =======
'introselect'        1        O(n)           0         no
================= ======= ============= ============ =======

All the partition algorithms make temporary copies of the data when
partitioning along any but the last axis.  Consequently, partitioning
along the last axis is faster and uses less space than partitioning
along any other axis.

The sort order for complex numbers is lexicographic. If both the real
and imaginary parts are non-nan then the order is determined by the
real parts except when they are equal, in which case the order is
determined by the imaginary parts.

Examples
--------
>>> a = np.array([3, 4, 2, 1])
>>> np.partition(a, 3)
array([2, 1, 3, 4])

>>> np.partition(a, (1, 3))
array([1, 2, 3, 4])


def argpartition(a, kth, axis=-<NUM_LIT:1>, kind='<STR_LIT>', order=None):

try:<EOL><INDENT>argpartition = a.argpartition<EOL><DEDENT>except AttributeError:<EOL><INDENT>return _wrapit(a, '<STR_LIT>',kth, axis, kind, order)<EOL><DEDENT>return argpartition(kth, axis, kind=kind, order=order)<EOL>

Perform an indirect partition along the given axis using the algorithm
specified by the `kind` keyword. It returns an array of indices of the
same shape as `a` that index data along the given axis in partitioned
order.

.. versionadded:: 1.8.0

Parameters
----------
a : array_like
    Array to sort.
kth : int or sequence of ints
    Element index to partition by. The kth element will be in its final
    sorted position and all smaller elements will be moved before it and
    all larger elements behind it.
    The order all elements in the partitions is undefined.
    If provided with a sequence of kth it will partition all of them into
    their sorted position at once.
axis : int or None, optional
    Axis along which to sort.  The default is -1 (the last axis). If None,
    the flattened array is used.
kind : {'introselect'}, optional
    Selection algorithm. Default is 'introselect'
order : list, optional
    When `a` is an array with fields defined, this argument specifies
    which fields to compare first, second, etc.  Not all fields need be
    specified.

Returns
-------
index_array : ndarray, int
    Array of indices that partition `a` along the specified axis.
    In other words, ``a[index_array]`` yields a sorted `a`.

See Also
--------
partition : Describes partition algorithms used.
ndarray.partition : Inplace partition.
argsort : Full indirect sort

Notes
-----
See `partition` for notes on the different selection algorithms.

Examples
--------
One dimensional array:

>>> x = np.array([3, 4, 2, 1])
>>> x[np.argpartition(x, 3)]
array([2, 1, 3, 4])
>>> x[np.argpartition(x, (1, 3))]
array([1, 2, 3, 4])

>>> x = [3, 4, 2, 1]
>>> np.array(x)[np.argpartition(x, 3)]
array([2, 1, 3, 4])


def sort(a, axis=-<NUM_LIT:1>, kind='<STR_LIT>', order=None):

if axis is None:<EOL><INDENT>a = asanyarray(a).flatten()<EOL>axis = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>a = asanyarray(a).copy(order="<STR_LIT>")<EOL><DEDENT>a.sort(axis, kind, order)<EOL>return a<EOL>

Return a sorted copy of an array.

Parameters
----------
a : array_like
    Array to be sorted.
axis : int or None, optional
    Axis along which to sort. If None, the array is flattened before
    sorting. The default is -1, which sorts along the last axis.
kind : {'quicksort', 'mergesort', 'heapsort'}, optional
    Sorting algorithm. Default is 'quicksort'.
order : list, optional
    When `a` is a structured array, this argument specifies which fields
    to compare first, second, and so on.  This list does not need to
    include all of the fields.

Returns
-------
sorted_array : ndarray
    Array of the same type and shape as `a`.

See Also
--------
ndarray.sort : Method to sort an array in-place.
argsort : Indirect sort.
lexsort : Indirect stable sort on multiple keys.
searchsorted : Find elements in a sorted array.
partition : Partial sort.

Notes
-----
The various sorting algorithms are characterized by their average speed,
worst case performance, work space size, and whether they are stable. A
stable sort keeps items with the same key in the same relative
order. The three available algorithms have the following
properties:

=========== ======= ============= ============ =======
   kind      speed   worst case    work space  stable
=========== ======= ============= ============ =======
'quicksort'    1     O(n^2)            0          no
'mergesort'    2     O(n*log(n))      ~n/2        yes
'heapsort'     3     O(n*log(n))       0          no
=========== ======= ============= ============ =======

All the sort algorithms make temporary copies of the data when
sorting along any but the last axis.  Consequently, sorting along
the last axis is faster and uses less space than sorting along
any other axis.

The sort order for complex numbers is lexicographic. If both the real
and imaginary parts are non-nan then the order is determined by the
real parts except when they are equal, in which case the order is
determined by the imaginary parts.

Previous to numpy 1.4.0 sorting real and complex arrays containing nan
values led to undefined behaviour. In numpy versions >= 1.4.0 nan
values are sorted to the end. The extended sort order is:

  * Real: [R, nan]
  * Complex: [R + Rj, R + nanj, nan + Rj, nan + nanj]

where R is a non-nan real value. Complex values with the same nan
placements are sorted according to the non-nan part if it exists.
Non-nan values are sorted as before.

Examples
--------
>>> a = np.array([[1,4],[3,1]])
>>> np.sort(a)                # sort along the last axis
array([[1, 4],
       [1, 3]])
>>> np.sort(a, axis=None)     # sort the flattened array
array([1, 1, 3, 4])
>>> np.sort(a, axis=0)        # sort along the first axis
array([[1, 1],
       [3, 4]])

Use the `order` keyword to specify a field to use when sorting a
structured array:

>>> dtype = [('name', 'S10'), ('height', float), ('age', int)]
>>> values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38),
...           ('Galahad', 1.7, 38)]
>>> a = np.array(values, dtype=dtype)       # create a structured array
>>> np.sort(a, order='height')                        # doctest: +SKIP
array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41),
       ('Lancelot', 1.8999999999999999, 38)],
      dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])

Sort by age, then height if ages are equal:

>>> np.sort(a, order=['age', 'height'])               # doctest: +SKIP
array([('Galahad', 1.7, 38), ('Lancelot', 1.8999999999999999, 38),
       ('Arthur', 1.8, 41)],
      dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])


def argsort(a, axis=-<NUM_LIT:1>, kind='<STR_LIT>', order=None):

try:<EOL><INDENT>argsort = a.argsort<EOL><DEDENT>except AttributeError:<EOL><INDENT>return _wrapit(a, '<STR_LIT>', axis, kind, order)<EOL><DEDENT>return argsort(axis, kind, order)<EOL>

Returns the indices that would sort an array.

Perform an indirect sort along the given axis using the algorithm specified
by the `kind` keyword. It returns an array of indices of the same shape as
`a` that index data along the given axis in sorted order.

Parameters
----------
a : array_like
    Array to sort.
axis : int or None, optional
    Axis along which to sort.  The default is -1 (the last axis). If None,
    the flattened array is used.
kind : {'quicksort', 'mergesort', 'heapsort'}, optional
    Sorting algorithm.
order : list, optional
    When `a` is an array with fields defined, this argument specifies
    which fields to compare first, second, etc.  Not all fields need be
    specified.

Returns
-------
index_array : ndarray, int
    Array of indices that sort `a` along the specified axis.
    In other words, ``a[index_array]`` yields a sorted `a`.

See Also
--------
sort : Describes sorting algorithms used.
lexsort : Indirect stable sort with multiple keys.
ndarray.sort : Inplace sort.
argpartition : Indirect partial sort.

Notes
-----
See `sort` for notes on the different sorting algorithms.

As of NumPy 1.4.0 `argsort` works with real/complex arrays containing
nan values. The enhanced sort order is documented in `sort`.

Examples
--------
One dimensional array:

>>> x = np.array([3, 1, 2])
>>> np.argsort(x)
array([1, 2, 0])

Two-dimensional array:

>>> x = np.array([[0, 3], [2, 2]])
>>> x
array([[0, 3],
       [2, 2]])

>>> np.argsort(x, axis=0)
array([[0, 1],
       [1, 0]])

>>> np.argsort(x, axis=1)
array([[0, 1],
       [0, 1]])

Sorting with keys:

>>> x = np.array([(1, 0), (0, 1)], dtype=[('x', '<i4'), ('y', '<i4')])
>>> x
array([(1, 0), (0, 1)],
      dtype=[('x', '<i4'), ('y', '<i4')])

>>> np.argsort(x, order=('x','y'))
array([1, 0])

>>> np.argsort(x, order=('y','x'))
array([0, 1])


try:<EOL><INDENT>argmax = a.argmax<EOL><DEDENT>except AttributeError:<EOL><INDENT>return _wrapit(a, '<STR_LIT>', axis)<EOL><DEDENT>return argmax(axis)<EOL>

Indices of the maximum values along an axis.

Parameters
----------
a : array_like
    Input array.
axis : int, optional
    By default, the index is into the flattened array, otherwise
    along the specified axis.

Returns
-------
index_array : ndarray of ints
    Array of indices into the array. It has the same shape as `a.shape`
    with the dimension along `axis` removed.

See Also
--------
ndarray.argmax, argmin
amax : The maximum value along a given axis.
unravel_index : Convert a flat index into an index tuple.

Notes
-----
In case of multiple occurrences of the maximum values, the indices
corresponding to the first occurrence are returned.

Examples
--------
>>> a = np.arange(6).reshape(2,3)
>>> a
array([[0, 1, 2],
       [3, 4, 5]])
>>> np.argmax(a)
5
>>> np.argmax(a, axis=0)
array([1, 1, 1])
>>> np.argmax(a, axis=1)
array([2, 2])

>>> b = np.arange(6)
>>> b[1] = 5
>>> b
array([0, 5, 2, 3, 4, 5])
>>> np.argmax(b) # Only the first occurrence is returned.
1


try:<EOL><INDENT>argmin = a.argmin<EOL><DEDENT>except AttributeError:<EOL><INDENT>return _wrapit(a, '<STR_LIT>', axis)<EOL><DEDENT>return argmin(axis)<EOL>

Return the indices of the minimum values along an axis.

See Also
--------
argmax : Similar function.  Please refer to `numpy.argmax` for detailed
    documentation.


def searchsorted(a, v, side='<STR_LIT:left>', sorter=None):

try:<EOL><INDENT>searchsorted = a.searchsorted<EOL><DEDENT>except AttributeError:<EOL><INDENT>return _wrapit(a, '<STR_LIT>', v, side, sorter)<EOL><DEDENT>return searchsorted(v, side, sorter)<EOL>

Find indices where elements should be inserted to maintain order.

Find the indices into a sorted array `a` such that, if the
corresponding elements in `v` were inserted before the indices, the
order of `a` would be preserved.

Parameters
----------
a : 1-D array_like
    Input array. If `sorter` is None, then it must be sorted in
    ascending order, otherwise `sorter` must be an array of indices
    that sort it.
v : array_like
    Values to insert into `a`.
side : {'left', 'right'}, optional
    If 'left', the index of the first suitable location found is given.
    If 'right', return the last such index.  If there is no suitable
    index, return either 0 or N (where N is the length of `a`).
sorter : 1-D array_like, optional
    .. versionadded:: 1.7.0
    Optional array of integer indices that sort array a into ascending
    order. They are typically the result of argsort.

Returns
-------
indices : array of ints
    Array of insertion points with the same shape as `v`.

See Also
--------
sort : Return a sorted copy of an array.
histogram : Produce histogram from 1-D data.

Notes
-----
Binary search is used to find the required insertion points.

As of Numpy 1.4.0 `searchsorted` works with real/complex arrays containing
`nan` values. The enhanced sort order is documented in `sort`.

Examples
--------
>>> np.searchsorted([1,2,3,4,5], 3)
2
>>> np.searchsorted([1,2,3,4,5], 3, side='right')
3
>>> np.searchsorted([1,2,3,4,5], [-10, 10, 2, 3])
array([0, 5, 1, 2])


if isinstance(new_shape, (int, nt.integer)):<EOL><INDENT>new_shape = (new_shape,)<EOL><DEDENT>a = ravel(a)<EOL>Na = len(a)<EOL>if not Na: return mu.zeros(new_shape, a.dtype.char)<EOL>total_size = um.multiply.reduce(new_shape)<EOL>n_copies = int(total_size / Na)<EOL>extra = total_size % Na<EOL>if total_size == <NUM_LIT:0>:<EOL><INDENT>return a[:<NUM_LIT:0>]<EOL><DEDENT>if extra != <NUM_LIT:0>:<EOL><INDENT>n_copies = n_copies+<NUM_LIT:1><EOL>extra = Na-extra<EOL><DEDENT>a = concatenate( (a,)*n_copies)<EOL>if extra > <NUM_LIT:0>:<EOL><INDENT>a = a[:-extra]<EOL><DEDENT>return reshape(a, new_shape)<EOL>

Return a new array with the specified shape.

If the new array is larger than the original array, then the new
array is filled with repeated copies of `a`.  Note that this behavior
is different from a.resize(new_shape) which fills with zeros instead
of repeated copies of `a`.

Parameters
----------
a : array_like
    Array to be resized.

new_shape : int or tuple of int
    Shape of resized array.

Returns
-------
reshaped_array : ndarray
    The new array is formed from the data in the old array, repeated
    if necessary to fill out the required number of elements.  The
    data are repeated in the order that they are stored in memory.

See Also
--------
ndarray.resize : resize an array in-place.

Examples
--------
>>> a=np.array([[0,1],[2,3]])
>>> np.resize(a,(1,4))
array([[0, 1, 2, 3]])
>>> np.resize(a,(2,4))
array([[0, 1, 2, 3],
       [0, 1, 2, 3]])


try:<EOL><INDENT>squeeze = a.squeeze<EOL><DEDENT>except AttributeError:<EOL><INDENT>return _wrapit(a, '<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>return squeeze(axis=axis)<EOL><DEDENT>except TypeError:<EOL><INDENT>return squeeze()<EOL><DEDENT>

Remove single-dimensional entries from the shape of an array.

Parameters
----------
a : array_like
    Input data.
axis : None or int or tuple of ints, optional
    .. versionadded:: 1.7.0

    Selects a subset of the single-dimensional entries in the
    shape. If an axis is selected with shape entry greater than
    one, an error is raised.

Returns
-------
squeezed : ndarray
    The input array, but with all or a subset of the
    dimensions of length 1 removed. This is always `a` itself
    or a view into `a`.

Examples
--------
>>> x = np.array([[[0], [1], [2]]])
>>> x.shape
(1, 3, 1)
>>> np.squeeze(x).shape
(3,)
>>> np.squeeze(x, axis=(2,)).shape
(1, 3)