/
arraymath.py
4727 lines (3762 loc) · 143 KB
/
arraymath.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
"""
Implementation of math operations on Array objects.
"""
import math
from collections import namedtuple
from enum import IntEnum
from functools import partial
import operator
import numpy as np
import llvmlite.llvmpy.core as lc
from numba import generated_jit
from numba.core import types, cgutils
from numba.core.extending import overload, overload_method, register_jitable
from numba.np.numpy_support import as_dtype, type_can_asarray
from numba.np.numpy_support import numpy_version
from numba.np.numpy_support import is_nonelike, check_is_integer
from numba.core.imputils import (lower_builtin, impl_ret_borrowed,
impl_ret_new_ref, impl_ret_untracked)
from numba.core.typing import signature
from numba.np.arrayobj import make_array, load_item, store_item, _empty_nd_impl
from numba.np.linalg import ensure_blas
from numba.core.extending import intrinsic
from numba.core.errors import (RequireLiteralValue, TypingError,
NumbaValueError, NumbaNotImplementedError,
NumbaTypeError)
from numba.core.overload_glue import glue_lowering
from numba.cpython.unsafe.tuple import tuple_setitem
def _check_blas():
# Checks if a BLAS is available so e.g. dot will work
try:
ensure_blas()
except ImportError:
return False
return True
_HAVE_BLAS = _check_blas()
@intrinsic
def _create_tuple_result_shape(tyctx, shape_list, shape_tuple):
"""
This routine converts shape list where the axis dimension has already
been popped to a tuple for indexing of the same size. The original shape
tuple is also required because it contains a length field at compile time
whereas the shape list does not.
"""
# The new tuple's size is one less than the original tuple since axis
# dimension removed.
nd = len(shape_tuple) - 1
# The return type of this intrinsic is an int tuple of length nd.
tupty = types.UniTuple(types.intp, nd)
# The function signature for this intrinsic.
function_sig = tupty(shape_list, shape_tuple)
def codegen(cgctx, builder, signature, args):
lltupty = cgctx.get_value_type(tupty)
# Create an empty int tuple.
tup = cgutils.get_null_value(lltupty)
# Get the shape list from the args and we don't need shape tuple.
[in_shape, _] = args
def array_indexer(a, i):
return a[i]
# loop to fill the tuple
for i in range(nd):
dataidx = cgctx.get_constant(types.intp, i)
# compile and call array_indexer
data = cgctx.compile_internal(builder, array_indexer,
types.intp(shape_list, types.intp),
[in_shape, dataidx])
tup = builder.insert_value(tup, data, i)
return tup
return function_sig, codegen
@intrinsic
def _gen_index_tuple(tyctx, shape_tuple, value, axis):
"""
Generates a tuple that can be used to index a specific slice from an
array for sum with axis. shape_tuple is the size of the dimensions of
the input array. 'value' is the value to put in the indexing tuple
in the axis dimension and 'axis' is that dimension. For this to work,
axis has to be a const.
"""
if not isinstance(axis, types.Literal):
raise RequireLiteralValue('axis argument must be a constant')
# Get the value of the axis constant.
axis_value = axis.literal_value
# The length of the indexing tuple to be output.
nd = len(shape_tuple)
# If the axis value is impossible for the given size array then
# just fake it like it was for axis 0. This will stop compile errors
# when it looks like it could be called from array_sum_axis but really
# can't because that routine checks the axis mismatch and raise an
# exception.
if axis_value >= nd:
axis_value = 0
# Calculate the type of the indexing tuple. All the non-axis
# dimensions have slice2 type and the axis dimension has int type.
before = axis_value
after = nd - before - 1
types_list = []
types_list += [types.slice2_type] * before
types_list += [types.intp]
types_list += [types.slice2_type] * after
# Creates the output type of the function.
tupty = types.Tuple(types_list)
# Defines the signature of the intrinsic.
function_sig = tupty(shape_tuple, value, axis)
def codegen(cgctx, builder, signature, args):
lltupty = cgctx.get_value_type(tupty)
# Create an empty indexing tuple.
tup = cgutils.get_null_value(lltupty)
# We only need value of the axis dimension here.
# The rest are constants defined above.
[_, value_arg, _] = args
def create_full_slice():
return slice(None, None)
# loop to fill the tuple with slice(None,None) before
# the axis dimension.
# compile and call create_full_slice
slice_data = cgctx.compile_internal(builder, create_full_slice,
types.slice2_type(),
[])
for i in range(0, axis_value):
tup = builder.insert_value(tup, slice_data, i)
# Add the axis dimension 'value'.
tup = builder.insert_value(tup, value_arg, axis_value)
# loop to fill the tuple with slice(None,None) after
# the axis dimension.
for i in range(axis_value + 1, nd):
tup = builder.insert_value(tup, slice_data, i)
return tup
return function_sig, codegen
#----------------------------------------------------------------------------
# Basic stats and aggregates
@lower_builtin(np.sum, types.Array)
@lower_builtin("array.sum", types.Array)
def array_sum(context, builder, sig, args):
zero = sig.return_type(0)
def array_sum_impl(arr):
c = zero
for v in np.nditer(arr):
c += v.item()
return c
res = context.compile_internal(builder, array_sum_impl, sig, args,
locals=dict(c=sig.return_type))
return impl_ret_borrowed(context, builder, sig.return_type, res)
@register_jitable
def _array_sum_axis_nop(arr, v):
return arr
def gen_sum_axis_impl(is_axis_const, const_axis_val, op, zero):
def inner(arr, axis):
"""
function that performs sums over one specific axis
The third parameter to gen_index_tuple that generates the indexing
tuples has to be a const so we can't just pass "axis" through since
that isn't const. We can check for specific values and have
different instances that do take consts. Supporting axis summation
only up to the fourth dimension for now.
typing/arraydecl.py:sum_expand defines the return type for sum with
axis. It is one dimension less than the input array.
"""
ndim = arr.ndim
if not is_axis_const:
# Catch where axis is negative or greater than 3.
if axis < 0 or axis > 3:
raise ValueError("Numba does not support sum with axis "
"parameter outside the range 0 to 3.")
# Catch the case where the user misspecifies the axis to be
# more than the number of the array's dimensions.
if axis >= ndim:
raise ValueError("axis is out of bounds for array")
# Convert the shape of the input array to a list.
ashape = list(arr.shape)
# Get the length of the axis dimension.
axis_len = ashape[axis]
# Remove the axis dimension from the list of dimensional lengths.
ashape.pop(axis)
# Convert this shape list back to a tuple using above intrinsic.
ashape_without_axis = _create_tuple_result_shape(ashape, arr.shape)
# Tuple needed here to create output array with correct size.
result = np.full(ashape_without_axis, zero, type(zero))
# Iterate through the axis dimension.
for axis_index in range(axis_len):
if is_axis_const:
# constant specialized version works for any valid axis value
index_tuple_generic = _gen_index_tuple(arr.shape, axis_index,
const_axis_val)
result += arr[index_tuple_generic]
else:
# Generate a tuple used to index the input array.
# The tuple is ":" in all dimensions except the axis
# dimension where it is "axis_index".
if axis == 0:
index_tuple1 = _gen_index_tuple(arr.shape, axis_index, 0)
result += arr[index_tuple1]
elif axis == 1:
index_tuple2 = _gen_index_tuple(arr.shape, axis_index, 1)
result += arr[index_tuple2]
elif axis == 2:
index_tuple3 = _gen_index_tuple(arr.shape, axis_index, 2)
result += arr[index_tuple3]
elif axis == 3:
index_tuple4 = _gen_index_tuple(arr.shape, axis_index, 3)
result += arr[index_tuple4]
return op(result, 0)
return inner
@lower_builtin(np.sum, types.Array, types.intp, types.DTypeSpec)
@lower_builtin(np.sum, types.Array, types.IntegerLiteral, types.DTypeSpec)
@lower_builtin("array.sum", types.Array, types.intp, types.DTypeSpec)
@lower_builtin("array.sum", types.Array, types.IntegerLiteral, types.DTypeSpec)
def array_sum_axis_dtype(context, builder, sig, args):
retty = sig.return_type
zero = getattr(retty, 'dtype', retty)(0)
# if the return is scalar in type then "take" the 0th element of the
# 0d array accumulator as the return value
if getattr(retty, 'ndim', None) is None:
op = np.take
else:
op = _array_sum_axis_nop
[ty_array, ty_axis, ty_dtype] = sig.args
is_axis_const = False
const_axis_val = 0
if isinstance(ty_axis, types.Literal):
# this special-cases for constant axis
const_axis_val = ty_axis.literal_value
# fix negative axis
if const_axis_val < 0:
const_axis_val = ty_array.ndim + const_axis_val
if const_axis_val < 0 or const_axis_val > ty_array.ndim:
raise ValueError("'axis' entry is out of bounds")
ty_axis = context.typing_context.resolve_value_type(const_axis_val)
axis_val = context.get_constant(ty_axis, const_axis_val)
# rewrite arguments
args = args[0], axis_val, args[2]
# rewrite sig
sig = sig.replace(args=[ty_array, ty_axis, ty_dtype])
is_axis_const = True
gen_impl = gen_sum_axis_impl(is_axis_const, const_axis_val, op, zero)
compiled = register_jitable(gen_impl)
def array_sum_impl_axis(arr, axis, dtype):
return compiled(arr, axis)
res = context.compile_internal(builder, array_sum_impl_axis, sig, args)
return impl_ret_new_ref(context, builder, sig.return_type, res)
@lower_builtin(np.sum, types.Array, types.DTypeSpec)
@lower_builtin("array.sum", types.Array, types.DTypeSpec)
def array_sum_dtype(context, builder, sig, args):
zero = sig.return_type(0)
def array_sum_impl(arr, dtype):
c = zero
for v in np.nditer(arr):
c += v.item()
return c
res = context.compile_internal(builder, array_sum_impl, sig, args,
locals=dict(c=sig.return_type))
return impl_ret_borrowed(context, builder, sig.return_type, res)
@lower_builtin(np.sum, types.Array, types.intp)
@lower_builtin(np.sum, types.Array, types.IntegerLiteral)
@lower_builtin("array.sum", types.Array, types.intp)
@lower_builtin("array.sum", types.Array, types.IntegerLiteral)
def array_sum_axis(context, builder, sig, args):
retty = sig.return_type
zero = getattr(retty, 'dtype', retty)(0)
# if the return is scalar in type then "take" the 0th element of the
# 0d array accumulator as the return value
if getattr(retty, 'ndim', None) is None:
op = np.take
else:
op = _array_sum_axis_nop
[ty_array, ty_axis] = sig.args
is_axis_const = False
const_axis_val = 0
if isinstance(ty_axis, types.Literal):
# this special-cases for constant axis
const_axis_val = ty_axis.literal_value
# fix negative axis
if const_axis_val < 0:
const_axis_val = ty_array.ndim + const_axis_val
if const_axis_val < 0 or const_axis_val > ty_array.ndim:
msg = f"'axis' entry ({const_axis_val}) is out of bounds"
raise NumbaValueError(msg)
ty_axis = context.typing_context.resolve_value_type(const_axis_val)
axis_val = context.get_constant(ty_axis, const_axis_val)
# rewrite arguments
args = args[0], axis_val
# rewrite sig
sig = sig.replace(args=[ty_array, ty_axis])
is_axis_const = True
gen_impl = gen_sum_axis_impl(is_axis_const, const_axis_val, op, zero)
compiled = register_jitable(gen_impl)
def array_sum_impl_axis(arr, axis):
return compiled(arr, axis)
res = context.compile_internal(builder, array_sum_impl_axis, sig, args)
return impl_ret_new_ref(context, builder, sig.return_type, res)
@lower_builtin(np.prod, types.Array)
@lower_builtin("array.prod", types.Array)
def array_prod(context, builder, sig, args):
def array_prod_impl(arr):
c = 1
for v in np.nditer(arr):
c *= v.item()
return c
res = context.compile_internal(builder, array_prod_impl, sig, args,
locals=dict(c=sig.return_type))
return impl_ret_borrowed(context, builder, sig.return_type, res)
@lower_builtin(np.cumsum, types.Array)
@lower_builtin("array.cumsum", types.Array)
def array_cumsum(context, builder, sig, args):
scalar_dtype = sig.return_type.dtype
dtype = as_dtype(scalar_dtype)
zero = scalar_dtype(0)
def array_cumsum_impl(arr):
out = np.empty(arr.size, dtype)
c = zero
for idx, v in enumerate(arr.flat):
c += v
out[idx] = c
return out
res = context.compile_internal(builder, array_cumsum_impl, sig, args,
locals=dict(c=scalar_dtype))
return impl_ret_new_ref(context, builder, sig.return_type, res)
@lower_builtin(np.cumprod, types.Array)
@lower_builtin("array.cumprod", types.Array)
def array_cumprod(context, builder, sig, args):
scalar_dtype = sig.return_type.dtype
dtype = as_dtype(scalar_dtype)
def array_cumprod_impl(arr):
out = np.empty(arr.size, dtype)
c = 1
for idx, v in enumerate(arr.flat):
c *= v
out[idx] = c
return out
res = context.compile_internal(builder, array_cumprod_impl, sig, args,
locals=dict(c=scalar_dtype))
return impl_ret_new_ref(context, builder, sig.return_type, res)
@lower_builtin(np.mean, types.Array)
@lower_builtin("array.mean", types.Array)
def array_mean(context, builder, sig, args):
zero = sig.return_type(0)
def array_mean_impl(arr):
# Can't use the naive `arr.sum() / arr.size`, as it would return
# a wrong result on integer sum overflow.
c = zero
for v in np.nditer(arr):
c += v.item()
return c / arr.size
res = context.compile_internal(builder, array_mean_impl, sig, args,
locals=dict(c=sig.return_type))
return impl_ret_untracked(context, builder, sig.return_type, res)
@lower_builtin(np.var, types.Array)
@lower_builtin("array.var", types.Array)
def array_var(context, builder, sig, args):
def array_var_impl(arr):
# Compute the mean
m = arr.mean()
# Compute the sum of square diffs
ssd = 0
for v in np.nditer(arr):
val = (v.item() - m)
ssd += np.real(val * np.conj(val))
return ssd / arr.size
res = context.compile_internal(builder, array_var_impl, sig, args)
return impl_ret_untracked(context, builder, sig.return_type, res)
@lower_builtin(np.std, types.Array)
@lower_builtin("array.std", types.Array)
def array_std(context, builder, sig, args):
def array_std_impl(arry):
return arry.var() ** 0.5
res = context.compile_internal(builder, array_std_impl, sig, args)
return impl_ret_untracked(context, builder, sig.return_type, res)
def zero_dim_msg(fn_name):
msg = ("zero-size array to reduction operation "
"{0} which has no identity".format(fn_name))
return msg
def _is_nat(x):
pass
@overload(_is_nat)
def ol_is_nat(x):
if numpy_version >= (1, 18):
return lambda x: np.isnat(x)
else:
nat = x('NaT')
return lambda x: x == nat
@lower_builtin(np.min, types.Array)
@lower_builtin("array.min", types.Array)
def array_min(context, builder, sig, args):
ty = sig.args[0].dtype
MSG = zero_dim_msg('minimum')
if isinstance(ty, (types.NPDatetime, types.NPTimedelta)):
# NP < 1.18: NaT is smaller than every other value, but it is
# ignored as far as min() is concerned.
# NP >= 1.18: NaT dominates like NaN
def array_min_impl(arry):
if arry.size == 0:
raise ValueError(MSG)
it = np.nditer(arry)
min_value = next(it).take(0)
if _is_nat(min_value):
return min_value
for view in it:
v = view.item()
if _is_nat(v):
if numpy_version >= (1, 18):
return v
else:
continue
if v < min_value:
min_value = v
return min_value
elif isinstance(ty, types.Complex):
def array_min_impl(arry):
if arry.size == 0:
raise ValueError(MSG)
it = np.nditer(arry)
min_value = next(it).take(0)
for view in it:
v = view.item()
if v.real < min_value.real:
min_value = v
elif v.real == min_value.real:
if v.imag < min_value.imag:
min_value = v
return min_value
elif isinstance(ty, types.Float):
def array_min_impl(arry):
if arry.size == 0:
raise ValueError(MSG)
it = np.nditer(arry)
min_value = next(it).take(0)
if np.isnan(min_value):
return min_value
for view in it:
v = view.item()
if np.isnan(v):
return v
if v < min_value:
min_value = v
return min_value
else:
def array_min_impl(arry):
if arry.size == 0:
raise ValueError(MSG)
it = np.nditer(arry)
min_value = next(it).take(0)
for view in it:
v = view.item()
if v < min_value:
min_value = v
return min_value
res = context.compile_internal(builder, array_min_impl, sig, args)
return impl_ret_borrowed(context, builder, sig.return_type, res)
@lower_builtin(np.max, types.Array)
@lower_builtin("array.max", types.Array)
def array_max(context, builder, sig, args):
ty = sig.args[0].dtype
MSG = zero_dim_msg('maximum')
if isinstance(ty, (types.NPDatetime, types.NPTimedelta)):
# NP < 1.18: NaT is smaller than every other value, but it is
# ignored as far as min() is concerned.
# NP >= 1.18: NaT dominates like NaN
def array_max_impl(arry):
if arry.size == 0:
raise ValueError(MSG)
it = np.nditer(arry)
max_value = next(it).take(0)
if _is_nat(max_value):
return max_value
for view in it:
v = view.item()
if _is_nat(v):
if numpy_version >= (1, 18):
return v
else:
continue
if v > max_value:
max_value = v
return max_value
elif isinstance(ty, types.Complex):
def array_max_impl(arry):
if arry.size == 0:
raise ValueError(MSG)
it = np.nditer(arry)
max_value = next(it).take(0)
for view in it:
v = view.item()
if v.real > max_value.real:
max_value = v
elif v.real == max_value.real:
if v.imag > max_value.imag:
max_value = v
return max_value
elif isinstance(ty, types.Float):
def array_max_impl(arry):
if arry.size == 0:
raise ValueError(MSG)
it = np.nditer(arry)
max_value = next(it).take(0)
if np.isnan(max_value):
return max_value
for view in it:
v = view.item()
if np.isnan(v):
return v
if v > max_value:
max_value = v
return max_value
else:
def array_max_impl(arry):
if arry.size == 0:
raise ValueError(MSG)
it = np.nditer(arry)
max_value = next(it).take(0)
for view in it:
v = view.item()
if v > max_value:
max_value = v
return max_value
res = context.compile_internal(builder, array_max_impl, sig, args)
return impl_ret_borrowed(context, builder, sig.return_type, res)
@register_jitable
def array_argmin_impl_datetime(arry):
if arry.size == 0:
raise ValueError("attempt to get argmin of an empty sequence")
it = np.nditer(arry)
min_value = next(it).take(0)
min_idx = 0
if _is_nat(min_value):
return min_idx
idx = 1
for view in it:
v = view.item()
if _is_nat(v):
if numpy_version >= (1, 18):
return idx
else:
idx += 1
continue
if v < min_value:
min_value = v
min_idx = idx
idx += 1
return min_idx
@register_jitable
def array_argmin_impl_float(arry):
if arry.size == 0:
raise ValueError("attempt to get argmin of an empty sequence")
for v in arry.flat:
min_value = v
min_idx = 0
break
if np.isnan(min_value):
return min_idx
idx = 0
for v in arry.flat:
if np.isnan(v):
return idx
if v < min_value:
min_value = v
min_idx = idx
idx += 1
return min_idx
@register_jitable
def array_argmin_impl_generic(arry):
if arry.size == 0:
raise ValueError("attempt to get argmin of an empty sequence")
for v in arry.flat:
min_value = v
min_idx = 0
break
else:
raise RuntimeError('unreachable')
idx = 0
for v in arry.flat:
if v < min_value:
min_value = v
min_idx = idx
idx += 1
return min_idx
@overload(np.argmin)
@overload_method(types.Array, "argmin")
def array_argmin(arr, axis=None):
if isinstance(arr.dtype, (types.NPDatetime, types.NPTimedelta)):
flatten_impl = array_argmin_impl_datetime
elif isinstance(arr.dtype, types.Float):
flatten_impl = array_argmin_impl_float
else:
flatten_impl = array_argmin_impl_generic
if is_nonelike(axis):
def array_argmin_impl(arr, axis=None):
return flatten_impl(arr)
else:
array_argmin_impl = build_argmax_or_argmin_with_axis_impl(
arr, axis, flatten_impl
)
return array_argmin_impl
@register_jitable
def array_argmax_impl_datetime(arry):
if arry.size == 0:
raise ValueError("attempt to get argmax of an empty sequence")
it = np.nditer(arry)
max_value = next(it).take(0)
max_idx = 0
if _is_nat(max_value):
return max_idx
idx = 1
for view in it:
v = view.item()
if _is_nat(v):
if numpy_version >= (1, 18):
return idx
else:
idx += 1
continue
if v > max_value:
max_value = v
max_idx = idx
idx += 1
return max_idx
@register_jitable
def array_argmax_impl_float(arry):
if arry.size == 0:
raise ValueError("attempt to get argmax of an empty sequence")
for v in arry.flat:
max_value = v
max_idx = 0
break
if np.isnan(max_value):
return max_idx
idx = 0
for v in arry.flat:
if np.isnan(v):
return idx
if v > max_value:
max_value = v
max_idx = idx
idx += 1
return max_idx
@register_jitable
def array_argmax_impl_generic(arry):
if arry.size == 0:
raise ValueError("attempt to get argmax of an empty sequence")
for v in arry.flat:
max_value = v
max_idx = 0
break
idx = 0
for v in arry.flat:
if v > max_value:
max_value = v
max_idx = idx
idx += 1
return max_idx
def build_argmax_or_argmin_with_axis_impl(arr, axis, flatten_impl):
"""
Given a function that implements the logic for handling a flattened
array, return the implementation function.
"""
check_is_integer(axis, "axis")
retty = arr.dtype
tuple_buffer = tuple(range(arr.ndim))
def impl(arr, axis=None):
if axis < 0:
axis = arr.ndim + axis
if axis < 0 or axis >= arr.ndim:
raise ValueError("axis is out of bounds")
# Short circuit 1-dimensional arrays:
if arr.ndim == 1:
return flatten_impl(arr)
# Make chosen axis the last axis:
tmp = tuple_buffer
for i in range(axis, arr.ndim - 1):
tmp = tuple_setitem(tmp, i, i + 1)
transpose_index = tuple_setitem(tmp, arr.ndim - 1, axis)
transposed_arr = arr.transpose(transpose_index)
# Flatten along that axis; since we've transposed, we can just get
# batches off the overall flattened array.
m = transposed_arr.shape[-1]
raveled = transposed_arr.ravel()
assert raveled.size == arr.size
assert transposed_arr.size % m == 0
out = np.empty(transposed_arr.size // m, retty)
for i in range(out.size):
out[i] = flatten_impl(raveled[i * m:(i + 1) * m])
# Reshape based on axis we didn't flatten over:
return out.reshape(transposed_arr.shape[:-1])
return impl
@overload(np.argmax)
@overload_method(types.Array, "argmax")
def array_argmax(arr, axis=None):
if isinstance(arr.dtype, (types.NPDatetime, types.NPTimedelta)):
flatten_impl = array_argmax_impl_datetime
elif isinstance(arr.dtype, types.Float):
flatten_impl = array_argmax_impl_float
else:
flatten_impl = array_argmax_impl_generic
if is_nonelike(axis):
def array_argmax_impl(arr, axis=None):
return flatten_impl(arr)
else:
array_argmax_impl = build_argmax_or_argmin_with_axis_impl(
arr, axis, flatten_impl
)
return array_argmax_impl
@overload(np.all)
@overload_method(types.Array, "all")
def np_all(a):
def flat_all(a):
for v in np.nditer(a):
if not v.item():
return False
return True
return flat_all
@overload(np.any)
@overload_method(types.Array, "any")
def np_any(a):
def flat_any(a):
for v in np.nditer(a):
if v.item():
return True
return False
return flat_any
@overload(np.average)
def np_average(arr, axis=None, weights=None):
if weights is None or isinstance(weights, types.NoneType):
def np_average_impl(arr, axis=None, weights=None):
arr = np.asarray(arr)
return np.mean(arr)
else:
if axis is None or isinstance(axis, types.NoneType):
def np_average_impl(arr, axis=None, weights=None):
arr = np.asarray(arr)
weights = np.asarray(weights)
if arr.shape != weights.shape:
if axis is None:
raise TypeError(
"Numba does not support average when shapes of "
"a and weights differ.")
if weights.ndim != 1:
raise TypeError(
"1D weights expected when shapes of "
"a and weights differ.")
scl = np.sum(weights)
if scl == 0.0:
raise ZeroDivisionError(
"Weights sum to zero, can't be normalized.")
avg = np.sum(np.multiply(arr, weights)) / scl
return avg
else:
def np_average_impl(arr, axis=None, weights=None):
raise TypeError("Numba does not support average with axis.")
return np_average_impl
def get_isnan(dtype):
"""
A generic isnan() function
"""
if isinstance(dtype, (types.Float, types.Complex)):
return np.isnan
else:
@register_jitable
def _trivial_isnan(x):
return False
return _trivial_isnan
@overload(np.iscomplex)
def np_iscomplex(x):
if type_can_asarray(x):
# NumPy uses asanyarray here!
return lambda x: np.asarray(x).imag != 0
return None
@overload(np.isreal)
def np_isreal(x):
if type_can_asarray(x):
# NumPy uses asanyarray here!
return lambda x: np.asarray(x).imag == 0
return None
@overload(np.iscomplexobj)
def iscomplexobj(x):
# Implementation based on NumPy
# https://github.com/numpy/numpy/blob/d9b1e32cb8ef90d6b4a47853241db2a28146a57d/numpy/lib/type_check.py#L282-L320
dt = determine_dtype(x)
if isinstance(x, types.Optional):
dt = determine_dtype(x.type)
iscmplx = np.issubdtype(dt, np.complexfloating)
if isinstance(x, types.Optional):
def impl(x):
if x is None:
return False
return iscmplx
else:
def impl(x):
return iscmplx
return impl
@overload(np.isrealobj)
def isrealobj(x):
# Return True if x is not a complex type.
# Implementation based on NumPy
# https://github.com/numpy/numpy/blob/ccfbcc1cd9a4035a467f2e982a565ab27de25b6b/numpy/lib/type_check.py#L290-L322
def impl(x):
return not np.iscomplexobj(x)
return impl
@overload(np.isscalar)
def np_isscalar(num):
res = isinstance(num, (types.Number, types.UnicodeType, types.Boolean))
def impl(num):
return res
return impl
def is_np_inf_impl(x, out, fn):
# if/else branch should be unified after PR #5606 is merged
if is_nonelike(out):
def impl(x, out=None):
return np.logical_and(np.isinf(x), fn(np.signbit(x)))
else:
def impl(x, out=None):
return np.logical_and(np.isinf(x), fn(np.signbit(x)), out)
return impl
@overload(np.isneginf)
def isneginf(x, out=None):
fn = register_jitable(lambda x: x)