6
'ndenumerate','ndindex']
6
'ndenumerate','ndindex',
7
'fill_diagonal','diag_indices','diag_indices_from']
9
10
import numpy.core.numeric as _nx
10
from numpy.core.numeric import asarray, ScalarType, array
11
from numpy.core.numeric import ( asarray, ScalarType, array, alltrue, cumprod,
11
13
from numpy.core.numerictypes import find_common_type
14
16
import function_base
15
import numpy.core.defmatrix as matrix
17
import numpy.matrixlib as matrix
18
from function_base import diff
16
19
makemat = matrix.matrix
18
21
# contributed by Stefan van der Walt
19
22
def unravel_index(x,dims):
21
Convert a flat index into an index tuple for an array of given shape.
24
Convert a flat index to an index tuple for an array of given shape.
31
Input shape, the shape of an array into which indexing is
37
Tuple of the same shape as `dims`, containing the unraveled index.
72
81
return tuple(x/dim_prod % dims)
75
""" Construct an open mesh from multiple sequences.
77
This function takes n 1-d sequences and returns n outputs with n
78
dimensions each such that the shape is 1 in all but one dimension and
79
the dimension with the non-unit shape value cycles through all n
82
Using ix_() one can quickly construct index arrays that will index
85
a[ix_([1,3,7],[2,5,8])] returns the array
85
Construct an open mesh from multiple sequences.
87
This function takes N 1-D sequences and returns N outputs with N
88
dimensions each, such that the shape is 1 in all but one dimension
89
and the dimension with the non-unit shape value cycles through all
92
Using `ix_` one can quickly construct index arrays that will index
93
the cross product. ``a[np.ix_([1,3],[2,5])]`` returns the array
94
``[[a[1,2] a[1,5]], [a[3,2] a[3,5]]]``.
102
out : tuple of ndarrays
103
N arrays with N dimensions each, with N the number of input
104
sequences. Together these arrays form an open mesh.
108
ogrid, mgrid, meshgrid
112
>>> a = np.arange(10).reshape(2, 5)
114
array([[0, 1, 2, 3, 4],
116
>>> ixgrid = np.ix_([0,1], [2,4])
119
[1]]), array([[2, 4]]))
120
>>> ixgrid[0].shape, ixgrid[1].shape
340
397
class RClass(AxisConcatenator):
341
"""Translates slice objects to concatenation along the first axis.
399
Translates slice objects to concatenation along the first axis.
401
This is a simple way to build up arrays quickly. There are two use cases.
403
1. If the index expression contains comma separated arrays, then stack
404
them along their first axis.
405
2. If the index expression contains slice notation or scalars then create
406
a 1-D array with a range indicated by the slice notation.
408
If slice notation is used, the syntax ``start:stop:step`` is equivalent
409
to ``np.arange(start, stop, step)`` inside of the brackets. However, if
410
``step`` is an imaginary number (i.e. 100j) then its integer portion is
411
interpreted as a number-of-points desired and the start and stop are
412
inclusive. In other words ``start:stop:stepj`` is interpreted as
413
``np.linspace(start, stop, step, endpoint=1)`` inside of the brackets.
414
After expansion of slice notation, all comma separated sequences are
415
concatenated together.
417
Optional character strings placed as the first element of the index
418
expression can be used to change the output. The strings 'r' or 'c' result
419
in matrix output. If the result is 1-D and 'r' is specified a 1 x N (row)
420
matrix is produced. If the result is 1-D and 'c' is specified, then a N x 1
421
(column) matrix is produced. If the result is 2-D then both provide the
424
A string integer specifies which axis to stack multiple comma separated
425
arrays along. A string of two comma-separated integers allows indication
426
of the minimum number of dimensions to force each entry into as the
427
second integer (the axis to concatenate along is still the first integer).
429
A string with three comma-separated integers allows specification of the
430
axis to concatenate along, the minimum number of dimensions to force the
431
entries to, and which axis should contain the start of the arrays which
432
are less than the specified number of dimensions. In other words the third
433
integer allows you to specify where the 1's should be placed in the shape
434
of the arrays that have their shapes upgraded. By default, they are placed
435
in the front of the shape tuple. The third argument allows you to specify
436
where the start of the array should be instead. Thus, a third argument of
437
'0' would place the 1's at the end of the array shape. Negative integers
438
specify where in the new shape tuple the last dimension of upgraded arrays
439
should be placed, so the default is '-1'.
443
Not a function, so takes no parameters
448
A concatenated ndarray or matrix.
452
concatenate : Join a sequence of arrays together.
453
c_ : Translates slice objects to concatenation along the second axis.
344
457
>>> np.r_[np.array([1,2,3]), 0, 0, np.array([4,5,6])]
345
458
array([1, 2, 3, 0, 0, 4, 5, 6])
459
>>> np.r_[-1:1:6j, [0]*3, 5, 6]
460
array([-1. , -0.6, -0.2, 0.2, 0.6, 1. , 0. , 0. , 0. , 5. , 6. ])
462
String integers specify the axis to concatenate along or the minimum
463
number of dimensions to force entries into.
465
>>> np.r_['-1', a, a] # concatenate along last axis
466
array([[0, 1, 2, 0, 1, 2],
468
>>> np.r_['0,2', [1,2,3], [4,5,6]] # concatenate along first axis, dim>=2
472
>>> np.r_['0,2,0', [1,2,3], [4,5,6]]
479
>>> np.r_['1,2,0', [1,2,3], [4,5,6]]
484
Using 'r' or 'c' as a first string argument creates a matrix.
486
>>> np.r_['r',[1,2,3], [4,5,6]]
487
matrix([[1, 2, 3, 4, 5, 6]])
348
490
def __init__(self):
353
495
class CClass(AxisConcatenator):
354
"""Translates slice objects to concatenation along the second axis.
497
Translates slice objects to concatenation along the second axis.
499
This is short-hand for ``np.r_['-1,2,0', index expression]``, which is
500
useful because of its common occurrence. In particular, arrays will be
501
stacked along their last axis after being upgraded to at least 2-D with
502
1's post-pended to the shape (column vectors made out of 1-D arrays).
504
For detailed documentation, see `r_`.
357
508
>>> np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])]
358
array([1, 2, 3, 0, 0, 4, 5, 6])
509
array([[1, 2, 3, 0, 0, 4, 5, 6]])
360
512
def __init__(self):
361
513
AxisConcatenator.__init__(self, -1, ndmin=2, trans1d=0)
474
661
A nicer way to build up index tuples for arrays.
664
Use one of the two predefined instances `index_exp` or `s_`
665
rather than directly using `IndexExpression`.
476
667
For any index combination, including slicing and axis insertion,
477
'a[indices]' is the same as 'a[index_exp[indices]]' for any
478
array 'a'. However, 'index_exp[indices]' can be used anywhere
668
``a[indices]`` is the same as ``a[np.index_exp[indices]]`` for any
669
array `a`. However, ``np.index_exp[indices]`` can be used anywhere
479
670
in Python code and returns a tuple of slice objects that can be
480
671
used in the construction of complex index expressions.
676
If True, always returns a tuple.
680
index_exp : Predefined instance that always returns a tuple:
681
`index_exp = IndexExpression(maketuple=True)`.
682
s_ : Predefined instance without tuple conversion:
683
`s_ = IndexExpression(maketuple=False)`.
687
You can do all this with `slice()` plus a few special objects,
688
but there's a lot to remember and this version is simpler because
689
it uses the standard array indexing syntax.
695
>>> np.index_exp[2::2]
698
>>> np.array([0, 1, 2, 3, 4])[np.s_[2::2]]
482
702
maxint = sys.maxint
483
703
def __init__(self, maketuple):
501
721
s_ = IndexExpression(maketuple=False)
503
723
# End contribution from Konrad.
726
# The following functions complement those in twodim_base, but are
727
# applicable to N-dimensions.
729
def fill_diagonal(a, val):
731
Fill the main diagonal of the given array of any dimensionality.
733
For an array `a` with ``a.ndim > 2``, the diagonal is the list of
734
locations with indices ``a[i, i, ..., i]`` all identical. This function
735
modifies the input array in-place, it does not return a value.
739
a : array, at least 2-D.
740
Array whose diagonal is to be filled, it gets modified in-place.
743
Value to be written on the diagonal, its type must be compatible with
748
diag_indices, diag_indices_from
752
.. versionadded:: 1.4.0
754
This functionality can be obtained via `diag_indices`, but internally
755
this version uses a much faster implementation that never constructs the
756
indices and uses simple slicing.
760
>>> a = zeros((3, 3), int)
761
>>> fill_diagonal(a, 5)
767
The same function can operate on a 4-D array:
769
>>> a = zeros((3, 3, 3, 3), int)
770
>>> fill_diagonal(a, 4)
772
We only show a few blocks for clarity:
789
raise ValueError("array must be at least 2-d")
791
# Explicit, fast formula for the common case. For 2-d arrays, we
792
# accept rectangular ones.
793
step = a.shape[1] + 1
795
# For more than d=2, the strided formula is only valid for arrays with
796
# all dimensions equal, so we check first.
797
if not alltrue(diff(a.shape)==0):
798
raise ValueError("All dimensions of input must be of equal length")
799
step = 1 + (cumprod(a.shape[:-1])).sum()
801
# Write the value out into the diagonal.
805
def diag_indices(n, ndim=2):
807
Return the indices to access the main diagonal of an array.
809
This returns a tuple of indices that can be used to access the main
810
diagonal of an array `a` with ``a.ndim >= 2`` dimensions and shape
811
(n, n, ..., n). For ``a.ndim = 2`` this is the usual diagonal, for
812
``a.ndim > 2`` this is the set of indices to access ``a[i, i, ..., i]``
813
for ``i = [0..n-1]``.
818
The size, along each dimension, of the arrays for which the returned
822
The number of dimensions.
830
.. versionadded:: 1.4.0
834
Create a set of indices to access the diagonal of a (4, 4) array:
836
>>> di = np.diag_indices(4)
838
(array([0, 1, 2, 3]), array([0, 1, 2, 3]))
839
>>> a = np.arange(16).reshape(4, 4)
841
array([[ 0, 1, 2, 3],
847
array([[100, 1, 2, 3],
852
Now, we create indices to manipulate a 3-D array:
854
>>> d3 = np.diag_indices(2, 3)
856
(array([0, 1]), array([0, 1]), array([0, 1]))
858
And use it to set the diagonal of an array of zeros to 1:
860
>>> a = np.zeros((2, 2, 2), dtype=np.int)
873
def diag_indices_from(arr):
875
Return the indices to access the main diagonal of an n-dimensional array.
877
See `diag_indices` for full details.
881
arr : array, at least 2-D
889
.. versionadded:: 1.4.0
893
if not arr.ndim >= 2:
894
raise ValueError("input array must be at least 2-d")
895
# For more than d=2, the strided formula is only valid for arrays with
896
# all dimensions equal, so we check first.
897
if not alltrue(diff(arr.shape) == 0):
898
raise ValueError("All dimensions of input must be of equal length")
900
return diag_indices(arr.shape[0], arr.ndim)