summaryrefslogtreecommitdiff
path: root/numpy/lib/index_tricks.py
diff options
context:
space:
mode:
Diffstat (limited to 'numpy/lib/index_tricks.py')
-rw-r--r--numpy/lib/index_tricks.py61
1 files changed, 41 insertions, 20 deletions
diff --git a/numpy/lib/index_tricks.py b/numpy/lib/index_tricks.py
index cba713ede..72d8e9de4 100644
--- a/numpy/lib/index_tricks.py
+++ b/numpy/lib/index_tricks.py
@@ -1,11 +1,12 @@
import functools
import sys
import math
+import warnings
import numpy.core.numeric as _nx
from numpy.core.numeric import (
asarray, ScalarType, array, alltrue, cumprod, arange, ndim
- )
+)
from numpy.core.numerictypes import find_common_type, issubdtype
import numpy.matrixlib as matrixlib
@@ -24,7 +25,7 @@ __all__ = [
'ravel_multi_index', 'unravel_index', 'mgrid', 'ogrid', 'r_', 'c_',
's_', 'index_exp', 'ix_', 'ndenumerate', 'ndindex', 'fill_diagonal',
'diag_indices', 'diag_indices_from'
- ]
+]
def _ix__dispatcher(*args):
@@ -105,6 +106,7 @@ def ix_(*args):
out.append(new)
return tuple(out)
+
class nd_grid:
"""
Construct a multi-dimensional "meshgrid".
@@ -154,19 +156,19 @@ class nd_grid:
start = 0
if step is None:
step = 1
- if isinstance(step, complex):
+ if isinstance(step, (_nx.complexfloating, complex)):
size.append(int(abs(step)))
typ = float
else:
size.append(
int(math.ceil((key[k].stop - start)/(step*1.0))))
- if (isinstance(step, float) or
- isinstance(start, float) or
- isinstance(key[k].stop, float)):
+ if (isinstance(step, (_nx.floating, float)) or
+ isinstance(start, (_nx.floating, float)) or
+ isinstance(key[k].stop, (_nx.floating, float))):
typ = float
if self.sparse:
nn = [_nx.arange(_x, dtype=_t)
- for _x, _t in zip(size, (typ,)*len(size))]
+ for _x, _t in zip(size, (typ,)*len(size))]
else:
nn = _nx.indices(size, typ)
for k in range(len(size)):
@@ -176,7 +178,7 @@ class nd_grid:
start = 0
if step is None:
step = 1
- if isinstance(step, complex):
+ if isinstance(step, (_nx.complexfloating, complex)):
step = int(abs(step))
if step != 1:
step = (key[k].stop - start)/float(step-1)
@@ -194,7 +196,7 @@ class nd_grid:
start = key.start
if start is None:
start = 0
- if isinstance(step, complex):
+ if isinstance(step, (_nx.complexfloating, complex)):
step = abs(step)
length = int(step)
if step != 1:
@@ -247,11 +249,14 @@ class MGridClass(nd_grid):
array([-1. , -0.5, 0. , 0.5, 1. ])
"""
+
def __init__(self):
- super(MGridClass, self).__init__(sparse=False)
+ super().__init__(sparse=False)
+
mgrid = MGridClass()
+
class OGridClass(nd_grid):
"""
`nd_grid` instance which returns an open multi-dimensional "meshgrid".
@@ -291,8 +296,10 @@ class OGridClass(nd_grid):
[4]]), array([[0, 1, 2, 3, 4]])]
"""
+
def __init__(self):
- super(OGridClass, self).__init__(sparse=True)
+ super().__init__(sparse=True)
+
ogrid = OGridClass()
@@ -344,7 +351,7 @@ class AxisConcatenator:
start = 0
if step is None:
step = 1
- if isinstance(step, complex):
+ if isinstance(step, (_nx.complexfloating, complex)):
size = int(abs(step))
newobj = linspace(start, stop, num=size)
else:
@@ -356,7 +363,7 @@ class AxisConcatenator:
elif isinstance(item, str):
if k != 0:
raise ValueError("special directives must be the "
- "first entry.")
+ "first entry.")
if item in ('r', 'c'):
matrix = True
col = (item == 'c')
@@ -375,8 +382,8 @@ class AxisConcatenator:
try:
axis = int(item)
continue
- except (ValueError, TypeError):
- raise ValueError("unknown special directive")
+ except (ValueError, TypeError) as e:
+ raise ValueError("unknown special directive") from e
elif type(item) in ScalarType:
newobj = array(item, ndmin=ndmin)
scalars.append(len(objs))
@@ -419,6 +426,7 @@ class AxisConcatenator:
# etc. because otherwise we couldn't get the doc string to come out right
# in help(r_)
+
class RClass(AxisConcatenator):
"""
Translates slice objects to concatenation along the first axis.
@@ -517,8 +525,10 @@ class RClass(AxisConcatenator):
def __init__(self):
AxisConcatenator.__init__(self, 0)
+
r_ = RClass()
+
class CClass(AxisConcatenator):
"""
Translates slice objects to concatenation along the second axis.
@@ -527,7 +537,7 @@ class CClass(AxisConcatenator):
useful because of its common occurrence. In particular, arrays will be
stacked along their last axis after being upgraded to at least 2-D with
1's post-pended to the shape (column vectors made out of 1-D arrays).
-
+
See Also
--------
column_stack : Stack 1-D arrays as columns into a 2-D array.
@@ -659,7 +669,15 @@ class ndindex:
Increment the multi-dimensional index by one.
This method is for backward compatibility only: do not use.
+
+ .. deprecated:: 1.20.0
+ This method has been advised against since numpy 1.8.0, but only
+ started emitting DeprecationWarning as of this version.
"""
+ # NumPy 1.20.0, 2020-09-08
+ warnings.warn(
+ "`ndindex.ndincr()` is deprecated, use `next(ndindex)` instead",
+ DeprecationWarning, stacklevel=2)
next(self)
def __next__(self):
@@ -742,6 +760,7 @@ class IndexExpression:
else:
return item
+
index_exp = IndexExpression(maketuple=True)
s_ = IndexExpression(maketuple=False)
@@ -769,9 +788,11 @@ def fill_diagonal(a, val, wrap=False):
a : array, at least 2-D.
Array whose diagonal is to be filled, it gets modified in-place.
- val : scalar
- Value to be written on the diagonal, its type must be compatible with
- that of the array a.
+ val : scalar or array_like
+ Value(s) to write on the diagonal. If `val` is scalar, the value is
+ written along the diagonal. If array-like, the flattened `val` is
+ written along the diagonal, repeating if necessary to fill all
+ diagonal entries.
wrap : bool
For tall matrices in NumPy version up to 1.6.2, the
@@ -874,7 +895,7 @@ def fill_diagonal(a, val, wrap=False):
# Explicit, fast formula for the common case. For 2-d arrays, we
# accept rectangular ones.
step = a.shape[1] + 1
- #This is needed to don't have tall matrix have the diagonal wrap.
+ # This is needed to don't have tall matrix have the diagonal wrap.
if not wrap:
end = a.shape[1] * a.shape[1]
else: