/
general.py
3956 lines (3305 loc) · 102 KB
/
general.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
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
"""Collection of general Ivy functions."""
# global
import gc
import inspect
import math
from functools import wraps
from numbers import Number
from typing import (
Callable,
Any,
Union,
List,
Tuple,
Dict,
Iterable,
Optional,
Sequence,
Literal,
)
import einops
import numpy as np
# local
import ivy
from ivy.utils.backend import current_backend, backend_stack
from ivy.functional.ivy.gradients import _is_variable
from ivy.utils.exceptions import handle_exceptions
from ivy.func_wrapper import (
handle_array_function,
inputs_to_ivy_arrays,
inputs_to_native_arrays,
to_native_arrays_and_back,
inputs_to_native_shapes,
outputs_to_ivy_shapes,
handle_out_argument,
handle_nestable,
handle_array_like_without_promotion,
handle_view_indexing,
)
from ivy.functional.ivy.device import dev
FN_CACHE = dict()
INF = float("inf")
precise_mode_stack = list()
queue_timeout_stack = list()
array_mode_stack = list()
shape_array_mode_stack = list()
nestable_mode_stack = list()
exception_trace_mode_stack = list()
trace_mode_dict = dict()
trace_mode_dict["frontend"] = "ivy/functional/frontends"
trace_mode_dict["ivy"] = "ivy/"
trace_mode_dict["full"] = ""
trace_mode_dict["none"] = ""
show_func_wrapper_trace_mode_stack = list()
min_denominator_stack = list()
min_base_stack = list()
tmp_dir_stack = list()
# Extra #
# ------#
class PreciseMode:
"""Precise Mode Context Manager."""
# noinspection PyShadowingNames
def __init__(self, precise_mode):
self._precise_mode = precise_mode
def __enter__(self):
set_precise_mode(self._precise_mode)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
unset_precise_mode()
if self and (exc_type is not None):
print(exc_tb)
raise exc_val
return self
@handle_exceptions
def set_precise_mode(mode: bool) -> None:
"""
Set the mode of whether to use a promotion table that avoids any precision loss or a
compute effecient table that avoids most wider-than-necessary promotions.
Parameter
---------
mode
boolean whether to use high precision promtion table
Examples
--------
>>> ivy.set_precise_mode(False)
>>> ivy.get_precise_mode()
False
>>> ivy.set_precise_mode(True)
>>> ivy.get_precise_mode()
True
"""
global precise_mode_stack
ivy.utils.assertions.check_isinstance(mode, bool)
precise_mode_stack.append(mode)
_update_promotion_table(precise=mode)
@handle_exceptions
def unset_precise_mode() -> None:
"""
Reset the mode of whether to use a promotion table that avoids any precision loss or
a compute effecient table that avoids most wider-than-necessary promotions.
Examples
--------
>>> ivy.set_precise_mode(False)
>>> ivy.get_precise_mode()
False
>>> ivy.unset_precise_mode()
>>> ivy.array_mode
True
"""
global precise_mode_stack
if precise_mode_stack:
precise_mode_stack.pop(-1)
# TODO: change when it's not the default mode anymore
_update_promotion_table(
precise=precise_mode_stack[-1] if len(precise_mode_stack) != 0 else True
)
@handle_exceptions
def get_precise_mode() -> bool:
"""
Get the current state of precise_mode.
Examples
--------
>>> ivy.get_precise_mode()
True
>>> ivy.set_precise_mode(False)
>>> ivy.get_precise_mode()
False
"""
global precise_mode_stack
if not precise_mode_stack:
return True # TODO: change when it's not the default mode anymore
return precise_mode_stack[-1]
def _update_promotion_table(precise):
"""Update the current datatype promotion table."""
if precise:
ivy.promotion_table = {
**ivy.array_api_promotion_table,
**ivy.common_extra_promotion_table,
**ivy.precise_extra_promotion_table,
}
else:
ivy.promotion_table = {
**ivy.array_api_promotion_table,
**ivy.common_extra_promotion_table,
**ivy.extra_promotion_table,
}
class ArrayMode:
"""Array Mode Context Manager."""
# noinspection PyShadowingNames
def __init__(self, array_mode):
self._array_mode = array_mode
def __enter__(self):
set_array_mode(self._array_mode)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
unset_array_mode()
if self and (exc_type is not None):
print(exc_tb)
raise exc_val
return self
def _parse_ellipsis(so, ndims):
pre = list()
for s in so:
if s is Ellipsis:
break
pre.append(s)
post = list()
for s in reversed(so):
if s is Ellipsis:
break
post.append(s)
return tuple(
pre
+ [slice(None, None, None) for _ in range(ndims - len(pre) - len(post))]
+ list(reversed(post))
)
def _parse_index(indices, shape):
ind = list()
for so in indices:
pre = list()
for s in so:
if s == -1:
pre.append(shape[len(pre) :][0] - 1)
break
pre.append(s.numpy())
post = list()
for s in reversed(so):
if s == -1:
break
post.append(s.numpy())
ind.append(
tuple(
pre
+ [
slice(None, None, None)
for _ in range(len(shape) - len(pre) - len(post))
]
+ list(reversed(post))
)
)
return ind
def get_referrers_recursive(
item, depth=0, max_depth=None, seen_set=None, local_set=None
):
"""
Summary.
Parameters
----------
item
depth
(Default value = 0)
max_depth
(Default value = None)
seen_set
(Default value = None)
local_set
(Default value = None`)
"""
seen_set = ivy.default(seen_set, set())
local_set = ivy.default(local_set, set())
ret_cont = ivy.Container(
repr=str(item).replace(" ", ""),
alphabetical_keys=False,
keyword_color_dict={"repr": "magenta"},
)
referrers = [
ref
for ref in gc.get_referrers(item)
if not (
isinstance(ref, dict)
and min([k in ref for k in ["depth", "max_depth", "seen_set", "local_set"]])
)
]
local_set.add(str(id(referrers)))
for ref in referrers:
ref_id = str(id(ref))
if ref_id in local_set or hasattr(ref, "cell_contents"):
continue
seen = ref_id in seen_set
seen_set.add(ref_id)
refs_rec = lambda: get_referrers_recursive(
ref, depth + 1, max_depth, seen_set, local_set
)
this_repr = "tracked" if seen else str(ref).replace(" ", "")
if not seen and (not max_depth or depth < max_depth):
val = ivy.Container(
repr=this_repr,
alphabetical_keys=False,
keyword_color_dict={"repr": "magenta"},
)
refs = refs_rec()
for k, v in refs.items():
val[k] = v
else:
val = this_repr
ret_cont[str(ref_id)] = val
return ret_cont
@handle_exceptions
def is_native_array(
x: Union[ivy.Array, ivy.NativeArray], /, *, exclusive: bool = False
) -> bool:
"""
Determine whether the input x is an :class:`ivy.NativeArray` instance.
Parameters
----------
x
The input to check
exclusive
Whether to check if the data type is exclusively an array, rather than a
variable or traced array.
Returns
-------
ret
Boolean, whether or not x is an :class:`ivy.NativeArray`.
Examples
--------
>>> x = ivy.array([0, 1, 2])
>>> ivy.is_native_array(x)
False
>>> x = ivy.native_array([9.1, -8.3, 2.8, 3.0])
>>> ivy.is_native_array(x, exclusive=True)
True
"""
try:
return current_backend(x).is_native_array(x, exclusive=exclusive)
except ValueError:
return False
@handle_exceptions
def is_ivy_array(
x: Union[ivy.Array, ivy.NativeArray], /, *, exclusive: Optional[bool] = False
) -> bool:
"""
Determine whether the input x is a valid Ivy Array.
Parameters
----------
x
The input to check
exclusive
Whether to check if the data type is exclusively an array, rather than a
variable or traced array.
Returns
-------
ret
Boolean, whether or not x is a valid Ivy Array.
Examples
--------
>>> x = ivy.array([0, 1, 2])
>>> ivy.is_ivy_array(x)
True
>>> x = ivy.native_array([9.1, -8.3, 2.8, 3.0])
>>> ivy.is_ivy_array(x, exclusive=True)
False
"""
return isinstance(x, ivy.Array) and ivy.is_native_array(x.data, exclusive=exclusive)
@handle_exceptions
def is_array(x: Any, /, *, exclusive: bool = False) -> bool:
"""
Determine whether the input x is either an Ivy Array or a Native Array.
Parameters
----------
x
The input to check
exclusive
Whether to check if the data type is exclusively an array, rather than a
variable or traced array.
Returns
-------
ret
Boolean, whether or not x is an array.
Examples
--------
>>> x = ivy.array([0, 1, 2])
>>> print(ivy.is_array(x))
True
>>> x = ivy.native_array([9.1, -8.3, 2.8, 3.0])
>>> print(ivy.is_array(x, exclusive=True))
True
>>> x = [2, 3]
>>> print(ivy.is_array(x))
False
"""
return ivy.is_ivy_array(x, exclusive=exclusive) or ivy.is_native_array(
x, exclusive=exclusive
)
@handle_exceptions
def is_ivy_container(x: Any, /) -> bool:
"""
Determine whether the input x is an Ivy Container.
Parameters
----------
x
The input to check
Returns
-------
ret
Boolean, whether or not x is an ivy container.
Examples
--------
>>> x = ivy.Container()
>>> print(ivy.is_ivy_container(x))
True
>>> x = [2, 3]
>>> print(ivy.is_ivy_container(x))
False
"""
return isinstance(x, ivy.Container)
ivy.array_mode = True
@handle_exceptions
def set_array_mode(mode: bool) -> None:
"""
Set the mode of whether to convert inputs to ivy.NativeArray, then convert outputs
back to ivy.Array.
Parameter
---------
mode
boolean whether to perform ivy.Array conversions
Examples
--------
>>> ivy.set_array_mode(False)
>>> ivy.array_mode
False
>>> ivy.set_array_mode(True)
>>> ivy.array_mode
True
"""
global array_mode_stack
ivy.utils.assertions.check_isinstance(mode, bool)
array_mode_stack.append(mode)
ivy.__setattr__("array_mode", mode, True)
@handle_exceptions
def unset_array_mode() -> None:
"""
Reset the mode of converting inputs to ivy.NativeArray, then converting outputs back
to ivy.Array to the previous state.
Examples
--------
>>> ivy.set_array_mode(False)
>>> ivy.array_mode
False
>>> ivy.unset_shape_array_mode()
>>> ivy.array_mode
True
"""
global array_mode_stack
if array_mode_stack:
array_mode_stack.pop(-1)
mode = array_mode_stack[-1] if array_mode_stack else True
ivy.__setattr__("array_mode", mode, True)
ivy.nestable_mode = True
@handle_exceptions
def set_nestable_mode(mode: bool) -> None:
"""
Set the mode of whether to check if function inputs are ivy.Container.
Parameter
---------
mode
boolean whether to check if function inputs are ivy.Container
Examples
--------
>>> ivy.set_nestable_mode(False)
>>> ivy.nestable_mode
False
>>> ivy.set_nestable_mode(True)
>>> ivy.nestable_mode
True
"""
global nestable_mode_stack
ivy.utils.assertions.check_isinstance(mode, bool)
nestable_mode_stack.append(mode)
ivy.__setattr__("nestable_mode", mode, True)
@handle_exceptions
def unset_nestable_mode() -> None:
"""
Reset the mode of whether to check if function inputs are ivy.Container to the
previous state.
Examples
--------
>>> ivy.set_nestable_mode(False)
>>> ivy.nestable_mode
False
>>> ivy.unset_nestable_mode()
>>> ivy.nestable_mode
True
"""
global nestable_mode_stack
if nestable_mode_stack:
nestable_mode_stack.pop(-1)
mode = nestable_mode_stack[-1] if nestable_mode_stack else True
ivy.__setattr__("nestable_mode", mode, True)
ivy.exception_trace_mode = "full"
@handle_exceptions
def set_exception_trace_mode(mode: Literal["ivy", "full", "frontend"]) -> None:
"""
Set the mode of whether to show frontend-truncated exception stack traces, ivy-
truncated exception stack traces or full exception stack traces.
Parameter
---------
mode
str exeption trace mode, one of `ivy`, `full` or `frontend`
Examples
--------
>>> ivy.set_exception_trace_mode("ivy")
>>> ivy.exception_trace_mode
'ivy'
>>> ivy.set_exception_trace_mode("full")
>>> ivy.exception_trace_mode
'full'
"""
global exception_trace_mode_stack
trace_modes = list(trace_mode_dict.keys())
ivy.utils.assertions.check_elem_in_list(
mode, trace_modes, False, "trace mode must be one of {}".format(trace_modes)
)
exception_trace_mode_stack.append(mode)
ivy.__setattr__("exception_trace_mode", mode, True)
@handle_exceptions
def unset_exception_trace_mode() -> None:
"""
Reset the trace mode to the previously set mode.
Examples
--------
>>> ivy.set_exception_trace_mode("ivy")
>>> ivy.exception_trace_mode
'ivy'
>>> ivy.unset_exception_trace_mode()
>>> ivy.exception_trace_mode
'full'
"""
global exception_trace_mode_stack
if exception_trace_mode_stack:
exception_trace_mode_stack.pop(-1)
mode = exception_trace_mode_stack[-1] if exception_trace_mode_stack else "full"
ivy.__setattr__("exception_trace_mode", mode, True)
ivy.show_func_wrapper_trace_mode = True
@handle_exceptions
def set_show_func_wrapper_trace_mode(mode: bool) -> None:
"""
Set the mode of whether to show the full stack trace with function wrapping traces.
Parameter
---------
mode
boolean whether to perform ivy.Array conversions
Examples
--------
>>> ivy.set_show_func_wrapper_trace_mode(False)
>>> ivy.show_func_wrapper_trace_mode
False
>>> ivy.set_show_func_wrapper_trace_mode(True)
>>> ivy.show_func_wrapper_trace_mode
True
"""
global show_func_wrapper_trace_mode_stack
ivy.utils.assertions.check_isinstance(mode, bool)
show_func_wrapper_trace_mode_stack.append(mode)
ivy.__setattr__("show_func_wrapper_trace_mode", mode, True)
@handle_exceptions
def unset_show_func_wrapper_trace_mode() -> None:
"""
Reset the mode of whether to show the full stack trace with function wrapping
traces.
Examples
--------
>>> ivy.set_show_func_wrapper_trace_mode(False)
>>> ivy.show_func_wrapper_trace_mode
False
>>> ivy.unset_show_func_wrapper_trace_mode()
>>> ivy.show_func_wrapper_trace_mode
True
"""
global show_func_wrapper_trace_mode_stack
if show_func_wrapper_trace_mode_stack:
show_func_wrapper_trace_mode_stack.pop(-1)
mode = (
show_func_wrapper_trace_mode_stack[-1]
if show_func_wrapper_trace_mode_stack
else True
)
ivy.__setattr__("show_func_wrapper_trace_mode", mode, True)
@handle_exceptions
@handle_nestable
@handle_array_like_without_promotion
@inputs_to_native_arrays
@handle_array_function
def array_equal(
x0: Union[ivy.Array, ivy.NativeArray],
x1: Union[ivy.Array, ivy.NativeArray],
/,
) -> bool:
"""
Determine whether two input arrays are equal across all elements.
Parameters
----------
x0
The first input array to compare.
x1
The second input array to compare.
Returns
-------
ret
Boolean, whether or not the input arrays are equal across all elements.
Examples
--------
>>> x = ivy.array([1,0,1])
>>> y = ivy.array([1,0,-1])
>>> z = ivy.array_equal(x,y)
>>> print(z)
False
>>> a = ivy.array([1, 2])
>>> b = ivy.array([1, 2])
>>> c = ivy.array_equal(a,b)
>>> print(c)
True
>>> i = ivy.array([1, 2])
>>> j = ivy.array([1, 2, 3])
>>> k = ivy.array_equal(i,j)
>>> print(k)
False
"""
return current_backend(x0).array_equal(x0, x1)
@handle_exceptions
@handle_nestable
@inputs_to_ivy_arrays
@handle_array_function
def all_equal(
*xs: Iterable[Any], equality_matrix: bool = False
) -> Union[bool, ivy.Array, ivy.NativeArray]:
"""
Determine whether the inputs are all equal.
Parameters
----------
xs
inputs to compare.
equality_matrix
Whether to return a matrix of equalities comparing each input with every other.
Default is ``False``.
Returns
-------
ret
Boolean, whether or not the inputs are equal, or matrix array of booleans if
equality_matrix=True is set.
Examples
--------
With :class:`ivy.Array` inputs:
>>> x1 = ivy.array([1, 1, 0, 0, 1, -1])
>>> x2 = ivy.array([1, 1, 0, 0, 1, -1])
>>> y = ivy.all_equal(x1, x2)
>>> print(y)
True
>>> x1 = ivy.array([0, 0])
>>> x2 = ivy.array([0, 0])
>>> x3 = ivy.array([1, 0])
>>> y = ivy.all_equal(x1, x2, x3, equality_matrix=True)
>>> print(y)
ivy.array([[ True, True, False],
[ True, True, False],
[False, False, True]])
With one :class:`ivy.Container` inputs:
>>> x1 = ivy.Container(a=ivy.array([0, 0, -1, 1, 0]),
... b=ivy.array([0, 0, -1, 1, 0]))
>>> x2 = ivy.array([0, 0, -1, 1, 0])
>>> y = ivy.all_equal(x1, x2, equality_matrix=False)
>>> print(y)
{
a: true,
b: true
}
With multiple :class:`ivy.Container` inputs:
>>> x1 = ivy.Container(a=ivy.array([1, 0, 1, 1]),
... b=ivy.array([1, 0, 0, 1]))
>>> x2 = ivy.Container(a=ivy.array([1, 0, 1, 1]),
... b=ivy.array([1, 0, -1, -1]))
>>> y = ivy.all_equal(x1, x2, equality_matrix=False)
>>> print(y)
{
a: true,
b: false
}
"""
equality_fn = ivy.array_equal if ivy.is_array(xs[0]) else lambda a, b: a == b
if equality_matrix:
num_arrays = len(xs)
mat = [[None for _ in range(num_arrays)] for _ in range(num_arrays)]
for i, xa in enumerate(xs):
for j_, xb in enumerate(xs[i:]):
j = j_ + i
res = equality_fn(xa, xb)
if ivy.is_native_array(res):
# noinspection PyTypeChecker
res = ivy.to_scalar(res)
# noinspection PyTypeChecker
mat[i][j] = res
# noinspection PyTypeChecker
mat[j][i] = res
return ivy.array(mat)
x0 = xs[0]
for x in xs[1:]:
if not equality_fn(x0, x):
return False
return True
@handle_exceptions
@handle_nestable
@handle_array_like_without_promotion
@inputs_to_native_arrays
@handle_array_function
def to_numpy(
x: Union[ivy.Array, ivy.NativeArray], /, *, copy: bool = True
) -> np.ndarray:
"""
Convert an array into a numpy array.
Parameters
----------
x
input array
copy
whether to copy the array to a new address or not.
Default is ``True``.
Returns
-------
ret
a numpy array copying all the element of the array ``x``.
Examples
--------
With :class:`ivy.Array` inputs:
>>> x = ivy.array([-1, 0, 1])
>>> y = ivy.to_numpy(x, copy=True)
>>> print(y)
[-1 0 1]
>>> x = ivy.array([[-1, 0, 1],[-1, 0, 1], [1,0,-1]])
>>> y = ivy.to_numpy(x, copy=True)
>>> print(y)
[[-1 0 1]
[-1 0 1]
[ 1 0 -1]]
With :class:`ivy.Container` input:
>>> x = ivy.Container(a=ivy.array([-1, 0, 1]))
>>> y = ivy.to_numpy(x)
>>> print(y)
{
a: array([-1, 0, 1], dtype=int32)
}
>>> x = ivy.Container(a=ivy.array([[-1.0, 0., 1.], [-1, 0, 1], [1, 0, -1]]),
... b=ivy.array([[-1, 0, 0], [1, 0, 1], [1, 1, 1]]))
>>> y = ivy.to_numpy(x)
>>> print(y)
{
a: array([[-1., 0., 1.],
[-1., 0., 1.],
[1., 0., -1.]], dtype=float32),
b: array([[-1, 0, 0],
[1, 0, 1],
[1, 1, 1]], dtype=int32)
}
"""
return current_backend(x).to_numpy(x, copy=copy)
@handle_exceptions
@handle_nestable
def isscalar(x: Any, /) -> bool:
return np.isscalar(x)
@handle_exceptions
@handle_nestable
@handle_array_like_without_promotion
@inputs_to_native_arrays
@handle_array_function
def to_scalar(x: Union[ivy.Array, ivy.NativeArray], /) -> Number:
"""
Convert an array with a single element into a scalar.
Parameters
----------
x
Input array with a single element.
Returns
-------
ret
a scalar copying the element of the array ``x``.
Both the description and the type hints above assumes an array input for simplicity,
but this function is *nestable*, and therefore also accepts :class:`ivy.Container`
instances in place of any of the arguments.
Functional Examples
-------------------
With :class:`ivy.Array` input:
>>> x = ivy.array([3])
>>> y = ivy.to_scalar(x)
>>> print(y)
3
With a mix of :class:`ivy.Container` and :class:`ivy.Array` input:
>>> x = ivy.Container(a=ivy.array([-1]), b=ivy.array([3]))
>>> y = ivy.to_scalar(x)
>>> print(y)
{
a: -1,
b: 3
}
>>> x = ivy.Container(a=ivy.array([1]), b=ivy.array([0]),
... c=ivy.array([-1]))
>>> y = ivy.to_scalar(x)
>>> print(y)
{
a: 1,
b: 0,
c: -1
}
"""
return current_backend(x).to_scalar(x)
@handle_exceptions
@handle_nestable
@handle_array_like_without_promotion
@inputs_to_native_arrays
@handle_array_function
def to_list(x: Union[ivy.Array, ivy.NativeArray], /) -> List:
"""
Create a (possibly nested) list from input array.
Parameters
----------
x
Input array.
Returns
-------
ret
A list representation of the input array ``x``.
Examples
--------
With :class:`ivy.Array` input:
>>> x = ivy.array([-1, 0, 1])
>>> y = ivy.to_list(x)
>>> print(y)
[-1, 0, 1]
>>> x = ivy.array([[ 1.1, 2.2, 3.3],
... [-4.4, -5.5, -6.6]])
>>> y = ivy.to_list(x)
>>> print(y)
[[1.100000023841858,2.200000047683716,3.299999952316284],
[-4.400000095367432,-5.5,-6.599999904632568]]
>>> x = ivy.array([[[-1, 0, 1],
... [ 1, 0, -1]],
... [[ 1, -1, 0],
... [ 1, 0, -1]]])
>>> y = ivy.to_list(x)
>>> print(y)
[[[-1, 0, 1], [1, 0, -1]], [[1, -1, 0], [1, 0, -1]]]
With a mix of :class:`ivy.Container` and :class:`ivy.Array` input:
>>> x = ivy.Container(a=ivy.array([-1, 0, 1]))
>>> y = ivy.to_list(x)
>>> print(y)
{
a: [-1, 0, 1]
}
>>> x = ivy.Container(a=ivy.array([[-1, 0, 1],
... [-1, 0, 1],
... [1, 0, -1]]))
>>> y = ivy.to_list(x)
>>> print(y)
{
a: [[-1, 0, 1], [-1, 0, 1], [1,0,-1]]
}
>>> x = ivy.Container(a=ivy.array([[[-1, 0, 1],[1, 0, -1]],
... [[1, -1, 0],[1, 0, -1]]]))
>>> y = ivy.to_list(x)
>>> print(y)
{
a: [[[-1, 0, 1], [1, 0, -1]], [[1, -1, 0], [1, 0, -1]]]
}
"""
return current_backend(x).to_list(x)
@handle_exceptions
@handle_nestable
@inputs_to_ivy_arrays
@handle_array_function
def clip_vector_norm(
x: Union[ivy.Array, ivy.NativeArray],
max_norm: float,
/,
*,
p: float = 2.0,
out: Optional[ivy.Array] = None,
) -> ivy.Array:
"""
Clips (limits) the vector p-norm of an array.