[pypy-commit] pypy default: merge remove-numpypy
bdkearns
noreply at buildbot.pypy.org
Wed Oct 30 17:13:46 CET 2013
Author: Brian Kearns <bdkearns at gmail.com>
Branch:
Changeset: r67738:f8579ebf6c24
Date: 2013-10-30 12:10 -0400
http://bitbucket.org/pypy/pypy/changeset/f8579ebf6c24/
Log: merge remove-numpypy
diff too long, truncating to 2000 out of 7423 lines
diff --git a/lib_pypy/numpypy/__init__.py b/lib_pypy/numpypy/__init__.py
deleted file mode 100644
--- a/lib_pypy/numpypy/__init__.py
+++ /dev/null
@@ -1,17 +0,0 @@
-from . import core
-from .core import *
-from . import lib
-from .lib import *
-
-from __builtin__ import bool, int, long, float, complex, object, unicode, str
-
-from .core import round, abs, max, min
-
-__version__ = '1.7.0'
-
-__all__ = ['__version__']
-__all__ += core.__all__
-__all__ += lib.__all__
-
-#import sys
-#sys.modules.setdefault('numpy', sys.modules['numpypy'])
diff --git a/lib_pypy/numpypy/core/__init__.py b/lib_pypy/numpypy/core/__init__.py
deleted file mode 100644
--- a/lib_pypy/numpypy/core/__init__.py
+++ /dev/null
@@ -1,19 +0,0 @@
-from __future__ import division, absolute_import, print_function
-
-from . import multiarray
-from . import umath
-from . import numeric
-from .numeric import *
-from . import fromnumeric
-from .fromnumeric import *
-from . import shape_base
-from .shape_base import *
-
-from .fromnumeric import amax as max, amin as min, \
- round_ as round
-from .numeric import absolute as abs
-
-__all__ = []
-__all__ += numeric.__all__
-__all__ += fromnumeric.__all__
-__all__ += shape_base.__all__
diff --git a/lib_pypy/numpypy/core/_methods.py b/lib_pypy/numpypy/core/_methods.py
deleted file mode 100644
--- a/lib_pypy/numpypy/core/_methods.py
+++ /dev/null
@@ -1,124 +0,0 @@
-"""
-Array methods which are called by the both the C-code for the method
-and the Python code for the NumPy-namespace function
-
-"""
-from __future__ import division, absolute_import, print_function
-
-import warnings
-
-from . import multiarray as mu
-from . import umath as um
-from .numeric import asanyarray
-from . import numerictypes as nt
-
-def _amax(a, axis=None, out=None, keepdims=False):
- return um.maximum.reduce(a, axis=axis,
- out=out, keepdims=keepdims)
-
-def _amin(a, axis=None, out=None, keepdims=False):
- return um.minimum.reduce(a, axis=axis,
- out=out, keepdims=keepdims)
-
-def _sum(a, axis=None, dtype=None, out=None, keepdims=False):
- return um.add.reduce(a, axis=axis, dtype=dtype,
- out=out, keepdims=keepdims)
-
-def _prod(a, axis=None, dtype=None, out=None, keepdims=False):
- return um.multiply.reduce(a, axis=axis, dtype=dtype,
- out=out, keepdims=keepdims)
-
-def _any(a, axis=None, dtype=None, out=None, keepdims=False):
- return um.logical_or.reduce(a, axis=axis, dtype=dtype, out=out,
- keepdims=keepdims)
-
-def _all(a, axis=None, dtype=None, out=None, keepdims=False):
- return um.logical_and.reduce(a, axis=axis, dtype=dtype, out=out,
- keepdims=keepdims)
-
-def _count_reduce_items(arr, axis):
- if axis is None:
- axis = tuple(range(arr.ndim))
- if not isinstance(axis, tuple):
- axis = (axis,)
- items = 1
- for ax in axis:
- items *= arr.shape[ax]
- return items
-
-def _mean(a, axis=None, dtype=None, out=None, keepdims=False):
- arr = asanyarray(a)
-
- rcount = _count_reduce_items(arr, axis)
- # Make this warning show up first
- if rcount == 0:
- warnings.warn("Mean of empty slice.", RuntimeWarning)
-
-
- # Cast bool, unsigned int, and int to float64 by default
- if dtype is None and issubclass(arr.dtype.type, (nt.integer, nt.bool_)):
- dtype = mu.dtype('f8')
-
- ret = um.add.reduce(arr, axis=axis, dtype=dtype, out=out, keepdims=keepdims)
- if isinstance(ret, mu.ndarray):
- ret = um.true_divide(
- ret, rcount, out=ret, casting='unsafe', subok=False)
- else:
- ret = ret.dtype.type(ret / rcount)
-
- return ret
-
-def _var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False):
- arr = asanyarray(a)
-
- rcount = _count_reduce_items(arr, axis)
- # Make this warning show up on top.
- if ddof >= rcount:
- warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning)
-
- # Cast bool, unsigned int, and int to float64 by default
- if dtype is None and issubclass(arr.dtype.type, (nt.integer, nt.bool_)):
- dtype = mu.dtype('f8')
-
- # Compute the mean.
- # Note that if dtype is not of inexact type then arraymean will
- # not be either.
- arrmean = um.add.reduce(arr, axis=axis, dtype=dtype, keepdims=True)
- if isinstance(arrmean, mu.ndarray):
- arrmean = um.true_divide(
- arrmean, rcount, out=arrmean, casting='unsafe', subok=False)
- else:
- arrmean = arrmean.dtype.type(arrmean / rcount)
-
- # Compute sum of squared deviations from mean
- # Note that x may not be inexact and that we need it to be an array,
- # not a scalar.
- x = asanyarray(arr - arrmean)
- if issubclass(arr.dtype.type, nt.complexfloating):
- x = um.multiply(x, um.conjugate(x), out=x).real
- else:
- x = um.multiply(x, x, out=x)
- ret = um.add.reduce(x, axis=axis, dtype=dtype, out=out, keepdims=keepdims)
-
- # Compute degrees of freedom and make sure it is not negative.
- rcount = max([rcount - ddof, 0])
-
- # divide by degrees of freedom
- if isinstance(ret, mu.ndarray):
- ret = um.true_divide(
- ret, rcount, out=ret, casting='unsafe', subok=False)
- else:
- ret = ret.dtype.type(ret / rcount)
-
- return ret
-
-def _std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False):
- ret = _var(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
- keepdims=keepdims)
-
- if isinstance(ret, mu.ndarray):
- ret = um.sqrt(ret, out=ret)
- else:
- ret = ret.dtype.type(um.sqrt(ret))
-
- return ret
diff --git a/lib_pypy/numpypy/core/arrayprint.py b/lib_pypy/numpypy/core/arrayprint.py
deleted file mode 100644
--- a/lib_pypy/numpypy/core/arrayprint.py
+++ /dev/null
@@ -1,751 +0,0 @@
-"""Array printing function
-
-$Id: arrayprint.py,v 1.9 2005/09/13 13:58:44 teoliphant Exp $
-"""
-__all__ = ["array2string", "set_printoptions", "get_printoptions"]
-__docformat__ = 'restructuredtext'
-
-#
-# Written by Konrad Hinsen <hinsenk at ere.umontreal.ca>
-# last revision: 1996-3-13
-# modified by Jim Hugunin 1997-3-3 for repr's and str's (and other details)
-# and by Perry Greenfield 2000-4-1 for numarray
-# and by Travis Oliphant 2005-8-22 for numpy
-
-import sys
-import numerictypes as _nt
-from umath import maximum, minimum, absolute, not_equal, isnan, isinf
-#from multiarray import format_longfloat, datetime_as_string, datetime_data
-from fromnumeric import ravel
-
-
-def product(x, y): return x*y
-
-_summaryEdgeItems = 3 # repr N leading and trailing items of each dimension
-_summaryThreshold = 1000 # total items > triggers array summarization
-
-_float_output_precision = 8
-_float_output_suppress_small = False
-_line_width = 75
-_nan_str = 'nan'
-_inf_str = 'inf'
-_formatter = None # formatting function for array elements
-
-if sys.version_info[0] >= 3:
- from functools import reduce
-
-def set_printoptions(precision=None, threshold=None, edgeitems=None,
- linewidth=None, suppress=None,
- nanstr=None, infstr=None,
- formatter=None):
- """
- 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)
- """
-
- global _summaryThreshold, _summaryEdgeItems, _float_output_precision, \
- _line_width, _float_output_suppress_small, _nan_str, _inf_str, \
- _formatter
- if linewidth is not None:
- _line_width = linewidth
- if threshold is not None:
- _summaryThreshold = threshold
- if edgeitems is not None:
- _summaryEdgeItems = edgeitems
- if precision is not None:
- _float_output_precision = precision
- if suppress is not None:
- _float_output_suppress_small = not not suppress
- if nanstr is not None:
- _nan_str = nanstr
- if infstr is not None:
- _inf_str = infstr
- _formatter = formatter
-
-def get_printoptions():
- """
- 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
-
- """
- d = dict(precision=_float_output_precision,
- threshold=_summaryThreshold,
- edgeitems=_summaryEdgeItems,
- linewidth=_line_width,
- suppress=_float_output_suppress_small,
- nanstr=_nan_str,
- infstr=_inf_str,
- formatter=_formatter)
- return d
-
-def _leading_trailing(a):
- import numeric as _nc
- if a.ndim == 1:
- if len(a) > 2*_summaryEdgeItems:
- b = _nc.concatenate((a[:_summaryEdgeItems],
- a[-_summaryEdgeItems:]))
- else:
- b = a
- else:
- if len(a) > 2*_summaryEdgeItems:
- l = [_leading_trailing(a[i]) for i in range(
- min(len(a), _summaryEdgeItems))]
- l.extend([_leading_trailing(a[-i]) for i in range(
- min(len(a), _summaryEdgeItems),0,-1)])
- else:
- l = [_leading_trailing(a[i]) for i in range(0, len(a))]
- b = _nc.concatenate(tuple(l))
- return b
-
-def _boolFormatter(x):
- if x:
- return ' True'
- else:
- return 'False'
-
-
-def repr_format(x):
- return repr(x)
-
-def _array2string(a, max_line_width, precision, suppress_small, separator=' ',
- prefix="", formatter=None):
-
- if max_line_width is None:
- max_line_width = _line_width
-
- if precision is None:
- precision = _float_output_precision
-
- if suppress_small is None:
- suppress_small = _float_output_suppress_small
-
- if formatter is None:
- formatter = _formatter
-
- if a.size > _summaryThreshold:
- summary_insert = "..., "
- data = _leading_trailing(a)
- else:
- summary_insert = ""
- data = ravel(a)
-
- formatdict = {'bool' : _boolFormatter,
- 'int' : IntegerFormat(data),
- 'float' : FloatFormat(data, precision, suppress_small),
- 'longfloat' : FloatFormat(data, precision, suppress_small),
- 'complexfloat' : ComplexFormat(data, precision,
- suppress_small),
- 'longcomplexfloat' : ComplexFormat(data, precision,
- suppress_small),
- 'datetime' : DatetimeFormat(data),
- 'timedelta' : TimedeltaFormat(data),
- 'numpystr' : repr_format,
- 'str' : str}
-
- if formatter is not None:
- fkeys = [k for k in formatter.keys() if formatter[k] is not None]
- if 'all' in fkeys:
- for key in formatdict.keys():
- formatdict[key] = formatter['all']
- if 'int_kind' in fkeys:
- for key in ['int']:
- formatdict[key] = formatter['int_kind']
- if 'float_kind' in fkeys:
- for key in ['float', 'longfloat']:
- formatdict[key] = formatter['float_kind']
- if 'complex_kind' in fkeys:
- for key in ['complexfloat', 'longcomplexfloat']:
- formatdict[key] = formatter['complex_kind']
- if 'str_kind' in fkeys:
- for key in ['numpystr', 'str']:
- formatdict[key] = formatter['str_kind']
- for key in formatdict.keys():
- if key in fkeys:
- formatdict[key] = formatter[key]
-
- try:
- format_function = a._format
- msg = "The `_format` attribute is deprecated in Numpy 2.0 and " \
- "will be removed in 2.1. Use the `formatter` kw instead."
- import warnings
- warnings.warn(msg, DeprecationWarning)
- except AttributeError:
- # find the right formatting function for the array
- dtypeobj = a.dtype.type
- if issubclass(dtypeobj, _nt.bool_):
- format_function = formatdict['bool']
- elif issubclass(dtypeobj, _nt.integer):
- #if issubclass(dtypeobj, _nt.timedelta64):
- # format_function = formatdict['timedelta']
- #else:
- format_function = formatdict['int']
- elif issubclass(dtypeobj, _nt.floating):
- if hasattr(_nt, 'longfloat') and issubclass(dtypeobj, _nt.longfloat):
- format_function = formatdict['longfloat']
- else:
- format_function = formatdict['float']
- elif issubclass(dtypeobj, _nt.complexfloating):
- if hasattr(_nt, 'clongfloat') and issubclass(dtypeobj, _nt.clongfloat):
- format_function = formatdict['longcomplexfloat']
- else:
- format_function = formatdict['complexfloat']
- elif issubclass(dtypeobj, (_nt.unicode_, _nt.string_)):
- format_function = formatdict['numpystr']
- #elif issubclass(dtypeobj, _nt.datetime64):
- # format_function = formatdict['datetime']
- else:
- format_function = formatdict['str']
-
- # skip over "["
- next_line_prefix = " "
- # skip over array(
- next_line_prefix += " "*len(prefix)
-
- lst = _formatArray(a, format_function, len(a.shape), max_line_width,
- next_line_prefix, separator,
- _summaryEdgeItems, summary_insert)[:-1]
- return lst
-
-def _convert_arrays(obj):
- import numeric as _nc
- newtup = []
- for k in obj:
- if isinstance(k, _nc.ndarray):
- k = k.tolist()
- elif isinstance(k, tuple):
- k = _convert_arrays(k)
- newtup.append(k)
- return tuple(newtup)
-
-
-def array2string(a, max_line_width=None, precision=None,
- suppress_small=None, separator=' ', prefix="",
- style=repr, formatter=None):
- """
- 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]'
-
- """
-
- if a.shape == ():
- x = a.item()
- try:
- lst = a._format(x)
- msg = "The `_format` attribute is deprecated in Numpy " \
- "2.0 and will be removed in 2.1. Use the " \
- "`formatter` kw instead."
- import warnings
- warnings.warn(msg, DeprecationWarning)
- except AttributeError:
- if isinstance(x, tuple):
- x = _convert_arrays(x)
- lst = style(x)
- elif reduce(product, a.shape) == 0:
- # treat as a null array if any of shape elements == 0
- lst = "[]"
- else:
- lst = _array2string(a, max_line_width, precision, suppress_small,
- separator, prefix, formatter=formatter)
- return lst
-
-def _extendLine(s, line, word, max_line_len, next_line_prefix):
- if len(line.rstrip()) + len(word.rstrip()) >= max_line_len:
- s += line.rstrip() + "\n"
- line = next_line_prefix
- line += word
- return s, line
-
-
-def _formatArray(a, format_function, rank, max_line_len,
- next_line_prefix, separator, edge_items, summary_insert):
- """formatArray is designed for two modes of operation:
-
- 1. Full output
-
- 2. Summarized output
-
- """
- if rank == 0:
- obj = a.item()
- if isinstance(obj, tuple):
- obj = _convert_arrays(obj)
- return str(obj)
-
- if summary_insert and 2*edge_items < len(a):
- leading_items, trailing_items, summary_insert1 = \
- edge_items, edge_items, summary_insert
- else:
- leading_items, trailing_items, summary_insert1 = 0, len(a), ""
-
- if rank == 1:
- s = ""
- line = next_line_prefix
- for i in xrange(leading_items):
- word = format_function(a[i]) + separator
- s, line = _extendLine(s, line, word, max_line_len, next_line_prefix)
-
- if summary_insert1:
- s, line = _extendLine(s, line, summary_insert1, max_line_len, next_line_prefix)
-
- for i in xrange(trailing_items, 1, -1):
- word = format_function(a[-i]) + separator
- s, line = _extendLine(s, line, word, max_line_len, next_line_prefix)
-
- word = format_function(a[-1])
- s, line = _extendLine(s, line, word, max_line_len, next_line_prefix)
- s += line + "]\n"
- s = '[' + s[len(next_line_prefix):]
- else:
- s = '['
- sep = separator.rstrip()
- for i in xrange(leading_items):
- if i > 0:
- s += next_line_prefix
- s += _formatArray(a[i], format_function, rank-1, max_line_len,
- " " + next_line_prefix, separator, edge_items,
- summary_insert)
- s = s.rstrip() + sep.rstrip() + '\n'*max(rank-1,1)
-
- if summary_insert1:
- s += next_line_prefix + summary_insert1 + "\n"
-
- for i in xrange(trailing_items, 1, -1):
- if leading_items or i != trailing_items:
- s += next_line_prefix
- s += _formatArray(a[-i], format_function, rank-1, max_line_len,
- " " + next_line_prefix, separator, edge_items,
- summary_insert)
- s = s.rstrip() + sep.rstrip() + '\n'*max(rank-1,1)
- if leading_items or trailing_items > 1:
- s += next_line_prefix
- s += _formatArray(a[-1], format_function, rank-1, max_line_len,
- " " + next_line_prefix, separator, edge_items,
- summary_insert).rstrip()+']\n'
- return s
-
-class FloatFormat(object):
- def __init__(self, data, precision, suppress_small, sign=False):
- self.precision = precision
- self.suppress_small = suppress_small
- self.sign = sign
- self.exp_format = False
- self.large_exponent = False
- self.max_str_len = 0
- try:
- self.fillFormat(data)
- except (TypeError, NotImplementedError):
- # if reduce(data) fails, this instance will not be called, just
- # instantiated in formatdict.
- pass
-
- def fillFormat(self, data):
- import numeric as _nc
- errstate = _nc.seterr(all='ignore')
- try:
- special = isnan(data) | isinf(data)
- valid = not_equal(data, 0) & ~special
- non_zero = absolute(data.compress(valid))
- if len(non_zero) == 0:
- max_val = 0.
- min_val = 0.
- else:
- max_val = maximum.reduce(non_zero)
- min_val = minimum.reduce(non_zero)
- if max_val >= 1.e8:
- self.exp_format = True
- if not self.suppress_small and (min_val < 0.0001
- or max_val/min_val > 1000.):
- self.exp_format = True
- finally:
- _nc.seterr(**errstate)
-
- if self.exp_format:
- self.large_exponent = 0 < min_val < 1e-99 or max_val >= 1e100
- self.max_str_len = 8 + self.precision
- if self.large_exponent:
- self.max_str_len += 1
- if self.sign:
- format = '%+'
- else:
- format = '%'
- format = format + '%d.%de' % (self.max_str_len, self.precision)
- else:
- format = '%%.%df' % (self.precision,)
- if len(non_zero):
- precision = max([_digits(x, self.precision, format)
- for x in non_zero])
- else:
- precision = 0
- precision = min(self.precision, precision)
- self.max_str_len = len(str(int(max_val))) + precision + 2
- if _nc.any(special):
- self.max_str_len = max(self.max_str_len,
- len(_nan_str),
- len(_inf_str)+1)
- if self.sign:
- format = '%#+'
- else:
- format = '%#'
- format = format + '%d.%df' % (self.max_str_len, precision)
-
- self.special_fmt = '%%%ds' % (self.max_str_len,)
- self.format = format
-
- def __call__(self, x, strip_zeros=True):
- import numeric as _nc
- err = _nc.seterr(invalid='ignore')
- try:
- if isnan(x):
- if self.sign:
- return self.special_fmt % ('+' + _nan_str,)
- else:
- return self.special_fmt % (_nan_str,)
- elif isinf(x):
- if x > 0:
- if self.sign:
- return self.special_fmt % ('+' + _inf_str,)
- else:
- return self.special_fmt % (_inf_str,)
- else:
- return self.special_fmt % ('-' + _inf_str,)
- finally:
- _nc.seterr(**err)
-
- s = self.format % x
- if self.large_exponent:
- # 3-digit exponent
- expsign = s[-3]
- if expsign == '+' or expsign == '-':
- s = s[1:-2] + '0' + s[-2:]
- elif self.exp_format:
- # 2-digit exponent
- if s[-3] == '0':
- s = ' ' + s[:-3] + s[-2:]
- elif strip_zeros:
- z = s.rstrip('0')
- s = z + ' '*(len(s)-len(z))
- return s
-
-
-def _digits(x, precision, format):
- s = format % x
- z = s.rstrip('0')
- return precision - len(s) + len(z)
-
-
-_MAXINT = sys.maxint
-_MININT = -sys.maxint-1
-class IntegerFormat(object):
- def __init__(self, data):
- try:
- max_str_len = max(len(str(maximum.reduce(data))),
- len(str(minimum.reduce(data))))
- self.format = '%' + str(max_str_len) + 'd'
- except (TypeError, NotImplementedError):
- # if reduce(data) fails, this instance will not be called, just
- # instantiated in formatdict.
- pass
- except ValueError:
- # this occurs when everything is NA
- pass
-
- def __call__(self, x):
- if _MININT < x < _MAXINT:
- return self.format % x
- else:
- return "%s" % x
-
-class LongFloatFormat(object):
- # XXX Have to add something to determine the width to use a la FloatFormat
- # Right now, things won't line up properly
- def __init__(self, precision, sign=False):
- self.precision = precision
- self.sign = sign
-
- def __call__(self, x):
- if isnan(x):
- if self.sign:
- return '+' + _nan_str
- else:
- return ' ' + _nan_str
- elif isinf(x):
- if x > 0:
- if self.sign:
- return '+' + _inf_str
- else:
- return ' ' + _inf_str
- else:
- return '-' + _inf_str
- elif x >= 0:
- if self.sign:
- return '+' + format_longfloat(x, self.precision)
- else:
- return ' ' + format_longfloat(x, self.precision)
- else:
- return format_longfloat(x, self.precision)
-
-
-class LongComplexFormat(object):
- def __init__(self, precision):
- self.real_format = LongFloatFormat(precision)
- self.imag_format = LongFloatFormat(precision, sign=True)
-
- def __call__(self, x):
- r = self.real_format(x.real)
- i = self.imag_format(x.imag)
- return r + i + 'j'
-
-
-class ComplexFormat(object):
- def __init__(self, x, precision, suppress_small):
- self.real_format = FloatFormat(x.real, precision, suppress_small)
- self.imag_format = FloatFormat(x.imag, precision, suppress_small,
- sign=True)
-
- def __call__(self, x):
- r = self.real_format(x.real, strip_zeros=False)
- i = self.imag_format(x.imag, strip_zeros=False)
- if not self.imag_format.exp_format:
- z = i.rstrip('0')
- i = z + 'j' + ' '*(len(i)-len(z))
- else:
- i = i + 'j'
- return r + i
-
-class DatetimeFormat(object):
- def __init__(self, x, unit=None,
- timezone=None, casting='same_kind'):
- # Get the unit from the dtype
- if unit is None:
- if x.dtype.kind == 'M':
- unit = datetime_data(x.dtype)[0]
- else:
- unit = 's'
-
- # If timezone is default, make it 'local' or 'UTC' based on the unit
- if timezone is None:
- # Date units -> UTC, time units -> local
- if unit in ('Y', 'M', 'W', 'D'):
- self.timezone = 'UTC'
- else:
- self.timezone = 'local'
- else:
- self.timezone = timezone
- self.unit = unit
- self.casting = casting
-
- def __call__(self, x):
- return "'%s'" % datetime_as_string(x,
- unit=self.unit,
- timezone=self.timezone,
- casting=self.casting)
-
-class TimedeltaFormat(object):
- def __init__(self, data):
- if data.dtype.kind == 'm':
- v = data.view('i8')
- max_str_len = max(len(str(maximum.reduce(v))),
- len(str(minimum.reduce(v))))
- self.format = '%' + str(max_str_len) + 'd'
-
- def __call__(self, x):
- return self.format % x.astype('i8')
-
diff --git a/lib_pypy/numpypy/core/fromnumeric.py b/lib_pypy/numpypy/core/fromnumeric.py
deleted file mode 100644
--- a/lib_pypy/numpypy/core/fromnumeric.py
+++ /dev/null
@@ -1,2924 +0,0 @@
-######################################################################
-# This is a copy of numpy/core/fromnumeric.py modified for numpypy
-######################################################################
-"""Module containing non-deprecated functions borrowed from Numeric.
-
-"""
-from __future__ import division, absolute_import, print_function
-
-import types
-
-from . import multiarray as mu
-from . import umath as um
-from . import numerictypes as nt
-from .numeric import asarray, array, asanyarray, concatenate
-from . import _methods
-
-
-# functions that are methods
-__all__ = [
- 'alen', 'all', 'alltrue', 'amax', 'amin', 'any', 'argmax',
- 'argmin', 'argpartition', 'argsort', 'around', 'choose', 'clip',
- 'compress', 'cumprod', 'cumproduct', 'cumsum', 'diagonal', 'mean',
- 'ndim', 'nonzero', 'partition', 'prod', 'product', 'ptp', 'put',
- 'rank', 'ravel', 'repeat', 'reshape', 'resize', 'round_',
- 'searchsorted', 'shape', 'size', 'sometrue', 'sort', 'squeeze',
- 'std', 'sum', 'swapaxes', 'take', 'trace', 'transpose', 'var',
- ]
-
-
-try:
- _gentype = types.GeneratorType
-except AttributeError:
- _gentype = type(None)
-
-# save away Python sum
-_sum_ = sum
-
-# functions that are now methods
-def _wrapit(obj, method, *args, **kwds):
- try:
- wrap = obj.__array_wrap__
- except AttributeError:
- wrap = None
- result = getattr(asarray(obj), method)(*args, **kwds)
- if wrap:
- if not isinstance(result, mu.ndarray):
- result = asarray(result)
- result = wrap(result)
- return result
-
-
-def take(a, indices, axis=None, out=None, mode='raise'):
- """
- 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
- --------
- 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]])
- """
- try:
- take = a.take
- except AttributeError:
- return _wrapit(a, 'take', indices, axis, out, mode)
- return take(indices, axis, out, mode)
-
-
-# not deprecated --- copy if necessary, view otherwise
-def reshape(a, newshape, order='C'):
- """
- 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]])
- """
- assert order == 'C'
- try:
- reshape = a.reshape
- except AttributeError:
- return _wrapit(a, 'reshape', newshape)
- return reshape(newshape)
-
-
-def choose(a, choices, out=None, mode='raise'):
- """
- 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:
- choose = a.choose
- except AttributeError:
- return _wrapit(a, 'choose', choices, out=out, mode=mode)
- return choose(choices, out=out, mode=mode)
-
-
-def repeat(a, repeats, axis=None):
- """
- 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]])
-
- """
- try:
- repeat = a.repeat
- except AttributeError:
- return _wrapit(a, 'repeat', repeats, axis)
- return repeat(repeats, axis)
-
-
-def put(a, ind, v, mode='raise'):
- """
- 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])
-
- """
- return a.put(ind, v, mode)
-
-
-def swapaxes(a, axis1, axis2):
- """
- 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:
- swapaxes = a.swapaxes
- except AttributeError:
- return _wrapit(a, 'swapaxes', axis1, axis2)
- return swapaxes(axis1, axis2)
-
-
-def transpose(a, axes=None):
- """
- 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)
-
- """
- if axes is not None:
- raise NotImplementedError('No "axes" arg yet.')
- try:
- transpose = a.transpose
- except AttributeError:
- return _wrapit(a, 'transpose')
- return transpose()
-
-
-def partition(a, kth, axis=-1, kind='introselect', order=None):
- """
- 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
- three 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])
-
- """
- if axis is None:
- a = asanyarray(a).flatten()
- axis = 0
- else:
- a = asanyarray(a).copy()
- a.partition(kth, axis=axis, kind=kind, order=order)
- return a
-
-
-def argpartition(a, kth, axis=-1, kind='introselect', order=None):
- """
- 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])
-
- """
- return a.argpartition(kth, axis, kind=kind, order=order)
-
-
-def sort(a, axis=-1, kind='quicksort', order=None):
- """
- 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')])
-
- """
- if axis is None:
- a = asanyarray(a).flatten()
- axis = 0
- else:
- a = asanyarray(a).copy()
- a.sort(axis, kind, order)
- return a
-
-
-def argsort(a, axis=-1, kind='quicksort', order=None):
- """
- 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:
- argsort = a.argsort
- except AttributeError:
- return _wrapit(a, 'argsort', axis, kind, order)
- return argsort(axis, kind, order)
-
-
-def argmax(a, axis=None):
- """
- 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
-
- """
- assert axis is None
- try:
- argmax = a.argmax
- except AttributeError:
- return _wrapit(a, 'argmax')
- return argmax()
-
-
-def argmin(a, axis=None):
- """
- Return the indices of the minimum values along an axis.
-
- See Also
- --------
- argmax : Similar function. Please refer to `numpy.argmax` for detailed
- documentation.
-
- """
- assert axis is None
- try:
- argmin = a.argmin
- except AttributeError:
- return _wrapit(a, 'argmin')
- return argmin()
-
-
-def searchsorted(a, v, side='left', sorter=None):
- """
- 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])
-
- """
- try:
- searchsorted = a.searchsorted
- except AttributeError:
- return _wrapit(a, 'searchsorted', v, side, sorter)
- return searchsorted(v, side, sorter)
-
-
-def resize(a, new_shape):
- """
- 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]])
-
- """
- if isinstance(new_shape, (int, nt.integer)):
- new_shape = (new_shape,)
- a = ravel(a)
- Na = len(a)
- if not Na: return mu.zeros(new_shape, a.dtype.char)
- total_size = um.multiply.reduce(new_shape)
- n_copies = int(total_size / Na)
- extra = total_size % Na
-
- if total_size == 0:
More information about the pypy-commit
mailing list