-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy path_creation_function.py
More file actions
1073 lines (868 loc) · 38.6 KB
/
_creation_function.py
File metadata and controls
1073 lines (868 loc) · 38.6 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
from __future__ import annotations
from functools import wraps
from typing import TYPE_CHECKING, Any, Callable
import arrayfire as af
from ._array_object import Array
from ._constants import Device
from ._dtypes import all_dtypes, float32, int32
if TYPE_CHECKING:
from ._constants import NestedSequence, SupportsBufferProtocol
def _check_valid_dtype(dtype: af.Dtype | None) -> None:
if dtype not in (None,) + all_dtypes:
raise ValueError("dtype must be one of the supported dtypes")
def _flatten_sequence(sequence: NestedSequence[bool | int | float]) -> NestedSequence[bool | int | float]:
"""Recursively flatten a nested list."""
if isinstance(sequence[0], list | tuple):
return [item for sublist in sequence for item in _flatten_sequence(sublist)] # type: ignore[arg-type] # FIXME
else:
return list(sequence)
def _determine_shape(sequence: NestedSequence[bool | int | float]) -> tuple[int, ...]:
"""Recursively determine the shape of the nested sequence."""
if isinstance(sequence, list | tuple) and isinstance(sequence[0], list | tuple):
return (len(sequence),) + _determine_shape(sequence[0])
else:
return (len(sequence),)
def _process_nested_sequence(sequence: NestedSequence[bool | int | float]) -> af.Array:
"""Process a nested sequence to create an ArrayFire array of appropriate dimensions."""
shape = _determine_shape(sequence)
flat_sequence = _flatten_sequence(sequence)
# TODO
# validate the default type
return af.Array(flat_sequence, shape=shape, dtype=af.float32) # type: ignore[arg-type] # FIXME
def manage_device(func: Callable) -> Callable:
@wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> Any:
_default_device = Device.use_default()
device = kwargs.get("device", _default_device)
# HACK
if func.__name__.endswith("_like") and device is None:
other = args[0]
device = other.device
if device is None:
device = _default_device
# Set the backend and device
af.set_backend(device.backend_type)
af.set_device(device.device_id)
try:
result = func(*args, **kwargs)
finally:
# Restore to the default backend and device settings
af.set_backend(_default_device.backend_type)
af.set_device(_default_device.device_id)
return result
return wrapper
@manage_device
def asarray(
obj: Array | bool | int | float | complex | NestedSequence[bool | int | float] | SupportsBufferProtocol,
/,
*,
dtype: af.Dtype | None = None,
device: Device | None = None,
copy: bool | None = None,
) -> Array:
"""
Converts the input to an array.
This function creates an array from an object, or wraps an existing array. If `obj` is already an array of the
desired data type and `copy` is False, no copy will be performed, and `obj` itself is returned. Otherwise, a new
array is created, possibly copying the data from `obj`, depending on the `copy` parameter.
Parameters
----------
obj : Array | bool | int | float | complex | NestedSequence | SupportsBufferProtocol
The input object to convert to an array. This can be a scalar, nested sequence (like lists of lists), or any
object exposing the buffer interface, and of course, an existing array.
dtype : af.Dtype | None, optional
The desired data type for the array. If `None`, the data type is inferred from the input object. Explicitly
specifying the data type allows the creation of an array with the intended data type.
device : Device | None, optional
The device on which to create the array. If `None`, the array is created on the default device. This parameter
can be used to specify the computational device (CPU, GPU, etc.) for the array's storage.
copy : bool | None, optional
If True, a new array is always created. If False, a new array is only created if necessary (i.e., if `obj` is
not already an array of the specified data type). If `None`, the behavior defaults to True (i.e., always copy).
Returns
-------
Array
An array representation of `obj`. If `obj` is already an array, it may be returned directly based on the `copy`
parameter and the data type match.
Examples
--------
>>> asarray([1, 2, 3])
Array([1, 2, 3])
>>> asarray([1, 2, 3], dtype=float32)
Array([1.0, 2.0, 3.0])
>>> a = array([1, 2, 3], device='cpu')
>>> asarray(a, device='gpu')
# A new array on GPU, containing [1, 2, 3]
>>> asarray(1.0, dtype=int32)
Array(1)
Notes
-----
- The `asarray` function is a convenient way to create arrays or convert other objects to arrays with specified
data type and storage device criteria. It is particularly useful for ensuring that numerical data is in the form
of an array for computational tasks.
- The `copy` parameter offers control over whether data is duplicated when creating the array, which can be
important for managing memory use and computational efficiency.
"""
_check_valid_dtype(dtype)
if dtype is None:
dtype = float32
if isinstance(obj, bool | int | float | complex):
afarray = af.constant(obj, dtype=dtype)
elif isinstance(obj, Array):
afarray = Array._array if not copy else af.copy_array(Array._array)
elif isinstance(obj, list | tuple):
afarray = _process_nested_sequence(obj)
else:
# HACK
afarray = af.Array(obj, dtype=dtype) # type: ignore[arg-type]
return Array._new(afarray)
def arange(
start: int | float,
/,
stop: int | float | None = None,
step: int | float = 1,
*,
dtype: af.Dtype | None = None,
device: Device | None = None,
) -> Array:
# TODO
return NotImplemented
@manage_device
def empty(
shape: int | tuple[int, ...],
*,
dtype: af.Dtype | None = None,
device: Device | None = None,
) -> Array:
"""
Returns an uninitialized array of a specified shape. The contents of the array are uninitialized,
meaning they will contain arbitrary data. This function is often used for efficiency in scenarios
where the entire array will be populated with data immediately after its creation, eliminating the
need for initial zeroing of memory.
Parameters
----------
shape : int or tuple of ints
The desired shape of the output array. An integer creates a one-dimensional array, while a tuple
creates an n-dimensional array with dimensions specified by the tuple.
dtype : af.Dtype | None, optional
The desired data type for the array. If not specified, the array's data type will be the default
floating-point data type determined by the array library. Specifying a data type is useful when
creating arrays intended for specific types of data.
device : Device | None, optional
The device on which to create the array. If not specified, the array will be created on the default
device. This parameter can be used to specify the computational device (e.g., CPU or GPU) for the
array's storage.
Returns
-------
Array
An array with the specified shape and data type, containing uninitialized data.
Examples
--------
>>> empty(3)
Array([..., ..., ...]) # Uninitialized data
>>> empty((2, 2), dtype=float64)
Array([[..., ...],
[..., ...]]) # Uninitialized data of float64 type
>>> empty((3, 4), device='gpu')
Array([[..., ..., ..., ...],
[..., ..., ..., ...],
[..., ..., ..., ...]]) # Uninitialized data on GPU
Notes
-----
- The contents of the returned array are uninitialized and accessing them without setting their values first
can result in undefined behavior.
- This function provides an efficient way to allocate memory for large arrays when it is known that all
elements will be explicitly assigned before any computation is performed on the array.
The use of `dtype` and `device` allows for control over the type and location of the allocated memory,
optimizing performance and compatibility with specific hardware or computational tasks.
"""
_check_valid_dtype(dtype)
if isinstance(shape, int):
shape = (shape,)
if dtype is None:
dtype = float32
array = af.Array(None, dtype=dtype, shape=shape)
return Array._new(array)
@manage_device
def empty_like(x: Array, /, *, dtype: af.Dtype | None = None, device: Device | None = None) -> Array:
"""
Returns an uninitialized array with the same shape and, optionally, the same data type as the input array `x`.
The contents of the new array are uninitialized, meaning they may contain arbitrary data (including potentially
sensitive data left over from other processes). This function is typically used for efficiency in scenarios where
the user intends to populate the array with data immediately after its creation.
Parameters
----------
x : Array
The input array from which to derive the shape of the output array. The data type of the output array is also
inferred from `x` unless `dtype` is explicitly specified.
dtype : af.Dtype | None, optional
The desired data type for the new array. If `None` (the default), the data type of the input array `x` is used.
This parameter allows the user to specify a different data type for the new array.
device : Device | None, optional
The device on which to create the new array. If `None`, the new array is created on the same device as the
input array `x`. This allows for the creation of arrays on specific devices (e.g., on a GPU).
Returns
-------
Array
An array having the same shape as `x`, with uninitialized data. The data type of the array is determined by the
`dtype` parameter if specified, otherwise by the data type of `x`.
Examples
--------
>>> x = array([1, 2, 3])
>>> y = empty_like(x)
# y is an uninitialized array with the same shape and data type as x
>>> x = array([[1.0, 2.0], [3.0, 4.0]])
>>> y = empty_like(x, dtype=int32)
# y is an uninitialized array with the same shape as x but with an int32 data type
>>> x = array([1, 2, 3], device='cpu')
>>> y = empty_like(x, device='gpu')
# y is an uninitialized array with the same shape as x, created on a GPU
Notes
-----
- The contents of the returned array are uninitialized. Accessing the data without first initializing it
may result in unpredictable behavior.
- The `dtype` and `device` parameters offer flexibility in the creation of the new array, allowing the user
to specify the data type and the computational device for the array.
"""
_check_valid_dtype(dtype)
if dtype is None:
dtype = x.dtype
return empty(x.shape, dtype=dtype, device=device) # type: ignore[no-any-return] # FIXME
@manage_device
def eye(
n_rows: int,
n_cols: int | None = None,
/,
*,
k: int = 0,
dtype: af.Dtype | None = None,
device: Device | None = None,
) -> Array:
"""
Returns a two-dimensional array with ones on the kth diagonal and zeros elsewhere.
This function is useful for creating identity matrices or variations thereof.
Parameters
----------
n_rows : int
The number of rows in the output array.
n_cols : int, optional
The number of columns in the output array. If None (the default), the output array will be square,
with the number of columns equal to `n_rows`.
k : int, optional, default: 0
The index of the diagonal to be filled with ones. `k=0` refers to the main diagonal. A positive `k`
refers to an upper diagonal, and a negative `k` to a lower diagonal.
dtype : af.Dtype | None, optional
The desired data type of the output array. If None, the default floating-point data type is used.
Specifying a data type allows for the creation of identity matrices with elements of that type.
device : Device | None, optional
The device on which to create the array. If None, the array is created on the default device. This
can be useful for ensuring the array is created in the appropriate memory space (e.g., on a GPU).
Returns
-------
Array
A 2D array with ones on the specified diagonal and zeros elsewhere. The shape of the array is
(n_rows, n_cols), with `n_cols` defaulting to `n_rows` if not specified.
Examples
--------
>>> eye(3)
Array([[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
>>> eye(3, 4, k=1)
Array([[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]])
>>> eye(4, 3, k=-1, dtype=int32)
Array([[0, 0, 0],
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
>>> eye(3, device='gpu')
Array([[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
Notes
-----
- The `dtype` and `device` parameters allow for detailed control over the type and location of the
resulting array, which can be important for performance and compatibility with other arrays or
operations in a program.
"""
_check_valid_dtype(dtype)
if n_cols is None:
n_cols = n_rows
if dtype is None:
dtype = float32
if n_rows <= abs(k):
return Array._new(af.constant(0, (n_rows, n_cols), dtype))
# Create an identity matrix as the base
array = af.identity((n_rows, n_cols), dtype=dtype)
if k == 0:
# No shift needed, directly return the identity matrix
return Array._new(array)
# Prepare a zeros array for padding
zeros_padding_vertical = af.constant(0, (abs(k), n_cols), dtype=dtype)
zeros_padding_horizontal = af.constant(0, (n_rows, abs(k)), dtype=dtype)
if k > 0:
# Shift the diagonal upwards by removing the last k columns and padding with zeros on the left
shifted_array = af.join(1, zeros_padding_horizontal, array[:, :-k])
else:
# Shift the diagonal downwards by removing the last k rows and padding with zeros on top
shifted_array = af.join(0, zeros_padding_vertical, array[: -abs(k), :])
return Array._new(shifted_array)
@manage_device
def full(
shape: int | tuple[int, ...],
fill_value: int | float,
*,
dtype: af.Dtype | None = None,
device: Device | None = None,
) -> Array:
"""
Returns a new array of a specified shape, filled with `fill_value`.
Parameters
----------
shape : int or tuple of ints
The shape of the new array. If an integer is provided, the result will be a 1-D array of that length.
A tuple can be used to specify the shape of a multi-dimensional array.
fill_value : int or float
The value used to fill the array. Can be an integer or floating-point number.
dtype : af.Dtype | None, optional
The desired data type for the new array. If not specified, the data type is inferred from the `fill_value`.
If `fill_value` is an integer, the default integer data type is used. For a floating-point number, the
default floating-point data type is chosen. The behavior is unspecified if `fill_value`'s precision exceeds
the capabilities of the chosen data type.
device : Device | None, optional
The device on which to create the array. If not specified, the array is created on the default device.
This can be used to specify creation of the array on a particular device, such as a GPU.
Returns
-------
Array
An array of shape `shape`, where each element is `fill_value`.
Notes
-----
- The behavior is unspecified if the `fill_value` exceeds the precision of the chosen data type.
- The `dtype` argument allows for specifying the desired data type explicitly. If `dtype` is None,
the data type is inferred from the `fill_value`.
Examples
--------
>>> full(3, 5)
Array([5, 5, 5])
>>> full((2, 2), 0.5)
Array([[0.5, 0.5],
[0.5, 0.5]])
>>> full((2, 3), 1, dtype=float64)
Array([[1.0, 1.0, 1.0],
[1.0, 1.0, 1.0]])
>>> full(4, True, dtype=bool)
Array([True, True, True, True])
This function is useful for creating arrays with a constant value throughout. The `device` parameter
allows for control over where the computation is performed, which can be particularly important for
performance in computational environments with multiple devices.
"""
_check_valid_dtype(dtype)
if isinstance(shape, int):
shape = (shape,)
# Default dtype handling based on 'fill_value' type if 'dtype' not provided
if dtype is None:
dtype = float32 if isinstance(fill_value, float) else int32
return Array._new(af.constant(fill_value, shape, dtype=dtype))
@manage_device
def full_like(
x: Array,
/,
fill_value: int | float,
*,
dtype: af.Dtype | None = None,
device: Device | None = None,
) -> Array:
"""
Returns a new array with the same shape as the input array `x`, filled with `fill_value`.
Parameters
----------
x : Array
The input array whose shape and data type (if `dtype` is None) are used to create the new array.
fill_value : int | float
The scalar value to fill the new array with.
dtype : af.Dtype | None, optional
The desired data type for the new array. If `None`, the data type of `x` is used. This allows
overriding the data type of the input array while keeping its shape.
device : Device | None, optional
The device on which to place the created array. If `None`, the array is created on the same device as `x`.
Returns
-------
Array
A new array having the same shape as `x`, where every element is set to `fill_value`.
Notes
-----
- If `fill_value` is of a different data type than `x` and `dtype` is `None`, the data type of the new array
will be inferred in a way that can represent `fill_value`.
- If `dtype` is specified, it determines the data type of the new array, irrespective of the data type of `x`.
Examples
--------
>>> x = array([[1, 2], [3, 4]])
>>> full_like(x, 5)
Array([[5, 5],
[5, 5]])
>>> full_like(x, 0.5, dtype=float32)
Array([[0.5, 0.5],
[0.5, 0.5]])
>>> full_like(x, 7, device='gpu')
Array([[7, 7],
[7, 7]])
In the above examples, the `full_like` function creates new arrays with the same shape as `x`,
but filled with the specified `fill_value`, and optionally with the specified data type and device.
"""
_check_valid_dtype(dtype)
if dtype is None:
dtype = x.dtype
return full(x.shape, fill_value, dtype=dtype, device=device) # type: ignore[no-any-return] # FIXME
@manage_device
def linspace(
start: int | float,
stop: int | float,
/,
num: int,
*,
dtype: af.Dtype | None = None,
device: Device | None = None,
endpoint: bool = True,
) -> Array:
"""
Returns `num` evenly spaced samples, calculated over the interval [`start`, `stop`].
The endpoint of the interval can optionally be excluded.
Parameters
----------
start : int | float
The starting value of the sequence.
stop : int | float
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
Number of samples to generate. Must be non-negative.
dtype : af.Dtype | None, optional, default: None
The data type of the output array. If `None`, the data type is inferred from `start` and `stop`.
The inferred data type will never be an integer data type because `linspace` always generates
floating point values.
device : Device | None, optional, default: None
The device on which to place the created array. If `None`, the device is inferred from the current
device context.
endpoint : bool, optional, default: True
If True, `stop` is the last sample. Otherwise, it is not included.
Returns
-------
Array
An array of `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).
See Also
--------
arange : Similar to `linspace`, but uses a step size (instead of the number of samples).
Notes
-----
- The output array is always a floating point array, even if `start`, `stop`, and `dtype` are all integers.
- If `num` is 1, the output array only contains the `start` value.
Examples
--------
>>> linspace(2.0, 3.0, num=5)
Array([2. , 2.25, 2.5 , 2.75, 3. ])
>>> linspace(2.0, 3.0, num=5, endpoint=False)
Array([2. , 2.2, 2.4, 2.6, 2.8])
"""
# BUG, FIXME
# # Default dtype handling based on 'start' and 'stop' types if 'dtype' not provided
# if dtype is None:
# dtype = float32
# # Generate the linearly spaced array
# if endpoint:
# step = (stop - start) / (num - 1) if num > 1 else 0
# else:
# step = (stop - start) / num
# array = af.seq(start, stop, step, dtype=dtype)
# result_array = array if array.size == num else af.moddims(array, (num,))
# return Array._new(result_array)
return NotImplemented
def meshgrid(*arrays: Array, indexing: str = "xy") -> list[Array]:
"""
Returns coordinate matrices from coordinate vectors.
Make N-D coordinate arrays for vectorized evaluations of N-D scalar/vector fields over N-D grids,
given one-dimensional coordinate arrays x1, x2,..., xn.
Parameters
----------
*arrays : Array
One-dimensional arrays representing the coordinates of a grid.
indexing : {'xy', 'ij'}, optional, default: 'xy'
Cartesian ('xy', default) or matrix ('ij') indexing of output.
In Cartesian indexing, the first dimension corresponds to the x-coordinate, and the second to the y-coordinate.
In matrix indexing, the first dimension corresponds to the row index, and the second to the column index.
Returns
-------
list[Array]
List of N arrays, where `N` is the number of provided one-dimensional input arrays.
Each returned array must have the same shape. If `indexing` is 'xy', the last dimension
of the arrays corresponds to changes in x1, and the second-to-last corresponds to changes in x2,
and so forth. If `indexing` is 'ij', then the first dimension of the arrays corresponds to changes
in x1, the second dimension to changes in x2, and so forth.
See Also
--------
arange, linspace
Notes
-----
This function supports both indexing conventions through the `indexing` keyword argument.
Giving the string 'xy' returns the grid with Cartesian indexing, while 'ij' returns the grid
with matrix indexing. The difference is that 'xy' indexing returns arrays where the last
dimension represents points that vary along what would conventionally be considered the x-axis,
and 'ij' indexing returns arrays where the first dimension represents points that vary along
what would conventionally be considered the row index of a matrix or 2D array.
Examples
--------
>>> x = array([1, 2, 3])
>>> y = array([4, 5, 6, 7])
>>> xv, yv = meshgrid(x, y)
>>> xv
Array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
>>> yv
Array([[4, 4, 4],
[5, 5, 5],
[6, 6, 6],
[7, 7, 7]])
With `indexing='ij'`, the shape is transposed.
>>> xv, yv = meshgrid(x, y, indexing='ij')
>>> xv
Array([[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3]])
>>> yv
Array([[4, 5, 6, 7],
[4, 5, 6, 7],
[4, 5, 6, 7]])
"""
# BUG, FIXME
# arrays_af = [arr._array for arr in arrays] # Convert custom Array to ArrayFire array for processing
# dims = [arr.size for arr in arrays_af] # Get the number of elements in each array
# result = []
# for i, arr in enumerate(arrays_af):
# import ipdb; ipdb.set_trace()
# shape = [1] * len(arrays)
# shape[i] = dims[i]
# tiled_arr = af.tile(arr, tuple(shape))
# # Expand each array to have the correct shape
# for j, dim in enumerate(dims):
# if j != i:
# import ipdb; ipdb.set_trace()
# tiled_arr = af.moddims(tiled_arr, tuple(shape))
# shape[j] = dim
# else:
# shape[j] = 1
# if indexing == "xy" and len(arrays) > 1 and i == 0:
# # Swap the first two dimensions for the x array in 'xy' indexing
# tiled_arr = af.moddims(tiled_arr, (dims[1], dims[0], *dims[2:]))
# elif indexing == "xy" and len(arrays) > 1 and i == 1:
# # Ensure the y array is correctly shaped in 'xy' indexing
# tiled_arr = af.reorder(tiled_arr, shape=(1, 0, *range(2, len(dims))))
# result.append(Array._new(tiled_arr))
# if indexing == "ij":
# # No need to modify the order for 'ij' indexing
# pass
# return result
return NotImplemented
@manage_device
def ones(
shape: int | tuple[int, ...],
*,
dtype: af.Dtype | None = None,
device: Device | None = None,
) -> Array:
"""
Returns a new array of given shape and type, filled with ones.
Parameters
----------
shape : int or tuple of ints
The shape of the new array, e.g., (2, 3) or 2. If the shape is an integer, the output will be
a one-dimensional array of that length. If the shape is a tuple, the output will have the
specified shape.
dtype : af.Dtype | None, optional
The desired data type for the array, e.g., float32. If dtype is None, the default data type
(float64) is used. Note: The availability of data types can vary by implementation.
device : Device | None, optional
The device on which to place the created array. If None, the array is created on the default
device. This can be used to create arrays on, for example, a GPU.
Returns
-------
Array
An array of shape `shape` and data type `dtype`, where all elements are ones.
Notes
-----
- While the `dtype` parameter is optional, specifying it can be important for ensuring that
the array has the desired type, especially for operations that are sensitive to the data type.
- The `device` parameter allows control over where the array is stored, which can be important
for computational efficiency, especially in environments with multiple devices like CPUs and GPUs.
Examples
--------
>>> ones(5)
Array([1, 1, 1, 1, 1])
>>> ones((2, 3), dtype=float32)
Array([[1.0, 1.0, 1.0],
[1.0, 1.0, 1.0]])
>>> ones((2, 2), device='gpu')
Array([[1, 1],
[1, 1]])
The behavior of the `dtype` and `device` parameters may vary depending on the implementation
and the available hardware.
"""
_check_valid_dtype(dtype)
if isinstance(shape, int):
shape = (shape,)
if dtype is None:
dtype = float32
return Array._new(af.constant(1, shape, dtype))
@manage_device
def ones_like(x: Array, /, *, dtype: af.Dtype | None = None, device: Device | None = None) -> Array:
"""
Returns a new array with the same shape and type as a given array, filled with ones.
Parameters
----------
x : Array
The shape and data type of `x` are used to create the new array. The contents of `x` are not used.
dtype : af.Dtype | None, optional
The desired data type for the new array. If None, the data type of `x` is used. This allows overriding
the data type of the input array while keeping its shape.
device : Device | None, optional
The device on which to place the created array. If None, the array is created on the same device as `x`.
This parameter allows the new array to be placed on a specified device, which can be different from the
device of `x`.
Returns
-------
Array
An array of the same shape as `x`, with all elements set to one (1). The data type of the array is determined
by the `dtype` parameter if specified, otherwise by the data type of `x`.
Notes
-----
- The `ones_like` function is useful for creating arrays that are initialized to 1 and have the same shape
and data type (or a specified data type) as another array.
- Specifying the `dtype` and `device` parameters can be useful for creating an array with a specific data
type or for placing the array on a specific computational device, which can be important for performance
and memory usage considerations.
Examples
--------
>>> x = array([[0, 1], [2, 3]])
>>> ones_like(x)
Array([[1, 1],
[1, 1]])
>>> ones_like(x, dtype=float32)
Array([[1.0, 1.0],
[1.0, 1.0]])
>>> ones_like(x, device='gpu')
Array([[1, 1],
[1, 1]])
The output reflects the shape and, optionally, the specified data type or device of the input array.
"""
_check_valid_dtype(dtype)
if dtype is None:
dtype = x.dtype
return ones(x.shape, dtype=dtype, device=device) # type: ignore[no-any-return] # FIXME
def tril(x: Array, /, *, k: int = 0) -> Array:
"""
Returns the lower triangular part of the array `x`, with elements above the kth diagonal zeroed.
The kth diagonal refers to the diagonal that runs from the top-left corner of the matrix to the bottom-right
corner. For k = 0, the diagonal is the main diagonal. A positive value of k includes elements above the main
diagonal, and a negative value excludes elements below the main diagonal.
Parameters
----------
x : Array
The input array from which the lower triangular part is extracted. The array must be at least two-dimensional.
k : int, optional, default: 0
Diagonal above which to zero elements. `k=0` is the main diagonal, `k>0` is above the main diagonal, and `k<0`
is below the main diagonal.
Returns
-------
Array
An array with the same shape and data type as `x`, where elements above the kth diagonal are zeroed, and the
lower triangular part is retained.
Examples
--------
>>> x = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> tril(x)
Array([[1, 0, 0],
[4, 5, 0],
[7, 8, 9]])
>>> tril(x, k=1)
Array([[1, 2, 0],
[4, 5, 6],
[7, 8, 9]])
>>> tril(x, k=-1)
Array([[0, 0, 0],
[4, 0, 0],
[7, 8, 0]])
Notes
-----
- The function is used to extract the lower triangular part of a matrix, which can be useful in various
numerical and algebraic operations.
- The behavior of `tril` on arrays with more than two dimensions is not specified; it primarily operates
on two-dimensional matrices.
The `k` parameter allows for flexibility in defining which part of the array is considered the lower
triangular portion, offering a straightforward way to manipulate matrices for lower-triangular matrix operations.
"""
dtype = x.dtype
_check_valid_dtype(dtype)
n_rows, n_cols = x.shape
array = x._array
row_indices = af.tile(af.iota((1, n_rows), tile_shape=(n_cols, 1)), (1, 1))
col_indices = af.tile(af.iota((n_cols, 1), tile_shape=(1, n_rows)), (1, 1))
mask = row_indices <= (col_indices + k)
return Array._new(array * af.cast(mask, dtype))
def triu(x: Array, /, *, k: int = 0) -> Array:
"""
Returns the upper triangular part of the array `x`, with elements below the kth diagonal zeroed.
The kth diagonal refers to the diagonal that runs from the top-left corner of the matrix to the bottom-right
corner. For k = 0, the diagonal is the main diagonal. A positive value of k includes elements above and on the main
diagonal, and a negative value includes elements further below the main diagonal.
Parameters
----------
x : Array
The input array from which the upper triangular part is extracted. The array must be at least two-dimensional.
k : int, optional, default: 0
Diagonal below which to zero elements. `k=0` zeroes elements below the main diagonal, `k>0` zeroes elements
further above the main diagonal, and `k<0` zeroes elements starting from diagonals below the main diagonal.
Returns
-------
Array
An array with the same shape and data type as `x`, where elements below the kth diagonal are zeroed, and the
upper triangular part is retained.
Examples
--------
>>> x = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> triu(x)
Array([[1, 2, 3],
[0, 5, 6],
[0, 0, 9]])
>>> triu(x, k=1)
Array([[0, 2, 3],
[0, 0, 6],
[0, 0, 0]])
>>> triu(x, k=-1)
Array([[1, 2, 3],
[4, 5, 6],
[0, 8, 9]])
Notes
-----
- The function is used to extract the upper triangular part of a matrix, which can be useful in various
numerical and algebraic operations, such as solving linear equations or matrix factorization.
- The behavior of `triu` on arrays with more than two dimensions is not specified; it primarily operates
on two-dimensional matrices.
The `k` parameter allows adjusting the definition of the "upper triangular" part, enabling more flexible
matrix manipulations based on the specific requirements of the operation or analysis being performed.
"""
dtype = x.dtype
_check_valid_dtype(dtype)
n_rows, n_cols = x.shape
array = x._array
row_indices = af.tile(af.iota((1, n_rows), tile_shape=(n_cols, 1)), (1, 1))
col_indices = af.tile(af.iota((n_cols, 1), tile_shape=(1, n_rows)), (1, 1))
mask = col_indices <= (row_indices - k)
return Array._new(array * af.cast(mask, dtype))
@manage_device
def zeros(
shape: int | tuple[int, ...],
*,
dtype: af.Dtype | None = None,
device: Device | None = None,
) -> Array:
"""
Returns a new array of given shape and type, filled with zeros.
This function is useful for creating arrays that serve as initial placeholders in various numerical
computations, providing a base for algorithms that require an initial array filled with zeros.
Parameters
----------
shape : int or tuple of ints
The shape of the new array. If an integer is provided, the result is a one-dimensional array of that length.
A tuple specifies the dimensions of the array for more than one dimension.
dtype : af.Dtype | None, optional
The desired data type for the array. If not specified, the default data type (typically float64) is used.
Specifying a data type can be important for the precise control of numerical computations.
device : Device | None, optional
The device on which to create the array. If not specified, the array is created on the default device.
This parameter can be used to control where the computation is performed, such as on a CPU or GPU,
which might be important for performance reasons or when working within specific computational environments.
Returns
-------
Array
An array with the specified shape and data type, where all elements are zeros.
Examples
--------
>>> zeros(5)
Array([0, 0, 0, 0, 0])
>>> zeros((2, 3), dtype=int32)
Array([[0, 0, 0],
[0, 0, 0]])
>>> zeros((2, 2), device='gpu')
Array([[0, 0],
[0, 0]])
# Note: The actual device specification will depend on the array library's implementation and the available
hardware.
Notes
-----
- The `dtype` and `device` parameters offer the flexibility to create the zero-filled array with specific
characteristics tailored to the needs of different computational tasks or hardware requirements.
The use of zeros in computational algorithms is widespread, serving as initial states, placeholders, or