-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathmodule.py
More file actions
9324 lines (7747 loc) · 273 KB
/
module.py
File metadata and controls
9324 lines (7747 loc) · 273 KB
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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2021-2023 NVIDIA Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import annotations
import math
import operator
import re
from collections import Counter
from itertools import chain
from typing import (
TYPE_CHECKING,
Any,
Iterable,
Literal,
Optional,
Sequence,
Tuple,
Union,
cast,
overload,
)
import numpy as np
import opt_einsum as oe # type: ignore [import]
from numpy.core.multiarray import ( # type: ignore [attr-defined]
normalize_axis_index,
)
from numpy.core.numeric import ( # type: ignore [attr-defined]
normalize_axis_tuple,
)
from cunumeric.coverage import is_implemented
from ._ufunc.comparison import logical_not, maximum, minimum, not_equal
from ._ufunc.floating import floor, isnan
from ._ufunc.math import add, multiply, subtract
from ._unary_red_utils import get_non_nan_unary_red_code
from .array import (
add_boilerplate,
check_writeable,
convert_to_cunumeric_ndarray,
ndarray,
)
from .config import BinaryOpCode, ScanCode, UnaryRedCode
from .runtime import runtime
from .settings import settings as cunumeric_settings
from .types import NdShape, NdShapeLike, OrderType, SortSide
from .utils import AxesPairLike, inner_modes, matmul_modes, tensordot_modes
if TYPE_CHECKING:
from os import PathLike
from typing import BinaryIO, Callable
import numpy.typing as npt
from ._ufunc.ufunc import CastingKind
from .types import BoundsMode, ConvolveMode, SelectKind, SortType
_builtin_abs = abs
_builtin_all = all
_builtin_any = any
_builtin_max = max
_builtin_min = min
_builtin_sum = sum
_builtin_range = range
casting_kinds: tuple[CastingKind, ...] = (
"no",
"equiv",
"safe",
"same_kind",
"unsafe",
)
#########################
# Array creation routines
#########################
# From shape or value
def empty(shape: NdShapeLike, dtype: npt.DTypeLike = np.float64) -> ndarray:
"""
empty(shape, dtype=float)
Return a new array of given shape and type, without initializing entries.
Parameters
----------
shape : int or tuple[int]
Shape of the empty array.
dtype : data-type, optional
Desired output data-type for the array. Default is `cunumeric.float64`.
Returns
-------
out : ndarray
Array of uninitialized (arbitrary) data of the given shape and dtype.
See Also
--------
numpy.empty
Availability
--------
Multiple GPUs, Multiple CPUs
"""
return ndarray(shape=shape, dtype=dtype)
@add_boilerplate("a")
def empty_like(
a: ndarray,
dtype: Optional[npt.DTypeLike] = None,
shape: Optional[NdShapeLike] = None,
) -> ndarray:
"""
empty_like(prototype, dtype=None)
Return a new array with the same shape and type as a given array.
Parameters
----------
prototype : array_like
The shape and data-type of `prototype` define these same attributes
of the returned array.
dtype : data-type, optional
Overrides the data type of the result.
shape : int or tuple[int], optional
Overrides the shape of the result.
Returns
-------
out : ndarray
Array of uninitialized (arbitrary) data with the same shape and type as
`prototype`.
See Also
--------
numpy.empty_like
Availability
--------
Multiple GPUs, Multiple CPUs
"""
shape = a.shape if shape is None else shape
if dtype is not None:
dtype = np.dtype(dtype)
else:
dtype = a.dtype
return ndarray(shape, dtype=dtype, inputs=(a,))
def eye(
N: int,
M: Optional[int] = None,
k: int = 0,
dtype: Optional[npt.DTypeLike] = np.float64,
) -> ndarray:
"""
Return a 2-D array with ones on the diagonal and zeros elsewhere.
Parameters
----------
N : int
Number of rows in the output.
M : int, optional
Number of columns in the output. If None, defaults to `N`.
k : int, optional
Index of the diagonal: 0 (the default) refers to the main diagonal,
a positive value refers to an upper diagonal, and a negative value
to a lower diagonal.
dtype : data-type, optional
Data-type of the returned array.
Returns
-------
I : ndarray
An array of shape (N, M) where all elements are equal to zero, except
for the `k`-th diagonal, whose values are equal to one.
See Also
--------
numpy.eye
Availability
--------
Multiple GPUs, Multiple CPUs
"""
if dtype is not None:
dtype = np.dtype(dtype)
if M is None:
M = N
k = operator.index(k)
result = ndarray((N, M), dtype)
result._thunk.eye(k)
return result
def identity(n: int, dtype: npt.DTypeLike = float) -> ndarray:
"""
Return the identity array.
The identity array is a square array with ones on
the main diagonal.
Parameters
----------
n : int
Number of rows (and columns) in `n` x `n` output.
dtype : data-type, optional
Data-type of the output. Defaults to ``float``.
Returns
-------
out : ndarray
`n` x `n` array with its main diagonal set to one, and all other
elements 0.
See Also
--------
numpy.identity
Availability
--------
Multiple GPUs, Multiple CPUs
"""
return eye(N=n, M=n, dtype=dtype)
def ones(shape: NdShapeLike, dtype: npt.DTypeLike = np.float64) -> ndarray:
"""
Return a new array of given shape and type, filled with ones.
Parameters
----------
shape : int or tuple[int]
Shape of the new array.
dtype : data-type, optional
The desired data-type for the array. Default is `cunumeric.float64`.
Returns
-------
out : ndarray
Array of ones with the given shape and dtype.
See Also
--------
numpy.ones
Availability
--------
Multiple GPUs, Multiple CPUs
"""
return full(shape, 1, dtype=dtype)
def ones_like(
a: ndarray,
dtype: Optional[npt.DTypeLike] = None,
shape: Optional[NdShapeLike] = None,
) -> ndarray:
"""
Return an array of ones with the same shape and type as a given array.
Parameters
----------
a : array_like
The shape and data-type of `a` define these same attributes of the
returned array.
dtype : data-type, optional
Overrides the data type of the result.
shape : int or tuple[int], optional
Overrides the shape of the result.
Returns
-------
out : ndarray
Array of ones with the same shape and type as `a`.
See Also
--------
numpy.ones_like
Availability
--------
Multiple GPUs, Multiple CPUs
"""
usedtype = a.dtype
if dtype is not None:
usedtype = np.dtype(dtype)
return full_like(a, 1, dtype=usedtype, shape=shape)
def zeros(shape: NdShapeLike, dtype: npt.DTypeLike = np.float64) -> ndarray:
"""
zeros(shape, dtype=float)
Return a new array of given shape and type, filled with zeros.
Parameters
----------
shape : int or tuple[int]
Shape of the new array.
dtype : data-type, optional
The desired data-type for the array. Default is `cunumeric.float64`.
Returns
-------
out : ndarray
Array of zeros with the given shape and dtype.
See Also
--------
numpy.zeros
Availability
--------
Multiple GPUs, Multiple CPUs
"""
if dtype is not None:
dtype = np.dtype(dtype)
return full(shape, 0, dtype=dtype)
def zeros_like(
a: ndarray,
dtype: Optional[npt.DTypeLike] = None,
shape: Optional[NdShapeLike] = None,
) -> ndarray:
"""
Return an array of zeros with the same shape and type as a given array.
Parameters
----------
a : array_like
The shape and data-type of `a` define these same attributes of
the returned array.
dtype : data-type, optional
Overrides the data type of the result.
shape : int or tuple[int], optional
Overrides the shape of the result.
Returns
-------
out : ndarray
Array of zeros with the same shape and type as `a`.
See Also
--------
numpy.zeros_like
Availability
--------
Multiple GPUs, Multiple CPUs
"""
usedtype = a.dtype
if dtype is not None:
usedtype = np.dtype(dtype)
return full_like(a, 0, dtype=usedtype, shape=shape)
def full(
shape: NdShapeLike,
value: Any,
dtype: Optional[npt.DTypeLike] = None,
) -> ndarray:
"""
Return a new array of given shape and type, filled with `fill_value`.
Parameters
----------
shape : int or tuple[int]
Shape of the new array.
fill_value : scalar
Fill value.
dtype : data-type, optional
The desired data-type for the array The default, None, means
`cunumeric.array(fill_value).dtype`.
Returns
-------
out : ndarray
Array of `fill_value` with the given shape and dtype.
See Also
--------
numpy.full
Availability
--------
Multiple GPUs, Multiple CPUs
"""
if dtype is None:
val = np.array(value)
else:
dtype = np.dtype(dtype)
val = np.array(value, dtype=dtype)
result = empty(shape, dtype=val.dtype)
result._thunk.fill(val)
return result
def full_like(
a: ndarray,
value: Union[int, float],
dtype: Optional[npt.DTypeLike] = None,
shape: Optional[NdShapeLike] = None,
) -> ndarray:
"""
Return a full array with the same shape and type as a given array.
Parameters
----------
a : array_like
The shape and data-type of `a` define these same attributes of
the returned array.
fill_value : scalar
Fill value.
dtype : data-type, optional
Overrides the data type of the result.
shape : int or tuple[int], optional
Overrides the shape of the result.
Returns
-------
out : ndarray
Array of `fill_value` with the same shape and type as `a`.
See Also
--------
numpy.full_like
Availability
--------
Multiple GPUs, Multiple CPUs
"""
if dtype is not None:
dtype = np.dtype(dtype)
else:
dtype = a.dtype
result = empty_like(a, dtype=dtype, shape=shape)
val = np.array(value, dtype=result.dtype)
result._thunk.fill(val)
return result
# From existing data
def array(
obj: Any,
dtype: Optional[np.dtype[Any]] = None,
copy: bool = True,
order: Union[OrderType, Literal["K"]] = "K",
subok: bool = False,
ndmin: int = 0,
) -> ndarray:
"""
array(object, dtype=None, copy=True)
Create an array.
Parameters
----------
object : array_like
An array, any object exposing the array interface, an object whose
__array__ method returns an array, or any (nested) sequence.
dtype : data-type, optional
The desired data-type for the array. If not given, then the type will
be determined as the minimum type required to hold the objects in the
sequence.
copy : bool, optional
If true (default), then the object is copied. Otherwise, a copy will
only be made if __array__ returns a copy, if obj is a nested sequence,
or if a copy is needed to satisfy any of the other requirements
(`dtype`, `order`, etc.).
order : ``{'K', 'A', 'C', 'F'}``, optional
Specify the memory layout of the array. If object is not an array, the
newly created array will be in C order (row major) unless 'F' is
specified, in which case it will be in Fortran order (column major).
If object is an array the following holds.
===== ========= ===================================================
order no copy copy=True
===== ========= ===================================================
'K' unchanged F & C order preserved, otherwise most similar order
'A' unchanged F order if input is F and not C, otherwise C order
'C' C order C order
'F' F order F order
===== ========= ===================================================
When ``copy=False`` and a copy is made for other reasons, the result is
the same as if ``copy=True``, with some exceptions for 'A', see the
Notes section. The default order is 'K'.
subok : bool, optional
If True, then sub-classes will be passed-through, otherwise
the returned array will be forced to be a base-class array (default).
ndmin : int, optional
Specifies the minimum number of dimensions that the resulting
array should have. Ones will be pre-pended to the shape as
needed to meet this requirement.
Returns
-------
out : ndarray
An array object satisfying the specified requirements.
See Also
--------
numpy.array
Availability
--------
Multiple GPUs, Multiple CPUs
"""
if not isinstance(obj, ndarray):
thunk = runtime.get_numpy_thunk(obj, share=(not copy), dtype=dtype)
result = ndarray(shape=None, thunk=thunk)
else:
result = obj
if dtype is not None and result.dtype != dtype:
result = result.astype(dtype)
elif copy and obj is result:
result = result.copy()
if result.ndim < ndmin:
shape = (1,) * (ndmin - result.ndim) + result.shape
result = result.reshape(shape)
return result
def asarray(a: Any, dtype: Optional[np.dtype[Any]] = None) -> ndarray:
"""
Convert the input to an array.
Parameters
----------
a : array_like
Input data, in any form that can be converted to an array. This
includes lists, lists of tuples, tuples, tuples of tuples, tuples
of lists and ndarrays.
dtype : data-type, optional
By default, the data-type is inferred from the input data.
Returns
-------
out : ndarray
Array interpretation of `a`. No copy is performed if the input is
already an ndarray with matching dtype. If `a` is a subclass of
ndarray, a base class ndarray is returned.
See Also
--------
numpy.asarray
Availability
--------
Multiple GPUs, Multiple CPUs
"""
if not isinstance(a, ndarray):
thunk = runtime.get_numpy_thunk(a, share=True, dtype=dtype)
writeable = a.flags.writeable if isinstance(a, np.ndarray) else True
array = ndarray(shape=None, thunk=thunk, writeable=writeable)
else:
array = a
if dtype is not None and array.dtype != dtype:
array = array.astype(dtype)
return array
@add_boilerplate("a")
def copy(a: ndarray) -> ndarray:
"""
Return an array copy of the given object.
Parameters
----------
a : array_like
Input data.
Returns
-------
arr : ndarray
Array interpretation of `a`.
See Also
--------
numpy.copy
Availability
--------
Multiple GPUs, Multiple CPUs
"""
result = empty_like(a, dtype=a.dtype)
result._thunk.copy(a._thunk, deep=True)
return result
def load(
file: str | bytes | PathLike[Any] | BinaryIO,
*,
max_header_size: int = 10000,
) -> ndarray:
"""
Load an array from a ``.npy`` file.
Parameters
----------
file : file-like object, string, or pathlib.Path
The file to read. File-like objects must support the
``seek()`` and ``read()`` methods and must always
be opened in binary mode.
max_header_size : int, optional
Maximum allowed size of the header. Large headers may not be safe
to load securely and thus require explicitly passing a larger value.
See :py:func:`ast.literal_eval()` for details.
Returns
-------
result : array
Data stored in the file.
Raises
------
OSError
If the input file does not exist or cannot be read.
See Also
--------
numpy.load
Notes
-----
cuNumeric does not currently support ``.npz`` and pickled files.
Availability
--------
Single CPU
"""
return array(
np.load(
file,
max_header_size=max_header_size, # type: ignore [call-arg]
)
)
# Numerical ranges
def arange(
start: Union[int, float] = 0,
stop: Optional[Union[int, float]] = None,
step: Optional[Union[int, float]] = 1,
dtype: Optional[npt.DTypeLike] = None,
) -> ndarray:
"""
arange([start,] stop[, step,], dtype=None)
Return evenly spaced values within a given interval.
Values are generated within the half-open interval ``[start, stop)``
(in other words, the interval including `start` but excluding `stop`).
For integer arguments the function is equivalent to the Python built-in
`range` function, but returns an ndarray rather than a list.
When using a non-integer step, such as 0.1, the results will often not
be consistent. It is better to use `cunumeric.linspace` for these cases.
Parameters
----------
start : int or float, optional
Start of interval. The interval includes this value. The default
start value is 0.
stop : int or float
End of interval. The interval does not include this value, except
in some cases where `step` is not an integer and floating point
round-off affects the length of `out`.
step : int or float, optional
Spacing between values. For any output `out`, this is the distance
between two adjacent values, ``out[i+1] - out[i]``. The default
step size is 1. If `step` is specified as a position argument,
`start` must also be given.
dtype : data-type
The type of the output array. If `dtype` is not given, infer the data
type from the other input arguments.
Returns
-------
arange : ndarray
Array of evenly spaced values.
For floating point arguments, the length of the result is
``ceil((stop - start)/step)``. Because of floating point overflow,
this rule may result in the last element of `out` being greater
than `stop`.
See Also
--------
numpy.arange
Availability
--------
Multiple GPUs, Multiple CPUs
"""
if stop is None:
stop = start
start = 0
if step is None:
step = 1
if dtype is None:
dtype = np.result_type(start, stop, step)
else:
dtype = np.dtype(dtype)
N = math.ceil((stop - start) / step)
result = ndarray((_builtin_max(0, N),), dtype)
result._thunk.arange(start, stop, step)
return result
@add_boilerplate("start", "stop")
def linspace(
start: ndarray,
stop: ndarray,
num: int = 50,
endpoint: bool = True,
retstep: bool = False,
dtype: Optional[npt.DTypeLike] = None,
axis: int = 0,
) -> Union[ndarray, tuple[ndarray, Union[float, ndarray]]]:
"""
Return evenly spaced numbers over a specified interval.
Returns `num` evenly spaced samples, calculated over the
interval [`start`, `stop`].
The endpoint of the interval can optionally be excluded.
Parameters
----------
start : array_like
The starting value of the sequence.
stop : array_like
The end value of the sequence, unless `endpoint` is set to False.
In that case, the sequence consists of all but the last of ``num + 1``
evenly spaced samples, so that `stop` is excluded. Note that the step
size changes when `endpoint` is False.
num : int, optional
Number of samples to generate. Default is 50. Must be non-negative.
endpoint : bool, optional
If True, `stop` is the last sample. Otherwise, it is not included.
Default is True.
retstep : bool, optional
If True, return (`samples`, `step`), where `step` is the spacing
between samples.
dtype : data-type, optional
The type of the output array. If `dtype` is not given, infer the data
type from the other input arguments.
axis : int, optional
The axis in the result to store the samples. Relevant only if start
or stop are array-like. By default (0), the samples will be along a
new axis inserted at the beginning. Use -1 to get an axis at the end.
Returns
-------
samples : ndarray
There are `num` equally spaced samples in the closed interval
``[start, stop]`` or the half-open interval ``[start, stop)``
(depending on whether `endpoint` is True or False).
step : float or ndarray, optional
Only returned if `retstep` is True
Size of spacing between samples.
See Also
--------
numpy.linspace
Availability
--------
Multiple GPUs, Multiple CPUs
"""
if num < 0:
raise ValueError("Number of samples, %s, must be non-negative." % num)
div = (num - 1) if endpoint else num
common_kind = np.result_type(start.dtype, stop.dtype).kind
dt = np.complex128 if common_kind == "c" else np.float64
if dtype is None:
dtype = dt
delta = stop - start
y = arange(0, num, dtype=dt)
out: tuple[Any, ...] # EllipsisType not even in typing_extensions yet
# Reshape these arrays into dimensions that allow them to broadcast
if delta.ndim > 0:
if axis is None or axis == 0:
# First dimension
y = y.reshape((-1,) + (1,) * delta.ndim)
# Nothing else needs to be reshaped here because
# they should all broadcast correctly with y
if endpoint and num > 1:
out = (-1,)
elif axis == -1 or axis == delta.ndim:
# Last dimension
y = y.reshape((1,) * delta.ndim + (-1,))
if endpoint and num > 1:
out = (Ellipsis, -1)
# Extend everything else with extra dimensions of 1 at the end
# so that they can broadcast with y
delta = delta.reshape(delta.shape + (1,))
start = start.reshape(start.shape + (1,))
elif axis < delta.ndim:
# Somewhere in the middle
y = y.reshape((1,) * axis + (-1,) + (1,) * (delta.ndim - axis))
# Start array might be smaller than delta because of broadcast
startax = start.ndim - len(delta.shape[axis:])
start = start.reshape(
start.shape[0:startax] + (1,) + start.shape[startax:]
)
if endpoint and num > 1:
out = (Ellipsis, -1) + (slice(None, None, None),) * len(
delta.shape[axis:]
)
delta = delta.reshape(
delta.shape[0:axis] + (1,) + delta.shape[axis:]
)
else:
raise ValueError(
"axis "
+ str(axis)
+ " is out of bounds for array of dimension "
+ str(delta.ndim + 1)
)
else:
out = (-1,)
# else delta is a scalar so start must be also
# therefore it will trivially broadcast correctly
step: Union[float, ndarray]
if div > 0:
step = delta / div
if delta.ndim == 0:
y *= step
else:
y = y * step
else:
# sequences with 0 items or 1 item with endpoint=True (i.e. div <= 0)
# have an undefined step
step = np.NaN
if delta.ndim == 0:
y *= delta
else:
y = y * delta
y += start.astype(y.dtype, copy=False)
if endpoint and num > 1:
y[out] = stop.astype(y.dtype, copy=False)
if np.issubdtype(dtype, np.integer):
floor(y, out=y)
if retstep:
return y.astype(dtype, copy=False), step
else:
return y.astype(dtype, copy=False)
# Building matrices
@add_boilerplate("v")
def diag(v: ndarray, k: int = 0) -> ndarray:
"""
Extract a diagonal or construct a diagonal array.
See the more detailed documentation for ``cunumeric.diagonal`` if you use
this function to extract a diagonal and wish to write to the resulting
array; whether it returns a copy or a view depends on what version of numpy
you are using.
Parameters
----------
v : array_like
If `v` is a 2-D array, return a copy of its `k`-th diagonal.
If `v` is a 1-D array, return a 2-D array with `v` on the `k`-th
diagonal.
k : int, optional
Diagonal in question. The default is 0. Use `k>0` for diagonals
above the main diagonal, and `k<0` for diagonals below the main
diagonal.
Returns
-------
out : ndarray
The extracted diagonal or constructed diagonal array.
See Also
--------
numpy.diag
Availability
--------
Multiple GPUs, Multiple CPUs
"""
if v.ndim == 0:
raise ValueError("Input must be 1- or 2-d")
elif v.ndim == 1:
return v.diagonal(offset=k, axis1=0, axis2=1, extract=False)
elif v.ndim == 2:
return v.diagonal(offset=k, axis1=0, axis2=1, extract=True)
else:
raise ValueError("diag requires 1- or 2-D array, use diagonal instead")
def tri(
N: int,
M: Optional[int] = None,
k: int = 0,
dtype: npt.DTypeLike = float,
*,
like: Optional[ndarray] = None,
) -> ndarray:
"""
An array with ones at and below the given diagonal and zeros elsewhere.
Parameters
----------
N : int
Number of rows in the array.
M : int, optional
Number of columns in the array.
By default, `M` is taken equal to `N`.
k : int, optional
The sub-diagonal at and below which the array is filled.
`k` = 0 is the main diagonal, while `k` < 0 is below it,
and `k` > 0 is above. The default is 0.
dtype : dtype, optional
Data type of the returned array. The default is float.
like : array_like
Reference object to allow the creation of arrays which are not NumPy
arrays. If an array-like passed in as `like` supports the
`__array_function__` protocol, the result will be defined by it. In
this case it ensures the creation of an array object compatible with
that passed in via this argument.
Returns
-------
tri : ndarray of shape (N, M)
Array with its lower triangle filled with ones and zero elsewhere;
in other words ``T[i,j] == 1`` for ``j <= i + k``, 0 otherwise.
See Also
--------
numpy.tri
Notes
-----
`like` argument is currently not supported
Availability
--------
Multiple GPUs, Multiple CPUs
"""
# TODO: add support for `like` (see issue #418)
if like is not None:
raise ValueError("like parameter is currently not supported")
if M is None: