-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
test_np_functions.py
4863 lines (3848 loc) · 155 KB
/
test_np_functions.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
# Tests numpy methods of <class 'function'>
import itertools
import math
import platform
from functools import partial
import warnings
import numpy as np
from numba.core.compiler import Flags
from numba import jit, njit, typeof
from numba.core import types
from numba.typed import List, Dict
from numba.np.numpy_support import numpy_version
from numba.core.errors import TypingError, NumbaDeprecationWarning
from numba.core.config import IS_WIN32, IS_32BITS
from numba.core.utils import pysignature
from numba.np.extensions import cross2d
from numba.tests.support import (TestCase, CompilationCache, MemoryLeakMixin,
needs_blas)
import unittest
no_pyobj_flags = Flags()
no_pyobj_flags.nrt = True
def sinc(x):
return np.sinc(x)
def angle1(x):
return np.angle(x)
def angle2(x, deg):
return np.angle(x, deg)
def array_equal(a, b):
return np.array_equal(a, b)
def intersect1d(a, b):
return np.intersect1d(a, b)
def append(arr, values, axis):
return np.append(arr, values, axis=axis)
def count_nonzero(arr, axis):
return np.count_nonzero(arr, axis=axis)
def delete(arr, obj):
return np.delete(arr, obj)
def diff1(a):
return np.diff(a)
def diff2(a, n):
return np.diff(a, n)
def bincount1(a):
return np.bincount(a)
def bincount2(a, w):
return np.bincount(a, weights=w)
def bincount3(a, w=None, minlength=0):
return np.bincount(a, w, minlength)
def searchsorted(a, v):
return np.searchsorted(a, v)
def searchsorted_left(a, v):
return np.searchsorted(a, v, side='left')
def searchsorted_right(a, v):
return np.searchsorted(a, v, side='right')
def digitize(*args):
return np.digitize(*args)
def histogram(*args):
return np.histogram(*args)
def machar(*args):
return np.MachAr()
def iscomplex(x):
return np.iscomplex(x)
def iscomplexobj(x):
return np.iscomplexobj(x)
def isscalar(x):
return np.isscalar(x)
def isreal(x):
return np.isreal(x)
def isrealobj(x):
return np.isrealobj(x)
def isneginf(x, out=None):
return np.isneginf(x, out)
def isposinf(x, out=None):
return np.isposinf(x, out)
def isnat(x):
return np.isnat(x)
def iinfo(*args):
return np.iinfo(*args)
def finfo(*args):
return np.finfo(*args)
def finfo_machar(*args):
return np.finfo(*args).machar
def fliplr(a):
return np.fliplr(a)
def flipud(a):
return np.flipud(a)
def flip(a):
return np.flip(a)
def logspace2(start, stop):
return np.logspace(start, stop)
def logspace3(start, stop, num=50):
return np.logspace(start, stop, num=num)
def rot90(a):
return np.rot90(a)
def rot90_k(a, k=1):
return np.rot90(a, k)
def array_split(a, indices, axis=0):
return np.array_split(a, indices, axis=axis)
def split(a, indices, axis=0):
return np.split(a, indices, axis=axis)
def correlate(a, v):
return np.correlate(a, v)
def convolve(a, v):
return np.convolve(a, v)
def tri_n(N):
return np.tri(N)
def tri_n_m(N, M=None):
return np.tri(N, M)
def tri_n_k(N, k=0):
return np.tri(N, k)
def tri_n_m_k(N, M=None, k=0):
return np.tri(N, M, k)
def tril_m(m):
return np.tril(m)
def tril_m_k(m, k=0):
return np.tril(m, k)
def tril_indices_n(n):
return np.tril_indices(n)
def tril_indices_n_k(n, k=0):
return np.tril_indices(n, k)
def tril_indices_n_m(n, m=None):
return np.tril_indices(n, m=m)
def tril_indices_n_k_m(n, k=0, m=None):
return np.tril_indices(n, k, m)
def tril_indices_from_arr(arr):
return np.tril_indices_from(arr)
def tril_indices_from_arr_k(arr, k=0):
return np.tril_indices_from(arr, k)
def triu_m(m):
return np.triu(m)
def triu_m_k(m, k=0):
return np.triu(m, k)
def triu_indices_n(n):
return np.triu_indices(n)
def triu_indices_n_k(n, k=0):
return np.triu_indices(n, k)
def triu_indices_n_m(n, m=None):
return np.triu_indices(n, m=m)
def triu_indices_n_k_m(n, k=0, m=None):
return np.triu_indices(n, k, m)
def triu_indices_from_arr(arr):
return np.triu_indices_from(arr)
def triu_indices_from_arr_k(arr, k=0):
return np.triu_indices_from(arr, k)
def vander(x, N=None, increasing=False):
return np.vander(x, N, increasing)
def partition(a, kth):
return np.partition(a, kth)
def cov(m, y=None, rowvar=True, bias=False, ddof=None):
return np.cov(m, y, rowvar, bias, ddof)
def corrcoef(x, y=None, rowvar=True):
return np.corrcoef(x, y, rowvar)
def ediff1d(ary, to_end=None, to_begin=None):
return np.ediff1d(ary, to_end, to_begin)
def roll(a, shift):
return np.roll(a, shift)
def asarray(a):
return np.asarray(a)
def asarray_kws(a, dtype):
return np.asarray(a, dtype=dtype)
def asfarray(a, dtype=np.float64):
return np.asfarray(a, dtype=dtype)
def asfarray_default_kwarg(a):
return np.asfarray(a)
def extract(condition, arr):
return np.extract(condition, arr)
def np_trapz(y):
return np.trapz(y)
def np_trapz_x(y, x):
return np.trapz(y, x)
def np_trapz_dx(y, dx):
return np.trapz(y, dx=dx)
def np_trapz_x_dx(y, x, dx):
return np.trapz(y, x, dx)
def np_allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False):
return np.allclose(a, b, rtol, atol, equal_nan)
def np_average(a, axis=None, weights=None):
return np.average(a, axis=axis, weights=weights)
def interp(x, xp, fp):
return np.interp(x, xp, fp)
def np_repeat(a, repeats):
return np.repeat(a, repeats)
def array_repeat(a, repeats):
return np.asarray(a).repeat(repeats)
def np_select(condlist, choicelist, default=0):
return np.select(condlist, choicelist, default=default)
def np_select_defaults(condlist, choicelist):
return np.select(condlist, choicelist)
def np_bartlett(M):
return np.bartlett(M)
def np_blackman(M):
return np.blackman(M)
def np_hamming(M):
return np.hamming(M)
def np_hanning(M):
return np.hanning(M)
def np_kaiser(M, beta):
return np.kaiser(M, beta)
def np_cross(a, b):
return np.cross(a, b)
def nb_cross2d(a, b):
return cross2d(a, b)
def flip_lr(a):
return np.fliplr(a)
def flip_ud(a):
return np.flipud(a)
def np_asarray_chkfinite(a, dtype=None):
return np.asarray_chkfinite(a, dtype)
def array_contains(a, key):
return key in a
def swapaxes(a, a1, a2):
return np.swapaxes(a, a1, a2)
class TestNPFunctions(MemoryLeakMixin, TestCase):
"""
Tests for various Numpy functions.
"""
def setUp(self):
super(TestNPFunctions, self).setUp()
self.ccache = CompilationCache()
self.rnd = np.random.RandomState(42)
def run_unary(self, pyfunc, x_types, x_values, flags=no_pyobj_flags,
func_extra_types=None, func_extra_args=None,
ignore_sign_on_zero=False, abs_tol=None, **kwargs):
"""
Runs tests for a unary function operating in the numerical real space.
Parameters
----------
pyfunc : a python function definition holding that calls the numpy
functions to be tested.
x_types: the types of the values being tested, see numba.types
x_values: the numerical values of the values to be tested
flags: flags to pass to the CompilationCache::ccache::compile function
func_extra_types: the types of additional arguments to the numpy
function
func_extra_args: additional arguments to the numpy function
ignore_sign_on_zero: boolean as to whether to allow zero values
with incorrect signs to be considered equal
prec: the required precision match, see assertPreciseEqual
Notes:
------
x_types and x_values must have the same length
"""
for tx, vx in zip(x_types, x_values):
if func_extra_args is None:
func_extra_types = func_extra_args = [()]
for xtypes, xargs in zip(func_extra_types, func_extra_args):
cr = self.ccache.compile(pyfunc, (tx,) + xtypes,
flags=flags)
cfunc = cr.entry_point
got = cfunc(vx, *xargs)
expected = pyfunc(vx, *xargs)
try:
scalty = tx.dtype
except AttributeError:
scalty = tx
prec = ('single'
if scalty in (types.float32, types.complex64)
else 'double')
msg = 'for input %r with prec %r' % (vx, prec)
self.assertPreciseEqual(got, expected,
prec=prec,
msg=msg,
ignore_sign_on_zero=ignore_sign_on_zero,
abs_tol=abs_tol, **kwargs)
def test_sinc(self):
"""
Tests the sinc() function.
This test is purely to assert numerical computations are correct.
"""
# Ignore sign of zeros, this will need masking depending on numpy
# version once the fix to numpy complex division is in upstream
# See: https://github.com/numpy/numpy/pull/6699
isoz = True
# Testing sinc(1.) leads to sin(pi)/pi, which is below machine
# precision in practice on most machines. Small floating point
# differences in sin() etc. may lead to large differences in the result
# that are at a range that is inaccessible using standard width
# floating point representations.
# e.g. Assume float64 type.
# sin(pi) ~= 1e-16, but should be zero
# sin(pi)/pi ~= 1e-17, should be zero, error carried from above
# float64 has log10(2^53)~=15.9 digits of precision and the magnitude
# change in the alg is > 16 digits (1.0...0 -> 0.0...0),
# so comparison via ULP is invalid.
# We therefore opt to assume that values under machine precision are
# equal in this case.
tol = "eps"
pyfunc = sinc
def check(x_types, x_values, **kwargs):
self.run_unary(pyfunc, x_types, x_values,
ignore_sign_on_zero=isoz, abs_tol=tol,
**kwargs)
# real domain scalar context
x_values = [1., -1., 0.0, -0.0, 0.5, -0.5, 5, -5, 5e-21, -5e-21]
x_types = [types.float32, types.float64] * (len(x_values) // 2)
check(x_types, x_values)
# real domain vector context
x_values = [np.array(x_values, dtype=np.float64)]
x_types = [typeof(v) for v in x_values]
check(x_types, x_values)
# complex domain scalar context
x_values = [1.+0j, -1+0j, 0.0+0.0j, -0.0+0.0j, 0+1j, 0-1j, 0.5+0.0j, # noqa
-0.5+0.0j, 0.5+0.5j, -0.5-0.5j, 5+5j, -5-5j, # noqa
# the following are to test sin(x)/x for small x
5e-21+0j, -5e-21+0j, 5e-21j, +(0-5e-21j) # noqa
]
x_types = [types.complex64, types.complex128] * (len(x_values) // 2)
check(x_types, x_values, ulps=2)
# complex domain vector context
x_values = [np.array(x_values, dtype=np.complex128)]
x_types = [typeof(v) for v in x_values]
check(x_types, x_values, ulps=2)
def test_sinc_exceptions(self):
pyfunc = sinc
cfunc = jit(nopython=True)(pyfunc)
with self.assertRaises(TypingError) as raises:
cfunc('str')
self.assertIn('Argument "x" must be a Number or array-like',
str(raises.exception))
def test_contains(self):
def arrs():
a_0 = np.arange(10, 50)
k_0 = 20
yield a_0, k_0
a_1 = np.arange(6)
k_1 = 10
yield a_1, k_1
single_val_a = np.asarray([20])
k_in = 20
k_out = 13
yield single_val_a, k_in
yield single_val_a, k_out
empty_arr = np.asarray([])
yield empty_arr, k_out
# np scalars
bool_arr = np.array([True, False])
yield bool_arr, True
yield bool_arr, k_0
np.random.seed(2)
float_arr = np.random.rand(10)
np.random.seed(2)
rand_k = np.random.rand()
present_k = float_arr[0]
yield float_arr, rand_k
yield float_arr, present_k
complx_arr = float_arr.view(np.complex128)
yield complx_arr, complx_arr[0]
yield complx_arr, rand_k
np.random.seed(2)
uint_arr = np.random.randint(10, size=15, dtype=np.uint8)
yield uint_arr, 5
yield uint_arr, 25
pyfunc = array_contains
cfunc = jit(nopython=True)(pyfunc)
for arr, key in arrs():
expected = pyfunc(arr, key)
received = cfunc(arr, key)
self.assertPreciseEqual(expected, received)
def test_angle(self, flags=no_pyobj_flags):
"""
Tests the angle() function.
This test is purely to assert numerical computations are correct.
"""
pyfunc1 = angle1
pyfunc2 = angle2
def check(x_types, x_values):
# angle(x)
self.run_unary(pyfunc1, x_types, x_values)
# angle(x, deg)
xtra_values = [(True,), (False,)]
xtra_types = [(types.bool_,)] * len(xtra_values)
self.run_unary(pyfunc2, x_types, x_values,
func_extra_types=xtra_types,
func_extra_args=xtra_values,)
# real domain scalar context
x_values = [1., -1., 0.0, -0.0, 0.5, -0.5, 5, -5]
x_types = [types.float32, types.float64] * (len(x_values) // 2 + 1)
check(x_types, x_values)
# real domain vector context
x_values = [np.array(x_values, dtype=np.float64)]
x_types = [typeof(v) for v in x_values]
check(x_types, x_values)
# complex domain scalar context
x_values = [1.+0j, -1+0j, 0.0+0.0j, -0.0+0.0j, 1j, -1j, 0.5+0.0j, # noqa
-0.5+0.0j, 0.5+0.5j, -0.5-0.5j, 5+5j, -5-5j] # noqa
x_types = [types.complex64, types.complex128] * (len(x_values) // 2 + 1)
check(x_types, x_values)
# complex domain vector context
x_values = np.array(x_values)
x_types = [types.complex64, types.complex128]
check(x_types, x_values)
def test_angle_exceptions(self):
pyfunc = angle1
cfunc = jit(nopython=True)(pyfunc)
with self.assertRaises(TypingError) as raises:
cfunc('hello')
self.assertIn('Argument "z" must be a complex or Array[complex]',
str(raises.exception))
def test_array_equal(self):
def arrays():
yield np.array([]), np.array([])
yield np.array([1, 2]), np.array([1, 2])
yield np.array([]), np.array([1])
x = np.arange(10).reshape(5, 2)
x[1][1] = 30
yield np.arange(10).reshape(5, 2), x
yield x, x
yield (1, 2, 3), (1, 2, 3)
yield 2, 2
yield 3, 2
yield True, True
yield True, False
yield True, 2
yield True, 1
yield False, 0
pyfunc = array_equal
cfunc = jit(nopython=True)(pyfunc)
for arr, obj in arrays():
expected = pyfunc(arr, obj)
got = cfunc(arr, obj)
self.assertPreciseEqual(expected, got)
def test_array_equal_exception(self):
pyfunc = array_equal
cfunc = jit(nopython=True)(pyfunc)
with self.assertRaises(TypingError) as raises:
cfunc(np.arange(3 * 4).reshape(3, 4), None)
self.assertIn(
'Both arguments to "array_equals" must be array-like',
str(raises.exception)
)
def test_intersect1d(self):
def arrays():
yield [], [] # two empty arrays
yield [1], [] # empty right
yield [], [1] # empty left
yield [1], [2] # singletons no intersection
yield [1], [1] # singletons one intersection
yield [1, 2], [1]
yield [1, 2, 2], [2, 2]
yield [1, 2], [2, 1]
yield [1, 2, 3], [1, 2, 3]
pyfunc = intersect1d
cfunc = jit(nopython=True)(pyfunc)
for a, b in arrays():
a = np.array(a)
b = np.array(b)
expected = pyfunc(a, b)
got = cfunc(a, b)
self.assertPreciseEqual(expected, got)
def test_count_nonzero(self):
def arrays():
yield np.array([]), None
yield np.zeros(10), None
yield np.arange(10), None
yield np.arange(3 * 4 * 5).reshape(3, 4, 5), None
yield np.arange(3 * 4).reshape(3, 4), 0
yield np.arange(3 * 4).reshape(3, 4), 1
pyfunc = count_nonzero
cfunc = jit(nopython=True)(pyfunc)
for arr, axis in arrays():
expected = pyfunc(arr, axis)
got = cfunc(arr, axis)
self.assertPreciseEqual(expected, got)
def test_np_append(self):
def arrays():
yield 2, 2, None
yield np.arange(10), 3, None
yield np.arange(10), np.arange(3), None
yield np.arange(10).reshape(5, 2), np.arange(3), None
yield np.array([[1, 2, 3], [4, 5, 6]]), np.array([[7, 8, 9]]), 0
arr = np.array([[1, 2, 3], [4, 5, 6]])
yield arr, arr, 1
pyfunc = append
cfunc = jit(nopython=True)(pyfunc)
for arr, obj, axis in arrays():
expected = pyfunc(arr, obj, axis)
got = cfunc(arr, obj, axis)
self.assertPreciseEqual(expected, got)
def test_np_append_exceptions(self):
pyfunc = append
cfunc = jit(nopython=True)(pyfunc)
arr = np.array([[1, 2, 3], [4, 5, 6]])
values = np.array([[7, 8, 9]])
axis = 0
# first argument must be array-like
with self.assertRaises(TypingError) as raises:
cfunc(None, values, axis)
self.assertIn(
'The first argument "arr" must be array-like',
str(raises.exception)
)
# second argument must also be array-like
with self.assertRaises(TypingError) as raises:
cfunc(arr, None, axis)
self.assertIn(
'The second argument "values" must be array-like',
str(raises.exception)
)
# third argument must be either nonelike or an integer
with self.assertRaises(TypingError) as raises:
cfunc(arr, values, axis=0.0)
self.assertIn(
'The third argument "axis" must be an integer',
str(raises.exception)
)
def test_delete(self):
def arrays():
# array, obj
#
# an array-like type
yield [1, 2, 3, 4, 5], 3
yield [1, 2, 3, 4, 5], [2, 3]
# 1d array, scalar
yield np.arange(10), 3
yield np.arange(10), -3 # Negative obj
# 1d array, list
yield np.arange(10), [3, 5, 6]
yield np.arange(10), [2, 3, 4, 5]
# 3d array, scalar
yield np.arange(3 * 4 * 5).reshape(3, 4, 5), 2
# 3d array, list
yield np.arange(3 * 4 * 5).reshape(3, 4, 5), [5, 30, 27, 8]
# slices
yield [1, 2, 3, 4], slice(1, 3, 1)
yield np.arange(10), slice(10)
pyfunc = delete
cfunc = jit(nopython=True)(pyfunc)
for arr, obj in arrays():
expected = pyfunc(arr, obj)
got = cfunc(arr, obj)
self.assertPreciseEqual(expected, got)
def test_delete_exceptions(self):
pyfunc = delete
cfunc = jit(nopython=True)(pyfunc)
self.disable_leak_check()
with self.assertRaises(TypingError) as raises:
cfunc([1, 2], 3.14)
self.assertIn(
'obj should be of Integer dtype',
str(raises.exception)
)
with self.assertRaises(TypingError) as raises:
cfunc(np.arange(10), [3.5, 5.6, 6.2])
self.assertIn(
'obj should be of Integer dtype',
str(raises.exception)
)
with self.assertRaises(TypingError) as raises:
cfunc(2, 3)
self.assertIn(
'arr must be either an Array or a Sequence',
str(raises.exception)
)
with self.assertRaises(IndexError) as raises:
cfunc([1, 2], 3)
self.assertIn(
'obj must be less than the len(arr)',
str(raises.exception),
)
def diff_arrays(self):
"""
Some test arrays for np.diff()
"""
a = np.arange(12) ** 3
yield a
b = a.reshape((3, 4))
yield b
c = np.arange(24).reshape((3, 2, 4)) ** 3
yield c
def test_diff1(self):
pyfunc = diff1
cfunc = jit(nopython=True)(pyfunc)
for arr in self.diff_arrays():
expected = pyfunc(arr)
got = cfunc(arr)
self.assertPreciseEqual(expected, got)
# 0-dim array
a = np.array(42)
with self.assertTypingError():
cfunc(a)
def test_diff2(self):
pyfunc = diff2
cfunc = jit(nopython=True)(pyfunc)
for arr in self.diff_arrays():
size = arr.shape[-1]
for n in (0, 1, 2, 3, size - 1, size, size + 1, 421):
expected = pyfunc(arr, n)
got = cfunc(arr, n)
self.assertPreciseEqual(expected, got)
def test_diff2_exceptions(self):
pyfunc = diff2
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
# 0-dim array
arr = np.array(42)
with self.assertTypingError():
cfunc(arr, 1)
# Invalid `n`
arr = np.arange(10)
for n in (-1, -2, -42):
with self.assertRaises(ValueError) as raises:
cfunc(arr, n)
self.assertIn("order must be non-negative", str(raises.exception))
def test_isscalar(self):
def values():
yield 3
yield np.asarray([3])
yield (3,)
yield 3j
yield 'numba'
yield int(10)
yield np.int16(12345)
yield 4.234
yield True
yield None
pyfunc = isscalar
cfunc = jit(nopython=True)(pyfunc)
for x in values():
expected = pyfunc(x)
got = cfunc(x)
self.assertEqual(expected, got, x)
def test_isobj_functions(self):
def values():
yield 1
yield 1 + 0j
yield np.asarray([3, 1 + 0j, True])
yield "hello world"
@jit(nopython=True)
def optional_fn(x, cond, cfunc):
y = x if cond else None
return cfunc(y)
pyfuncs = [iscomplexobj, isrealobj]
for pyfunc in pyfuncs:
cfunc = jit(nopython=True)(pyfunc)
for x in values():
expected = pyfunc(x)
got = cfunc(x)
self.assertEqual(expected, got)
# optional type
expected_optional = optional_fn.py_func(x, True, pyfunc)
got_optional = optional_fn(x, True, cfunc)
self.assertEqual(expected_optional, got_optional)
# none type
expected_none = optional_fn.py_func(x, False, pyfunc)
got_none = optional_fn(x, False, cfunc)
self.assertEqual(expected_none, got_none)
self.assertEqual(len(cfunc.signatures), 8)
def test_is_real_or_complex(self):
def values():
yield np.array([1 + 1j, 1 + 0j, 4.5, 3, 2, 2j])
yield np.array([1, 2, 3])
yield 3
yield 12j
yield 1 + 4j
yield 10 + 0j
yield (1 + 4j, 2 + 0j)
yield np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
pyfuncs = [iscomplex, isreal]
for pyfunc in pyfuncs:
cfunc = jit(nopython=True)(pyfunc)
for x in values():
expected = pyfunc(x)
got = cfunc(x)
self.assertPreciseEqual(expected, got)
def test_isneg_or_ispos_inf(self):
def values():
yield np.NINF, None
yield np.inf, None
yield np.PINF, None
yield np.asarray([-np.inf, 0., np.inf]), None
yield np.NINF, np.zeros(1, dtype=np.bool)
yield np.inf, np.zeros(1, dtype=np.bool)
yield np.PINF, np.zeros(1, dtype=np.bool)
yield np.NINF, np.empty(12)
yield np.asarray([-np.inf, 0., np.inf]), np.zeros(3, dtype=np.bool)
pyfuncs = [isneginf, isposinf]
for pyfunc in pyfuncs:
cfunc = jit(nopython=True)(pyfunc)
for x, out in values():
expected = pyfunc(x, out)
got = cfunc(x, out)
self.assertPreciseEqual(expected, got)
def bincount_sequences(self):
"""
Some test sequences for np.bincount()
"""
a = [1, 2, 5, 2, 3, 20]
b = np.array([5, 8, 42, 5])
c = self.rnd.randint(0, 100, size=300).astype(np.int8)
return (a, b, c)
def test_bincount1(self):
pyfunc = bincount1
cfunc = jit(nopython=True)(pyfunc)
for seq in self.bincount_sequences():
expected = pyfunc(seq)
got = cfunc(seq)
self.assertPreciseEqual(expected, got)
def test_bincount1_exceptions(self):
pyfunc = bincount1
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
# Negative input
with self.assertRaises(ValueError) as raises:
cfunc([2, -1])
self.assertIn("first argument must be non-negative",
str(raises.exception))