/
generate.py
588 lines (455 loc) · 17.7 KB
/
generate.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
# class s_(object):
import functools
import numbers
import operator
import numpy
import cupy
from cupy._creation import from_data
from cupy._manipulation import join
class AxisConcatenator(object):
"""Translates slice objects to concatenation along an axis.
For detailed documentation on usage, see :func:`cupy.r_`.
This implementation is partially borrowed from NumPy's one.
"""
def _output_obj(self, obj, ndim, ndmin, trans1d):
k2 = ndmin - ndim
if trans1d < 0:
trans1d += k2 + 1
defaxes = list(range(ndmin))
k1 = trans1d
axes = defaxes[:k1] + defaxes[k2:] + \
defaxes[k1:k2]
return obj.transpose(axes)
def __init__(self, axis=0, matrix=False, ndmin=1, trans1d=-1):
self.axis = axis
self.trans1d = trans1d
self.matrix = matrix
self.ndmin = ndmin
def __getitem__(self, key):
trans1d = self.trans1d
ndmin = self.ndmin
objs = []
arrays = []
scalars = []
if isinstance(key, str):
raise NotImplementedError
if not isinstance(key, tuple):
key = (key,)
for i, k in enumerate(key):
if isinstance(k, slice):
raise NotImplementedError
elif isinstance(k, str):
if i != 0:
raise ValueError(
'special directives must be the first entry.')
raise NotImplementedError
elif type(k) in numpy.ScalarType:
newobj = from_data.array(k, ndmin=ndmin)
scalars.append(i)
else:
newobj = from_data.array(k, copy=False, ndmin=ndmin)
if ndmin > 1:
ndim = from_data.array(k, copy=False).ndim
if trans1d != -1 and ndim < ndmin:
newobj = self._output_obj(newobj, ndim, ndmin, trans1d)
arrays.append(newobj)
objs.append(newobj)
final_dtype = numpy.result_type(*arrays, *[key[k] for k in scalars])
if final_dtype is not None:
for k in scalars:
objs[k] = objs[k].astype(final_dtype)
return join.concatenate(tuple(objs), axis=self.axis)
def __len__(self):
return 0
class CClass(AxisConcatenator):
def __init__(self):
super(CClass, self).__init__(-1, ndmin=2, trans1d=0)
c_ = CClass()
"""Translates slice objects to concatenation along the second axis.
This is a CuPy object that corresponds to :obj:`cupy.r_`, which is
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).
For detailed documentation, see :obj:`r_`.
This implementation is partially borrowed from NumPy's one.
Returns:
cupy.ndarray: Joined array.
.. seealso:: :obj:`numpy.c_`
Examples
--------
>>> a = cupy.array([[1, 2, 3]], dtype=np.int32)
>>> b = cupy.array([[4, 5, 6]], dtype=np.int32)
>>> cupy.c_[a, 0, 0, b]
array([[1, 2, 3, 0, 0, 4, 5, 6]], dtype=int32)
"""
class RClass(AxisConcatenator):
def __init__(self):
super(RClass, self).__init__()
r_ = RClass()
"""Translates slice objects to concatenation along the first axis.
This is a simple way to build up arrays quickly.
If the index expression contains comma separated arrays, then stack
them along their first axis.
This object can build up from normal CuPy arrays.
Therefore, the other objects (e.g. writing strings like '2,3,4',
or using imaginary numbers like [1,2,3j],
or using string integers like '-1') are not implemented yet
compared with NumPy.
This implementation is partially borrowed from NumPy's one.
Returns:
cupy.ndarray: Joined array.
.. seealso:: :obj:`numpy.r_`
Examples
--------
>>> a = cupy.array([1, 2, 3], dtype=np.int32)
>>> b = cupy.array([4, 5, 6], dtype=np.int32)
>>> cupy.r_[a, 0, 0, b]
array([1, 2, 3, 0, 0, 4, 5, 6], dtype=int32)
"""
def indices(dimensions, dtype=int):
"""Returns an array representing the indices of a grid.
Computes an array where the subarrays contain index values 0,1,...
varying only along the corresponding axis.
Args:
dimensions: The shape of the grid.
dtype: Data type specifier. It is int by default.
Returns:
ndarray:
The array of grid indices,
``grid.shape = (len(dimensions),) + tuple(dimensions)``.
Examples
--------
>>> grid = cupy.indices((2, 3))
>>> grid.shape
(2, 2, 3)
>>> grid[0] # row indices
array([[0, 0, 0],
[1, 1, 1]])
>>> grid[1] # column indices
array([[0, 1, 2],
[0, 1, 2]])
.. seealso:: :func:`numpy.indices`
"""
dimensions = tuple(dimensions)
N = len(dimensions)
shape = (1,) * N
res = cupy.empty((N,) + dimensions, dtype=dtype)
for i, dim in enumerate(dimensions):
res[i] = cupy.arange(dim, dtype=dtype).reshape(
shape[:i] + (dim,) + shape[i + 1:]
)
return res
def ix_(*args):
"""Construct an open mesh from multiple sequences.
This function takes N 1-D sequences and returns N outputs with N
dimensions each, such that the shape is 1 in all but one dimension
and the dimension with the non-unit shape value cycles through all
N dimensions.
Using `ix_` one can quickly construct index arrays that will index
the cross product. ``a[cupy.ix_([1,3],[2,5])]`` returns the array
``[[a[1,2] a[1,5]], [a[3,2] a[3,5]]]``.
Args:
*args: 1-D sequences
Returns:
tuple of ndarrays:
N arrays with N dimensions each, with N the number of input sequences.
Together these arrays form an open mesh.
Examples
--------
>>> a = cupy.arange(10).reshape(2, 5)
>>> a
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
>>> ixgrid = cupy.ix_([0,1], [2,4])
>>> ixgrid
(array([[0],
[1]]), array([[2, 4]]))
.. warning::
This function may synchronize the device.
.. seealso:: :func:`numpy.ix_`
"""
# TODO(niboshi): Avoid nonzero which may synchronize the device.
out = []
nd = len(args)
for k, new in enumerate(args):
new = from_data.asarray(new)
if new.ndim != 1:
raise ValueError('Cross index must be 1 dimensional')
if new.size == 0:
# Explicitly type empty arrays to avoid float default
new = new.astype(numpy.intp)
if cupy.issubdtype(new.dtype, cupy.bool_):
new, = new.nonzero() # may synchronize
new = new.reshape((1,) * k + (new.size,) + (1,) * (nd - k - 1))
out.append(new)
return tuple(out)
def ravel_multi_index(multi_index, dims, mode='wrap', order='C'):
"""
Converts a tuple of index arrays into an array of flat indices, applying
boundary modes to the multi-index.
Args:
multi_index (tuple of cupy.ndarray) : A tuple of integer arrays, one
array for each dimension.
dims (tuple of ints): The shape of array into which the indices from
``multi_index`` apply.
mode ('raise', 'wrap' or 'clip'), optional: Specifies how out-of-bounds
indices are handled. Can specify either one mode or a tuple of
modes, one mode per index:
- *'raise'* -- raise an error
- *'wrap'* -- wrap around (default)
- *'clip'* -- clip to the range
In 'clip' mode, a negative index which would normally wrap will
clip to 0 instead.
order ('C' or 'F'), optional: Determines whether the multi-index should
be viewed as indexing in row-major (C-style) or column-major
(Fortran-style) order.
Returns:
raveled_indices (cupy.ndarray): An array of indices into the flattened
version of an array of dimensions ``dims``.
.. warning::
This function may synchronize the device when ``mode == 'raise'``.
Notes
-----
Note that the default `mode` (``'wrap'``) is different than in NumPy. This
is done to avoid potential device synchronization.
Examples
--------
>>> cupy.ravel_multi_index(cupy.asarray([[3,6,6],[4,5,1]]), (7,6))
array([22, 41, 37])
>>> cupy.ravel_multi_index(cupy.asarray([[3,6,6],[4,5,1]]), (7,6),
... order='F')
array([31, 41, 13])
>>> cupy.ravel_multi_index(cupy.asarray([[3,6,6],[4,5,1]]), (4,6),
... mode='clip')
array([22, 23, 19])
>>> cupy.ravel_multi_index(cupy.asarray([[3,6,6],[4,5,1]]), (4,4),
... mode=('clip', 'wrap'))
array([12, 13, 13])
>>> cupy.ravel_multi_index(cupy.asarray((3,1,4,1)), (6,7,8,9))
array(1621)
.. seealso:: :func:`numpy.ravel_multi_index`, :func:`unravel_index`
"""
ndim = len(dims)
if len(multi_index) != ndim:
raise ValueError(
"parameter multi_index must be a sequence of "
"length {}".format(ndim))
for d in dims:
if not isinstance(d, numbers.Integral):
raise TypeError(
"{} object cannot be interpreted as an integer".format(
type(d)))
if isinstance(mode, str):
mode = (mode, ) * ndim
if functools.reduce(operator.mul, dims) > cupy.iinfo(cupy.int64).max:
raise ValueError("invalid dims: array size defined by dims is larger "
"than the maximum possible size")
s = 1
ravel_strides = [1] * ndim
order = 'C' if order is None else order.upper()
if order == 'C':
for i in range(ndim - 2, -1, -1):
s = s * dims[i + 1]
ravel_strides[i] = s
elif order == 'F':
for i in range(1, ndim):
s = s * dims[i - 1]
ravel_strides[i] = s
else:
raise ValueError('order not understood')
multi_index = cupy.broadcast_arrays(*multi_index)
raveled_indices = cupy.zeros(multi_index[0].shape, dtype=cupy.int64)
for d, stride, idx, _mode in zip(dims, ravel_strides, multi_index, mode):
if not isinstance(idx, cupy.ndarray):
raise TypeError("elements of multi_index must be cupy arrays")
if not cupy.can_cast(idx, cupy.int64, 'same_kind'):
raise TypeError(
'multi_index entries could not be cast from dtype(\'{}\') to '
'dtype(\'{}\') according to the rule \'same_kind\''.format(
idx.dtype, cupy.int64().dtype))
idx = idx.astype(cupy.int64, copy=False)
if _mode == "raise":
if cupy.any(cupy.logical_or(idx >= d, idx < 0)):
raise ValueError("invalid entry in coordinates array")
elif _mode == "clip":
idx = cupy.clip(idx, 0, d - 1)
elif _mode == 'wrap':
idx = idx % d
else:
raise ValueError('Unrecognized mode: {}'.format(_mode))
raveled_indices += stride * idx
return raveled_indices
def unravel_index(indices, dims, order='C'):
"""Converts array of flat indices into a tuple of coordinate arrays.
Args:
indices (cupy.ndarray): An integer array whose elements are indices
into the flattened version of an array of dimensions :obj:`dims`.
dims (tuple of ints): The shape of the array to use for unraveling
indices.
order ('C' or 'F'): Determines whether the indices should be viewed as
indexing in row-major (C-style) or column-major (Fortran-style)
order.
Returns:
tuple of ndarrays:
Each array in the tuple has the same shape as the indices array.
Examples
--------
>>> cupy.unravel_index(cupy.array([22, 41, 37]), (7, 6))
(array([3, 6, 6]), array([4, 5, 1]))
>>> cupy.unravel_index(cupy.array([31, 41, 13]), (7, 6), order='F')
(array([3, 6, 6]), array([4, 5, 1]))
.. warning::
This function may synchronize the device.
.. seealso:: :func:`numpy.unravel_index`, :func:`ravel_multi_index`
"""
order = 'C' if order is None else order.upper()
if order == 'C':
dims = reversed(dims)
elif order == 'F':
pass
else:
raise ValueError('order not understood')
if not cupy.can_cast(indices, cupy.int64, 'same_kind'):
raise TypeError(
'Iterator operand 0 dtype could not be cast '
'from dtype(\'{}\') to dtype(\'{}\') '
'according to the rule \'same_kind\''.format(
indices.dtype, cupy.int64().dtype))
if (indices < 0).any(): # synchronize!
raise ValueError('invalid entry in index array')
unraveled_coords = []
for dim in dims:
unraveled_coords.append(indices % dim)
indices = indices // dim
if (indices > 0).any(): # synchronize!
raise ValueError('invalid entry in index array')
if order == 'C':
unraveled_coords = reversed(unraveled_coords)
return tuple(unraveled_coords)
def mask_indices(n, mask_func, k=0):
"""
Return the indices to access (n, n) arrays, given a masking function.
Assume `mask_func` is a function that, for a square array a of
size ``(n, n)`` with a possible offset argument `k`, when called
as ``mask_func(a, k)`` returns a new array with zeros in certain
locations (functions like :func:`~cupy.triu` or :func:`~cupy.tril` do
precisely this). Then this function returns the indices where the non-zero
values would be located.
Args:
n (int): The returned indices will be valid to access arrays
of shape (n, n).
mask_func (callable): A function whose call signature is
similar to that of :func:`~cupy.triu`, :func:`~tril`. That is,
``mask_func(x, k)`` returns a boolean array, shaped like
`x`. `k` is an optional argument to the function.
k (scalar): An optional argument which is passed through to
`mask_func`. Functions like :func:`~cupy.triu`, :func:`~cupy.tril`
take a second argument that is interpreted as an offset.
Returns:
tuple of arrays: The `n` arrays of indices corresponding to
the locations where ``mask_func(np.ones((n, n)), k)`` is
True.
.. warning::
This function may synchronize the device.
.. seealso:: :func:`numpy.mask_indices`
"""
a = cupy.ones((n, n), dtype=cupy.int8)
return mask_func(a, k).nonzero()
# TODO(okuta): Implement diag_indices
# TODO(okuta): Implement diag_indices_from
def tril_indices(n, k=0, m=None):
"""Returns the indices of the lower triangular matrix.
Here, the first group of elements contains row coordinates
of all indices and the second group of elements
contains column coordinates.
Parameters
----------
n : int
The row dimension of the arrays for which the returned
indices will be valid.
k : int, optional
Diagonal above which to zero elements. `k = 0`
(the default) is the main diagonal, `k < 0` is
below it and `k > 0` is above.
m : int, optional
The column dimension of the arrays for which the
returned arrays will be valid. By default, `m = n`.
Returns
-------
y : tuple of ndarrays
The indices for the triangle. The returned tuple
contains two arrays, each with the indices along
one dimension of the array.
See Also
--------
numpy.tril_indices
"""
tri_ = cupy.tri(n, m, k=k, dtype=bool)
return tuple(cupy.broadcast_to(inds, tri_.shape)[tri_]
for inds in cupy.indices(tri_.shape, dtype=int))
def tril_indices_from(arr, k=0):
"""Returns the indices for the lower-triangle of arr.
Parameters
----------
arr : cupy.ndarray
The indices are valid for square arrays
whose dimensions are the same as arr.
k : int, optional
Diagonal offset.
See Also
--------
numpy.tril_indices_from
"""
if arr.ndim != 2:
raise ValueError("input array must be 2-d")
return tril_indices(arr.shape[-2], k=k, m=arr.shape[-1])
def triu_indices(n, k=0, m=None):
"""Returns the indices of the upper triangular matrix.
Here, the first group of elements contains row coordinates
of all indices and the second group of elements
contains column coordinates.
Parameters
----------
n : int
The size of the arrays for which the returned indices will
be valid.
k : int, optional
Refers to the diagonal offset. By default, `k = 0` i.e.
the main dialogal. The positive value of `k`
denotes the diagonals above the main diagonal, while the negative
value includes the diagonals below the main diagonal.
m : int, optional
The column dimension of the arrays for which the
returned arrays will be valid. By default, `m = n`.
Returns
-------
y : tuple of ndarrays
The indices for the triangle. The returned tuple
contains two arrays, each with the indices along
one dimension of the array.
See Also
--------
numpy.triu_indices
"""
tri_ = ~cupy.tri(n, m, k=k - 1, dtype=bool)
return tuple(cupy.broadcast_to(inds, tri_.shape)[tri_]
for inds in cupy.indices(tri_.shape, dtype=int))
def triu_indices_from(arr, k=0):
"""Returns indices for the upper-triangle of arr.
Parameters
----------
arr : cupy.ndarray
The indices are valid for square arrays.
k : int, optional
Diagonal offset (see 'triu_indices` for details).
Returns
-------
triu_indices_from : tuple of ndarrays
Indices for the upper-triangle of `arr`.
See Also
--------
numpy.triu_indices_from
"""
if arr.ndim != 2:
raise ValueError("input array must be 2-d")
return triu_indices(arr.shape[-2], k=k, m=arr.shape[-1])