diff --git a/.gitattributes b/.gitattributes index 3b548dcba2a6e0b277c6cb7f8d7bfa0fce2343ec..41cb5ecd0afb0a113e8ce7481454071af076c5ed 100644 --- a/.gitattributes +++ b/.gitattributes @@ -89,3 +89,4 @@ lib/python3.10/site-packages/av/container/input.cpython-310-x86_64-linux-gnu.so lib/python3.10/site-packages/av/container/output.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text lib/python3.10/site-packages/av/container/streams.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text lib/python3.10/site-packages/av/data/stream.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +lib/python3.10/site-packages/av/video/plane.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text diff --git a/lib/python3.10/site-packages/av/video/plane.cpython-310-x86_64-linux-gnu.so b/lib/python3.10/site-packages/av/video/plane.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..1c37bf61e90532a62408208cf0782fe3946b788b --- /dev/null +++ b/lib/python3.10/site-packages/av/video/plane.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:971d0d600b4e6f4731d029f1f83d780b6ac9a80d69b1e4cec0f3ab6d30db253c +size 429249 diff --git a/lib/python3.10/site-packages/babel/locale-data/en_SS.dat b/lib/python3.10/site-packages/babel/locale-data/en_SS.dat new file mode 100644 index 0000000000000000000000000000000000000000..7192fd1381be6737d434c4497767d78a9bb40d28 Binary files /dev/null and b/lib/python3.10/site-packages/babel/locale-data/en_SS.dat differ diff --git a/lib/python3.10/site-packages/babel/locale-data/fo_DK.dat b/lib/python3.10/site-packages/babel/locale-data/fo_DK.dat new file mode 100644 index 0000000000000000000000000000000000000000..669088d75173dd1690c69e453d8960c25a4b5a93 Binary files /dev/null and b/lib/python3.10/site-packages/babel/locale-data/fo_DK.dat differ diff --git a/lib/python3.10/site-packages/babel/locale-data/fr_GF.dat b/lib/python3.10/site-packages/babel/locale-data/fr_GF.dat new file mode 100644 index 0000000000000000000000000000000000000000..eb9ffc902a5f0da8fe66221a023cd4dc3fc1944d Binary files /dev/null and b/lib/python3.10/site-packages/babel/locale-data/fr_GF.dat differ diff --git a/lib/python3.10/site-packages/babel/locale-data/ie_EE.dat b/lib/python3.10/site-packages/babel/locale-data/ie_EE.dat new file mode 100644 index 0000000000000000000000000000000000000000..91566139adf95acb1a94eaa6e119314597a25ba7 Binary files /dev/null and b/lib/python3.10/site-packages/babel/locale-data/ie_EE.dat differ diff --git a/lib/python3.10/site-packages/babel/locale-data/kw.dat b/lib/python3.10/site-packages/babel/locale-data/kw.dat new file mode 100644 index 0000000000000000000000000000000000000000..3d103e3792d51747659d00f345b174d5bbf27a1f Binary files /dev/null and b/lib/python3.10/site-packages/babel/locale-data/kw.dat differ diff --git a/lib/python3.10/site-packages/babel/locale-data/mic_CA.dat b/lib/python3.10/site-packages/babel/locale-data/mic_CA.dat new file mode 100644 index 0000000000000000000000000000000000000000..f43465a947872a0f4ec053bd7c88228619d50efb Binary files /dev/null and b/lib/python3.10/site-packages/babel/locale-data/mic_CA.dat differ diff --git a/lib/python3.10/site-packages/babel/locale-data/prg.dat b/lib/python3.10/site-packages/babel/locale-data/prg.dat new file mode 100644 index 0000000000000000000000000000000000000000..06219914d6b96ee3ef9d57adcdf6348b21cc253e Binary files /dev/null and b/lib/python3.10/site-packages/babel/locale-data/prg.dat differ diff --git a/lib/python3.10/site-packages/babel/locale-data/ps_AF.dat b/lib/python3.10/site-packages/babel/locale-data/ps_AF.dat new file mode 100644 index 0000000000000000000000000000000000000000..94a50bffb0731a4244db3bc63bccc03552ae2d46 Binary files /dev/null and b/lib/python3.10/site-packages/babel/locale-data/ps_AF.dat differ diff --git a/lib/python3.10/site-packages/babel/locale-data/sw_KE.dat b/lib/python3.10/site-packages/babel/locale-data/sw_KE.dat new file mode 100644 index 0000000000000000000000000000000000000000..f19305af90b915b31fedf29b2740ebbb1d45e491 Binary files /dev/null and b/lib/python3.10/site-packages/babel/locale-data/sw_KE.dat differ diff --git a/lib/python3.10/site-packages/numba/tests/__init__.py b/lib/python3.10/site-packages/numba/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d2a38c69038c9ed68838f08b0a7014d2728b5855 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/__init__.py @@ -0,0 +1,33 @@ +import gc +from os.path import dirname, join +import multiprocessing +import sys +import time +import unittest +import warnings + +from unittest.suite import TestSuite +from numba.testing import load_testsuite + + +try: + import faulthandler +except ImportError: + faulthandler = None +else: + try: + # May fail in IPython Notebook with UnsupportedOperation + faulthandler.enable() + except Exception as e: + msg = "Failed to enable faulthandler due to:\n{err}" + warnings.warn(msg.format(err=e)) + +def load_tests(loader, tests, pattern): + suite = TestSuite() + suite.addTests(load_testsuite(loader, dirname(__file__))) + # Numba CUDA tests are located in a separate directory: + cuda_dir = join(dirname(dirname(__file__)), 'cuda/tests') + suite.addTests(loader.discover(cuda_dir)) + + return suite + diff --git a/lib/python3.10/site-packages/numba/tests/cache_usecases.py b/lib/python3.10/site-packages/numba/tests/cache_usecases.py new file mode 100644 index 0000000000000000000000000000000000000000..372311777526d160603e862a6c1d2d58eb316b1a --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/cache_usecases.py @@ -0,0 +1,172 @@ +""" +This file will be copied to a temporary directory in order to +exercise caching compiled Numba functions. + +See test_dispatcher.py. +""" + +import sys + +import numpy as np + +from numba import jit, prange +from numba.core import types + +from numba.tests.ctypes_usecases import c_sin +from numba.tests.support import TestCase, captured_stderr + + +@jit(cache=True, nopython=True) +def simple_usecase(x): + return x + +def simple_usecase_caller(x): + return simple_usecase(x) + + +@jit(cache=True, nopython=True) +def add_usecase(x, y): + return x + y + Z + + +@jit(cache=True, forceobj=True) +def add_objmode_usecase(x, y): + object() + return x + y + Z + + +@jit(nopython=True) +def add_nocache_usecase(x, y): + return x + y + Z + + +@jit(cache=True, nopython=True) +def inner(x, y): + return x + y + Z + +@jit(cache=True, nopython=True) +def outer(x, y): + return inner(-y, x) + +@jit(cache=False, nopython=True) +def outer_uncached(x, y): + return inner(-y, x) + + +@jit(cache=True, forceobj=True) +def looplifted(n): + object() + res = 0 + for i in range(n): + res = res + i + return res + + +@jit(cache=True, nopython=True) +def use_c_sin(x): + return c_sin(x) + +@jit(cache=True, nopython=True) +def use_c_sin_nest1(x): + return use_c_sin(x) + +@jit(cache=True, nopython=True) +def use_c_sin_nest2(x): + return use_c_sin_nest1(x) + + +@jit(cache=True, nopython=True) +def ambiguous_function(x): + return x + 2 + +renamed_function1 = ambiguous_function + +@jit(cache=True, nopython=True) +def ambiguous_function(x): + return x + 6 + +renamed_function2 = ambiguous_function + + +def make_closure(x): + @jit(cache=True, nopython=True) + def closure(y): + return x + y + + return closure + +closure1 = make_closure(3) +closure2 = make_closure(5) +closure3 = make_closure(7) +closure4 = make_closure(9) + + +biggie = np.arange(10**6) + +@jit(cache=True, nopython=True) +def use_big_array(): + return biggie + + +Z = 1 + +# Exercise returning a record instance. This used to hardcode the dtype +# pointer's value in the bitcode. + +packed_record_type = np.dtype([('a', np.int8), ('b', np.float64)]) +aligned_record_type = np.dtype([('a', np.int8), ('b', np.float64)], align=True) + +packed_arr = np.empty(2, dtype=packed_record_type) +for i in range(packed_arr.size): + packed_arr[i]['a'] = i + 1 + packed_arr[i]['b'] = i + 42.5 + +aligned_arr = np.array(packed_arr, dtype=aligned_record_type) + +@jit(cache=True, nopython=True) +def record_return(ary, i): + return ary[i] + + +class _TestModule(TestCase): + """ + Tests for functionality of this module's functions. + Note this does not define any "test_*" method, instead check_module() + should be called by hand. + """ + + def check_module(self, mod): + self.assertPreciseEqual(mod.add_usecase(2, 3), 6) + self.assertPreciseEqual(mod.add_objmode_usecase(2, 3), 6) + self.assertPreciseEqual(mod.outer_uncached(3, 2), 2) + self.assertPreciseEqual(mod.outer(3, 2), 2) + + packed_rec = mod.record_return(mod.packed_arr, 1) + self.assertPreciseEqual(tuple(packed_rec), (2, 43.5)) + aligned_rec = mod.record_return(mod.aligned_arr, 1) + self.assertPreciseEqual(tuple(aligned_rec), (2, 43.5)) + + +@jit(cache=True) +def first_class_function_mul(x): + return x * x + + +@jit(cache=True) +def first_class_function_add(x): + return x + x + + +@jit(cache=True) +def first_class_function_usecase(f, x): + return f(x) + + +def self_test(): + mod = sys.modules[__name__] + _TestModule().check_module(mod) + + +@jit(parallel=True, cache=True, nopython=True) +def parfor_usecase(ary): + return ary * ary + ary diff --git a/lib/python3.10/site-packages/numba/tests/cffi_usecases.py b/lib/python3.10/site-packages/numba/tests/cffi_usecases.py new file mode 100644 index 0000000000000000000000000000000000000000..a101b977d8895846abba5cd96157380afe2d6926 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/cffi_usecases.py @@ -0,0 +1,197 @@ +import sys + +import numpy as np + +import numba.core.typing.cffi_utils as cffi_support +from numba.tests.support import import_dynamic, temp_directory +from numba.core.types import complex128 + + +def load_inline_module(): + """ + Create an inline module, return the corresponding ffi and dll objects. + """ + from cffi import FFI + + # We can't rely on libc availability on Windows anymore, so we use our + # own compiled wrappers (see https://bugs.python.org/issue23606). + + defs = """ + double _numba_test_sin(double x); + double _numba_test_cos(double x); + double _numba_test_funcptr(double (*func)(double)); + bool _numba_test_boolean(void); + """ + + ffi = FFI() + ffi.cdef(defs) + # Load the _helperlib namespace + from numba import _helperlib + return ffi, ffi.dlopen(_helperlib.__file__) + + +def load_ool_module(): + """ + Compile an out-of-line module, return the corresponding ffi and + module objects. + """ + from cffi import FFI + + numba_complex = """ + typedef struct _numba_complex { + double real; + double imag; + } numba_complex; + """ + + bool_define = """ + #ifdef _MSC_VER + #define false 0 + #define true 1 + #define bool int + #else + #include + #endif + """ + + defs = numba_complex + """ + bool boolean(void); + double sin(double x); + double cos(double x); + int foo(int a, int b, int c); + void vsSin(int n, float* x, float* y); + void vdSin(int n, double* x, double* y); + void vector_real(numba_complex *c, double *real, int n); + void vector_imag(numba_complex *c, double *imag, int n); + """ + + source = numba_complex + bool_define + """ + static bool boolean(void) + { + return true; + } + + static int foo(int a, int b, int c) + { + return a + b * c; + } + + void vsSin(int n, float* x, float* y) { + int i; + for (i=0; i 0: + return fa(x) + else: + return fb(x) + +def use_user_defined_symbols(): + return cffi_foo(1, 2, 3) + +# The from_buffer method is member of cffi.FFI, and also of CompiledFFI objects +# (cffi_usecases_ool.ffi is a CompiledFFI object) so we use both in these +# functions. + +def vector_sin_float32(x, y): + vsSin(len(x), ffi.from_buffer(x), ffi_ool.from_buffer(y)) + +def vector_sin_float64(x, y): + vdSin(len(x), ffi.from_buffer(x), ffi_ool.from_buffer(y)) + + +# For testing pointer to structs from buffers + +def vector_extract_real(x, y): + vector_real(ffi.from_buffer(x), ffi.from_buffer(y), len(x)) + +def vector_extract_imag(x, y): + vector_imag(ffi.from_buffer(x), ffi.from_buffer(y), len(x)) diff --git a/lib/python3.10/site-packages/numba/tests/complex_usecases.py b/lib/python3.10/site-packages/numba/tests/complex_usecases.py new file mode 100644 index 0000000000000000000000000000000000000000..113cd69217adacc21dcdba1d9a27155e376625e5 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/complex_usecases.py @@ -0,0 +1,93 @@ +import cmath + + +def div_usecase(x, y): + return x / y + + +def real_usecase(x): + return x.real + +def imag_usecase(x): + return x.imag + +def conjugate_usecase(x): + return x.conjugate() + + +def acos_usecase(x): + return cmath.acos(x) + +def cos_usecase(x): + return cmath.cos(x) + +def asin_usecase(x): + return cmath.asin(x) + +def sin_usecase(x): + return cmath.sin(x) + +def atan_usecase(x): + return cmath.atan(x) + +def tan_usecase(x): + return cmath.tan(x) + +def acosh_usecase(x): + return cmath.acosh(x) + +def cosh_usecase(x): + return cmath.cosh(x) + +def asinh_usecase(x): + return cmath.asinh(x) + +def sinh_usecase(x): + return cmath.sinh(x) + +def atanh_usecase(x): + return cmath.atanh(x) + +def tanh_usecase(x): + return cmath.tanh(x) + +def exp_usecase(x): + return cmath.exp(x) + +def isfinite_usecase(x): + return cmath.isfinite(x) + +def isinf_usecase(x): + return cmath.isinf(x) + +def isnan_usecase(x): + return cmath.isnan(x) + +def log_usecase(x): + return cmath.log(x) + +def log_base_usecase(x, base): + return cmath.log(x, base) + +def log10_usecase(x): + return cmath.log10(x) + +def phase_usecase(x): + return cmath.phase(x) + +def polar_usecase(x): + return cmath.polar(x) + +_two = 2.0 + +def polar_as_complex_usecase(x): + # HACK: clear errno by invoking float.__pow__ + # (workaround for http://bugs.python.org/issue24489) + _two ** _two + return complex(*cmath.polar(x)) + +def rect_usecase(r, phi): + return cmath.rect(r, phi) + +def sqrt_usecase(x): + return cmath.sqrt(x) diff --git a/lib/python3.10/site-packages/numba/tests/ctypes_usecases.py b/lib/python3.10/site-packages/numba/tests/ctypes_usecases.py new file mode 100644 index 0000000000000000000000000000000000000000..5ed8d3ab8e1a480bd1f0f82127b176eca648686f --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/ctypes_usecases.py @@ -0,0 +1,114 @@ +from ctypes import * +import sys + +import numpy as np + + +is_windows = sys.platform.startswith('win32') + +# We can't rely on libc availability on Windows anymore, so we use our +# own compiled wrappers (see https://bugs.python.org/issue23606). + +from numba import _helperlib +libnumba = CDLL(_helperlib.__file__) +del _helperlib + +# A typed C function (cdecl under Windows) + +c_sin = libnumba._numba_test_sin +c_sin.argtypes = [c_double] +c_sin.restype = c_double + +def use_c_sin(x): + return c_sin(x) + +c_cos = libnumba._numba_test_cos +c_cos.argtypes = [c_double] +c_cos.restype = c_double + +def use_two_funcs(x): + return c_sin(x) - c_cos(x) + +# Typed C functions accepting an array pointer +# (either as a "void *" or as a typed pointer) + +c_vsquare = libnumba._numba_test_vsquare +c_vsquare.argtypes = [c_int, c_void_p, c_void_p] + +c_vcube = libnumba._numba_test_vsquare +c_vcube.argtypes = [c_int, POINTER(c_double), POINTER(c_double)] + +def use_c_vsquare(x): + out = np.empty_like(x) + c_vsquare(x.size, x.ctypes, out.ctypes) + return out + +def use_c_vcube(x): + out = np.empty_like(x) + c_vcube(x.size, x.ctypes, out.ctypes) + return out + +# An untyped C function + +c_untyped = libnumba._numba_test_exp + +def use_c_untyped(x): + return c_untyped(x) + +# A C function wrapped in a CFUNCTYPE + +ctype_wrapping = CFUNCTYPE(c_double, c_double)(use_c_sin) + +def use_ctype_wrapping(x): + return ctype_wrapping(x) + +# A Python API function + +savethread = pythonapi.PyEval_SaveThread +savethread.argtypes = [] +savethread.restype = c_void_p + +restorethread = pythonapi.PyEval_RestoreThread +restorethread.argtypes = [c_void_p] +restorethread.restype = None + +if is_windows: + # A function with the stdcall calling convention + c_sleep = windll.kernel32.Sleep + c_sleep.argtypes = [c_uint] + c_sleep.restype = None + + def use_c_sleep(x): + c_sleep(x) + + +def use_c_pointer(x): + """ + Running in Python will cause a segfault. + """ + threadstate = savethread() + x += 1 + restorethread(threadstate) + return x + + +def use_func_pointer(fa, fb, x): + if x > 0: + return fa(x) + else: + return fb(x) + + +mydct = {'what': 1232121} + +def call_me_maybe(arr): + return mydct[arr[0].decode('ascii')] + +# Create a callback into the python interpreter +py_call_back = CFUNCTYPE(c_int, py_object)(call_me_maybe) + + +def take_array_ptr(ptr): + return ptr + +c_take_array_ptr = CFUNCTYPE(c_void_p, c_void_p)(take_array_ptr) diff --git a/lib/python3.10/site-packages/numba/tests/doctest_usecase.py b/lib/python3.10/site-packages/numba/tests/doctest_usecase.py new file mode 100644 index 0000000000000000000000000000000000000000..1761ba08a47ff67b7285b081659e0e474e81b0a2 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/doctest_usecase.py @@ -0,0 +1,31 @@ +""" +Test that all docstrings are the same: + +>>> len({f.__doc__ for f in (a, b, c, d)}) +1 +""" +from numba import guvectorize, int64, njit, vectorize + + +def a(): + """>>> x = 1""" + return 1 + + +@njit +def b(): + """>>> x = 1""" + return 1 + + +@guvectorize([(int64[:], int64, int64[:])], "(n),()->(n)") +def c(x, y, res): + """>>> x = 1""" + for i in range(x.shape[0]): + res[i] = x[i] + y + + +@vectorize([int64(int64, int64)]) +def d(x, y): + """>>> x = 1""" + return x + y diff --git a/lib/python3.10/site-packages/numba/tests/enum_usecases.py b/lib/python3.10/site-packages/numba/tests/enum_usecases.py new file mode 100644 index 0000000000000000000000000000000000000000..995dbd917afb0abb2e48185ecb14adef692e2489 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/enum_usecases.py @@ -0,0 +1,55 @@ +from enum import Enum, IntEnum + + +class Color(Enum): + red = 1 + green = 2 + blue = 3 + + +class Shake(Enum): + vanilla = 7 + chocolate = 4 + cookies = 9 + # Same as Color.blue + mint = 3 + + +class Planet(Enum): + MERCURY = (3.303e+23, 2.4397e6) + VENUS = (4.869e+24, 6.0518e6) + EARTH = (5.976e+24, 6.37814e6) + MARS = (6.421e+23, 3.3972e6) + JUPITER = (1.9e+27, 7.1492e7) + SATURN = (5.688e+26, 6.0268e7) + URANUS = (8.686e+25, 2.5559e7) + NEPTUNE = (1.024e+26, 2.4746e7) + + +class HeterogeneousEnum(Enum): + red = 1.0 + green = 2.0 + blue = 3j + + +class Shape(IntEnum): + # Same as Color.green + circle = 2 + # Same as RequestError.internal_error + square = 500 + + +class RequestError(IntEnum): + dummy = 2 + not_found = 404 + internal_error = 500 + +class IntEnumWithNegatives(IntEnum): + # Used for testing of hash, need to make sure -1 -> -2 to comply with CPy + one = 1 + two = 2 + too = 2 + three = 3 + negone = -1 + negtwo = -2 + negthree = -3 diff --git a/lib/python3.10/site-packages/numba/tests/parfor_iss9490_usecase.py b/lib/python3.10/site-packages/numba/tests/parfor_iss9490_usecase.py new file mode 100644 index 0000000000000000000000000000000000000000..15e5d41130e48ea6c7c6540a5bac335c5d8002b6 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/parfor_iss9490_usecase.py @@ -0,0 +1,78 @@ +""" +This is a testcase for https://github.com/numba/numba/issues/9490. +The bug is very sensitive to the control-flow and variable uses. +It is impossible to shrink the reproducer in any meaningful way. + +The test is also sensitive to PYTHONHASHSEED. +PYTHONHASHSEED=1 will trigger the bug. + +Example of traceback: + + File "/numba/parfors/parfor.py", line 2070, in _arrayexpr_to_parfor + index_vars, loopnests = _mk_parfor_loops(pass_states.typemap, size_vars, + scope, loc) + File "/numba/parfors/parfor.py", line 1981, in _mk_parfor_loops + for size_var in size_vars: +TypeError: Failed in nopython mode pipeline (step: convert to parfors) +'NoneType' object is not iterable +""" + +import numba +import numpy as np + + +@numba.jit(nopython=True, parallel=True) +def stable_fit(X, y, threshold=3): + min_obs = int(X.shape[1] * 1.5) + beta = np.zeros((X.shape[1], y.shape[1]), dtype=np.float64) + residuals = np.full_like(y, np.nan) + stable = np.empty((y.shape[1])) + for idx in numba.prange(y.shape[1]): + y_sub = y[:, idx] + isna = np.isnan(y_sub) + X_sub = X[~isna] + y_sub = y_sub[~isna] + is_stable = False + + # Run until minimum observations + # or until stability is reached + for jdx in range(len(y_sub), min_obs - 1, -2): + # Timeseries gets reduced by two elements + # each iteration + y_ = y_sub[-jdx:] + X_ = X_sub[-jdx:] + beta_sub = np.linalg.solve(np.dot(X_.T, X_), np.dot(X_.T, y_)) + resid_sub = np.dot(X_, beta_sub) - y_ + # Check for stability + rmse = np.sqrt(np.mean(resid_sub ** 2)) + first = np.fabs(resid_sub[0]) / rmse < threshold + last = np.fabs(resid_sub[-1]) / rmse < threshold + slope = np.fabs(beta_sub[1]) / rmse < threshold + # Break if stability is reached + is_stable = slope & first & last + if is_stable: + break + + beta[:, idx] = beta_sub + residuals[-jdx:, idx] = resid_sub + stable[idx] = is_stable + return beta, residuals, stable.astype(np.bool_) + + +def check(): + np.random.seed(0) + X_shape = (10, 4) + y_shape = (10, 5) + X = np.random.random(X_shape) + y = np.random.random(y_shape) + + got_beta, got_residuals, got_stable = stable_fit(X, y) + exp_beta, exp_residuals, exp_stable = stable_fit.py_func(X, y) + + np.testing.assert_allclose(got_beta, exp_beta) + np.testing.assert_allclose(got_residuals, exp_residuals) + np.testing.assert_allclose(got_stable, exp_stable) + + +if __name__ == "__main__": + check() diff --git a/lib/python3.10/site-packages/numba/tests/test_analysis.py b/lib/python3.10/site-packages/numba/tests/test_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..c50defe335e09a0af1e4e7a2ba5a97dd4e85fc6c --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_analysis.py @@ -0,0 +1,1007 @@ +# Tests numba.analysis functions +import collections +import types as pytypes + +import numpy as np +from numba.core.compiler import run_frontend, Flags, StateDict +from numba import jit, njit, literal_unroll +from numba.core import types, errors, ir, rewrites, ir_utils, cpu +from numba.core import postproc +from numba.core.inline_closurecall import InlineClosureCallPass +from numba.tests.support import (TestCase, MemoryLeakMixin, SerialMixin, + IRPreservingTestPipeline) +from numba.core.analysis import dead_branch_prune, rewrite_semantic_constants +from numba.core.untyped_passes import (ReconstructSSA, TranslateByteCode, + IRProcessing, DeadBranchPrune, + PreserveIR) +from numba.core.compiler import DefaultPassBuilder, CompilerBase, PassManager + + +_GLOBAL = 123 + +enable_pyobj_flags = Flags() +enable_pyobj_flags.enable_pyobject = True + + +def compile_to_ir(func): + func_ir = run_frontend(func) + state = StateDict() + state.func_ir = func_ir + state.typemap = None + state.calltypes = None + # Transform to SSA + ReconstructSSA().run_pass(state) + # call this to get print etc rewrites + rewrites.rewrite_registry.apply('before-inference', state) + return func_ir + + +class TestBranchPruneBase(MemoryLeakMixin, TestCase): + """ + Tests branch pruning + """ + _DEBUG = False + + # find *all* branches + def find_branches(self, the_ir): + branches = [] + for blk in the_ir.blocks.values(): + tmp = [_ for _ in blk.find_insts(cls=ir.Branch)] + branches.extend(tmp) + return branches + + def assert_prune(self, func, args_tys, prune, *args, **kwargs): + # This checks that the expected pruned branches have indeed been pruned. + # func is a python function to assess + # args_tys is the numba types arguments tuple + # prune arg is a list, one entry per branch. The value in the entry is + # encoded as follows: + # True: using constant inference only, the True branch will be pruned + # False: using constant inference only, the False branch will be pruned + # None: under no circumstances should this branch be pruned + # *args: the argument instances to pass to the function to check + # execution is still valid post transform + # **kwargs: + # - flags: args to pass to `jit` default is `nopython=True`, + # e.g. permits use of e.g. object mode. + + func_ir = compile_to_ir(func) + before = func_ir.copy() + if self._DEBUG: + print("=" * 80) + print("before inline") + func_ir.dump() + + # run closure inlining to ensure that nonlocals in closures are visible + inline_pass = InlineClosureCallPass(func_ir, + cpu.ParallelOptions(False),) + inline_pass.run() + + # Remove all Dels, and re-run postproc + post_proc = postproc.PostProcessor(func_ir) + post_proc.run() + + rewrite_semantic_constants(func_ir, args_tys) + if self._DEBUG: + print("=" * 80) + print("before prune") + func_ir.dump() + + dead_branch_prune(func_ir, args_tys) + + after = func_ir + if self._DEBUG: + print("after prune") + func_ir.dump() + + before_branches = self.find_branches(before) + self.assertEqual(len(before_branches), len(prune)) + + # what is expected to be pruned + expect_removed = [] + for idx, prune in enumerate(prune): + branch = before_branches[idx] + if prune is True: + expect_removed.append(branch.truebr) + elif prune is False: + expect_removed.append(branch.falsebr) + elif prune is None: + pass # nothing should be removed! + elif prune == 'both': + expect_removed.append(branch.falsebr) + expect_removed.append(branch.truebr) + else: + assert 0, "unreachable" + + # compare labels + original_labels = set([_ for _ in before.blocks.keys()]) + new_labels = set([_ for _ in after.blocks.keys()]) + # assert that the new labels are precisely the original less the + # expected pruned labels + try: + self.assertEqual(new_labels, original_labels - set(expect_removed)) + except AssertionError as e: + print("new_labels", sorted(new_labels)) + print("original_labels", sorted(original_labels)) + print("expect_removed", sorted(expect_removed)) + raise e + + supplied_flags = kwargs.pop('flags', {'nopython': True}) + # NOTE: original testing used `compile_isolated` hence use of `cres`. + cres = jit(args_tys, **supplied_flags)(func).overloads[args_tys] + if args is None: + res = cres.entry_point() + expected = func() + else: + res = cres.entry_point(*args) + expected = func(*args) + self.assertEqual(res, expected) + + +class TestBranchPrune(TestBranchPruneBase, SerialMixin): + + def test_single_if(self): + + def impl(x): + if 1 == 0: + return 3.14159 + + self.assert_prune(impl, (types.NoneType('none'),), [True], None) + + def impl(x): + if 1 == 1: + return 3.14159 + + self.assert_prune(impl, (types.NoneType('none'),), [False], None) + + def impl(x): + if x is None: + return 3.14159 + + self.assert_prune(impl, (types.NoneType('none'),), [False], None) + self.assert_prune(impl, (types.IntegerLiteral(10),), [True], 10) + + def impl(x): + if x == 10: + return 3.14159 + + self.assert_prune(impl, (types.NoneType('none'),), [True], None) + self.assert_prune(impl, (types.IntegerLiteral(10),), [None], 10) + + def impl(x): + if x == 10: + z = 3.14159 # noqa: F841 # no effect + + self.assert_prune(impl, (types.NoneType('none'),), [True], None) + self.assert_prune(impl, (types.IntegerLiteral(10),), [None], 10) + + def impl(x): + z = None + y = z + if x == y: + return 100 + + self.assert_prune(impl, (types.NoneType('none'),), [False], None) + self.assert_prune(impl, (types.IntegerLiteral(10),), [True], 10) + + def test_single_if_else(self): + + def impl(x): + if x is None: + return 3.14159 + else: + return 1.61803 + + self.assert_prune(impl, (types.NoneType('none'),), [False], None) + self.assert_prune(impl, (types.IntegerLiteral(10),), [True], 10) + + def test_single_if_const_val(self): + + def impl(x): + if x == 100: + return 3.14159 + + self.assert_prune(impl, (types.NoneType('none'),), [True], None) + self.assert_prune(impl, (types.IntegerLiteral(100),), [None], 100) + + def impl(x): + # switch the condition order + if 100 == x: + return 3.14159 + + self.assert_prune(impl, (types.NoneType('none'),), [True], None) + self.assert_prune(impl, (types.IntegerLiteral(100),), [None], 100) + + def test_single_if_else_two_const_val(self): + + def impl(x, y): + if x == y: + return 3.14159 + else: + return 1.61803 + + self.assert_prune(impl, (types.IntegerLiteral(100),) * 2, [None], 100, + 100) + self.assert_prune(impl, (types.NoneType('none'),) * 2, [False], None, + None) + self.assert_prune(impl, (types.IntegerLiteral(100), + types.NoneType('none'),), [True], 100, None) + self.assert_prune(impl, (types.IntegerLiteral(100), + types.IntegerLiteral(1000)), [None], 100, 1000) + + def test_single_if_else_w_following_undetermined(self): + + def impl(x): + x_is_none_work = False + if x is None: + x_is_none_work = True + else: + dead = 7 # noqa: F841 # no effect + + if x_is_none_work: + y = 10 + else: + y = -3 + return y + + self.assert_prune(impl, (types.NoneType('none'),), [False, None], None) + self.assert_prune(impl, (types.IntegerLiteral(10),), [True, None], 10) + + def impl(x): + x_is_none_work = False + if x is None: + x_is_none_work = True + else: + pass + + if x_is_none_work: + y = 10 + else: + y = -3 + return y + + # Python 3.10 creates a block with a NOP in it for the `pass` which + # means it gets pruned. + self.assert_prune(impl, (types.NoneType('none'),), [False, None], + None) + + self.assert_prune(impl, (types.IntegerLiteral(10),), [True, None], 10) + + def test_double_if_else_rt_const(self): + + def impl(x): + one_hundred = 100 + x_is_none_work = 4 + if x is None: + x_is_none_work = 100 + else: + dead = 7 # noqa: F841 # no effect + + if x_is_none_work == one_hundred: + y = 10 + else: + y = -3 + + return y, x_is_none_work + + self.assert_prune(impl, (types.NoneType('none'),), [False, None], None) + self.assert_prune(impl, (types.IntegerLiteral(10),), [True, None], 10) + + def test_double_if_else_non_literal_const(self): + + def impl(x): + one_hundred = 100 + if x == one_hundred: + y = 3.14159 + else: + y = 1.61803 + return y + + # no prune as compilation specialization on literal value not permitted + self.assert_prune(impl, (types.IntegerLiteral(10),), [None], 10) + self.assert_prune(impl, (types.IntegerLiteral(100),), [None], 100) + + def test_single_two_branches_same_cond(self): + + def impl(x): + if x is None: + y = 10 + else: + y = 40 + + if x is not None: + z = 100 + else: + z = 400 + + return z, y + + self.assert_prune(impl, (types.NoneType('none'),), [False, True], None) + self.assert_prune(impl, (types.IntegerLiteral(10),), [True, False], 10) + + def test_cond_is_kwarg_none(self): + + def impl(x=None): + if x is None: + y = 10 + else: + y = 40 + + if x is not None: + z = 100 + else: + z = 400 + + return z, y + + self.assert_prune(impl, (types.Omitted(None),), + [False, True], None) + self.assert_prune(impl, (types.NoneType('none'),), [False, True], None) + self.assert_prune(impl, (types.IntegerLiteral(10),), [True, False], 10) + + def test_cond_is_kwarg_value(self): + + def impl(x=1000): + if x == 1000: + y = 10 + else: + y = 40 + + if x != 1000: + z = 100 + else: + z = 400 + + return z, y + + self.assert_prune(impl, (types.Omitted(1000),), [None, None], 1000) + self.assert_prune(impl, (types.IntegerLiteral(1000),), [None, None], + 1000) + self.assert_prune(impl, (types.IntegerLiteral(0),), [None, None], 0) + self.assert_prune(impl, (types.NoneType('none'),), [True, False], None) + + def test_cond_rewrite_is_correct(self): + # this checks that when a condition is replaced, it is replace by a + # true/false bit that correctly represents the evaluated condition + def fn(x): + if x is None: + return 10 + return 12 + + def check(func, arg_tys, bit_val): + func_ir = compile_to_ir(func) + + # check there is 1 branch + before_branches = self.find_branches(func_ir) + self.assertEqual(len(before_branches), 1) + + # check the condition in the branch is a binop + pred_var = before_branches[0].cond + pred_defn = ir_utils.get_definition(func_ir, pred_var) + self.assertEqual(pred_defn.op, 'call') + condition_var = pred_defn.args[0] + condition_op = ir_utils.get_definition(func_ir, condition_var) + self.assertEqual(condition_op.op, 'binop') + + # do the prune, this should kill the dead branch and rewrite the + #'condition to a true/false const bit + if self._DEBUG: + print("=" * 80) + print("before prune") + func_ir.dump() + dead_branch_prune(func_ir, arg_tys) + if self._DEBUG: + print("=" * 80) + print("after prune") + func_ir.dump() + + # after mutation, the condition should be a const value `bit_val` + new_condition_defn = ir_utils.get_definition(func_ir, condition_var) + self.assertTrue(isinstance(new_condition_defn, ir.Const)) + self.assertEqual(new_condition_defn.value, bit_val) + + check(fn, (types.NoneType('none'),), 1) + check(fn, (types.IntegerLiteral(10),), 0) + + def test_global_bake_in(self): + + def impl(x): + if _GLOBAL == 123: + return x + else: + return x + 10 + + self.assert_prune(impl, (types.IntegerLiteral(1),), [False], 1) + + global _GLOBAL + tmp = _GLOBAL + + try: + _GLOBAL = 5 + + def impl(x): + if _GLOBAL == 123: + return x + else: + return x + 10 + + self.assert_prune(impl, (types.IntegerLiteral(1),), [True], 1) + finally: + _GLOBAL = tmp + + def test_freevar_bake_in(self): + + _FREEVAR = 123 + + def impl(x): + if _FREEVAR == 123: + return x + else: + return x + 10 + + self.assert_prune(impl, (types.IntegerLiteral(1),), [False], 1) + + _FREEVAR = 12 + + def impl(x): + if _FREEVAR == 123: + return x + else: + return x + 10 + + self.assert_prune(impl, (types.IntegerLiteral(1),), [True], 1) + + def test_redefined_variables_are_not_considered_in_prune(self): + # see issue #4163, checks that if a variable that is an argument is + # redefined in the user code it is not considered const + + def impl(array, a=None): + if a is None: + a = 0 + if a < 0: + return 10 + return 30 + + self.assert_prune(impl, + (types.Array(types.float64, 2, 'C'), + types.NoneType('none'),), + [None, None], + np.zeros((2, 3)), None) + + def test_comparison_operators(self): + # see issue #4163, checks that a variable that is an argument and has + # value None survives TypeError from invalid comparison which should be + # dead + + def impl(array, a=None): + x = 0 + if a is None: + return 10 # dynamic exec would return here + # static analysis requires that this is executed with a=None, + # hence TypeError + if a < 0: + return 20 + return x + + self.assert_prune(impl, + (types.Array(types.float64, 2, 'C'), + types.NoneType('none'),), + [False, 'both'], + np.zeros((2, 3)), None) + + self.assert_prune(impl, + (types.Array(types.float64, 2, 'C'), + types.float64,), + [None, None], + np.zeros((2, 3)), 12.) + + def test_redefinition_analysis_same_block(self): + # checks that a redefinition in a block with prunable potential doesn't + # break + + def impl(array, x, a=None): + b = 2 + if x < 4: + b = 12 + if a is None: # known true + a = 7 # live + else: + b = 15 # dead + if a < 0: # valid as a result of the redefinition of 'a' + return 10 + return 30 + b + a + + self.assert_prune(impl, + (types.Array(types.float64, 2, 'C'), + types.float64, types.NoneType('none'),), + [None, False, None], + np.zeros((2, 3)), 1., None) + + def test_redefinition_analysis_different_block_can_exec(self): + # checks that a redefinition in a block that may be executed prevents + # pruning + + def impl(array, x, a=None): + b = 0 + if x > 5: + a = 11 # a redefined, cannot tell statically if this will exec + if x < 4: + b = 12 + if a is None: # cannot prune, cannot determine if re-defn occurred + b += 5 + else: + b += 7 + if a < 0: + return 10 + return 30 + b + + self.assert_prune(impl, + (types.Array(types.float64, 2, 'C'), + types.float64, types.NoneType('none'),), + [None, None, None, None], + np.zeros((2, 3)), 1., None) + + def test_redefinition_analysis_different_block_cannot_exec(self): + # checks that a redefinition in a block guarded by something that + # has prune potential + + def impl(array, x=None, a=None): + b = 0 + if x is not None: + a = 11 + if a is None: + b += 5 + else: + b += 7 + return 30 + b + + self.assert_prune(impl, + (types.Array(types.float64, 2, 'C'), + types.NoneType('none'), types.NoneType('none')), + [True, None], + np.zeros((2, 3)), None, None) + + self.assert_prune(impl, + (types.Array(types.float64, 2, 'C'), + types.NoneType('none'), types.float64), + [True, None], + np.zeros((2, 3)), None, 1.2) + + self.assert_prune(impl, + (types.Array(types.float64, 2, 'C'), + types.float64, types.NoneType('none')), + [None, None], + np.zeros((2, 3)), 1.2, None) + + def test_closure_and_nonlocal_can_prune(self): + # Closures must be inlined ahead of branch pruning in case nonlocal + # is used. See issue #6585. + def impl(): + x = 1000 + + def closure(): + nonlocal x + x = 0 + + closure() + + if x == 0: + return True + else: + return False + + self.assert_prune(impl, (), [False,],) + + def test_closure_and_nonlocal_cannot_prune(self): + # Closures must be inlined ahead of branch pruning in case nonlocal + # is used. See issue #6585. + def impl(n): + x = 1000 + + def closure(t): + nonlocal x + x = t + + closure(n) + + if x == 0: + return True + else: + return False + + self.assert_prune(impl, (types.int64,), [None,], 1) + + +class TestBranchPrunePredicates(TestBranchPruneBase, SerialMixin): + # Really important thing to remember... the branch on predicates end up as + # POP_JUMP_IF_ and the targets are backwards compared to normal, i.e. + # the true condition is far jump and the false the near i.e. `if x` would + # end up in Numba IR as e.g. `branch x 10, 6`. + + _TRUTHY = (1, "String", True, 7.4, 3j) + _FALSEY = (0, "", False, 0.0, 0j, None) + + def _literal_const_sample_generator(self, pyfunc, consts): + """ + This takes a python function, pyfunc, and manipulates its co_const + __code__ member to create a new function with different co_consts as + supplied in argument consts. + + consts is a dict {index: value} of co_const tuple index to constant + value used to update a pyfunc clone's co_const. + """ + pyfunc_code = pyfunc.__code__ + + # translate consts spec to update the constants + co_consts = {k: v for k, v in enumerate(pyfunc_code.co_consts)} + for k, v in consts.items(): + co_consts[k] = v + new_consts = tuple([v for _, v in sorted(co_consts.items())]) + + # create code object with mutation + new_code = pyfunc_code.replace(co_consts=new_consts) + + # get function + return pytypes.FunctionType(new_code, globals()) + + def test_literal_const_code_gen(self): + def impl(x): + _CONST1 = "PLACEHOLDER1" + if _CONST1: + return 3.14159 + else: + _CONST2 = "PLACEHOLDER2" + return _CONST2 + 4 + + new = self._literal_const_sample_generator(impl, {1:0, 3:20}) + iconst = impl.__code__.co_consts + nconst = new.__code__.co_consts + self.assertEqual(iconst, (None, "PLACEHOLDER1", 3.14159, + "PLACEHOLDER2", 4)) + self.assertEqual(nconst, (None, 0, 3.14159, 20, 4)) + self.assertEqual(impl(None), 3.14159) + self.assertEqual(new(None), 24) + + def test_single_if_const(self): + + def impl(x): + _CONST1 = "PLACEHOLDER1" + if _CONST1: + return 3.14159 + + for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True): + for const in c_inp: + func = self._literal_const_sample_generator(impl, {1: const}) + self.assert_prune(func, (types.NoneType('none'),), [prune], + None) + + def test_single_if_negate_const(self): + + def impl(x): + _CONST1 = "PLACEHOLDER1" + if not _CONST1: + return 3.14159 + + for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True): + for const in c_inp: + func = self._literal_const_sample_generator(impl, {1: const}) + self.assert_prune(func, (types.NoneType('none'),), [prune], + None) + + def test_single_if_else_const(self): + + def impl(x): + _CONST1 = "PLACEHOLDER1" + if _CONST1: + return 3.14159 + else: + return 1.61803 + + for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True): + for const in c_inp: + func = self._literal_const_sample_generator(impl, {1: const}) + self.assert_prune(func, (types.NoneType('none'),), [prune], + None) + + def test_single_if_else_negate_const(self): + + def impl(x): + _CONST1 = "PLACEHOLDER1" + if not _CONST1: + return 3.14159 + else: + return 1.61803 + + for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True): + for const in c_inp: + func = self._literal_const_sample_generator(impl, {1: const}) + self.assert_prune(func, (types.NoneType('none'),), [prune], + None) + + def test_single_if_freevar(self): + for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True): + for const in c_inp: + + def func(x): + if const: + return 3.14159, const + self.assert_prune(func, (types.NoneType('none'),), [prune], + None) + + def test_single_if_negate_freevar(self): + for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True): + for const in c_inp: + + def func(x): + if not const: + return 3.14159, const + self.assert_prune(func, (types.NoneType('none'),), [prune], + None) + + def test_single_if_else_freevar(self): + for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True): + for const in c_inp: + + def func(x): + if const: + return 3.14159, const + else: + return 1.61803, const + self.assert_prune(func, (types.NoneType('none'),), [prune], + None) + + def test_single_if_else_negate_freevar(self): + for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True): + for const in c_inp: + + def func(x): + if not const: + return 3.14159, const + else: + return 1.61803, const + self.assert_prune(func, (types.NoneType('none'),), [prune], + None) + + # globals in this section have absurd names after their test usecase names + # so as to prevent collisions and permit tests to run in parallel + def test_single_if_global(self): + global c_test_single_if_global + + for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True): + for c in c_inp: + c_test_single_if_global = c + + def func(x): + if c_test_single_if_global: + return 3.14159, c_test_single_if_global + + self.assert_prune(func, (types.NoneType('none'),), [prune], + None) + + def test_single_if_negate_global(self): + global c_test_single_if_negate_global + + for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True): + for c in c_inp: + c_test_single_if_negate_global = c + + def func(x): + if c_test_single_if_negate_global: + return 3.14159, c_test_single_if_negate_global + + self.assert_prune(func, (types.NoneType('none'),), [prune], + None) + + def test_single_if_else_global(self): + global c_test_single_if_else_global + + for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True): + for c in c_inp: + c_test_single_if_else_global = c + + def func(x): + if c_test_single_if_else_global: + return 3.14159, c_test_single_if_else_global + else: + return 1.61803, c_test_single_if_else_global + self.assert_prune(func, (types.NoneType('none'),), [prune], + None) + + def test_single_if_else_negate_global(self): + global c_test_single_if_else_negate_global + + for c_inp, prune in (self._TRUTHY, False), (self._FALSEY, True): + for c in c_inp: + c_test_single_if_else_negate_global = c + + def func(x): + if not c_test_single_if_else_negate_global: + return 3.14159, c_test_single_if_else_negate_global + else: + return 1.61803, c_test_single_if_else_negate_global + self.assert_prune(func, (types.NoneType('none'),), [prune], + None) + + def test_issue_5618(self): + + @njit + def foo(): + values = np.zeros(1) + tmp = 666 + if tmp: + values[0] = tmp + return values + + self.assertPreciseEqual(foo.py_func()[0], 666.) + self.assertPreciseEqual(foo()[0], 666.) + + +class TestBranchPruneSSA(MemoryLeakMixin, TestCase): + # Tests SSA rewiring of phi nodes after branch pruning. + + class SSAPrunerCompiler(CompilerBase): + def define_pipelines(self): + # This is a simple pipeline that does branch pruning on IR in SSA + # form, then types and lowers as per the standard nopython pipeline. + pm = PassManager("testing pm") + pm.add_pass(TranslateByteCode, "analyzing bytecode") + pm.add_pass(IRProcessing, "processing IR") + # SSA early + pm.add_pass(ReconstructSSA, "ssa") + pm.add_pass(DeadBranchPrune, "dead branch pruning") + # type and then lower as usual + pm.add_pass(PreserveIR, "preserves the IR as metadata") + dpb = DefaultPassBuilder + typed_passes = dpb.define_typed_pipeline(self.state) + pm.passes.extend(typed_passes.passes) + lowering_passes = dpb.define_nopython_lowering_pipeline(self.state) + pm.passes.extend(lowering_passes.passes) + pm.finalize() + return [pm] + + def test_ssa_update_phi(self): + # This checks that dead branch pruning is rewiring phi nodes correctly + # after a block containing an incoming for a phi is removed. + + @njit(pipeline_class=self.SSAPrunerCompiler) + def impl(p=None, q=None): + z = 1 + r = False + if p is None: + r = True # live + + if r and q is not None: + z = 20 # dead + + # one of the incoming blocks for z is dead, the phi needs an update + # were this not done, it would refer to variables that do not exist + # and result in a lowering error. + return z, r + + self.assertPreciseEqual(impl(), impl.py_func()) + + def test_ssa_replace_phi(self): + # This checks that when a phi only has one incoming, because the other + # has been pruned, that a direct assignment is used instead. + + @njit(pipeline_class=self.SSAPrunerCompiler) + def impl(p=None): + z = 0 + if p is None: + z = 10 + else: + z = 20 + + return z + + self.assertPreciseEqual(impl(), impl.py_func()) + func_ir = impl.overloads[impl.signatures[0]].metadata['preserved_ir'] + + # check the func_ir, make sure there's no phi nodes + for blk in func_ir.blocks.values(): + self.assertFalse([*blk.find_exprs('phi')]) + + +class TestBranchPrunePostSemanticConstRewrites(TestBranchPruneBase): + # Tests that semantic constants rewriting works by virtue of branch pruning + + def test_array_ndim_attr(self): + + def impl(array): + if array.ndim == 2: + if array.shape[1] == 2: + return 1 + else: + return 10 + + self.assert_prune(impl, (types.Array(types.float64, 2, 'C'),), [False, + None], + np.zeros((2, 3))) + self.assert_prune(impl, (types.Array(types.float64, 1, 'C'),), [True, + 'both'], + np.zeros((2,))) + + def test_tuple_len(self): + + def impl(tup): + if len(tup) == 3: + if tup[2] == 2: + return 1 + else: + return 0 + + self.assert_prune(impl, (types.UniTuple(types.int64, 3),), [False, + None], + tuple([1, 2, 3])) + self.assert_prune(impl, (types.UniTuple(types.int64, 2),), [True, + 'both'], + tuple([1, 2])) + + def test_attr_not_len(self): + # The purpose of this test is to make sure that the conditions guarding + # the rewrite part do not themselves raise exceptions. + # This produces an `ir.Expr` call node for `float.as_integer_ratio`, + # which is a getattr() on `float`. + + @njit + def test(): + float.as_integer_ratio(1.23) + + # this should raise a TypingError + with self.assertRaises(errors.TypingError) as e: + test() + + self.assertIn("Unknown attribute 'as_integer_ratio'", str(e.exception)) + + def test_ndim_not_on_array(self): + + FakeArray = collections.namedtuple('FakeArray', ['ndim']) + fa = FakeArray(ndim=2) + + def impl(fa): + if fa.ndim == 2: + return fa.ndim + else: + object() + + # check prune works for array ndim + self.assert_prune(impl, (types.Array(types.float64, 2, 'C'),), [False], + np.zeros((2, 3))) + + # check prune fails for something with `ndim` attr that is not array + FakeArrayType = types.NamedUniTuple(types.int64, 1, FakeArray) + self.assert_prune(impl, (FakeArrayType,), [None], fa, + flags={'nopython':False, 'forceobj':True}) + + def test_semantic_const_propagates_before_static_rewrites(self): + # see issue #5015, the ndim needs writing in as a const before + # the rewrite passes run to make e.g. getitems static where possible + @njit + def impl(a, b): + return a.shape[:b.ndim] + + args = (np.zeros((5, 4, 3, 2)), np.zeros((1, 1))) + + self.assertPreciseEqual(impl(*args), impl.py_func(*args)) + + def test_tuple_const_propagation(self): + @njit(pipeline_class=IRPreservingTestPipeline) + def impl(*args): + s = 0 + for arg in literal_unroll(args): + s += len(arg) + return s + + inp = ((), (1, 2, 3), ()) + self.assertPreciseEqual(impl(*inp), impl.py_func(*inp)) + + ol = impl.overloads[impl.signatures[0]] + func_ir = ol.metadata['preserved_ir'] + # make sure one of the inplace binop args is a Const + binop_consts = set() + for blk in func_ir.blocks.values(): + for expr in blk.find_exprs('inplace_binop'): + inst = blk.find_variable_assignment(expr.rhs.name) + self.assertIsInstance(inst.value, ir.Const) + binop_consts.add(inst.value.value) + self.assertEqual(binop_consts, {len(x) for x in inp}) diff --git a/lib/python3.10/site-packages/numba/tests/test_annotations.py b/lib/python3.10/site-packages/numba/tests/test_annotations.py new file mode 100644 index 0000000000000000000000000000000000000000..90e70eac808722d4b156c7ed36bb8ddd09bf9000 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_annotations.py @@ -0,0 +1,252 @@ +import re +from io import StringIO + +import numba +from numba.core import types +from numba import jit, njit +from numba.tests.support import override_config, TestCase +import unittest + +try: + import jinja2 +except ImportError: + jinja2 = None + +try: + import pygments +except ImportError: + pygments = None + + +@unittest.skipIf(jinja2 is None, "please install the 'jinja2' package") +class TestAnnotation(TestCase): + + @TestCase.run_test_in_subprocess # annotations compound per module + def test_exercise_code_path(self): + """ + Ensures template.html is available + """ + + def foo(n, a): + s = a + for i in range(n): + s += i + return s + + cfunc = njit((types.int32, types.int32))(foo) + cres = cfunc.overloads[cfunc.signatures[0]] + ta = cres.type_annotation + + buf = StringIO() + ta.html_annotate(buf) + output = buf.getvalue() + buf.close() + self.assertIn("foo", output) + + @TestCase.run_test_in_subprocess # annotations compound per module + def test_exercise_code_path_with_lifted_loop(self): + """ + Ensures that lifted loops are handled correctly in obj mode + """ + # the functions to jit + def bar(x): + return x + + def foo(x): + h = 0. + for i in range(x): # py 38 needs two loops for one to lift?! + h = h + i + for k in range(x): + h = h + k + if x: + h = h - bar(x) + return h + + # compile into an isolated context + cfunc = jit((types.intp,), forceobj=True, looplift=True)(foo) + cres = cfunc.overloads[cfunc.signatures[0]] + + ta = cres.type_annotation + + buf = StringIO() + ta.html_annotate(buf) + output = buf.getvalue() + buf.close() + self.assertIn("bar", output) + self.assertIn("foo", output) + self.assertIn("LiftedLoop", output) + + @TestCase.run_test_in_subprocess # annotations compound per module + def test_html_output_with_lifted_loop(self): + """ + Test some format and behavior of the html annotation with lifted loop + """ + @numba.jit(forceobj=True) + def udt(x): + object() # to force object mode + z = 0 + for i in range(x): # this line is tagged + z += i + return z + + # Regex pattern to check for the "lifted_tag" in the line of the loop + re_lifted_tag = re.compile( + r'\s*' + r'\s*
' + r'\s*' + r'\s*' + r'\s*[0-9]+:' + r'\s*[ ]+for i in range\(x\): # this line is tagged\s*', + re.MULTILINE) + + # Compile int64 version + sig_i64 = (types.int64,) + udt.compile(sig_i64) # compile with lifted loop + cres = udt.overloads[sig_i64] + + # Make html output + buf = StringIO() + cres.type_annotation.html_annotate(buf) + output = buf.getvalue() + buf.close() + + # There should be only one function output. + self.assertEqual(output.count("Function name: udt"), 1) + + sigfmt = "with signature: {} -> pyobject" + self.assertEqual(output.count(sigfmt.format(sig_i64)), 1) + # Ensure the loop is tagged + self.assertEqual(len(re.findall(re_lifted_tag, output)), 1, + msg='%s not found in %s' % (re_lifted_tag, output)) + + # Compile float64 version + sig_f64 = (types.float64,) + udt.compile(sig_f64) + cres = udt.overloads[sig_f64] + + # Make html output + buf = StringIO() + cres.type_annotation.html_annotate(buf) + output = buf.getvalue() + buf.close() + + # There should be two function output + self.assertEqual(output.count("Function name: udt"), 2) + self.assertEqual(output.count(sigfmt.format(sig_i64)), 1) + self.assertEqual(output.count(sigfmt.format(sig_f64)), 1) + # Ensure the loop is tagged in both output + self.assertEqual(len(re.findall(re_lifted_tag, output)), 2) + + @unittest.skipIf(pygments is None, "please install the 'pygments' package") + def test_pretty_print(self): + + @numba.njit + def foo(x, y): + return x, y + + foo(1, 2) + # Exercise the method + foo.inspect_types(pretty=True) + + # Exercise but supply a not None file kwarg, this is invalid + with self.assertRaises(ValueError) as raises: + foo.inspect_types(pretty=True, file='should be None') + self.assertIn('`file` must be None if `pretty=True`', + str(raises.exception)) + + +class TestTypeAnnotation(unittest.TestCase): + + def findpatloc(self, lines, pat): + for i, ln in enumerate(lines): + if pat in ln: + return i + raise ValueError("can't find {!r}".format(pat)) + + def getlines(self, func): + strbuf = StringIO() + func.inspect_types(strbuf) + return strbuf.getvalue().splitlines() + + def test_delete(self): + @numba.njit + def foo(appleorange, berrycherry): + return appleorange + berrycherry + + foo(1, 2) + + lines = self.getlines(foo) + + # Ensure deletion show up after their use + sa = self.findpatloc(lines, 'appleorange = arg(0, name=appleorange)') + sb = self.findpatloc(lines, 'berrycherry = arg(1, name=berrycherry)') + + ea = self.findpatloc(lines, 'del appleorange') + eb = self.findpatloc(lines, 'del berrycherry') + + self.assertLess(sa, ea) + self.assertLess(sb, eb) + + def _lifetimes_impl(self, extend): + with override_config('EXTEND_VARIABLE_LIFETIMES', extend): + @njit + def foo(a): + b = a + return b + x = 10 + b = foo(x) + self.assertEqual(b, x) + + lines = self.getlines(foo) + + sa = self.findpatloc(lines, 'a = arg(0, name=a)') + sb = self.findpatloc(lines, 'b = a') + + cast_ret = self.findpatloc(lines, 'cast(value=b)') + + dela = self.findpatloc(lines, 'del a') + delb = self.findpatloc(lines, 'del b') + + return sa, sb, cast_ret, dela, delb + + def test_delete_standard_lifetimes(self): + # without extended lifetimes, dels occur as soon as dead + # + # label 0 + # a = arg(0, name=a) :: int64 + # b = a :: int64 + # del a + # $8return_value.2 = cast(value=b) :: int64 + # del b + # return $8return_value.2 + + sa, sb, cast_ret, dela, delb = self._lifetimes_impl(extend=0) + + self.assertLess(sa, dela) + self.assertLess(sb, delb) + # del a is before cast and del b is after + self.assertLess(dela, cast_ret) + self.assertGreater(delb, cast_ret) + + def test_delete_extended_lifetimes(self): + # with extended lifetimes, dels are last in block: + # + # label 0 + # a = arg(0, name=a) :: int64 + # b = a :: int64 + # $8return_value.2 = cast(value=b) :: int64 + # del a + # del b + # return $8return_value.2 + + sa, sb, cast_ret, dela, delb = self._lifetimes_impl(extend=1) + + self.assertLess(sa, dela) + self.assertLess(sb, delb) + # dels are after the cast + self.assertGreater(dela, cast_ret) + self.assertGreater(delb, cast_ret) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_array_exprs.py b/lib/python3.10/site-packages/numba/tests/test_array_exprs.py new file mode 100644 index 0000000000000000000000000000000000000000..090bbd5ad483dde698299ac7f02d81812e11a0ee --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_array_exprs.py @@ -0,0 +1,742 @@ +import gc +from io import StringIO + +import numpy as np + +from numba import njit, vectorize +from numba import typeof +from numba.core import utils, types, typing, ir, compiler, cpu, cgutils +from numba.core.compiler import Compiler, Flags +from numba.core.registry import cpu_target +from numba.tests.support import (MemoryLeakMixin, TestCase, temp_directory, + create_temp_module) +from numba.extending import ( + overload, + models, + lower_builtin, + register_model, + make_attribute_wrapper, + type_callable, + typeof_impl +) +import operator +import textwrap + +import unittest + + +class Namespace(dict): + def __getattr__(s, k): + return s[k] if k in s else super(Namespace, s).__getattr__(k) + +def axy(a, x, y): + return a * x + y + +def ax2(a, x, y): + return a * x + y + +def pos_root(As, Bs, Cs): + return (-Bs + (((Bs ** 2.) - (4. * As * Cs)) ** 0.5)) / (2. * As) + +def neg_root_common_subexpr(As, Bs, Cs): + _2As = 2. * As + _4AsCs = 2. * _2As * Cs + _Bs2_4AsCs = (Bs ** 2. - _4AsCs) + return (-Bs - (_Bs2_4AsCs ** 0.5)) / _2As + +def neg_root_complex_subexpr(As, Bs, Cs): + _2As = 2. * As + _4AsCs = 2. * _2As * Cs + _Bs2_4AsCs = (Bs ** 2. - _4AsCs) + 0j # Force into the complex domain. + return (-Bs - (_Bs2_4AsCs ** 0.5)) / _2As + +vaxy = vectorize(axy) + +def call_stuff(a0, a1): + return np.cos(vaxy(a0, np.sin(a1) - 1., 1.)) + +def are_roots_imaginary(As, Bs, Cs): + return (Bs ** 2 - 4 * As * Cs) < 0 + +def div_add(As, Bs, Cs): + return As / Bs + Cs + +def cube(As): + return As ** 3 + +def explicit_output(a, b, out): + np.cos(a, out) + return np.add(out, b, out) + +def variable_name_reuse(a, b, c, d): + u = a + b + u = u - a * b + u = u * c + d + return u + + +# From issue #1264 +def distance_matrix(vectors): + n_vectors = vectors.shape[0] + result = np.empty((n_vectors, n_vectors), dtype=np.float64) + + for i in range(n_vectors): + for j in range(i, n_vectors): + result[i,j] = result[j,i] = np.sum( + (vectors[i] - vectors[j]) ** 2) ** 0.5 + + return result + + +class RewritesTester(Compiler): + @classmethod + def mk_pipeline(cls, args, return_type=None, flags=None, locals={}, + library=None, typing_context=None, target_context=None): + if not flags: + flags = Flags() + flags.nrt = True + if typing_context is None: + typing_context = cpu_target.typing_context + if target_context is None: + target_context = cpu_target.target_context + return cls(typing_context, target_context, library, args, return_type, + flags, locals) + + @classmethod + def mk_no_rw_pipeline(cls, args, return_type=None, flags=None, locals={}, + library=None, **kws): + if not flags: + flags = Flags() + flags.no_rewrites = True + return cls.mk_pipeline(args, return_type, flags, locals, library, **kws) + + +class TestArrayExpressions(MemoryLeakMixin, TestCase): + + def _compile_function(self, fn, arg_tys): + """ + Compile the given function both without and with rewrites enabled. + """ + control_pipeline = RewritesTester.mk_no_rw_pipeline(arg_tys) + cres_0 = control_pipeline.compile_extra(fn) + control_cfunc = cres_0.entry_point + + test_pipeline = RewritesTester.mk_pipeline(arg_tys) + cres_1 = test_pipeline.compile_extra(fn) + test_cfunc = cres_1.entry_point + + return control_pipeline, control_cfunc, test_pipeline, test_cfunc + + def test_simple_expr(self): + ''' + Using a simple array expression, verify that rewriting is taking + place, and is fusing loops. + ''' + A = np.linspace(0,1,10) + X = np.linspace(2,1,10) + Y = np.linspace(1,2,10) + arg_tys = [typeof(arg) for arg in (A, X, Y)] + + control_pipeline, nb_axy_0, test_pipeline, nb_axy_1 = \ + self._compile_function(axy, arg_tys) + + control_pipeline2 = RewritesTester.mk_no_rw_pipeline(arg_tys) + cres_2 = control_pipeline2.compile_extra(ax2) + nb_ctl = cres_2.entry_point + + expected = nb_axy_0(A, X, Y) + actual = nb_axy_1(A, X, Y) + control = nb_ctl(A, X, Y) + np.testing.assert_array_equal(expected, actual) + np.testing.assert_array_equal(control, actual) + + ir0 = control_pipeline.state.func_ir.blocks + ir1 = test_pipeline.state.func_ir.blocks + ir2 = control_pipeline2.state.func_ir.blocks + self.assertEqual(len(ir0), len(ir1)) + self.assertEqual(len(ir0), len(ir2)) + # The rewritten IR should be smaller than the original. + self.assertGreater(len(ir0[0].body), len(ir1[0].body)) + self.assertEqual(len(ir0[0].body), len(ir2[0].body)) + + def _get_array_exprs(self, block): + for instr in block: + if isinstance(instr, ir.Assign): + if isinstance(instr.value, ir.Expr): + if instr.value.op == 'arrayexpr': + yield instr + + def _array_expr_to_set(self, expr, out=None): + ''' + Convert an array expression tree into a set of operators. + ''' + if out is None: + out = set() + if not isinstance(expr, tuple): + raise ValueError("{0} not a tuple".format(expr)) + operation, operands = expr + processed_operands = [] + for operand in operands: + if isinstance(operand, tuple): + operand, _ = self._array_expr_to_set(operand, out) + processed_operands.append(operand) + processed_expr = operation, tuple(processed_operands) + out.add(processed_expr) + return processed_expr, out + + def _test_root_function(self, fn=pos_root): + A = np.random.random(10) + B = np.random.random(10) + 1. # Increase likelihood of real + # root (could add 2 to force all + # roots to be real). + C = np.random.random(10) + arg_tys = [typeof(arg) for arg in (A, B, C)] + + control_pipeline = RewritesTester.mk_no_rw_pipeline(arg_tys) + control_cres = control_pipeline.compile_extra(fn) + nb_fn_0 = control_cres.entry_point + + test_pipeline = RewritesTester.mk_pipeline(arg_tys) + test_cres = test_pipeline.compile_extra(fn) + nb_fn_1 = test_cres.entry_point + + np_result = fn(A, B, C) + nb_result_0 = nb_fn_0(A, B, C) + nb_result_1 = nb_fn_1(A, B, C) + np.testing.assert_array_almost_equal(np_result, nb_result_0) + np.testing.assert_array_almost_equal(nb_result_0, nb_result_1) + + return Namespace(locals()) + + def _test_cube_function(self, fn=cube): + A = np.arange(10, dtype=np.float64) + arg_tys = (typeof(A),) + + control_pipeline = RewritesTester.mk_no_rw_pipeline(arg_tys) + control_cres = control_pipeline.compile_extra(fn) + nb_fn_0 = control_cres.entry_point + + test_pipeline = RewritesTester.mk_pipeline(arg_tys) + test_cres = test_pipeline.compile_extra(fn) + nb_fn_1 = test_cres.entry_point + + expected = A ** 3 + self.assertPreciseEqual(expected, nb_fn_0(A)) + self.assertPreciseEqual(expected, nb_fn_1(A)) + + return Namespace(locals()) + + def _test_explicit_output_function(self, fn): + """ + Test function having a (a, b, out) signature where *out* is + an output array the function writes into. + """ + A = np.arange(10, dtype=np.float64) + B = A + 1 + arg_tys = (typeof(A),) * 3 + + control_pipeline, control_cfunc, test_pipeline, test_cfunc = \ + self._compile_function(fn, arg_tys) + + def run_func(fn): + out = np.zeros_like(A) + fn(A, B, out) + return out + + expected = run_func(fn) + self.assertPreciseEqual(expected, run_func(control_cfunc)) + self.assertPreciseEqual(expected, run_func(test_cfunc)) + + return Namespace(locals()) + + def _assert_array_exprs(self, block, expected_count): + """ + Assert the *block* has the expected number of array expressions + in it. + """ + rewrite_count = len(list(self._get_array_exprs(block))) + self.assertEqual(rewrite_count, expected_count) + + def _assert_total_rewrite(self, control_ir, test_ir, trivial=False): + """ + Given two dictionaries of Numba IR blocks, check to make sure the + control IR has no array expressions, while the test IR + contains one and only one. + """ + # Both IRs have the same number of blocks (presumably 1) + self.assertEqual(len(control_ir), len(test_ir)) + control_block = control_ir[0].body + test_block = test_ir[0].body + self._assert_array_exprs(control_block, 0) + self._assert_array_exprs(test_block, 1) + if not trivial: + # If the expression wasn't trivial, the block length should + # have decreased (since a sequence of exprs was replaced + # with a single nested array expr). + self.assertGreater(len(control_block), len(test_block)) + + def _assert_no_rewrite(self, control_ir, test_ir): + """ + Given two dictionaries of Numba IR blocks, check to make sure + the control IR and the test IR both have no array expressions. + """ + self.assertEqual(len(control_ir), len(test_ir)) + # All blocks should be identical, and not rewritten + for k, v in control_ir.items(): + control_block = v.body + test_block = test_ir[k].body + self.assertEqual(len(control_block), len(test_block)) + self._assert_array_exprs(control_block, 0) + self._assert_array_exprs(test_block, 0) + + def test_trivial_expr(self): + """ + Ensure even a non-nested expression is rewritten, as it can enable + scalar optimizations such as rewriting `x ** 2`. + """ + ns = self._test_cube_function() + self._assert_total_rewrite(ns.control_pipeline.state.func_ir.blocks, + ns.test_pipeline.state.func_ir.blocks, + trivial=True) + + def test_complicated_expr(self): + ''' + Using the polynomial root function, ensure the full expression is + being put in the same kernel with no remnants of intermediate + array expressions. + ''' + ns = self._test_root_function() + self._assert_total_rewrite(ns.control_pipeline.state.func_ir.blocks, + ns.test_pipeline.state.func_ir.blocks) + + def test_common_subexpressions(self, fn=neg_root_common_subexpr): + ''' + Attempt to verify that rewriting will incorporate user common + subexpressions properly. + ''' + ns = self._test_root_function(fn) + ir0 = ns.control_pipeline.state.func_ir.blocks + ir1 = ns.test_pipeline.state.func_ir.blocks + self.assertEqual(len(ir0), len(ir1)) + self.assertGreater(len(ir0[0].body), len(ir1[0].body)) + self.assertEqual(len(list(self._get_array_exprs(ir0[0].body))), 0) + # Verify that we didn't rewrite everything into a monolithic + # array expression since we stored temporary values in + # variables that might be used later (from the optimization's + # point of view). + array_expr_instrs = list(self._get_array_exprs(ir1[0].body)) + self.assertGreater(len(array_expr_instrs), 1) + # Now check that we haven't duplicated any subexpressions in + # the rewritten code. + array_sets = list(self._array_expr_to_set(instr.value.expr)[1] + for instr in array_expr_instrs) + for expr_set_0, expr_set_1 in zip(array_sets[:-1], array_sets[1:]): + intersections = expr_set_0.intersection(expr_set_1) + if intersections: + self.fail("Common subexpressions detected in array " + "expressions ({0})".format(intersections)) + + def test_complex_subexpression(self): + return self.test_common_subexpressions(neg_root_complex_subexpr) + + def test_ufunc_and_dufunc_calls(self): + ''' + Verify that ufunc and DUFunc calls are being properly included in + array expressions. + ''' + A = np.random.random(10) + B = np.random.random(10) + arg_tys = [typeof(arg) for arg in (A, B)] + + vaxy_descr = vaxy._dispatcher.targetdescr + control_pipeline = RewritesTester.mk_no_rw_pipeline( + arg_tys, + typing_context=vaxy_descr.typing_context, + target_context=vaxy_descr.target_context) + cres_0 = control_pipeline.compile_extra(call_stuff) + nb_call_stuff_0 = cres_0.entry_point + + test_pipeline = RewritesTester.mk_pipeline( + arg_tys, + typing_context=vaxy_descr.typing_context, + target_context=vaxy_descr.target_context) + cres_1 = test_pipeline.compile_extra(call_stuff) + nb_call_stuff_1 = cres_1.entry_point + + expected = call_stuff(A, B) + control = nb_call_stuff_0(A, B) + actual = nb_call_stuff_1(A, B) + np.testing.assert_array_almost_equal(expected, control) + np.testing.assert_array_almost_equal(expected, actual) + + self._assert_total_rewrite(control_pipeline.state.func_ir.blocks, + test_pipeline.state.func_ir.blocks) + + def test_cmp_op(self): + ''' + Verify that comparison operators are supported by the rewriter. + ''' + ns = self._test_root_function(are_roots_imaginary) + self._assert_total_rewrite(ns.control_pipeline.state.func_ir.blocks, + ns.test_pipeline.state.func_ir.blocks) + + def test_explicit_output(self): + """ + Check that ufunc calls with explicit outputs are not rewritten. + """ + ns = self._test_explicit_output_function(explicit_output) + self._assert_no_rewrite(ns.control_pipeline.state.func_ir.blocks, + ns.test_pipeline.state.func_ir.blocks) + + +class TestRewriteIssues(MemoryLeakMixin, TestCase): + + def test_issue_1184(self): + from numba import jit + import numpy as np + + @jit(nopython=True) + def foo(arr): + return arr + + @jit(nopython=True) + def bar(arr): + c = foo(arr) + d = foo(arr) # two calls to trigger rewrite + return c, d + + arr = np.arange(10) + out_c, out_d = bar(arr) + self.assertIs(out_c, out_d) + self.assertIs(out_c, arr) + + def test_issue_1264(self): + n = 100 + x = np.random.uniform(size=n*3).reshape((n,3)) + expected = distance_matrix(x) + actual = njit(distance_matrix)(x) + np.testing.assert_array_almost_equal(expected, actual) + # Avoid sporadic failures in MemoryLeakMixin.tearDown() + gc.collect() + + def test_issue_1372(self): + """Test array expression with duplicated term""" + from numba import njit + + @njit + def foo(a, b): + b = np.sin(b) + return b + b + a + + a = np.random.uniform(10) + b = np.random.uniform(10) + expect = foo.py_func(a, b) + got = foo(a, b) + np.testing.assert_allclose(got, expect) + + def test_unary_arrayexpr(self): + """ + Typing of unary array expression (np.negate) can be incorrect. + """ + @njit + def foo(a, b): + return b - a + -a + + b = 1.5 + a = np.arange(10, dtype=np.int32) + + expect = foo.py_func(a, b) + got = foo(a, b) + self.assertPreciseEqual(got, expect) + + def test_bitwise_arrayexpr(self): + """ + Typing of bitwise boolean array expression can be incorrect + (issue #1813). + """ + @njit + def foo(a, b): + return ~(a & (~b)) + + a = np.array([True, True, False, False]) + b = np.array([False, True, False, True]) + + expect = foo.py_func(a, b) + got = foo(a, b) + self.assertPreciseEqual(got, expect) + + def test_annotations(self): + """ + Type annotation of array expressions with disambiguated + variable names (issue #1466). + """ + cfunc = njit(variable_name_reuse) + + a = np.linspace(0, 1, 10) + cfunc(a, a, a, a) + + buf = StringIO() + cfunc.inspect_types(buf) + res = buf.getvalue() + self.assertIn("# u.1 = ", res) + self.assertIn("# u.2 = ", res) + + def test_issue_5599_name_collision(self): + # The original error will fail in lowering of the array_expr + @njit + def f(x): + arr = np.ones(x) + + for _ in range(2): + val = arr * arr + arr = arr.copy() + return arr + + got = f(5) + expect = f.py_func(5) + np.testing.assert_array_equal(got, expect) + + +class TestSemantics(MemoryLeakMixin, unittest.TestCase): + + def test_division_by_zero(self): + # Array expressions should follow the Numpy error model + # i.e. 1./0. returns +inf instead of raising ZeroDivisionError + pyfunc = div_add + cfunc = njit(pyfunc) + + a = np.float64([0.0, 1.0, float('inf')]) + b = np.float64([0.0, 0.0, 1.0]) + c = np.ones_like(a) + + expect = pyfunc(a, b, c) + got = cfunc(a, b, c) + np.testing.assert_array_equal(expect, got) + + +class TestOptionals(MemoryLeakMixin, unittest.TestCase): + """ Tests the arrival and correct lowering of Optional types at a arrayexpr + derived ufunc, see #3972""" + + def test_optional_scalar_type(self): + + @njit + def arr_expr(x, y): + return x + y + + @njit + def do_call(x, y): + if y > 0: + z = None + else: + z = y + return arr_expr(x, z) + + args = (np.arange(5), -1.2) + + # check result + res = do_call(*args) + expected = do_call.py_func(*args) + np.testing.assert_allclose(res, expected) + + # check type + s = arr_expr.signatures + oty = s[0][1] + self.assertTrue(isinstance(oty, types.Optional)) + self.assertTrue(isinstance(oty.type, types.Float)) + + def test_optional_array_type(self): + + @njit + def arr_expr(x, y): + return x + y + + @njit + def do_call(x, y): + if y[0] > 0: + z = None + else: + z = y + return arr_expr(x, z) + + args = (np.arange(5), np.arange(5.)) + + # check result + res = do_call(*args) + expected = do_call.py_func(*args) + np.testing.assert_allclose(res, expected) + + # check type + s = arr_expr.signatures + oty = s[0][1] + self.assertTrue(isinstance(oty, types.Optional)) + self.assertTrue(isinstance(oty.type, types.Array)) + self.assertTrue(isinstance(oty.type.dtype, types.Float)) + + +class TestOptionalsExceptions(MemoryLeakMixin, unittest.TestCase): + # same as above, but the Optional resolves to None and TypeError's + + def test_optional_scalar_type_exception_on_none(self): + + self.disable_leak_check() + + @njit + def arr_expr(x, y): + return x + y + + @njit + def do_call(x, y): + if y > 0: + z = None + else: + z = y + return arr_expr(x, z) + + args = (np.arange(5), 1.0) + + # check result + with self.assertRaises(TypeError) as raises: + do_call(*args) + + self.assertIn("expected float64, got None", str(raises.exception)) + + # check type + s = arr_expr.signatures + oty = s[0][1] + self.assertTrue(isinstance(oty, types.Optional)) + self.assertTrue(isinstance(oty.type, types.Float)) + + def test_optional_array_type_exception_on_none(self): + + self.disable_leak_check() + + @njit + def arr_expr(x, y): + return x + y + + @njit + def do_call(x, y): + if y[0] > 0: + z = None + else: + z = y + return arr_expr(x, z) + + args = (np.arange(5), np.arange(1., 5.)) + + # check result + with self.assertRaises(TypeError) as raises: + do_call(*args) + + excstr = str(raises.exception) + self.assertIn("expected array(float64,", excstr) + self.assertIn("got None", excstr) + + # check type + s = arr_expr.signatures + oty = s[0][1] + self.assertTrue(isinstance(oty, types.Optional)) + self.assertTrue(isinstance(oty.type, types.Array)) + self.assertTrue(isinstance(oty.type.dtype, types.Float)) + + +class TestExternalTypes(MemoryLeakMixin, unittest.TestCase): + """ Tests RewriteArrayExprs with external (user defined) types, + see #5157""" + + source_lines = textwrap.dedent(""" + from numba.core import types + + class FooType(types.Type): + def __init__(self): + super(FooType, self).__init__(name='Foo') + """) + + def make_foo_type(self, FooType): + class Foo(object): + def __init__(self, value): + self.value = value + + @register_model(FooType) + class FooModel(models.StructModel): + def __init__(self, dmm, fe_type): + members = [("value", types.intp)] + models.StructModel.__init__(self, dmm, fe_type, members) + + make_attribute_wrapper(FooType, "value", "value") + + @type_callable(Foo) + def type_foo(context): + def typer(value): + return FooType() + + return typer + + @lower_builtin(Foo, types.intp) + def impl_foo(context, builder, sig, args): + typ = sig.return_type + [value] = args + foo = cgutils.create_struct_proxy(typ)(context, builder) + foo.value = value + return foo._getvalue() + + @typeof_impl.register(Foo) + def typeof_foo(val, c): + return FooType() + + return Foo, FooType + + def test_external_type(self): + with create_temp_module(self.source_lines) as test_module: + Foo, FooType = self.make_foo_type(test_module.FooType) + + # sum of foo class instance and array return an array + # binary operation with foo class instance as one of args + @overload(operator.add) + def overload_foo_add(lhs, rhs): + if isinstance(lhs, FooType) and isinstance(rhs, types.Array): + def imp(lhs, rhs): + return np.array([lhs.value, rhs[0]]) + + return imp + + # sum of 2 foo class instances return an array + # binary operation with 2 foo class instances as args + @overload(operator.add) + def overload_foo_add(lhs, rhs): + if isinstance(lhs, FooType) and isinstance(rhs, FooType): + def imp(lhs, rhs): + return np.array([lhs.value, rhs.value]) + + return imp + + # neg of foo class instance return an array + # unary operation with foo class instance arg + @overload(operator.neg) + def overload_foo_neg(x): + if isinstance(x, FooType): + def imp(x): + return np.array([-x.value]) + + return imp + + @njit + def arr_expr_sum1(x, y): + return Foo(x) + np.array([y]) + + @njit + def arr_expr_sum2(x, y): + return Foo(x) + Foo(y) + + @njit + def arr_expr_neg(x): + return -Foo(x) + + np.testing.assert_array_equal(arr_expr_sum1(0, 1), np.array([0, 1])) + np.testing.assert_array_equal(arr_expr_sum2(2, 3), np.array([2, 3])) + np.testing.assert_array_equal(arr_expr_neg(4), np.array([-4])) + + +if __name__ == "__main__": + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_array_manipulation.py b/lib/python3.10/site-packages/numba/tests/test_array_manipulation.py new file mode 100644 index 0000000000000000000000000000000000000000..2539319fd560a759004484e715c31b9ed076a68e --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_array_manipulation.py @@ -0,0 +1,1588 @@ +from functools import partial +from itertools import permutations + +import numpy as np + +import unittest +from numba import jit, njit, from_dtype, typeof +from numba.core.errors import TypingError +from numba.core import types, errors +from numba.tests.support import TestCase, MemoryLeakMixin + +enable_pyobj_flags = {'forceobj': True} + +no_pyobj_flags = {'_nrt': True, 'nopython': True} + + +def from_generic(pyfuncs_to_use): + """Decorator for generic check functions. + Iterates over 'pyfuncs_to_use', calling 'func' with the iterated + item as first argument. Example: + + @from_generic(numpy_array_reshape, array_reshape) + def check_only_shape(pyfunc, arr, shape, expected_shape): + # Only check Numba result to avoid Numpy bugs + self.memory_leak_setup() + got = generic_run(pyfunc, arr, shape) + self.assertEqual(got.shape, expected_shape) + self.assertEqual(got.size, arr.size) + del got + self.memory_leak_teardown() + """ + def decorator(func): + def result(*args, **kwargs): + return [func(pyfunc, *args, **kwargs) for pyfunc in pyfuncs_to_use] + return result + return decorator + + +@njit +def array_reshape(arr, newshape): + return arr.reshape(newshape) + +@njit +def numpy_array_reshape(arr, newshape): + return np.reshape(arr, newshape) + + +def numpy_broadcast_to(arr, shape): + return np.broadcast_to(arr, shape) + + +def numpy_broadcast_shapes(*args): + return np.broadcast_shapes(*args) + + +def numpy_broadcast_arrays(*args): + return np.broadcast_arrays(*args) + + +def numpy_broadcast_to_indexing(arr, shape, idx): + return np.broadcast_to(arr, shape)[idx] + + +def flatten_array(a): + return a.flatten() + + +def ravel_array(a): + return a.ravel() + + +def ravel_array_size(a): + return a.ravel().size + + +def numpy_ravel_array(a): + return np.ravel(a) + + +def transpose_array(a): + return a.transpose() + + +def numpy_transpose_array(a): + return np.transpose(a) + + +@njit +def numpy_transpose_array_axes_kwarg(arr, axes): + return np.transpose(arr, axes=axes) + + +@njit +def numpy_transpose_array_axes_kwarg_copy(arr, axes): + return np.transpose(arr, axes=axes).copy() + + +@njit +def array_transpose_axes(arr, axes): + return arr.transpose(axes) + + +@njit +def array_transpose_axes_copy(arr, axes): + return arr.transpose(axes).copy() + + +@njit +def transpose_issue_4708(m, n): + r1 = np.reshape(np.arange(m * n * 3), (m, 3, n)) + r2 = np.reshape(np.arange(n * 3), (n, 3)) + r_dif = (r1 - r2.T).T + r_dif = np.transpose(r_dif, (2, 0, 1)) + z = r_dif + 1 + return z + + +def squeeze_array(a): + return a.squeeze() + + +def expand_dims(a, axis): + return np.expand_dims(a, axis) + + +def atleast_1d(*args): + return np.atleast_1d(*args) + + +def atleast_2d(*args): + return np.atleast_2d(*args) + + +def atleast_3d(*args): + return np.atleast_3d(*args) + + +def as_strided1(a): + # as_strided() with implicit shape + strides = (a.strides[0] // 2,) + a.strides[1:] + return np.lib.stride_tricks.as_strided(a, strides=strides) + + +def as_strided2(a): + # Rolling window example as in https://github.com/numba/numba/issues/1884 + window = 3 + shape = a.shape[:-1] + (a.shape[-1] - window + 1, window) + strides = a.strides + (a.strides[-1],) + return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides) + + +@njit +def sliding_window_view(x, window_shape, axis=None): + return np.lib.stride_tricks.sliding_window_view(x, window_shape, axis=axis) + + +def bad_index(arr, arr2d): + x = arr.x, + y = arr.y + # note that `x` is a tuple, which causes a new axis to be created. + arr2d[x, y] = 1.0 + + +def bad_float_index(arr): + # 2D index required for this function because 1D index + # fails typing + return arr[1, 2.0] + + +def numpy_fill_diagonal(arr, val, wrap=False): + return np.fill_diagonal(arr, val, wrap) + + +def numpy_shape(arr): + return np.shape(arr) + +def numpy_size(arr): + return np.size(arr) + + +def numpy_flatnonzero(a): + return np.flatnonzero(a) + + +def numpy_argwhere(a): + return np.argwhere(a) + +def numpy_resize(a, new_shape): + return np.resize(a, new_shape) + + +class TestArrayManipulation(MemoryLeakMixin, TestCase): + """ + Check shape-changing operations on arrays. + """ + def test_array_reshape(self): + pyfuncs_to_use = [array_reshape, numpy_array_reshape] + + def generic_run(pyfunc, arr, shape): + return pyfunc(arr, shape) + + @from_generic(pyfuncs_to_use) + def check(pyfunc, arr, shape): + expected = pyfunc.py_func(arr, shape) + self.memory_leak_setup() + got = generic_run(pyfunc, arr, shape) + self.assertPreciseEqual(got, expected) + del got + self.memory_leak_teardown() + + @from_generic(pyfuncs_to_use) + def check_only_shape(pyfunc, arr, shape, expected_shape): + # Only check Numba result to avoid Numpy bugs + self.memory_leak_setup() + got = generic_run(pyfunc, arr, shape) + self.assertEqual(got.shape, expected_shape) + self.assertEqual(got.size, arr.size) + del got + self.memory_leak_teardown() + + @from_generic(pyfuncs_to_use) + def check_err_shape(pyfunc, arr, shape): + with self.assertRaises(NotImplementedError) as raises: + generic_run(pyfunc, arr, shape) + self.assertEqual(str(raises.exception), + "incompatible shape for array") + + @from_generic(pyfuncs_to_use) + def check_err_size(pyfunc, arr, shape): + with self.assertRaises(ValueError) as raises: + generic_run(pyfunc, arr, shape) + self.assertEqual(str(raises.exception), + "total size of new array must be unchanged") + + @from_generic(pyfuncs_to_use) + def check_err_multiple_negative(pyfunc, arr, shape): + with self.assertRaises(ValueError) as raises: + generic_run(pyfunc, arr, shape) + self.assertEqual(str(raises.exception), + "multiple negative shape values") + + + # C-contiguous + arr = np.arange(24) + check(arr, (24,)) + check(arr, (4, 6)) + check(arr, (8, 3)) + check(arr, (8, 1, 3)) + check(arr, (1, 8, 1, 1, 3, 1)) + arr = np.arange(24).reshape((2, 3, 4)) + check(arr, (24,)) + check(arr, (4, 6)) + check(arr, (8, 3)) + check(arr, (8, 1, 3)) + check(arr, (1, 8, 1, 1, 3, 1)) + check_err_size(arr, ()) + check_err_size(arr, (25,)) + check_err_size(arr, (8, 4)) + arr = np.arange(24).reshape((1, 8, 1, 1, 3, 1)) + check(arr, (24,)) + check(arr, (4, 6)) + check(arr, (8, 3)) + check(arr, (8, 1, 3)) + + # F-contiguous + arr = np.arange(24).reshape((2, 3, 4)).T + check(arr, (4, 3, 2)) + check(arr, (1, 4, 1, 3, 1, 2, 1)) + check_err_shape(arr, (2, 3, 4)) + check_err_shape(arr, (6, 4)) + check_err_shape(arr, (2, 12)) + + # Test negative shape value + arr = np.arange(25).reshape(5,5) + check(arr, -1) + check(arr, (-1,)) + check(arr, (-1, 5)) + check(arr, (5, -1, 5)) + check(arr, (5, 5, -1)) + check_err_size(arr, (-1, 4)) + check_err_multiple_negative(arr, (-1, -2, 5, 5)) + check_err_multiple_negative(arr, (5, 5, -1, -1)) + + # 0-sized arrays + def check_empty(arr): + check(arr, 0) + check(arr, (0,)) + check(arr, (1, 0, 2)) + check(arr, (0, 55, 1, 0, 2)) + # -1 is buggy in Numpy with 0-sized arrays + check_only_shape(arr, -1, (0,)) + check_only_shape(arr, (-1,), (0,)) + check_only_shape(arr, (0, -1), (0, 0)) + check_only_shape(arr, (4, -1), (4, 0)) + check_only_shape(arr, (-1, 0, 4), (0, 0, 4)) + check_err_size(arr, ()) + check_err_size(arr, 1) + check_err_size(arr, (1, 2)) + + arr = np.array([]) + check_empty(arr) + check_empty(arr.reshape((3, 2, 0))) + + # Exceptions leak references + self.disable_leak_check() + + def test_array_transpose_axes(self): + pyfuncs_to_use = [numpy_transpose_array_axes_kwarg, + numpy_transpose_array_axes_kwarg_copy, + array_transpose_axes, + array_transpose_axes_copy] + + @from_generic(pyfuncs_to_use) + def check(pyfunc, arr, axes): + expected = pyfunc.py_func(arr, axes) + got = pyfunc(arr, axes) + self.assertPreciseEqual(got, expected) + self.assertEqual(got.flags.f_contiguous, + expected.flags.f_contiguous) + self.assertEqual(got.flags.c_contiguous, + expected.flags.c_contiguous) + + @from_generic(pyfuncs_to_use) + def check_err_axis_repeated(pyfunc, arr, axes): + with self.assertRaises(ValueError) as raises: + pyfunc(arr, axes) + self.assertEqual(str(raises.exception), + "repeated axis in transpose") + + @from_generic(pyfuncs_to_use) + def check_err_axis_oob(pyfunc, arr, axes): + with self.assertRaises(ValueError) as raises: + pyfunc(arr, axes) + self.assertEqual(str(raises.exception), + "axis is out of bounds for array of given dimension") + + @from_generic(pyfuncs_to_use) + def check_err_invalid_args(pyfunc, arr, axes): + with self.assertRaises((TypeError, TypingError)): + pyfunc(arr, axes) + + arrs = [np.arange(24), + np.arange(24).reshape(4, 6), + np.arange(24).reshape(2, 3, 4), + np.arange(24).reshape(1, 2, 3, 4), + np.arange(64).reshape(8, 4, 2)[::3,::2,:]] + + for i in range(len(arrs)): + # First check `None`, the default, which is to reverse dims + check(arrs[i], None) + # Check supplied axis permutations + for axes in permutations(tuple(range(arrs[i].ndim))): + ndim = len(axes) + neg_axes = tuple([x - ndim for x in axes]) + check(arrs[i], axes) + check(arrs[i], neg_axes) + + @from_generic([transpose_issue_4708]) + def check_issue_4708(pyfunc, m, n): + expected = pyfunc.py_func(m, n) + got = pyfunc(m, n) + # values in arrays are equals, + # but stronger assertions not hold (layout and strides equality) + np.testing.assert_equal(got, expected) + + check_issue_4708(3, 2) + check_issue_4708(2, 3) + check_issue_4708(5, 4) + + # Exceptions leak references + self.disable_leak_check() + + check_err_invalid_args(arrs[1], "foo") + check_err_invalid_args(arrs[1], ("foo",)) + check_err_invalid_args(arrs[1], 5.3) + check_err_invalid_args(arrs[2], (1.2, 5)) + + check_err_axis_repeated(arrs[1], (0, 0)) + check_err_axis_repeated(arrs[2], (2, 0, 0)) + check_err_axis_repeated(arrs[3], (3, 2, 1, 1)) + + check_err_axis_oob(arrs[0], (1,)) + check_err_axis_oob(arrs[0], (-2,)) + check_err_axis_oob(arrs[1], (0, 2)) + check_err_axis_oob(arrs[1], (-3, 2)) + check_err_axis_oob(arrs[1], (0, -3)) + check_err_axis_oob(arrs[2], (3, 1, 2)) + check_err_axis_oob(arrs[2], (-4, 1, 2)) + check_err_axis_oob(arrs[3], (3, 1, 2, 5)) + check_err_axis_oob(arrs[3], (3, 1, 2, -5)) + + with self.assertRaises(TypingError) as e: + jit(nopython=True)(numpy_transpose_array)((np.array([0, 1]),)) + self.assertIn("np.transpose does not accept tuples", + str(e.exception)) + + def test_numpy_resize_basic(self): + pyfunc = numpy_resize + cfunc = njit(pyfunc) + def inputs(): + # Taken from https://github.com/numpy/numpy/blob/f0b2fca91a1f5f50ff696895072f6fe9e69c1466/numpy/core/tests/test_numeric.py#L24-L64 noqa: E501 + yield np.array([[1, 2], [3, 4]]), (2, 4) + yield np.array([[1, 2], [3, 4]]), (4, 2) + yield np.array([[1, 2], [3, 4]]), (4, 3) + yield np.array([[1, 2], [3, 4]]), (0,) + yield np.array([[1, 2], [3, 4]]), (0, 2) + yield np.array([[1, 2], [3, 4]]), (2, 0) + yield np.zeros(0, dtype = float), (2, 1) + # other + yield np.array([[1, 2], [3, 4]]), (4,) + yield np.array([[1, 2], [3, 4]]), 4 + yield np.zeros((1, 3), dtype = int), (2, 1) + yield np.array([], dtype = float), (4, 2) + yield [0, 1, 2, 3], (2, 3) + yield 4, (2, 3) + + for a, new_shape in inputs(): + self.assertPreciseEqual(pyfunc(a, new_shape), cfunc(a, new_shape)) + + def test_numpy_resize_exception(self): + # Exceptions leak references + self.disable_leak_check() + + cfunc = njit(numpy_resize) + + with self.assertRaises(TypingError) as raises: + cfunc("abc", (2, 3)) + self.assertIn(('The argument "a" must be array-like'), + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc(np.array([[0,1],[2,3]]), "abc") + self.assertIn(('The argument "new_shape" must be an integer or ' + 'a tuple of integers'), + str(raises.exception)) + + with self.assertRaises(ValueError) as raises: + cfunc(np.array([[0,1],[2,3]]), (-2, 3)) + self.assertIn(('All elements of `new_shape` must be non-negative'), + str(raises.exception)) + + with self.assertRaises(ValueError) as raises: + cfunc(np.array([[0,1],[2,3]]), -4) + self.assertIn(('All elements of `new_shape` must be non-negative'), + str(raises.exception)) + + def test_expand_dims(self): + pyfunc = expand_dims + cfunc = njit(pyfunc) + + def check(arr, axis): + expected = pyfunc(arr, axis) + self.memory_leak_setup() + got = cfunc(arr, axis) + self.assertPreciseEqual(got, expected) + del got + self.memory_leak_teardown() + + def check_all_axes(arr): + for axis in range(-arr.ndim - 1, arr.ndim + 1): + check(arr, axis) + + # 1d + arr = np.arange(5) + check_all_axes(arr) + # 3d (C, F, A) + arr = np.arange(24).reshape((2, 3, 4)) + check_all_axes(arr) + check_all_axes(arr.T) + check_all_axes(arr[::-1]) + # 0d + arr = np.array(42) + check_all_axes(arr) + + def test_expand_dims_exceptions(self): + pyfunc = expand_dims + cfunc = jit(nopython=True)(pyfunc) + arr = np.arange(5) + + with self.assertTypingError() as raises: + cfunc('hello', 3) + self.assertIn('First argument "a" must be an array', str(raises.exception)) + + with self.assertTypingError() as raises: + cfunc(arr, 'hello') + self.assertIn('Argument "axis" must be an integer', str(raises.exception)) + + + def check_atleast_nd(self, pyfunc, cfunc): + def check_result(got, expected): + # We would like to check the result has the same contiguity, + # but we can't rely on the "flags" attribute when there are + # 1-sized dimensions. + self.assertStridesEqual(got, expected) + self.assertPreciseEqual(got.flatten(), expected.flatten()) + + def check_single(arg): + check_result(cfunc(arg), pyfunc(arg)) + + def check_tuple(*args): + expected_tuple = pyfunc(*args) + got_tuple = cfunc(*args) + self.assertEqual(len(got_tuple), len(expected_tuple)) + for got, expected in zip(got_tuple, expected_tuple): + check_result(got, expected) + + # 0d + a1 = np.array(42) + a2 = np.array(5j) + check_single(a1) + check_tuple(a1, a2) + # 1d + b1 = np.arange(5) + b2 = np.arange(6) + 1j + b3 = b1[::-1] + check_single(b1) + check_tuple(b1, b2, b3) + # 2d + c1 = np.arange(6).reshape((2, 3)) + c2 = c1.T + c3 = c1[::-1] + check_single(c1) + check_tuple(c1, c2, c3) + # 3d + d1 = np.arange(24).reshape((2, 3, 4)) + d2 = d1.T + d3 = d1[::-1] + check_single(d1) + check_tuple(d1, d2, d3) + # 4d + e = np.arange(16).reshape((2, 2, 2, 2)) + check_single(e) + # mixed dimensions + check_tuple(a1, b2, c3, d2) + + def test_atleast_1d(self): + pyfunc = atleast_1d + cfunc = jit(nopython=True)(pyfunc) + self.check_atleast_nd(pyfunc, cfunc) + + def test_atleast_2d(self): + pyfunc = atleast_2d + cfunc = jit(nopython=True)(pyfunc) + self.check_atleast_nd(pyfunc, cfunc) + + def test_atleast_3d(self): + pyfunc = atleast_3d + cfunc = jit(nopython=True)(pyfunc) + self.check_atleast_nd(pyfunc, cfunc) + + def check_as_strided(self, pyfunc): + cfunc = njit(pyfunc) + + def check(arr): + expected = pyfunc(arr) + got = cfunc(arr) + self.assertPreciseEqual(got, expected) + + arr = np.arange(24) + check(arr) + check(arr.reshape((6, 4))) + check(arr.reshape((4, 1, 6))) + + def test_as_strided(self): + self.check_as_strided(as_strided1) + self.check_as_strided(as_strided2) + + def test_as_strided_stride_none(self): + + @jit + def foo(): + arr = np.arange(24).reshape((6, 4)) + return np.lib.stride_tricks.as_strided(arr, strides=None) + + with self.assertRaises(errors.TypingError) as raises: + foo() + + msg = "strides argument cannot be None" + self.assertIn(msg, str(raises.exception)) + + def test_sliding_window_view(self): + def check(arr, window_shape, axis): + # Our version is always writeable (NumPy default is False). + expected = np.lib.stride_tricks.sliding_window_view( + arr, window_shape, axis, writeable=True + ) + got = sliding_window_view(arr, window_shape, axis) + self.assertPreciseEqual(got, expected) + + # 1d array, different ways of specifying the axis. + arr1 = np.arange(24) + for axis in [None, 0, -1, (0,)]: + with self.subTest(f"1d array, axis={axis}"): + check(arr1, 5, axis) + + # 2d array, 1d window. + arr2 = np.arange(200).reshape(10, 20) + for axis in [0, -1]: + with self.subTest(f"2d array, axis={axis}"): + check(arr2, 5, axis) + + # 2d array, 2d window. + for axis in [None, (0, 1), (1, 0), (1, -2)]: + with self.subTest(f"2d array, axis={axis}"): + check(arr2, (5, 8), axis) + + # 4d array, 2d window. + arr4 = np.arange(200).reshape(4, 5, 5, 2) + for axis in [(1, 2), (-2, -3)]: + with self.subTest(f"4d array, axis={axis}"): + check(arr4, (3, 2), axis) + + # Repeated axis. + with self.subTest("2d array, repeated axes"): + check(arr2, (5, 3, 3), (0, 1, 0)) + + def test_sliding_window_view_errors(self): + def _raises(msg, *args): + with self.assertRaises(ValueError) as raises: + sliding_window_view(*args) + self.assertIn(msg, str(raises.exception)) + + def _typing_error(msg, *args): + with self.assertRaises(errors.TypingError) as raises: + sliding_window_view(*args) + self.assertIn(msg, str(raises.exception)) + + # Exceptions leak references + self.disable_leak_check() + + arr1 = np.arange(24) + arr2 = np.arange(200).reshape(10, 20) + + # Window shape cannot be larger than dimension or negative. + with self.subTest("1d window shape too large"): + _raises("window_shape cannot be larger", arr1, 25, None) + with self.subTest("2d window shape too large"): + _raises("window_shape cannot be larger", arr2, (4, 21), None) + with self.subTest("1d window negative size"): + _raises("`window_shape` cannot contain negative", arr1, -1, None) + with self.subTest("2d window with a negative size"): + _raises("`window_shape` cannot contain negative", arr2, (4, -3), None) + + # window_shape and axis parameters must be compatible. + with self.subTest("1d array, 2d window shape"): + _raises("matching length window_shape and axis", arr1, (10, 2), None) + with self.subTest("2d window shape, only one axis given"): + _raises("matching length window_shape and axis", arr2, (10, 2), 1) + with self.subTest("1d window shape, 2 axes given"): + _raises("matching length window_shape and axis", arr1, 5, (0, 0)) + + # Axis values out of bounds. + with self.subTest("1d array, second axis"): + _raises("Argument axis out of bounds", arr1, 4, 1) + with self.subTest("1d array, axis -2"): + _raises("Argument axis out of bounds", arr1, 4, -2) + with self.subTest("2d array, fourth axis"): + _raises("Argument axis out of bounds", arr2, (4, 4), (0, 3)) + with self.subTest("2d array, axis -3"): + _raises("Argument axis out of bounds", arr2, (4, 4), (0, -3)) + + # Useful messages for unsupported types. + with self.subTest("window_shape=None"): + _typing_error( + "window_shape must be an integer or tuple of integer", arr1, None + ) + with self.subTest("window_shape=float"): + _typing_error( + "window_shape must be an integer or tuple of integer", arr1, 3.1 + ) + with self.subTest("window_shape=tuple(float)"): + _typing_error( + "window_shape must be an integer or tuple of integer", arr1, (3.1,) + ) + with self.subTest("axis=float"): + _typing_error( + "axis must be None, an integer or tuple of integer", arr1, 4, 3.1 + ) + with self.subTest("axis=tuple(float)"): + _typing_error( + "axis must be None, an integer or tuple of integer", arr1, 4, (3.1,) + ) + + + def test_flatten_array(self, flags=enable_pyobj_flags, layout='C'): + a = np.arange(9).reshape(3, 3) + if layout == 'F': + a = a.T + + pyfunc = flatten_array + arraytype1 = typeof(a) + if layout == 'A': + # Force A layout + arraytype1 = arraytype1.copy(layout='A') + + self.assertEqual(arraytype1.layout, layout) + cfunc = jit((arraytype1,), **flags)(pyfunc) + + expected = pyfunc(a) + got = cfunc(a) + np.testing.assert_equal(expected, got) + + def test_flatten_array_npm(self): + self.test_flatten_array(flags=no_pyobj_flags) + self.test_flatten_array(flags=no_pyobj_flags, layout='F') + self.test_flatten_array(flags=no_pyobj_flags, layout='A') + + def test_ravel_array(self, flags=enable_pyobj_flags): + def generic_check(pyfunc, a, assume_layout): + # compile + arraytype1 = typeof(a) + self.assertEqual(arraytype1.layout, assume_layout) + cfunc = jit((arraytype1,), **flags)(pyfunc) + + expected = pyfunc(a) + got = cfunc(a) + # Check result matches + np.testing.assert_equal(expected, got) + # Check copying behavior + py_copied = (a.ctypes.data != expected.ctypes.data) + nb_copied = (a.ctypes.data != got.ctypes.data) + self.assertEqual(py_copied, assume_layout != 'C') + self.assertEqual(py_copied, nb_copied) + + check_method = partial(generic_check, ravel_array) + check_function = partial(generic_check, numpy_ravel_array) + + def check(*args, **kwargs): + check_method(*args, **kwargs) + check_function(*args, **kwargs) + + # Check 2D + check(np.arange(9).reshape(3, 3), assume_layout='C') + check(np.arange(9).reshape(3, 3, order='F'), assume_layout='F') + check(np.arange(18).reshape(3, 3, 2)[:, :, 0], assume_layout='A') + + # Check 3D + check(np.arange(18).reshape(2, 3, 3), assume_layout='C') + check(np.arange(18).reshape(2, 3, 3, order='F'), assume_layout='F') + check(np.arange(36).reshape(2, 3, 3, 2)[:, :, :, 0], assume_layout='A') + + def test_ravel_array_size(self, flags=enable_pyobj_flags): + a = np.arange(9).reshape(3, 3) + + pyfunc = ravel_array_size + arraytype1 = typeof(a) + cfunc = jit((arraytype1,), **flags)(pyfunc) + + expected = pyfunc(a) + got = cfunc(a) + np.testing.assert_equal(expected, got) + + def test_ravel_array_npm(self): + self.test_ravel_array(flags=no_pyobj_flags) + + def test_ravel_array_size_npm(self): + self.test_ravel_array_size(flags=no_pyobj_flags) + + def test_transpose_array(self, flags=enable_pyobj_flags): + @from_generic([transpose_array, numpy_transpose_array]) + def check(pyfunc): + a = np.arange(9).reshape(3, 3) + + arraytype1 = typeof(a) + cfunc = jit((arraytype1,), **flags)(pyfunc) + + expected = pyfunc(a) + got = cfunc(a) + np.testing.assert_equal(expected, got) + + check() + + def test_transpose_array_npm(self): + self.test_transpose_array(flags=no_pyobj_flags) + + def test_squeeze_array(self, flags=enable_pyobj_flags): + a = np.arange(2 * 1 * 3 * 1 * 4).reshape(2, 1, 3, 1, 4) + + pyfunc = squeeze_array + arraytype1 = typeof(a) + cfunc = jit((arraytype1,), **flags)(pyfunc) + + expected = pyfunc(a) + got = cfunc(a) + np.testing.assert_equal(expected, got) + + def test_squeeze_array_npm(self): + with self.assertRaises(errors.TypingError) as raises: + self.test_squeeze_array(flags=no_pyobj_flags) + + self.assertIn("squeeze", str(raises.exception)) + + def test_add_axis(self): + @njit + def np_new_axis_getitem(a, idx): + return a[idx] + + @njit + def np_new_axis_setitem(a, idx, item): + a[idx] = item + return a + + a = np.arange(4 * 5 * 6 * 7).reshape((4, 5, 6, 7)) + idx_cases = [ + (slice(None), np.newaxis), + (np.newaxis, slice(None)), + (slice(1), np.newaxis, 1), + (np.newaxis, 2, slice(None)), + (slice(1), Ellipsis, np.newaxis, 1), + (1, np.newaxis, Ellipsis), + (np.newaxis, slice(1), np.newaxis, 1), + (1, Ellipsis, None, np.newaxis), + (np.newaxis, slice(1), Ellipsis, np.newaxis, 1), + (1, np.newaxis, np.newaxis, Ellipsis), + (np.newaxis, 1, np.newaxis, Ellipsis), + (slice(3), 1, np.newaxis, None), + (np.newaxis, 1, Ellipsis, None), + ] + pyfunc_getitem = np_new_axis_getitem.py_func + cfunc_getitem = np_new_axis_getitem + + pyfunc_setitem = np_new_axis_setitem.py_func + cfunc_setitem = np_new_axis_setitem + + for idx in idx_cases: + expected = pyfunc_getitem(a, idx) + got = cfunc_getitem(a, idx) + np.testing.assert_equal(expected, got) + + a_empty = np.zeros_like(a) + item = a[idx] + + expected = pyfunc_setitem(a_empty.copy(), idx, item) + got = cfunc_setitem(a_empty.copy(), idx, item) + np.testing.assert_equal(expected, got) + + def test_bad_index_npm(self): + with self.assertTypingError() as raises: + arraytype1 = from_dtype(np.dtype([('x', np.int32), + ('y', np.int32)])) + arraytype2 = types.Array(types.int32, 2, 'C') + njit((arraytype1, arraytype2))(bad_index) + self.assertIn('Unsupported array index type', str(raises.exception)) + + def test_bad_float_index_npm(self): + with self.assertTypingError() as raises: + njit((types.Array(types.float64, 2, 'C'),))(bad_float_index) + self.assertIn('Unsupported array index type float64', + str(raises.exception)) + + def test_fill_diagonal_basic(self): + pyfunc = numpy_fill_diagonal + cfunc = jit(nopython=True)(pyfunc) + + def _shape_variations(n): + # square + yield (n, n) + # tall and thin + yield (2 * n, n) + # short and fat + yield (n, 2 * n) + # a bit taller than wide; odd numbers of rows and cols + yield ((2 * n + 1), (2 * n - 1)) + # 4d, all dimensions same + yield (n, n, n, n) + # weird edge case + yield (1, 1, 1) + + def _val_variations(): + yield 1 + yield 3.142 + yield np.nan + yield -np.inf + yield True + yield np.arange(4) + yield (4,) + yield [8, 9] + yield np.arange(54).reshape(9, 3, 2, 1) # contiguous C + yield np.asfortranarray(np.arange(9).reshape(3, 3)) # contiguous F + yield np.arange(9).reshape(3, 3)[::-1] # non-contiguous + + # contiguous arrays + def _multi_dimensional_array_variations(n): + for shape in _shape_variations(n): + yield np.zeros(shape, dtype=np.float64) + yield np.asfortranarray(np.ones(shape, dtype=np.float64)) + + # non-contiguous arrays + def _multi_dimensional_array_variations_strided(n): + for shape in _shape_variations(n): + tmp = np.zeros(tuple([x * 2 for x in shape]), dtype=np.float64) + slicer = tuple(slice(0, x * 2, 2) for x in shape) + yield tmp[slicer] + + def _check_fill_diagonal(arr, val): + for wrap in None, True, False: + a = arr.copy() + b = arr.copy() + + if wrap is None: + params = {} + else: + params = {'wrap': wrap} + + pyfunc(a, val, **params) + cfunc(b, val, **params) + self.assertPreciseEqual(a, b) + + for arr in _multi_dimensional_array_variations(3): + for val in _val_variations(): + _check_fill_diagonal(arr, val) + + for arr in _multi_dimensional_array_variations_strided(3): + for val in _val_variations(): + _check_fill_diagonal(arr, val) + + # non-numeric input arrays + arr = np.array([True] * 9).reshape(3, 3) + _check_fill_diagonal(arr, False) + _check_fill_diagonal(arr, [False, True, False]) + _check_fill_diagonal(arr, np.array([True, False, True])) + + def test_fill_diagonal_exception_cases(self): + pyfunc = numpy_fill_diagonal + cfunc = jit(nopython=True)(pyfunc) + val = 1 + + # Exceptions leak references + self.disable_leak_check() + + # first argument unsupported number of dimensions + for a in np.array([]), np.ones(5): + with self.assertRaises(TypingError) as raises: + cfunc(a, val) + assert "The first argument must be at least 2-D" in str(raises.exception) + + # multi-dimensional input where dimensions are not all equal + with self.assertRaises(ValueError) as raises: + a = np.zeros((3, 3, 4)) + cfunc(a, val) + self.assertEqual("All dimensions of input must be of equal length", str(raises.exception)) + + # cases where val has incompatible type / value + def _assert_raises(arr, val): + with self.assertRaises(ValueError) as raises: + cfunc(arr, val) + self.assertEqual("Unable to safely conform val to a.dtype", str(raises.exception)) + + arr = np.zeros((3, 3), dtype=np.int32) + val = np.nan + _assert_raises(arr, val) + + val = [3.3, np.inf] + _assert_raises(arr, val) + + val = np.array([1, 2, 1e10], dtype=np.int64) + _assert_raises(arr, val) + + arr = np.zeros((3, 3), dtype=np.float32) + val = [1.4, 2.6, -1e100] + _assert_raises(arr, val) + + val = 1.1e100 + _assert_raises(arr, val) + + val = np.array([-1e100]) + _assert_raises(arr, val) + + def test_broadcast_to(self): + pyfunc = numpy_broadcast_to + cfunc = jit(nopython=True)(pyfunc) + + # Tests taken from + # https://github.com/numpy/numpy/blob/75f852edf94a7293e7982ad516bee314d7187c2d/numpy/lib/tests/test_stride_tricks.py#L234-L257 # noqa: E501 + data = [ + [np.array(0), (0,)], + [np.array(0), (1,)], + [np.array(0), (3,)], + [np.ones(1), (1,)], + [np.ones(1), (2,)], + [np.ones(1), (1, 2, 3)], + [np.arange(3), (3,)], + [np.arange(3), (1, 3)], + [np.arange(3), (2, 3)], + # test if shape is not a tuple + [np.ones(0), 0], + [np.ones(1), 1], + [np.ones(1), 2], + # these cases with size 0 are strange, but they reproduce the behavior + # of broadcasting with ufuncs + [np.ones(1), (0,)], + [np.ones((1, 2)), (0, 2)], + [np.ones((2, 1)), (2, 0)], + # numpy accepts scalar values as first argument to np.broadcast_to + [2, (2, 2)], + # tuple input + [(1, 2), (2, 2)], + ] + for input_array, shape in data: + expected = pyfunc(input_array, shape) + got = cfunc(input_array, shape) + self.assertPreciseEqual(got, expected) + + def test_broadcast_to_0d_array(self): + pyfunc = numpy_broadcast_to + cfunc = jit(nopython=True)(pyfunc) + + inputs = [ + np.array(123), + 123, + True, + # can't do np.asarray() on the types below + # 'hello', + # np.timedelta64(10, 'Y'), + # np.datetime64(10, 'Y'), + ] + + shape = () + for arr in inputs: + expected = pyfunc(arr, shape) + got = cfunc(arr, shape) + self.assertPreciseEqual(expected, got) + # ensure that np.broadcast_to returned a read-only array + self.assertFalse(got.flags['WRITEABLE']) + + def test_broadcast_to_raises(self): + pyfunc = numpy_broadcast_to + cfunc = jit(nopython=True)(pyfunc) + + # Tests taken from + # https://github.com/numpy/numpy/blob/75f852edf94a7293e7982ad516bee314d7187c2d/numpy/lib/tests/test_stride_tricks.py#L260-L276 # noqa: E501 + data = [ + [np.zeros((0,)), (), TypingError, + 'Cannot broadcast a non-scalar to a scalar array'], + [np.zeros((1,)), (), TypingError, + 'Cannot broadcast a non-scalar to a scalar array'], + [np.zeros((3,)), (), TypingError, + 'Cannot broadcast a non-scalar to a scalar array'], + [(), (), TypingError, + 'Cannot broadcast a non-scalar to a scalar array'], + [(123,), (), TypingError, + 'Cannot broadcast a non-scalar to a scalar array'], + [np.zeros((3,)), (1,), ValueError, + 'operands could not be broadcast together with remapped shapes'], + [np.zeros((3,)), (2,), ValueError, + 'operands could not be broadcast together with remapped shapes'], + [np.zeros((3,)), (4,), ValueError, + 'operands could not be broadcast together with remapped shapes'], + [np.zeros((1, 2)), (2, 1), ValueError, + 'operands could not be broadcast together with remapped shapes'], + [np.zeros((1, 1)), (1,), ValueError, + 'input operand has more dimensions than allowed by the axis remapping'], + [np.zeros((2, 2)), (3,), ValueError, + 'input operand has more dimensions than allowed by the axis remapping'], + [np.zeros((1,)), -1, ValueError, + 'all elements of broadcast shape must be non-negative'], + [np.zeros((1,)), (-1,), ValueError, + 'all elements of broadcast shape must be non-negative'], + [np.zeros((1, 2)), (-1, 2), ValueError, + 'all elements of broadcast shape must be non-negative'], + [np.zeros((1, 2)), (1.1, 2.2), TypingError, + 'The second argument "shape" must be a tuple of integers'], + ['hello', (3,), TypingError, + 'The first argument "array" must be array-like'], + [3, (2, 'a'), TypingError, + 'object cannot be interpreted as an integer'], + ] + self.disable_leak_check() + for arr, target_shape, err, msg in data: + with self.assertRaises(err) as raises: + cfunc(arr, target_shape) + self.assertIn(msg, str(raises.exception)) + + def test_broadcast_to_corner_cases(self): + @njit + def _broadcast_to_1(): + return np.broadcast_to('a', (2, 3)) + + expected = _broadcast_to_1.py_func() + got = _broadcast_to_1() + self.assertPreciseEqual(expected, got) + + def test_broadcast_to_change_view(self): + pyfunc = numpy_broadcast_to + cfunc = jit(nopython=True)(pyfunc) + input_array = np.zeros(2, dtype=np.int32) + shape = (2, 2) + view = cfunc(input_array, shape) + input_array[0] = 10 + + self.assertEqual(input_array.sum(), 10) + self.assertEqual(view.sum(), 20) + + def test_broadcast_to_indexing(self): + pyfunc = numpy_broadcast_to_indexing + cfunc = jit(nopython=True)(pyfunc) + data = [ + [np.ones(2), (2, 2), (1,)], + ] + for input_array, shape, idx in data: + expected = pyfunc(input_array, shape, idx) + got = cfunc(input_array, shape, idx) + self.assertPreciseEqual(got, expected) + + def test_broadcast_to_array_attrs(self): + # See issue #8534. This tests that broadcast array attributes have the + # correct value when accessed. + @njit + def foo(arr): + ret = np.broadcast_to(arr, (2, 3)) + return ret, ret.size, ret.shape, ret.strides + + arr = np.arange(3) + + expected = foo.py_func(arr) + got = foo(arr) + self.assertPreciseEqual(expected, got) + + def test_broadcast_shapes(self): + pyfunc = numpy_broadcast_shapes + cfunc = jit(nopython=True)(pyfunc) + + # Tests taken from + # https://github.com/numpy/numpy/blob/623bc1fae1d47df24e7f1e29321d0c0ba2771ce0/numpy/lib/tests/test_stride_tricks.py#L296-L334 + data = [ + # [[], ()], # cannot compute fingerprint of empty list + [()], + [(), ()], + [(7,)], + [(1, 2),], + [(1, 1)], + [(1, 1), (3, 4)], + [(6, 7), (5, 6, 1), (7,), (5, 1, 7)], + [(5, 6, 1)], + [(1, 3), (3, 1)], + [(1, 0), (0, 0)], + [(0, 1), (0, 0)], + [(1, 0), (0, 1)], + [(1, 1), (0, 0)], + [(1, 1), (1, 0)], + [(1, 1), (0, 1)], + [(), (0,)], + [(0,), (0, 0)], + [(0,), (0, 1)], + [(1,), (0, 0)], + [(), (0, 0)], + [(1, 1), (0,)], + [(1,), (0, 1)], + [(1,), (1, 0)], + [(), (1, 0)], + [(), (0, 1)], + [(1,), (3,)], + [2, (3, 2)], + ] + for input_shape in data: + expected = pyfunc(*input_shape) + got = cfunc(*input_shape) + self.assertIsInstance(got, tuple) + self.assertPreciseEqual(expected, got) + + def test_broadcast_shapes_raises(self): + pyfunc = numpy_broadcast_shapes + cfunc = jit(nopython=True)(pyfunc) + + self.disable_leak_check() + + # Tests taken from + # https://github.com/numpy/numpy/blob/623bc1fae1d47df24e7f1e29321d0c0ba2771ce0/numpy/lib/tests/test_stride_tricks.py#L337-L351 + data = [ + [(3,), (4,)], + [(2, 3), (2,)], + [(3,), (3,), (4,)], + [(1, 3, 4), (2, 3, 3)], + [(1, 2), (3, 1), (3, 2), (10, 5)], + [2, (2, 3)], + ] + for input_shape in data: + with self.assertRaises(ValueError) as raises: + cfunc(*input_shape) + + self.assertIn("shape mismatch: objects cannot be broadcast to a single shape", + str(raises.exception)) + + def test_broadcast_shapes_negative_dimension(self): + pyfunc = numpy_broadcast_shapes + cfunc = jit(nopython=True)(pyfunc) + + self.disable_leak_check() + with self.assertRaises(ValueError) as raises: + cfunc((1, 2), (2), (-2)) + + self.assertIn("negative dimensions are not allowed", str(raises.exception)) + + def test_broadcast_shapes_invalid_type(self): + pyfunc = numpy_broadcast_shapes + cfunc = jit(nopython=True)(pyfunc) + + self.disable_leak_check() + + inps = [ + ((1, 2), ('hello',)), + (3.4,), + ('string',), + ((1.2, 'a')), + (1, ((1.2, 'a'))), + ] + + for inp in inps: + with self.assertRaises(TypingError) as raises: + cfunc(*inp) + + self.assertIn("must be either an int or tuple[int]", str(raises.exception)) + + def test_shape(self): + pyfunc = numpy_shape + cfunc = jit(nopython=True)(pyfunc) + + def check(x): + expected = pyfunc(x) + got = cfunc(x) + self.assertPreciseEqual(got, expected) + + # check arrays + for t in [(), (1,), (2, 3,), (4, 5, 6)]: + arr = np.empty(t) + check(arr) + + # check some types that go via asarray + for t in [1, False, [1,], [[1, 2,],[3, 4]], (1,), (1, 2, 3)]: + check(arr) + + with self.assertRaises(TypingError) as raises: + cfunc('a') + + self.assertIn("The argument to np.shape must be array-like", + str(raises.exception)) + + def test_size(self): + pyfunc = numpy_size + cfunc = jit(nopython=True)(pyfunc) + + def check(x): + expected = pyfunc(x) + got = cfunc(x) + self.assertPreciseEqual(got, expected) + + # check arrays + for t in [(), (1,), (2, 3,), (4, 5, 6)]: + arr = np.empty(t) + check(arr) + + # check scalar values + for t in [1, False, 3.14, np.int8(4), np.float32(2.718)]: + check(t) + + with self.assertRaises(TypingError) as raises: + cfunc('a') + + self.assertIn("The argument to np.size must be array-like", + str(raises.exception)) + + def test_flatnonzero_basic(self): + pyfunc = numpy_flatnonzero + cfunc = jit(nopython=True)(pyfunc) + + def a_variations(): + yield np.arange(-5, 5) + yield np.full(5, fill_value=0) + yield np.array([]) + a = self.random.randn(100) + a[np.abs(a) > 0.2] = 0.0 + yield a + yield a.reshape(5, 5, 4) + yield a.reshape(50, 2, order='F') + yield a.reshape(25, 4)[1::2] + yield a * 1j + + for a in a_variations(): + expected = pyfunc(a) + got = cfunc(a) + self.assertPreciseEqual(expected, got) + + def test_argwhere_basic(self): + pyfunc = numpy_argwhere + cfunc = jit(nopython=True)(pyfunc) + + def a_variations(): + yield np.arange(-5, 5) > 2 + yield np.full(5, fill_value=0) + yield np.full(5, fill_value=1) + yield np.array([]) + yield np.array([-1.0, 0.0, 1.0]) + a = self.random.randn(100) + yield a > 0.2 + yield a.reshape(5, 5, 4) > 0.5 + yield a.reshape(50, 2, order='F') > 0.5 + yield a.reshape(25, 4)[1::2] > 0.5 + yield a == a - 1 + yield a > -a + + for a in a_variations(): + expected = pyfunc(a) + got = cfunc(a) + self.assertPreciseEqual(expected, got) + + @staticmethod + def array_like_variations(): + yield ((1.1, 2.2), (3.3, 4.4), (5.5, 6.6)) + yield (0.0, 1.0, 0.0, -6.0) + yield ([0, 1], [2, 3]) + yield () + yield np.nan + yield 0 + yield 1 + yield False + yield True + yield (True, False, True) + yield 2 + 1j + # the following are not array-like, but NumPy does not raise + yield None + yield 'a_string' + yield '' + + + def test_flatnonzero_array_like(self): + pyfunc = numpy_flatnonzero + cfunc = jit(nopython=True)(pyfunc) + + for a in self.array_like_variations(): + expected = pyfunc(a) + got = cfunc(a) + self.assertPreciseEqual(expected, got) + + def test_argwhere_array_like(self): + pyfunc = numpy_argwhere + cfunc = jit(nopython=True)(pyfunc) + for a in self.array_like_variations(): + expected = pyfunc(a) + got = cfunc(a) + self.assertPreciseEqual(expected, got) + + def broadcast_arrays_assert_correct_shape(self, input_shapes, expected_shape): + # Broadcast a list of arrays with the given input shapes and check the + # common output shape. + pyfunc = numpy_broadcast_arrays + cfunc = jit(nopython=True)(pyfunc) + + inarrays = [np.zeros(s) for s in input_shapes] + outarrays = cfunc(*inarrays) + expected = [expected_shape] * len(inarrays) + got = [a.shape for a in outarrays] + self.assertPreciseEqual(expected, got) + + def test_broadcast_arrays_same_input_shapes(self): + # Tests taken from + # https://github.com/numpy/numpy/blob/623bc1fae1d47df24e7f1e29321d0c0ba2771ce0/numpy/lib/tests/test_stride_tricks.py#L83-L107 # noqa: E501 + # Check that the final shape is just the input shape. + pyfunc = numpy_broadcast_arrays + cfunc = jit(nopython=True)(pyfunc) + + data = [ + # (), + (1,), + (3,), + (0, 1), + (0, 3), + (1, 0), + (3, 0), + (1, 3), + (3, 1), + (3, 3), + ] + for shape in data: + input_shapes = [shape] + # Single input. + self.broadcast_arrays_assert_correct_shape(input_shapes, shape) + # Double input. + input_shapes2 = [shape, shape] + self.broadcast_arrays_assert_correct_shape(input_shapes2, shape) + # Triple input. + input_shapes3 = [shape, shape, shape] + self.broadcast_arrays_assert_correct_shape(input_shapes3, shape) + + def test_broadcast_arrays_two_compatible_by_ones_input_shapes(self): + # Tests taken from + # https://github.com/numpy/numpy/blob/623bc1fae1d47df24e7f1e29321d0c0ba2771ce0/numpy/lib/tests/test_stride_tricks.py#L110-L132 + # Check that two different input shapes of the same length, but some have + # ones, broadcast to the correct shape. + + data = [ + [[(1,), (3,)], (3,)], + [[(1, 3), (3, 3)], (3, 3)], + [[(3, 1), (3, 3)], (3, 3)], + [[(1, 3), (3, 1)], (3, 3)], + [[(1, 1), (3, 3)], (3, 3)], + [[(1, 1), (1, 3)], (1, 3)], + [[(1, 1), (3, 1)], (3, 1)], + [[(1, 0), (0, 0)], (0, 0)], + [[(0, 1), (0, 0)], (0, 0)], + [[(1, 0), (0, 1)], (0, 0)], + [[(1, 1), (0, 0)], (0, 0)], + [[(1, 1), (1, 0)], (1, 0)], + [[(1, 1), (0, 1)], (0, 1)], + ] + for input_shapes, expected_shape in data: + self.broadcast_arrays_assert_correct_shape(input_shapes, expected_shape) + # Reverse the input shapes since broadcasting should be symmetric. + self.broadcast_arrays_assert_correct_shape(input_shapes[::-1], expected_shape) + + def test_broadcast_arrays_two_compatible_by_prepending_ones_input_shapes(self): + # Tests taken from + # https://github.com/numpy/numpy/blob/623bc1fae1d47df24e7f1e29321d0c0ba2771ce0/numpy/lib/tests/test_stride_tricks.py#L135-L164 + # Check that two different input shapes (of different lengths) broadcast + # to the correct shape. + + data = [ + [[(), (3,)], (3,)], + [[(3,), (3, 3)], (3, 3)], + [[(3,), (3, 1)], (3, 3)], + [[(1,), (3, 3)], (3, 3)], + [[(), (3, 3)], (3, 3)], + [[(1, 1), (3,)], (1, 3)], + [[(1,), (3, 1)], (3, 1)], + [[(1,), (1, 3)], (1, 3)], + [[(), (1, 3)], (1, 3)], + [[(), (3, 1)], (3, 1)], + [[(), (0,)], (0,)], + [[(0,), (0, 0)], (0, 0)], + [[(0,), (0, 1)], (0, 0)], + [[(1,), (0, 0)], (0, 0)], + [[(), (0, 0)], (0, 0)], + [[(1, 1), (0,)], (1, 0)], + [[(1,), (0, 1)], (0, 1)], + [[(1,), (1, 0)], (1, 0)], + [[(), (1, 0)], (1, 0)], + [[(), (0, 1)], (0, 1)], + ] + for input_shapes, expected_shape in data: + self.broadcast_arrays_assert_correct_shape(input_shapes, expected_shape) + # Reverse the input shapes since broadcasting should be symmetric. + self.broadcast_arrays_assert_correct_shape(input_shapes[::-1], expected_shape) + + def test_broadcast_arrays_scalar_input(self): + pyfunc = numpy_broadcast_arrays + cfunc = jit(nopython=True)(pyfunc) + data = [ + [[True, False], (1,)], + [[1, 2], (1,)], + [[(1, 2), 2], (2,)], + ] + for inarrays, expected_shape in data: + outarrays = cfunc(*inarrays) + got = [a.shape for a in outarrays] + expected = [expected_shape] * len(inarrays) + self.assertPreciseEqual(expected, got) + + def test_broadcast_arrays_tuple_input(self): + pyfunc = numpy_broadcast_arrays + cfunc = jit(nopython=True)(pyfunc) + outarrays = cfunc((123, 456), (789,)) + expected = [(2,), (2,)] + got = [a.shape for a in outarrays] + self.assertPreciseEqual(expected, got) + + def test_broadcast_arrays_non_array_input(self): + pyfunc = numpy_broadcast_arrays + cfunc = jit(nopython=True)(pyfunc) + outarrays = cfunc(np.intp(2), np.zeros((1, 3), dtype=np.intp)) + expected = [(1, 3), (1, 3)] + got = [a.shape for a in outarrays] + self.assertPreciseEqual(expected, got) + + def test_broadcast_arrays_invalid_mixed_input_types(self): + pyfunc = numpy_broadcast_arrays + cfunc = jit(nopython=True)(pyfunc) + + self.disable_leak_check() + + with self.assertRaises(TypingError) as raises: + arr = np.arange(6).reshape((2, 3)) + b = True + cfunc(arr, b) + self.assertIn('Mismatch of argument types', str(raises.exception)) + + def test_broadcast_arrays_invalid_input(self): + pyfunc = numpy_broadcast_arrays + cfunc = jit(nopython=True)(pyfunc) + + self.disable_leak_check() + + with self.assertRaises(TypingError) as raises: + arr = np.zeros(3, dtype=np.int64) + s = 'hello world' + cfunc(arr, s) + self.assertIn('Argument "1" must be array-like', str(raises.exception)) + + def test_broadcast_arrays_incompatible_shapes_raise_valueerror(self): + # Check that a ValueError is raised for incompatible shapes. + pyfunc = numpy_broadcast_arrays + cfunc = jit(nopython=True)(pyfunc) + + self.disable_leak_check() + + data = [ + [(3,), (4,)], + [(2, 3), (2,)], + [(3,), (3,), (4,)], + [(1, 3, 4), (2, 3, 3)], + ] + for input_shapes in data: + for shape in [input_shapes, input_shapes[::-1]]: + # Reverse the input shapes since broadcasting should be symmetric. + with self.assertRaises(ValueError) as raises: + inarrays = [np.zeros(s) for s in shape] + cfunc(*inarrays) + self.assertIn("shape mismatch: objects cannot be broadcast to a single shape", + str(raises.exception)) + + def test_readonly_after_flatten(self): + # Reproduces Issue #8370 + def unfold_flatten(x, y): + r, c = x.shape + a = np.broadcast_to(x, (y, r, c)) + b = np.swapaxes(a, 0, 1) + cc = b.flatten() + d = np.reshape(cc, (-1, c)) + d[y - 1:, :] = d[: 1 - y] + return d + + pyfunc = unfold_flatten + cfunc = jit(nopython=True)(pyfunc) + + # If issue #8370 is not fixed: This will fail. + res_nb = cfunc(np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]), 2) + res_py = pyfunc(np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]), 2) + + np.testing.assert_array_equal(res_py, res_nb) + + def test_readonly_after_ravel(self): + # Reproduces another suggested problem in Issue #8370 + def unfold_ravel(x, y): + r, c = x.shape + a = np.broadcast_to(x, (y, r, c)) + b = np.swapaxes(a, 0, 1) + cc = b.ravel() + d = np.reshape(cc, (-1, c)) + d[y - 1:, :] = d[: 1 - y] + return d + + pyfunc = unfold_ravel + cfunc = jit(nopython=True)(pyfunc) + + # If issue #8370 is not fixed: This will fail. + res_nb = cfunc(np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]), 2) + res_py = pyfunc(np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]), 2) + + np.testing.assert_array_equal(res_py, res_nb) + + def test_mutability_after_ravel(self): + # Reproduces another suggested problem in Issue #8370 + # Namely that ravel should only return a writable array + # if a copy took place... otherwise leave it as it is. + self.disable_leak_check() + a_c = np.arange(9).reshape((3, 3)).copy() + a_f = a_c.copy(order='F') + a_c.flags.writeable = False + a_f.flags.writeable = False + + def try_ravel_w_copy(a): + result = a.ravel() + return result + + pyfunc = try_ravel_w_copy + cfunc = jit(nopython=True)(pyfunc) + + ret_c = cfunc(a_c) + ret_f = cfunc(a_f) + + msg = 'No copy was performed, so the ' \ + 'resulting array must not be writeable' + self.assertTrue(not ret_c.flags.writeable, msg) + + msg = 'A copy was performed, yet the resulting array is not modifiable' + self.assertTrue(ret_f.flags.writeable, msg) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_asnumbatype.py b/lib/python3.10/site-packages/numba/tests/test_asnumbatype.py new file mode 100644 index 0000000000000000000000000000000000000000..8684874608ee3c4ec0eb1fcbe0e6a16ce09cee5c --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_asnumbatype.py @@ -0,0 +1,170 @@ +""" +Tests for the as_numba_type() machinery. +""" +import typing as py_typing + + +import unittest + +from numba.core import types +from numba.core.errors import TypingError +from numba.core.typing.typeof import typeof +from numba.core.typing.asnumbatype import as_numba_type, AsNumbaTypeRegistry +from numba.experimental.jitclass import jitclass +from numba.tests.support import TestCase + + +class TestAsNumbaType(TestCase): + + int_nb_type = typeof(0) + float_nb_type = typeof(0.0) + complex_nb_type = typeof(complex(0)) + str_nb_type = typeof("numba") + bool_nb_type = typeof(True) + none_nb_type = typeof(None) + + def test_simple_types(self): + self.assertEqual(as_numba_type(int), self.int_nb_type) + self.assertEqual(as_numba_type(float), self.float_nb_type) + self.assertEqual(as_numba_type(complex), self.complex_nb_type) + self.assertEqual(as_numba_type(str), self.str_nb_type) + self.assertEqual(as_numba_type(bool), self.bool_nb_type) + self.assertEqual(as_numba_type(type(None)), self.none_nb_type) + + def test_numba_types(self): + numba_types = [ + types.intp, + types.boolean, + types.ListType(types.float64), + types.DictType( + types.intp, types.Tuple([types.float32, types.float32]) + ), + ] + + for ty in numba_types: + self.assertEqual(as_numba_type(ty), ty) + + def test_single_containers(self): + self.assertEqual( + as_numba_type(py_typing.List[float]), + types.ListType(self.float_nb_type), + ) + self.assertEqual( + as_numba_type(py_typing.Dict[float, str]), + types.DictType(self.float_nb_type, self.str_nb_type), + ) + self.assertEqual( + as_numba_type(py_typing.Set[complex]), + types.Set(self.complex_nb_type), + ) + self.assertEqual( + as_numba_type(py_typing.Tuple[float, float]), + types.Tuple([self.float_nb_type, self.float_nb_type]), + ) + self.assertEqual( + as_numba_type(py_typing.Tuple[float, complex]), + types.Tuple([self.float_nb_type, self.complex_nb_type]), + ) + + def test_optional(self): + self.assertEqual( + as_numba_type(py_typing.Optional[float]), + types.Optional(self.float_nb_type), + ) + self.assertEqual( + as_numba_type(py_typing.Union[str, None]), + types.Optional(self.str_nb_type), + ) + self.assertEqual( + as_numba_type(py_typing.Union[None, bool]), + types.Optional(self.bool_nb_type), + ) + + # Optional[x] is a special case of Union[x, None]. We raise a + # TypingError if the right type is not NoneType. + with self.assertRaises(TypingError) as raises: + as_numba_type(py_typing.Union[int, float]) + self.assertIn("Cannot type Union that is not an Optional", + str(raises.exception)) + + def test_nested_containers(self): + IntList = py_typing.List[int] + self.assertEqual( + as_numba_type(py_typing.List[IntList]), + types.ListType(types.ListType(self.int_nb_type)), + ) + self.assertEqual( + as_numba_type(py_typing.List[py_typing.Dict[float, bool]]), + types.ListType( + types.DictType(self.float_nb_type, self.bool_nb_type) + ), + ) + self.assertEqual( + as_numba_type( + py_typing.Set[py_typing.Tuple[py_typing.Optional[int], float]]), + types.Set(types.Tuple( + [types.Optional(self.int_nb_type), self.float_nb_type])), + ) + + def test_jitclass_registers(self): + + @jitclass + class MyInt: + x: int + + def __init__(self, value): + self.x = value + + self.assertEqual(as_numba_type(MyInt), MyInt.class_type.instance_type) + + def test_type_alias(self): + Pair = py_typing.Tuple[int, int] + ListOfPairs = py_typing.List[Pair] + + pair_nb_type = types.Tuple((self.int_nb_type, self.int_nb_type)) + self.assertEqual(as_numba_type(Pair), pair_nb_type) + self.assertEqual( + as_numba_type(ListOfPairs), types.ListType(pair_nb_type) + ) + + def test_overwrite_type(self): + as_numba_type = AsNumbaTypeRegistry() + self.assertEqual(as_numba_type(float), self.float_nb_type) + as_numba_type.register(float, types.float32) + self.assertEqual(as_numba_type(float), types.float32) + self.assertNotEqual(as_numba_type(float), self.float_nb_type) + + def test_any_throws(self): + Any = py_typing.Any + + any_types = [ + py_typing.Optional[Any], + py_typing.List[Any], + py_typing.Set[Any], + py_typing.Dict[float, Any], + py_typing.Dict[Any, float], + py_typing.Tuple[int, Any], + ] + + for bad_py_type in any_types: + with self.assertRaises(TypingError) as raises: + as_numba_type(bad_py_type) + self.assertIn( + "Cannot infer numba type of python type", + str(raises.exception), + ) + + def test_bad_union_throws(self): + bad_unions = [ + py_typing.Union[str, int], + py_typing.Union[int, type(None), py_typing.Tuple[bool, bool]], + ] + + for bad_py_type in bad_unions: + with self.assertRaises(TypingError) as raises: + as_numba_type(bad_py_type) + self.assertIn("Cannot type Union", str(raises.exception)) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_auto_constants.py b/lib/python3.10/site-packages/numba/tests/test_auto_constants.py new file mode 100644 index 0000000000000000000000000000000000000000..e58c8a1947be711b32e6369002e992ca66d839f5 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_auto_constants.py @@ -0,0 +1,38 @@ +import math +import sys + +import numpy as np + +from numba import njit +import numba.tests.usecases as uc +import unittest + + +class TestAutoConstants(unittest.TestCase): + def test_numpy_nan(self): + + @njit + def f(): + return np.nan + + self.assertTrue(math.isnan(f())) + self.assertTrue(math.isnan(f.py_func())) + + def test_sys_constant(self): + + @njit + def f(): + return sys.hexversion + + self.assertEqual(f(), f.py_func()) + + def test_module_string_constant(self): + + @njit + def f(): + return uc._GLOBAL_STR + self.assertEqual(f(), f.py_func()) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_boundscheck.py b/lib/python3.10/site-packages/numba/tests/test_boundscheck.py new file mode 100644 index 0000000000000000000000000000000000000000..f6f904298d95106d0d6d796764168d049ee74d22 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_boundscheck.py @@ -0,0 +1,268 @@ +import numpy as np + +from numba.cuda.testing import SerialMixin +from numba import typeof, cuda, njit +from numba.core.types import float64 +from numba.tests.support import TestCase, MemoryLeakMixin +from numba.core import config +import unittest + + +def basic_array_access(a): + return a[10] + + +def slice_array_access(a): + # The first index (slice) is not bounds checked + return a[10:, 10] + + +def fancy_array_access(x): + a = np.array([1, 2, 3]) + return x[a] + + +def fancy_array_modify(x): + a = np.array([1, 2, 3]) + x[a] = 0 + return x + + +class TestBoundsCheckNoError(MemoryLeakMixin, TestCase): + + @TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': ''}) + def test_basic_array_boundscheck(self): + self.assertIsNone(config.BOUNDSCHECK) + + a = np.arange(5) + # Check the numpy behavior to make sure the test is correct + with self.assertRaises(IndexError): + # TODO: When we raise the same error message as numpy, test that + # they are the same + basic_array_access(a) + + at = typeof(a) + noboundscheck = njit((at,))(basic_array_access) + # Check that the default flag doesn't raise + noboundscheck(a) + # boundscheck(a) is tested in TestBoundsCheckError below + + @TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': ''}) + def test_slice_array_boundscheck(self): + self.assertIsNone(config.BOUNDSCHECK) + + a = np.ones((5, 5)) + b = np.ones((5, 20)) + with self.assertRaises(IndexError): + # TODO: When we raise the same error message as numpy, test that + # they are the same + slice_array_access(a) + # Out of bounds on a slice doesn't raise + slice_array_access(b) + + at = typeof(a) + rt = float64[:] + noboundscheck = njit(rt(at))(slice_array_access) + boundscheck = njit(rt(at), boundscheck=True)(slice_array_access) + # Check that the default flag doesn't raise + noboundscheck(a) + noboundscheck(b) + # boundscheck(a) is tested in TestBoundsCheckError below + + # Doesn't raise + boundscheck(b) + + @TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': ''}) + def test_fancy_indexing_boundscheck(self): + self.assertIsNone(config.BOUNDSCHECK) + + a = np.arange(3) + b = np.arange(4) + + # Check the numpy behavior to ensure the test is correct. + with self.assertRaises(IndexError): + # TODO: When we raise the same error message as numpy, test that + # they are the same + fancy_array_access(a) + fancy_array_access(b) + + at = typeof(a) + rt = at.dtype[:] + noboundscheck = njit(rt(at))(fancy_array_access) + boundscheck = njit(rt(at), boundscheck=True)(fancy_array_access) + # Check that the default flag doesn't raise + noboundscheck(a) + noboundscheck(b) + # boundscheck(a) is tested in TestBoundsCheckError below + + # Doesn't raise + boundscheck(b) + + +class TestNoCudaBoundsCheck(SerialMixin, TestCase): + @unittest.skipIf(not cuda.is_available(), "NO CUDA") + @TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': '1'}) + def test_no_cuda_boundscheck(self): + self.assertTrue(config.BOUNDSCHECK) + with self.assertRaises(NotImplementedError): + @cuda.jit(boundscheck=True) + def func(): + pass + + # Make sure we aren't raising "not supported" error if we aren't + # requesting bounds checking anyway. Related pull request: #5257 + @cuda.jit(boundscheck=False) + def func3(): + pass + + @cuda.jit + def func2(x, a): + a[1] = x[1] + + a = np.ones((1,)) + x = np.zeros((1,)) + # Out of bounds but doesn't raise (it does raise in the simulator, + # so skip there) + if not config.ENABLE_CUDASIM: + func2[1, 1](x, a) + + +# This is a separate test because the jitted functions that raise exceptions +# have memory leaks. +class TestBoundsCheckError(TestCase): + @TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': ''}) + def test_basic_array_boundscheck(self): + self.assertIsNone(config.BOUNDSCHECK) + + a = np.arange(5) + # Check the numpy behavior to make sure the test is correct + with self.assertRaises(IndexError): + # TODO: When we raise the same error message as numpy, test that + # they are the same + basic_array_access(a) + + at = typeof(a) + boundscheck = njit((at,), boundscheck=True)(basic_array_access) + + with self.assertRaises(IndexError): + boundscheck(a) + + @TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': ''}) + def test_slice_array_boundscheck(self): + self.assertIsNone(config.BOUNDSCHECK) + + a = np.ones((5, 5)) + b = np.ones((5, 20)) + with self.assertRaises(IndexError): + # TODO: When we raise the same error message as numpy, test that + # they are the same + slice_array_access(a) + # Out of bounds on a slice doesn't raise + slice_array_access(b) + + at = typeof(a) + rt = float64[:] + boundscheck = njit(rt(at), boundscheck=True)(slice_array_access) + + with self.assertRaises(IndexError): + boundscheck(a) + + @TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': ''}) + def test_fancy_indexing_boundscheck(self): + self.assertIsNone(config.BOUNDSCHECK) + + a = np.arange(3) + b = np.arange(4) + + # Check the numpy behavior to ensure the test is correct. + with self.assertRaises(IndexError): + # TODO: When we raise the same error message as numpy, test that + # they are the same + fancy_array_access(a) + fancy_array_access(b) + + at = typeof(a) + rt = at.dtype[:] + boundscheck = njit(rt(at), boundscheck=True)(fancy_array_access) + + with self.assertRaises(IndexError): + boundscheck(a) + + @TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': ''}) + def test_fancy_indexing_with_modification_boundscheck(self): + self.assertIsNone(config.BOUNDSCHECK) + + a = np.arange(3) + b = np.arange(4) + + # Check the numpy behavior to ensure the test is correct. + with self.assertRaises(IndexError): + # TODO: When we raise the same error message as numpy, test that + # they are the same + fancy_array_modify(a) + fancy_array_modify(b) + + at = typeof(a) + rt = at.dtype[:] + boundscheck = njit(rt(at), boundscheck=True)(fancy_array_modify) + + with self.assertRaises(IndexError): + boundscheck(a) + + +class TestBoundsEnvironmentVariable(TestCase): + def setUp(self): + @njit + def default(x): + return x[1] + + @njit(boundscheck=False) + def off(x): + return x[1] + + @njit(boundscheck=True) + def on(x): + return x[1] + + self.default = default + self.off = off + self.on = on + + @TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': ''}) + def test_boundscheck_unset(self): + self.assertIsNone(config.BOUNDSCHECK) + + a = np.array([1]) + + # Doesn't raise + self.default(a) + self.off(a) + + with self.assertRaises(IndexError): + self.on(a) + + @TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': '1'}) + def test_boundscheck_enabled(self): + self.assertTrue(config.BOUNDSCHECK) + + a = np.array([1]) + + with self.assertRaises(IndexError): + self.default(a) + self.off(a) + self.on(a) + + @TestCase.run_test_in_subprocess(envvars={'NUMBA_BOUNDSCHECK': '0'}) + def test_boundscheck_disabled(self): + self.assertFalse(config.BOUNDSCHECK) + + a = np.array([1]) + + # Doesn't raise + self.default(a) + self.off(a) + self.on(a) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_byteflow.py b/lib/python3.10/site-packages/numba/tests/test_byteflow.py new file mode 100644 index 0000000000000000000000000000000000000000..041e1d65b20f7fcdc49857903748727cecc29a16 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_byteflow.py @@ -0,0 +1,94 @@ +""" +Test byteflow.py specific issues +""" +import unittest + +from numba.tests.support import TestCase +from numba.core.compiler import run_frontend + + +class TestByteFlowIssues(TestCase): + def test_issue_5087(self): + # This is an odd issue. The exact number of print below is + # necessary to trigger it. Too many or too few will alter the behavior. + # Also note that the function below will not be executed. The problem + # occurs at compilation. The definition below is invalid for execution. + # The problem occurs in the bytecode analysis. + def udt(): + print + print + print + + for i in range: + print + print + print + print + print + print + print + print + print + print + print + print + print + print + print + print + print + print + + for j in range: + print + print + print + print + print + print + print + for k in range: + for l in range: + print + + print + print + print + print + print + print + print + print + print + if print: + for n in range: + print + else: + print + + run_frontend(udt) + + def test_issue_5097(self): + # Inspired by https://github.com/numba/numba/issues/5097 + def udt(): + for i in range(0): + if i > 0: + pass + a = None # noqa: F841 + + run_frontend(udt) + + def test_issue_5680(self): + # From https://github.com/numba/numba/issues/5680#issuecomment-625351336 + def udt(): + for k in range(0): + if 1 == 1: + ... + if 'a' == 'a': + ... + + run_frontend(udt) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_cfunc.py b/lib/python3.10/site-packages/numba/tests/test_cfunc.py new file mode 100644 index 0000000000000000000000000000000000000000..1920b2e22e9fb8bff06ae5209618ad0d17aa29f8 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_cfunc.py @@ -0,0 +1,408 @@ +""" +Tests for @cfunc and friends. +""" + + +import ctypes +import os +import subprocess +import sys +from collections import namedtuple + +import numpy as np + +from numba import cfunc, carray, farray, njit +from numba.core import types, typing, utils +import numba.core.typing.cffi_utils as cffi_support +from numba.tests.support import (TestCase, skip_unless_cffi, tag, + captured_stderr) +import unittest +from numba.np import numpy_support + + +def add_usecase(a, b): + return a + b + +def div_usecase(a, b): + c = a / b + return c + +def square_usecase(a): + return a ** 2 + +add_sig = "float64(float64, float64)" + +div_sig = "float64(int64, int64)" + +square_sig = "float64(float64)" + +def objmode_usecase(a, b): + object() + return a + b + +# Test functions for carray() and farray() + +CARRAY_USECASE_OUT_LEN = 8 + +def make_cfarray_usecase(func): + + def cfarray_usecase(in_ptr, out_ptr, m, n): + # Tuple shape + in_ = func(in_ptr, (m, n)) + # Integer shape + out = func(out_ptr, CARRAY_USECASE_OUT_LEN) + out[0] = in_.ndim + out[1:3] = in_.shape + out[3:5] = in_.strides + out[5] = in_.flags.c_contiguous + out[6] = in_.flags.f_contiguous + s = 0 + for i, j in np.ndindex(m, n): + s += in_[i, j] * (i - j) + out[7] = s + + return cfarray_usecase + +carray_usecase = make_cfarray_usecase(carray) +farray_usecase = make_cfarray_usecase(farray) + + +def make_cfarray_dtype_usecase(func): + # Same as make_cfarray_usecase(), but with explicit dtype. + + def cfarray_usecase(in_ptr, out_ptr, m, n): + # Tuple shape + in_ = func(in_ptr, (m, n), dtype=np.float32) + # Integer shape + out = func(out_ptr, CARRAY_USECASE_OUT_LEN, np.float32) + out[0] = in_.ndim + out[1:3] = in_.shape + out[3:5] = in_.strides + out[5] = in_.flags.c_contiguous + out[6] = in_.flags.f_contiguous + s = 0 + for i, j in np.ndindex(m, n): + s += in_[i, j] * (i - j) + out[7] = s + + return cfarray_usecase + +carray_dtype_usecase = make_cfarray_dtype_usecase(carray) +farray_dtype_usecase = make_cfarray_dtype_usecase(farray) + +carray_float32_usecase_sig = types.void(types.CPointer(types.float32), + types.CPointer(types.float32), + types.intp, types.intp) + +carray_float64_usecase_sig = types.void(types.CPointer(types.float64), + types.CPointer(types.float64), + types.intp, types.intp) + +carray_voidptr_usecase_sig = types.void(types.voidptr, types.voidptr, + types.intp, types.intp) + + +class TestCFunc(TestCase): + + def test_basic(self): + """ + Basic usage and properties of a cfunc. + """ + f = cfunc(add_sig)(add_usecase) + + self.assertEqual(f.__name__, "add_usecase") + self.assertEqual(f.__qualname__, "add_usecase") + self.assertIs(f.__wrapped__, add_usecase) + + symbol = f.native_name + self.assertIsInstance(symbol, str) + self.assertIn("add_usecase", symbol) + + addr = f.address + self.assertIsInstance(addr, int) + + ct = f.ctypes + self.assertEqual(ctypes.cast(ct, ctypes.c_void_p).value, addr) + + self.assertPreciseEqual(ct(2.0, 3.5), 5.5) + + @skip_unless_cffi + def test_cffi(self): + from numba.tests import cffi_usecases + ffi, lib = cffi_usecases.load_inline_module() + + f = cfunc(square_sig)(square_usecase) + + res = lib._numba_test_funcptr(f.cffi) + self.assertPreciseEqual(res, 2.25) # 1.5 ** 2 + + def test_locals(self): + # By forcing the intermediate result into an integer, we + # truncate the ultimate function result + f = cfunc(div_sig, locals={'c': types.int64})(div_usecase) + self.assertPreciseEqual(f.ctypes(8, 3), 2.0) + + def test_errors(self): + f = cfunc(div_sig)(div_usecase) + + with captured_stderr() as err: + self.assertPreciseEqual(f.ctypes(5, 2), 2.5) + self.assertEqual(err.getvalue(), "") + + with captured_stderr() as err: + res = f.ctypes(5, 0) + # This is just a side effect of Numba zero-initializing + # stack variables, and could change in the future. + self.assertPreciseEqual(res, 0.0) + err = err.getvalue() + self.assertIn("ZeroDivisionError:", err) + self.assertIn("Exception ignored", err) + + def test_llvm_ir(self): + f = cfunc(add_sig)(add_usecase) + ir = f.inspect_llvm() + self.assertIn(f.native_name, ir) + self.assertIn("fadd double", ir) + + def test_object_mode(self): + """ + Object mode is currently unsupported. + """ + with self.assertRaises(NotImplementedError): + cfunc(add_sig, forceobj=True)(add_usecase) + with self.assertTypingError() as raises: + cfunc(add_sig)(objmode_usecase) + self.assertIn("Untyped global name 'object'", str(raises.exception)) + + +class TestCArray(TestCase): + """ + Tests for carray() and farray(). + """ + + def run_carray_usecase(self, pointer_factory, func): + a = np.arange(10, 16).reshape((2, 3)).astype(np.float32) + out = np.empty(CARRAY_USECASE_OUT_LEN, dtype=np.float32) + func(pointer_factory(a), pointer_factory(out), *a.shape) + return out + + def check_carray_usecase(self, pointer_factory, pyfunc, cfunc): + expected = self.run_carray_usecase(pointer_factory, pyfunc) + got = self.run_carray_usecase(pointer_factory, cfunc) + self.assertPreciseEqual(expected, got) + + def make_voidptr(self, arr): + return arr.ctypes.data_as(ctypes.c_void_p) + + def make_float32_pointer(self, arr): + return arr.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) + + def make_float64_pointer(self, arr): + return arr.ctypes.data_as(ctypes.POINTER(ctypes.c_double)) + + def check_carray_farray(self, func, order): + def eq(got, expected): + # Same layout, dtype, shape, etc. + self.assertPreciseEqual(got, expected) + # Same underlying data + self.assertEqual(got.ctypes.data, expected.ctypes.data) + + base = np.arange(6).reshape((2, 3)).astype(np.float32).copy(order=order) + + # With typed pointer and implied dtype + a = func(self.make_float32_pointer(base), base.shape) + eq(a, base) + # Integer shape + a = func(self.make_float32_pointer(base), base.size) + eq(a, base.ravel('K')) + + # With typed pointer and explicit dtype + a = func(self.make_float32_pointer(base), base.shape, base.dtype) + eq(a, base) + a = func(self.make_float32_pointer(base), base.shape, np.float32) + eq(a, base) + + # With voidptr and explicit dtype + a = func(self.make_voidptr(base), base.shape, base.dtype) + eq(a, base) + a = func(self.make_voidptr(base), base.shape, np.int32) + eq(a, base.view(np.int32)) + + # voidptr without dtype + with self.assertRaises(TypeError): + func(self.make_voidptr(base), base.shape) + # Invalid pointer type + with self.assertRaises(TypeError): + func(base.ctypes.data, base.shape) + # Mismatching dtype + with self.assertRaises(TypeError) as raises: + func(self.make_float32_pointer(base), base.shape, np.int32) + self.assertIn("mismatching dtype 'int32' for pointer", + str(raises.exception)) + + def test_carray(self): + """ + Test pure Python carray(). + """ + self.check_carray_farray(carray, 'C') + + def test_farray(self): + """ + Test pure Python farray(). + """ + self.check_carray_farray(farray, 'F') + + def make_carray_sigs(self, formal_sig): + """ + Generate a bunch of concrete signatures by varying the width + and signedness of size arguments (see issue #1923). + """ + for actual_size in (types.intp, types.int32, types.intc, + types.uintp, types.uint32, types.uintc): + args = tuple(actual_size if a == types.intp else a + for a in formal_sig.args) + yield formal_sig.return_type(*args) + + def check_numba_carray_farray(self, usecase, dtype_usecase): + # With typed pointers and implicit dtype + pyfunc = usecase + for sig in self.make_carray_sigs(carray_float32_usecase_sig): + f = cfunc(sig)(pyfunc) + self.check_carray_usecase(self.make_float32_pointer, pyfunc, f.ctypes) + + # With typed pointers and explicit (matching) dtype + pyfunc = dtype_usecase + for sig in self.make_carray_sigs(carray_float32_usecase_sig): + f = cfunc(sig)(pyfunc) + self.check_carray_usecase(self.make_float32_pointer, pyfunc, f.ctypes) + # With typed pointers and mismatching dtype + with self.assertTypingError() as raises: + f = cfunc(carray_float64_usecase_sig)(pyfunc) + self.assertIn("mismatching dtype 'float32' for pointer type 'float64*'", + str(raises.exception)) + + # With voidptr + pyfunc = dtype_usecase + for sig in self.make_carray_sigs(carray_voidptr_usecase_sig): + f = cfunc(sig)(pyfunc) + self.check_carray_usecase(self.make_float32_pointer, pyfunc, f.ctypes) + + def test_numba_carray(self): + """ + Test Numba-compiled carray() against pure Python carray() + """ + self.check_numba_carray_farray(carray_usecase, carray_dtype_usecase) + + def test_numba_farray(self): + """ + Test Numba-compiled farray() against pure Python farray() + """ + self.check_numba_carray_farray(farray_usecase, farray_dtype_usecase) + + +@skip_unless_cffi +class TestCffiStruct(TestCase): + c_source = """ +typedef struct _big_struct { + int i1; + float f2; + double d3; + float af4[9]; +} big_struct; + +typedef struct _error { + int bits:4; +} error; + +typedef double (*myfunc)(big_struct*, size_t); +""" + + def get_ffi(self, src=c_source): + from cffi import FFI + + ffi = FFI() + ffi.cdef(src) + return ffi + + def test_type_parsing(self): + ffi = self.get_ffi() + # Check struct typedef + big_struct = ffi.typeof('big_struct') + nbtype = cffi_support.map_type(big_struct, use_record_dtype=True) + self.assertIsInstance(nbtype, types.Record) + self.assertEqual(len(nbtype), 4) + self.assertEqual(nbtype.typeof('i1'), types.int32) + self.assertEqual(nbtype.typeof('f2'), types.float32) + self.assertEqual(nbtype.typeof('d3'), types.float64) + self.assertEqual( + nbtype.typeof('af4'), + types.NestedArray(dtype=types.float32, shape=(9,)), + ) + + # Check function typedef + myfunc = ffi.typeof('myfunc') + sig = cffi_support.map_type(myfunc, use_record_dtype=True) + self.assertIsInstance(sig, typing.Signature) + self.assertEqual(sig.args[0], types.CPointer(nbtype)) + self.assertEqual(sig.args[1], types.uintp) + self.assertEqual(sig.return_type, types.float64) + + def test_cfunc_callback(self): + ffi = self.get_ffi() + big_struct = ffi.typeof('big_struct') + nb_big_struct = cffi_support.map_type(big_struct, use_record_dtype=True) + sig = cffi_support.map_type(ffi.typeof('myfunc'), use_record_dtype=True) + + @njit + def calc(base): + tmp = 0 + for i in range(base.size): + elem = base[i] + tmp += elem.i1 * elem.f2 / elem.d3 + tmp += base[i].af4.sum() + return tmp + + @cfunc(sig) + def foo(ptr, n): + base = carray(ptr, n) + return calc(base) + + # Make data + mydata = ffi.new('big_struct[3]') + ptr = ffi.cast('big_struct*', mydata) + for i in range(3): + ptr[i].i1 = i * 123 + ptr[i].f2 = i * 213 + ptr[i].d3 = (1 + i) * 213 + for j in range(9): + ptr[i].af4[j] = i * 10 + j + + # Address of my data + addr = int(ffi.cast('size_t', ptr)) + got = foo.ctypes(addr, 3) + + # Make numpy array from the cffi buffer + array = np.ndarray( + buffer=ffi.buffer(mydata), + dtype=numpy_support.as_dtype(nb_big_struct), + shape=3, + ) + expect = calc(array) + self.assertEqual(got, expect) + + def test_unsupport_bitsize(self): + ffi = self.get_ffi() + with self.assertRaises(ValueError) as raises: + cffi_support.map_type( + ffi.typeof('error'), + use_record_dtype=True, + ) + # When bitsize is provided, bitshift defaults to 0. + self.assertEqual( + "field 'bits' has bitshift, this is not supported", + str(raises.exception) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_codegen.py b/lib/python3.10/site-packages/numba/tests/test_codegen.py new file mode 100644 index 0000000000000000000000000000000000000000..65f7b7e14957fc787063b952d4de2031790ce188 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_codegen.py @@ -0,0 +1,264 @@ +""" +Tests for numba.core.codegen. +""" + + +import warnings +import base64 +import ctypes +import pickle +import re +import subprocess +import sys +import weakref + +import llvmlite.binding as ll + +import unittest +from numba import njit +from numba.core.codegen import JITCPUCodegen +from numba.core.compiler_lock import global_compiler_lock +from numba.tests.support import TestCase + + +asm_sum = r""" + define i32 @sum(i32 %.1, i32 %.2) { + %.3 = add i32 %.1, %.2 + ret i32 %.3 + } + """ + +# Note we're using a rather mangled function name to check that it +# is compatible with object serialization. + +asm_sum_inner = """ + define i32 @"__main__.ising_element_update$1.array(int8,_2d,_C).int64.int64"(i32 %.1, i32 %.2) { + %.3 = add i32 %.1, %.2 + ret i32 %.3 + } +""" # noqa: E501 + +asm_sum_outer = """ + declare i32 @"__main__.ising_element_update$1.array(int8,_2d,_C).int64.int64"(i32 %.1, i32 %.2) + + define i32 @sum(i32 %.1, i32 %.2) { + %.3 = call i32 @"__main__.ising_element_update$1.array(int8,_2d,_C).int64.int64"(i32 %.1, i32 %.2) + ret i32 %.3 + } +""" # noqa: E501 + + +ctypes_sum_ty = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_int) + + +class JITCPUCodegenTestCase(TestCase): + """ + Test the JIT code generation. + """ + + def setUp(self): + global_compiler_lock.acquire() + self.codegen = JITCPUCodegen('test_codegen') + + def tearDown(self): + del self.codegen + global_compiler_lock.release() + + def compile_module(self, asm, linking_asm=None): + library = self.codegen.create_library('compiled_module') + ll_module = ll.parse_assembly(asm) + ll_module.verify() + library.add_llvm_module(ll_module) + if linking_asm: + linking_library = self.codegen.create_library('linking_module') + ll_module = ll.parse_assembly(linking_asm) + ll_module.verify() + linking_library.add_llvm_module(ll_module) + library.add_linking_library(linking_library) + return library + + @classmethod + def _check_unserialize_sum(cls, state): + codegen = JITCPUCodegen('other_codegen') + library = codegen.unserialize_library(state) + ptr = library.get_pointer_to_function("sum") + assert ptr, ptr + cfunc = ctypes_sum_ty(ptr) + res = cfunc(2, 3) + assert res == 5, res + + def test_get_pointer_to_function(self): + library = self.compile_module(asm_sum) + ptr = library.get_pointer_to_function("sum") + self.assertIsInstance(ptr, int) + cfunc = ctypes_sum_ty(ptr) + self.assertEqual(cfunc(2, 3), 5) + # Note: With llvm3.9.1, deleting `library` will cause memory error in + # the following code during running of optimization passes in + # LLVM. The reason of the error is unclear. The error is known to + # replicate on osx64 and linux64. + + # Same, but with dependency on another library + library2 = self.compile_module(asm_sum_outer, asm_sum_inner) + ptr = library2.get_pointer_to_function("sum") + self.assertIsInstance(ptr, int) + cfunc = ctypes_sum_ty(ptr) + self.assertEqual(cfunc(2, 3), 5) + + def test_magic_tuple(self): + tup = self.codegen.magic_tuple() + pickle.dumps(tup) + cg2 = JITCPUCodegen('xxx') + self.assertEqual(cg2.magic_tuple(), tup) + + # Serialization tests. + + def _check_serialize_unserialize(self, state): + self._check_unserialize_sum(state) + + def _check_unserialize_other_process(self, state): + arg = base64.b64encode(pickle.dumps(state, -1)) + code = """if 1: + import base64 + import pickle + import sys + from numba.tests.test_codegen import %(test_class)s + + state = pickle.loads(base64.b64decode(sys.argv[1])) + %(test_class)s._check_unserialize_sum(state) + """ % dict(test_class=self.__class__.__name__) + subprocess.check_call([sys.executable, '-c', code, arg.decode()]) + + def test_serialize_unserialize_bitcode(self): + library = self.compile_module(asm_sum_outer, asm_sum_inner) + state = library.serialize_using_bitcode() + self._check_serialize_unserialize(state) + + def test_unserialize_other_process_bitcode(self): + library = self.compile_module(asm_sum_outer, asm_sum_inner) + state = library.serialize_using_bitcode() + self._check_unserialize_other_process(state) + + def test_serialize_unserialize_object_code(self): + library = self.compile_module(asm_sum_outer, asm_sum_inner) + library.enable_object_caching() + state = library.serialize_using_object_code() + self._check_serialize_unserialize(state) + + def test_unserialize_other_process_object_code(self): + library = self.compile_module(asm_sum_outer, asm_sum_inner) + library.enable_object_caching() + state = library.serialize_using_object_code() + self._check_unserialize_other_process(state) + + def test_cache_disabled_inspection(self): + """ + """ + library = self.compile_module(asm_sum_outer, asm_sum_inner) + library.enable_object_caching() + state = library.serialize_using_object_code() + + # exercise the valid behavior + with warnings.catch_warnings(record=True) as w: + old_llvm = library.get_llvm_str() + old_asm = library.get_asm_str() + library.get_function_cfg('sum') + self.assertEqual(len(w), 0) + + # unserialize + codegen = JITCPUCodegen('other_codegen') + library = codegen.unserialize_library(state) + + # the inspection methods would warn and give incorrect result + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + self.assertNotEqual(old_llvm, library.get_llvm_str()) + self.assertEqual(len(w), 1) + self.assertIn("Inspection disabled", str(w[0].message)) + + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + self.assertNotEqual(library.get_asm_str(), old_asm) + self.assertEqual(len(w), 1) + self.assertIn("Inspection disabled", str(w[0].message)) + + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + with self.assertRaises(NameError) as raises: + library.get_function_cfg('sum') + self.assertEqual(len(w), 1) + self.assertIn("Inspection disabled", str(w[0].message)) + self.assertIn("sum", str(raises.exception)) + + # Lifetime tests + + @unittest.expectedFailure # MCJIT removeModule leaks and it is disabled + def test_library_lifetime(self): + library = self.compile_module(asm_sum_outer, asm_sum_inner) + # Exercise code generation + library.enable_object_caching() + library.serialize_using_bitcode() + library.serialize_using_object_code() + u = weakref.ref(library) + v = weakref.ref(library._final_module) + del library + # Both the library and its backing LLVM module are collected + self.assertIs(u(), None) + self.assertIs(v(), None) + + +class TestWrappers(TestCase): + + def test_noinline_on_main_call(self): + # Checks that the cpython and cfunc wrapper produces a call with the + # "noinline" attr present for the decorated function. + + # Creating a refcounted object induces a side-effect that prevents IPO + # from eliding the call to the function with LLVM 15. See Issue #9658: + # https://github.com/numba/numba/issues/9658 + @njit + def foo(): + return list([1]) + + foo() + sig = foo.signatures[0] + + ol = foo.overloads[sig] + name = ol.fndesc.mangled_name.replace("$", r"\$") + p1 = r".*call.*{}".format(name) + p2 = r".*(#[0-9]+).*" + call_site = re.compile(p1 + p2) + + lines = foo.inspect_llvm(sig).splitlines() + meta_data_idx = [] + for l in lines: + matched = call_site.match(l) + if matched: + meta_data_idx.append(matched.groups()[0]) + + # should be 2 calls, one from cpython wrapper one from cfunc wrapper + self.assertEqual(len(meta_data_idx), 2) + # both calls should refer to the same metadata item + self.assertEqual(meta_data_idx[0], meta_data_idx[1]) + + p1 = r"^attributes\s+{}".format(meta_data_idx[0]) + p2 = r"\s+=\s+{(.*)}.*$" + attr_site = re.compile(p1 + p2) + + for l in reversed(lines): + matched = attr_site.match(l) + if matched: + meta_data = matched.groups()[0] + lmeta = meta_data.strip().split(' ') + for x in lmeta: + if 'noinline' in x: + break + else: + continue + break + else: + return self.fail("Metadata did not match 'noinline'") + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_ctypes.py b/lib/python3.10/site-packages/numba/tests/test_ctypes.py new file mode 100644 index 0000000000000000000000000000000000000000..c1a7edf5099f6415576dda54faa52f8d18f150e5 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_ctypes.py @@ -0,0 +1,255 @@ +from ctypes import * +import sys +import threading + +import numpy as np + + +from numba import jit, njit +from numba.core import types, errors +from numba.core.typing import ctypes_utils +from numba.tests.support import MemoryLeakMixin, tag, TestCase +from numba.tests.ctypes_usecases import * +import unittest + + +class TestCTypesTypes(TestCase): + + def _conversion_tests(self, check): + check(c_double, types.float64) + check(c_int, types.intc) + check(c_uint16, types.uint16) + check(c_size_t, types.size_t) + check(c_ssize_t, types.ssize_t) + + check(c_void_p, types.voidptr) + check(POINTER(c_float), types.CPointer(types.float32)) + check(POINTER(POINTER(c_float)), + types.CPointer(types.CPointer(types.float32))) + + check(None, types.void) + + def test_from_ctypes(self): + """ + Test converting a ctypes type to a Numba type. + """ + def check(cty, ty): + got = ctypes_utils.from_ctypes(cty) + self.assertEqual(got, ty) + + self._conversion_tests(check) + + # An unsupported type + with self.assertRaises(TypeError) as raises: + ctypes_utils.from_ctypes(c_wchar_p) + self.assertIn("Unsupported ctypes type", str(raises.exception)) + + def test_to_ctypes(self): + """ + Test converting a Numba type to a ctypes type. + """ + def check(cty, ty): + got = ctypes_utils.to_ctypes(ty) + self.assertEqual(got, cty) + + self._conversion_tests(check) + + # An unsupported type + with self.assertRaises(TypeError) as raises: + ctypes_utils.to_ctypes(types.ellipsis) + self.assertIn("Cannot convert Numba type '...' to ctypes type", + str(raises.exception)) + + +class TestCTypesUseCases(MemoryLeakMixin, TestCase): + + def test_c_sin(self): + pyfunc = use_c_sin + cfunc = njit((types.double,))(pyfunc) + x = 3.14 + self.assertEqual(pyfunc(x), cfunc(x)) + + def test_two_funcs(self): + # Check that two constant functions don't get mixed up. + pyfunc = use_two_funcs + cfunc = njit((types.double,))(pyfunc) + x = 3.14 + self.assertEqual(pyfunc(x), cfunc(x)) + + @unittest.skipUnless(is_windows, "Windows-specific test") + def test_stdcall(self): + # Just check that it doesn't crash + cfunc = njit((types.uintc,))(use_c_sleep) + + cfunc(1) + + def test_ctype_wrapping(self): + pyfunc = use_ctype_wrapping + cfunc = njit((types.double,))(pyfunc) + x = 3.14 + self.assertEqual(pyfunc(x), cfunc(x)) + + def test_ctype_voidptr(self): + pyfunc = use_c_pointer + # pyfunc will segfault if called + cfunc = njit((types.int32,))(pyfunc) + x = 123 + self.assertEqual(cfunc(x), x + 1) + + def test_function_pointer(self): + pyfunc = use_func_pointer + cfunc = jit(nopython=True)(pyfunc) + for (fa, fb, x) in [ + (c_sin, c_cos, 1.0), + (c_sin, c_cos, -1.0), + (c_cos, c_sin, 1.0), + (c_cos, c_sin, -1.0)]: + expected = pyfunc(fa, fb, x) + got = cfunc(fa, fb, x) + self.assertEqual(got, expected) + # A single specialization was compiled for all calls + self.assertEqual(len(cfunc.overloads), 1, cfunc.overloads) + + def test_untyped_function(self): + with self.assertRaises(TypeError) as raises: + njit((types.double,))(use_c_untyped) + self.assertIn("ctypes function '_numba_test_exp' doesn't define its argument types", + str(raises.exception)) + + def test_python_call_back(self): + mydct = {'what': 1232121} + + def call_me_maybe(arr): + return mydct[arr[0].decode('ascii')] + + # Create a callback into the python interpreter + py_call_back = CFUNCTYPE(c_int, py_object)(call_me_maybe) + + def pyfunc(a): + what = py_call_back(a) + return what + + cfunc = jit(nopython=True, nogil=True)(pyfunc) + arr = np.array(["what"], dtype='S10') + self.assertEqual(pyfunc(arr), cfunc(arr)) + + def test_python_call_back_threaded(self): + def pyfunc(a, repeat): + out = 0 + for _ in range(repeat): + out += py_call_back(a) + return out + + cfunc = jit(nopython=True, nogil=True)(pyfunc) + + arr = np.array(["what"], dtype='S10') + repeat = 1000 + + expected = pyfunc(arr, repeat) + outputs = [] + + # Warm up + cfunc(arr, repeat) + + # Test the function in multiple threads to exercise the + # GIL ensure/release code + + def run(func, arr, repeat): + outputs.append(func(arr, repeat)) + + threads = [threading.Thread(target=run, args=(cfunc, arr, repeat)) + for _ in range(10)] + + # Start threads + for th in threads: + th.start() + + # End threads + for th in threads: + th.join() + + # Check results + for got in outputs: + self.assertEqual(expected, got) + + def test_passing_array_ctypes_data(self): + """ + Test the ".ctypes.data" attribute of an array can be passed + as a "void *" parameter. + """ + def pyfunc(arr): + return c_take_array_ptr(arr.ctypes.data) + + cfunc = jit(nopython=True, nogil=True)(pyfunc) + + arr = np.arange(5) + + expected = pyfunc(arr) + got = cfunc(arr) + + self.assertEqual(expected, got) + + def check_array_ctypes(self, pyfunc): + cfunc = jit(nopython=True)(pyfunc) + + arr = np.linspace(0, 10, 5) + expected = arr ** 2.0 + got = cfunc(arr) + self.assertPreciseEqual(expected, got) + return cfunc + + def test_passing_array_ctypes_voidptr(self): + """ + Test the ".ctypes" attribute of an array can be passed + as a "void *" parameter. + """ + self.check_array_ctypes(use_c_vsquare) + + def test_passing_array_ctypes_voidptr_pass_ptr(self): + """ + Test the ".ctypes" attribute of an array can be passed + as a pointer parameter of the right type. + """ + cfunc = self.check_array_ctypes(use_c_vcube) + + # Non-compatible pointers are not accepted (here float32* vs. float64*) + with self.assertRaises(errors.TypingError) as raises: + cfunc(np.float32([0.0])) + + self.assertIn("No implementation of function ExternalFunctionPointer", + str(raises.exception)) + + def test_storing_voidptr_to_int_array(self): + # Make C callback that returns a void* + cproto = CFUNCTYPE(c_void_p) + + @cproto + def get_voidstar(): + return 0xdeadbeef + + # Make python functions that use the C callback + def pyfunc(a): + ptr = get_voidstar() + a[0] = ptr + return ptr + + # Compile it + cfunc = njit((types.uintp[::1],))(pyfunc) + + # Setup inputs + arr_got = np.zeros(1, dtype=np.uintp) + arr_expect = arr_got.copy() + + # Run functions + ret_got = cfunc(arr_got) + ret_expect = pyfunc(arr_expect) + + # Check + self.assertEqual(ret_expect, 0xdeadbeef) + self.assertPreciseEqual(ret_got, ret_expect) + self.assertPreciseEqual(arr_got, arr_expect) + + +if __name__ == '__main__': + unittest.main() + diff --git a/lib/python3.10/site-packages/numba/tests/test_deprecations.py b/lib/python3.10/site-packages/numba/tests/test_deprecations.py new file mode 100644 index 0000000000000000000000000000000000000000..48b5a36aec59b9bc15c672486d947d13ca595870 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_deprecations.py @@ -0,0 +1,262 @@ +import warnings +import unittest +from contextlib import contextmanager + +from numba import jit, vectorize, guvectorize +from numba.core.errors import (NumbaDeprecationWarning, + NumbaPendingDeprecationWarning, NumbaWarning) +from numba.tests.support import TestCase, needs_setuptools + + +@contextmanager +def _catch_numba_deprecation_warnings(): + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("ignore", category=NumbaWarning) + warnings.simplefilter("always", category=NumbaDeprecationWarning) + yield w + + +class TestDeprecation(TestCase): + + def check_warning(self, warnings, expected_str, category, check_rtd=True): + self.assertEqual(len(warnings), 1) + self.assertEqual(warnings[0].category, category) + self.assertIn(expected_str, str(warnings[0].message)) + if check_rtd: + self.assertIn("https://numba.readthedocs.io", + str(warnings[0].message)) + + @TestCase.run_test_in_subprocess + def test_explicit_false_nopython_kwarg(self): + # tests that explicitly setting `nopython=False` in @jit raises a + # warning about it doing nothing. + with _catch_numba_deprecation_warnings() as w: + + @jit(nopython=False) + def foo(): + pass + + foo() + + msg = "The keyword argument 'nopython=False' was supplied" + self.check_warning(w, msg, NumbaDeprecationWarning, check_rtd=False) + + @TestCase.run_test_in_subprocess + def test_vectorize_missing_nopython_kwarg_not_reported(self): + # Checks that use of @vectorize without a nopython kwarg doesn't raise + # a warning about lack of said kwarg. + + with _catch_numba_deprecation_warnings() as w: + # This compiles via nopython mode directly + @vectorize('float64(float64)') + def foo(a): + return a + 1 + + self.assertFalse(w) + + @TestCase.run_test_in_subprocess + def test_vectorize_nopython_false_is_reported(self): + # Checks that use of @vectorize with nopython=False raises a warning + # about supplying it. + + with _catch_numba_deprecation_warnings() as w: + # This compiles via nopython mode directly + @vectorize('float64(float64)', nopython=False) + def foo(a): + return a + 1 + + msg = "The keyword argument 'nopython=False' was supplied" + self.check_warning(w, msg, NumbaDeprecationWarning, check_rtd=False) + + @TestCase.run_test_in_subprocess + def test_vectorize_objmode_direct_compilation_no_warnings(self): + # Checks that use of @vectorize with forceobj=True raises no warnings. + + with _catch_numba_deprecation_warnings() as w: + # Compiles via objmode directly with no warnings raised + @vectorize('float64(float64)', forceobj=True) + def foo(a): + object() + return a + 1 + + self.assertFalse(w) + + @TestCase.run_test_in_subprocess + def test_vectorize_objmode_compilation_nopython_false_warns(self): + # Checks that use of @vectorize with forceobj set and nopython set as + # False raises no warnings. + + with _catch_numba_deprecation_warnings() as w: + # Compiles via objmode directly with no warnings raised + @vectorize('float64(float64)', forceobj=True, nopython=False) + def foo(a): + object() + return a + 1 + + msg = "The keyword argument 'nopython=False' was supplied" + self.check_warning(w, msg, NumbaDeprecationWarning, check_rtd=False) + + @TestCase.run_test_in_subprocess + def test_vectorize_parallel_true_no_warnings(self): + # Checks that use of @vectorize with the parallel target doesn't + # raise warnings about nopython kwarg, the parallel target doesn't + # support objmode so nopython=True is implicit. + with _catch_numba_deprecation_warnings() as w: + @vectorize('float64(float64)', target='parallel') + def foo(x): + return x + 1 + + self.assertFalse(w) + + @TestCase.run_test_in_subprocess + def test_vectorize_parallel_true_nopython_true_no_warnings(self): + # Checks that use of @vectorize with the parallel target and + # nopython=True doesn't raise warnings about nopython kwarg. + with _catch_numba_deprecation_warnings() as w: + @vectorize('float64(float64)', target='parallel', nopython=True) + def foo(x): + return x + 1 + + self.assertFalse(w) + + @TestCase.run_test_in_subprocess + def test_vectorize_parallel_true_nopython_false_warns(self): + # Checks that use of @vectorize with the parallel target and + # nopython=False raises a warning about the nopython kwarg being False. + with _catch_numba_deprecation_warnings() as w: + @vectorize('float64(float64)', target='parallel', nopython=False) + def foo(x): + return x + 1 + + msg = "The keyword argument 'nopython=False' was supplied" + self.check_warning(w, msg, NumbaDeprecationWarning, check_rtd=False) + + @TestCase.run_test_in_subprocess + def test_vectorize_calling_jit_with_nopython_false_warns_from_jit(self): + # Checks the scope of the suppression of deprecation warnings that are + # present in e.g. vectorize. The function `bar` should raise a + # deprecation warning, the `@vectorize`d `foo` function should not, + # even though both don't have a nopython kwarg. + + # First check that the @vectorize call doesn't raise anything + with _catch_numba_deprecation_warnings() as w: + @vectorize('float64(float64)', forceobj=True) + def foo(x): + return bar(x + 1) + + def bar(*args): + pass + + self.assertFalse(w) + + @TestCase.run_test_in_subprocess + def test_guvectorize_implicit_nopython_no_warnings(self): + # Checks that use of @guvectorize with implicit nopython compilation + # does not warn on compilation. + with _catch_numba_deprecation_warnings() as w: + + @guvectorize('void(float64[::1], float64[::1])', '(n)->(n)') + def bar(a, b): + a += 1 + + self.assertFalse(w) + + @TestCase.run_test_in_subprocess + def test_guvectorize_forceobj_no_warnings(self): + # Checks that use of @guvectorize with direct objmode compilation does + # not warn. + with _catch_numba_deprecation_warnings() as w: + + @guvectorize('void(float64[::1], float64[::1])', '(n)->(n)', + forceobj=True) + def bar(a, b): + object() + a += 1 + + self.assertFalse(w) + + @TestCase.run_test_in_subprocess + def test_guvectorize_parallel_implicit_nopython_no_warnings(self): + # Checks that use of @guvectorize with parallel target and implicit + # nopython mode compilation does not warn. + with _catch_numba_deprecation_warnings() as w: + + @guvectorize('void(float64[::1], float64[::1])', '(n)->(n)', + target='parallel') + def bar(a, b): + a += 1 + + self.assertFalse(w) + + @TestCase.run_test_in_subprocess + def test_guvectorize_parallel_forceobj_no_warnings(self): + # Checks that use of @guvectorize with parallel target and direct + # objmode compilation does not warn. + with _catch_numba_deprecation_warnings() as w: + + # This compiles somewhat surprisingly for the parallel target using + # object mode?! + @guvectorize('void(float64[::1], float64[::1])', '(n)->(n)', + target='parallel', forceobj=True) + def bar(a, b): + object() + a += 1 + + self.assertFalse(w) + + @TestCase.run_test_in_subprocess + def test_reflection_of_mutable_container(self): + # tests that reflection in list/set warns + def foo_list(a): + return a.append(1) + + def foo_set(a): + return a.add(1) + + for f in [foo_list, foo_set]: + container = f.__name__.strip('foo_') + inp = eval(container)([10, ]) + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("ignore", category=NumbaWarning) + warnings.simplefilter("always", + category=NumbaPendingDeprecationWarning) + jit(nopython=True)(f)(inp) + self.assertEqual(len(w), 1) + self.assertEqual(w[0].category, NumbaPendingDeprecationWarning) + warn_msg = str(w[0].message) + msg = ("Encountered the use of a type that is scheduled for " + "deprecation") + self.assertIn(msg, warn_msg) + msg = ("\'reflected %s\' found for argument" % container) + self.assertIn(msg, warn_msg) + self.assertIn("https://numba.readthedocs.io", warn_msg) + + @needs_setuptools + @TestCase.run_test_in_subprocess + def test_pycc_module(self): + # checks import of module warns + + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always", + category=NumbaPendingDeprecationWarning) + import numba.pycc # noqa: F401 + + expected_str = ("The 'pycc' module is pending deprecation.") + self.check_warning(w, expected_str, NumbaPendingDeprecationWarning) + + @needs_setuptools + @TestCase.run_test_in_subprocess + def test_pycc_CC(self): + # check the most commonly used functionality (CC) warns + + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always", + category=NumbaPendingDeprecationWarning) + from numba.pycc import CC # noqa: F401 + + expected_str = ("The 'pycc' module is pending deprecation.") + self.check_warning(w, expected_str, NumbaPendingDeprecationWarning) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_dispatcher.py b/lib/python3.10/site-packages/numba/tests/test_dispatcher.py new file mode 100644 index 0000000000000000000000000000000000000000..1aa5e9232dba1bc08fd4b962a86ca5265264c388 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_dispatcher.py @@ -0,0 +1,1193 @@ +import multiprocessing +import platform +import threading +import pickle +import weakref +from itertools import chain +from io import StringIO + +import numpy as np + +from numba import njit, jit, typeof, vectorize +from numba.core import types, errors +from numba import _dispatcher +from numba.tests.support import TestCase, captured_stdout +from numba.np.numpy_support import as_dtype +from numba.core.dispatcher import Dispatcher +from numba.extending import overload +from numba.tests.support import needs_lapack, SerialMixin +from numba.testing.main import _TIMEOUT as _RUNNER_TIMEOUT +import unittest + + +_TEST_TIMEOUT = _RUNNER_TIMEOUT - 60. + + +try: + import jinja2 +except ImportError: + jinja2 = None + +try: + import pygments +except ImportError: + pygments = None + +_is_armv7l = platform.machine() == 'armv7l' + + +def dummy(x): + return x + + +def add(x, y): + return x + y + + +def addsub(x, y, z): + return x - y + z + + +def addsub_defaults(x, y=2, z=3): + return x - y + z + + +def star_defaults(x, y=2, *z): + return x, y, z + + +def generated_usecase(x, y=5): + if isinstance(x, types.Complex): + def impl(x, y): + return x + y + else: + def impl(x, y): + return x - y + return impl + + +def bad_generated_usecase(x, y=5): + if isinstance(x, types.Complex): + def impl(x): + return x + else: + def impl(x, y=6): + return x - y + return impl + + +def dtype_generated_usecase(a, b, dtype=None): + if isinstance(dtype, (types.misc.NoneType, types.misc.Omitted)): + out_dtype = np.result_type(*(np.dtype(ary.dtype.name) + for ary in (a, b))) + elif isinstance(dtype, (types.DType, types.NumberClass)): + out_dtype = as_dtype(dtype) + else: + raise TypeError("Unhandled Type %s" % type(dtype)) + + def _fn(a, b, dtype=None): + return np.ones(a.shape, dtype=out_dtype) + + return _fn + + +class BaseTest(TestCase): + + jit_args = dict(nopython=True) + + def compile_func(self, pyfunc): + def check(*args, **kwargs): + expected = pyfunc(*args, **kwargs) + result = f(*args, **kwargs) + self.assertPreciseEqual(result, expected) + f = jit(**self.jit_args)(pyfunc) + return f, check + + +class TestDispatcher(BaseTest): + + def test_equality(self): + @jit + def foo(x): + return x + + @jit + def bar(x): + return x + + # Written this way to verify `==` returns a bool (gh-5838). Using + # `assertTrue(foo == foo)` or `assertEqual(foo, foo)` would defeat the + # purpose of this test. + self.assertEqual(foo == foo, True) + self.assertEqual(foo == bar, False) + self.assertEqual(foo == None, False) # noqa: E711 + + def test_dyn_pyfunc(self): + @jit + def foo(x): + return x + + foo(1) + [cr] = foo.overloads.values() + # __module__ must be match that of foo + self.assertEqual(cr.entry_point.__module__, foo.py_func.__module__) + + def test_no_argument(self): + @jit + def foo(): + return 1 + + # Just make sure this doesn't crash + foo() + + def test_coerce_input_types(self): + # Issue #486: do not allow unsafe conversions if we can still + # compile other specializations. + c_add = jit(nopython=True)(add) + self.assertPreciseEqual(c_add(123, 456), add(123, 456)) + self.assertPreciseEqual(c_add(12.3, 45.6), add(12.3, 45.6)) + self.assertPreciseEqual(c_add(12.3, 45.6j), add(12.3, 45.6j)) + self.assertPreciseEqual(c_add(12300000000, 456), add(12300000000, 456)) + + # Now force compilation of only a single specialization + c_add = jit('(i4, i4)', nopython=True)(add) + self.assertPreciseEqual(c_add(123, 456), add(123, 456)) + # Implicit (unsafe) conversion of float to int + self.assertPreciseEqual(c_add(12.3, 45.6), add(12, 45)) + with self.assertRaises(TypeError): + # Implicit conversion of complex to int disallowed + c_add(12.3, 45.6j) + + def test_ambiguous_new_version(self): + """Test compiling new version in an ambiguous case + """ + @jit + def foo(a, b): + return a + b + + INT = 1 + FLT = 1.5 + self.assertAlmostEqual(foo(INT, FLT), INT + FLT) + self.assertEqual(len(foo.overloads), 1) + self.assertAlmostEqual(foo(FLT, INT), FLT + INT) + self.assertEqual(len(foo.overloads), 2) + self.assertAlmostEqual(foo(FLT, FLT), FLT + FLT) + self.assertEqual(len(foo.overloads), 3) + # The following call is ambiguous because (int, int) can resolve + # to (float, int) or (int, float) with equal weight. + self.assertAlmostEqual(foo(1, 1), INT + INT) + self.assertEqual(len(foo.overloads), 4, "didn't compile a new " + "version") + + def test_lock(self): + """ + Test that (lazy) compiling from several threads at once doesn't + produce errors (see issue #908). + """ + errors = [] + + @jit + def foo(x): + return x + 1 + + def wrapper(): + try: + self.assertEqual(foo(1), 2) + except Exception as e: + errors.append(e) + + threads = [threading.Thread(target=wrapper) for i in range(16)] + for t in threads: + t.start() + for t in threads: + t.join() + self.assertFalse(errors) + + def test_explicit_signatures(self): + f = jit("(int64,int64)")(add) + # Approximate match (unsafe conversion) + self.assertPreciseEqual(f(1.5, 2.5), 3) + self.assertEqual(len(f.overloads), 1, f.overloads) + f = jit(["(int64,int64)", "(float64,float64)"])(add) + # Exact signature matches + self.assertPreciseEqual(f(1, 2), 3) + self.assertPreciseEqual(f(1.5, 2.5), 4.0) + # Approximate match (int32 -> float64 is a safe conversion) + self.assertPreciseEqual(f(np.int32(1), 2.5), 3.5) + # No conversion + with self.assertRaises(TypeError) as cm: + f(1j, 1j) + self.assertIn("No matching definition", str(cm.exception)) + self.assertEqual(len(f.overloads), 2, f.overloads) + # A more interesting one... + f = jit(["(float32,float32)", "(float64,float64)"])(add) + self.assertPreciseEqual(f(np.float32(1), np.float32(2**-25)), 1.0) + self.assertPreciseEqual(f(1, 2**-25), 1.0000000298023224) + # Fail to resolve ambiguity between the two best overloads + f = jit(["(float32,float64)", + "(float64,float32)", + "(int64,int64)"])(add) + with self.assertRaises(TypeError) as cm: + f(1.0, 2.0) + # The two best matches are output in the error message, as well + # as the actual argument types. + self.assertRegex( + str(cm.exception), + r"Ambiguous overloading for ]*> " + r"\(float64, float64\):\n" + r"\(float32, float64\) -> float64\n" + r"\(float64, float32\) -> float64" + ) + # The integer signature is not part of the best matches + self.assertNotIn("int64", str(cm.exception)) + + def test_signature_mismatch(self): + tmpl = ("Signature mismatch: %d argument types given, but function " + "takes 2 arguments") + with self.assertRaises(TypeError) as cm: + jit("()")(add) + self.assertIn(tmpl % 0, str(cm.exception)) + with self.assertRaises(TypeError) as cm: + jit("(intc,)")(add) + self.assertIn(tmpl % 1, str(cm.exception)) + with self.assertRaises(TypeError) as cm: + jit("(intc,intc,intc)")(add) + self.assertIn(tmpl % 3, str(cm.exception)) + # With forceobj=True, an empty tuple is accepted + jit("()", forceobj=True)(add) + with self.assertRaises(TypeError) as cm: + jit("(intc,)", forceobj=True)(add) + self.assertIn(tmpl % 1, str(cm.exception)) + + def test_matching_error_message(self): + f = jit("(intc,intc)")(add) + with self.assertRaises(TypeError) as cm: + f(1j, 1j) + self.assertEqual(str(cm.exception), + "No matching definition for argument type(s) " + "complex128, complex128") + + def test_disabled_compilation(self): + @jit + def foo(a): + return a + + foo.compile("(float32,)") + foo.disable_compile() + with self.assertRaises(RuntimeError) as raises: + foo.compile("(int32,)") + self.assertEqual(str(raises.exception), "compilation disabled") + self.assertEqual(len(foo.signatures), 1) + + def test_disabled_compilation_through_list(self): + @jit(["(float32,)", "(int32,)"]) + def foo(a): + return a + + with self.assertRaises(RuntimeError) as raises: + foo.compile("(complex64,)") + self.assertEqual(str(raises.exception), "compilation disabled") + self.assertEqual(len(foo.signatures), 2) + + def test_disabled_compilation_nested_call(self): + @jit(["(intp,)"]) + def foo(a): + return a + + @jit + def bar(): + foo(1) + foo(np.ones(1)) # no matching definition + + with self.assertRaises(errors.TypingError) as raises: + bar() + + m = r".*Invalid use of.*with parameters \(array\(float64, 1d, C\)\).*" + self.assertRegex(str(raises.exception), m) + + def test_fingerprint_failure(self): + """ + Failure in computing the fingerprint cannot affect a nopython=False + function. On the other hand, with nopython=True, a ValueError should + be raised to report the failure with fingerprint. + """ + def foo(x): + return x + + # Empty list will trigger failure in compile_fingerprint + errmsg = 'cannot compute fingerprint of empty list' + with self.assertRaises(ValueError) as raises: + _dispatcher.compute_fingerprint([]) + self.assertIn(errmsg, str(raises.exception)) + # It should work in objmode + objmode_foo = jit(forceobj=True)(foo) + self.assertEqual(objmode_foo([]), []) + # But, not in nopython=True + strict_foo = jit(nopython=True)(foo) + with self.assertRaises(ValueError) as raises: + strict_foo([]) + self.assertIn(errmsg, str(raises.exception)) + + # Test in loop lifting context + @jit(forceobj=True) + def bar(): + object() # force looplifting + x = [] + for i in range(10): + x = objmode_foo(x) + return x + + self.assertEqual(bar(), []) + # Make sure it was looplifted + [cr] = bar.overloads.values() + self.assertEqual(len(cr.lifted), 1) + + def test_serialization(self): + """ + Test serialization of Dispatcher objects + """ + @jit(nopython=True) + def foo(x): + return x + 1 + + self.assertEqual(foo(1), 2) + + # get serialization memo + memo = Dispatcher._memo + Dispatcher._recent.clear() + memo_size = len(memo) + + # pickle foo and check memo size + serialized_foo = pickle.dumps(foo) + # increases the memo size + self.assertEqual(memo_size + 1, len(memo)) + + # unpickle + foo_rebuilt = pickle.loads(serialized_foo) + self.assertEqual(memo_size + 1, len(memo)) + + self.assertIs(foo, foo_rebuilt) + + # do we get the same object even if we delete all the explicit + # references? + id_orig = id(foo_rebuilt) + del foo + del foo_rebuilt + self.assertEqual(memo_size + 1, len(memo)) + new_foo = pickle.loads(serialized_foo) + self.assertEqual(id_orig, id(new_foo)) + + # now clear the recent cache + ref = weakref.ref(new_foo) + del new_foo + Dispatcher._recent.clear() + self.assertEqual(memo_size, len(memo)) + + # show that deserializing creates a new object + pickle.loads(serialized_foo) + self.assertIs(ref(), None) + + @needs_lapack + @unittest.skipIf(_is_armv7l, "Unaligned loads unsupported") + def test_misaligned_array_dispatch(self): + # for context see issue #2937 + def foo(a): + return np.linalg.matrix_power(a, 1) + + jitfoo = jit(nopython=True)(foo) + + n = 64 + r = int(np.sqrt(n)) + dt = np.int8 + count = np.complex128().itemsize // dt().itemsize + + tmp = np.arange(n * count + 1, dtype=dt) + + # create some arrays as Cartesian production of: + # [F/C] x [aligned/misaligned] + C_contig_aligned = tmp[:-1].view(np.complex128).reshape(r, r) + C_contig_misaligned = tmp[1:].view(np.complex128).reshape(r, r) + F_contig_aligned = C_contig_aligned.T + F_contig_misaligned = C_contig_misaligned.T + + # checking routine + def check(name, a): + a[:, :] = np.arange(n, dtype=np.complex128).reshape(r, r) + expected = foo(a) + got = jitfoo(a) + np.testing.assert_allclose(expected, got) + + # The checks must be run in this order to create the dispatch key + # sequence that causes invalid dispatch noted in #2937. + # The first two should hit the cache as they are aligned, supported + # order and under 5 dimensions. The second two should end up in the + # fallback path as they are misaligned. + check("C_contig_aligned", C_contig_aligned) + check("F_contig_aligned", F_contig_aligned) + check("C_contig_misaligned", C_contig_misaligned) + check("F_contig_misaligned", F_contig_misaligned) + + @unittest.skipIf(_is_armv7l, "Unaligned loads unsupported") + def test_immutability_in_array_dispatch(self): + + # RO operation in function + def foo(a): + return np.sum(a) + + jitfoo = jit(nopython=True)(foo) + + n = 64 + r = int(np.sqrt(n)) + dt = np.int8 + count = np.complex128().itemsize // dt().itemsize + + tmp = np.arange(n * count + 1, dtype=dt) + + # create some arrays as Cartesian production of: + # [F/C] x [aligned/misaligned] + C_contig_aligned = tmp[:-1].view(np.complex128).reshape(r, r) + C_contig_misaligned = tmp[1:].view(np.complex128).reshape(r, r) + F_contig_aligned = C_contig_aligned.T + F_contig_misaligned = C_contig_misaligned.T + + # checking routine + def check(name, a, disable_write_bit=False): + a[:, :] = np.arange(n, dtype=np.complex128).reshape(r, r) + if disable_write_bit: + a.flags.writeable = False + expected = foo(a) + got = jitfoo(a) + np.testing.assert_allclose(expected, got) + + # all of these should end up in the fallback path as they have no write + # bit set + check("C_contig_aligned", C_contig_aligned, disable_write_bit=True) + check("F_contig_aligned", F_contig_aligned, disable_write_bit=True) + check("C_contig_misaligned", C_contig_misaligned, + disable_write_bit=True) + check("F_contig_misaligned", F_contig_misaligned, + disable_write_bit=True) + + @needs_lapack + @unittest.skipIf(_is_armv7l, "Unaligned loads unsupported") + def test_misaligned_high_dimension_array_dispatch(self): + + def foo(a): + return np.linalg.matrix_power(a[0, 0, 0, 0, :, :], 1) + + jitfoo = jit(nopython=True)(foo) + + def check_properties(arr, layout, aligned): + self.assertEqual(arr.flags.aligned, aligned) + if layout == "C": + self.assertEqual(arr.flags.c_contiguous, True) + if layout == "F": + self.assertEqual(arr.flags.f_contiguous, True) + + n = 729 + r = 3 + dt = np.int8 + count = np.complex128().itemsize // dt().itemsize + + tmp = np.arange(n * count + 1, dtype=dt) + + # create some arrays as Cartesian production of: + # [F/C] x [aligned/misaligned] + C_contig_aligned = tmp[:-1].view(np.complex128).\ + reshape(r, r, r, r, r, r) + check_properties(C_contig_aligned, 'C', True) + C_contig_misaligned = tmp[1:].view(np.complex128).\ + reshape(r, r, r, r, r, r) + check_properties(C_contig_misaligned, 'C', False) + F_contig_aligned = C_contig_aligned.T + check_properties(F_contig_aligned, 'F', True) + F_contig_misaligned = C_contig_misaligned.T + check_properties(F_contig_misaligned, 'F', False) + + # checking routine + def check(name, a): + a[:, :] = np.arange(n, dtype=np.complex128).\ + reshape(r, r, r, r, r, r) + expected = foo(a) + got = jitfoo(a) + np.testing.assert_allclose(expected, got) + + # these should all hit the fallback path as the cache is only for up to + # 5 dimensions + check("F_contig_misaligned", F_contig_misaligned) + check("C_contig_aligned", C_contig_aligned) + check("F_contig_aligned", F_contig_aligned) + check("C_contig_misaligned", C_contig_misaligned) + + def test_dispatch_recompiles_for_scalars(self): + # for context #3612, essentially, compiling a lambda x:x for a + # numerically wide type (everything can be converted to a complex128) + # and then calling again with e.g. an int32 would lead to the int32 + # being converted to a complex128 whereas it ought to compile an int32 + # specialization. + def foo(x): + return x + + # jit and compile on dispatch for 3 scalar types, expect 3 signatures + jitfoo = jit(nopython=True)(foo) + jitfoo(np.complex128(1 + 2j)) + jitfoo(np.int32(10)) + jitfoo(np.bool_(False)) + self.assertEqual(len(jitfoo.signatures), 3) + expected_sigs = [(types.complex128,), (types.int32,), (types.bool_,)] + self.assertEqual(jitfoo.signatures, expected_sigs) + + # now jit with signatures so recompilation is forbidden + # expect 1 signature and type conversion + jitfoo = jit([(types.complex128,)], nopython=True)(foo) + jitfoo(np.complex128(1 + 2j)) + jitfoo(np.int32(10)) + jitfoo(np.bool_(False)) + self.assertEqual(len(jitfoo.signatures), 1) + expected_sigs = [(types.complex128,)] + self.assertEqual(jitfoo.signatures, expected_sigs) + + def test_dispatcher_raises_for_invalid_decoration(self): + # For context see https://github.com/numba/numba/issues/4750. + + @jit(nopython=True) + def foo(x): + return x + + with self.assertRaises(TypeError) as raises: + jit(foo) + err_msg = str(raises.exception) + self.assertIn( + "A jit decorator was called on an already jitted function", err_msg) + self.assertIn("foo", err_msg) + self.assertIn(".py_func", err_msg) + + with self.assertRaises(TypeError) as raises: + jit(BaseTest) + err_msg = str(raises.exception) + self.assertIn("The decorated object is not a function", err_msg) + self.assertIn(f"{type(BaseTest)}", err_msg) + + +class TestSignatureHandling(BaseTest): + """ + Test support for various parameter passing styles. + """ + + def test_named_args(self): + """ + Test passing named arguments to a dispatcher. + """ + f, check = self.compile_func(addsub) + check(3, z=10, y=4) + check(3, 4, 10) + check(x=3, y=4, z=10) + # All calls above fall under the same specialization + self.assertEqual(len(f.overloads), 1) + # Errors + with self.assertRaises(TypeError) as cm: + f(3, 4, y=6, z=7) + self.assertIn("too many arguments: expected 3, got 4", + str(cm.exception)) + with self.assertRaises(TypeError) as cm: + f() + self.assertIn("not enough arguments: expected 3, got 0", + str(cm.exception)) + with self.assertRaises(TypeError) as cm: + f(3, 4, y=6) + self.assertIn("missing argument 'z'", str(cm.exception)) + + def test_default_args(self): + """ + Test omitting arguments with a default value. + """ + f, check = self.compile_func(addsub_defaults) + check(3, z=10, y=4) + check(3, 4, 10) + check(x=3, y=4, z=10) + # Now omitting some values + check(3, z=10) + check(3, 4) + check(x=3, y=4) + check(3) + check(x=3) + # Errors + with self.assertRaises(TypeError) as cm: + f(3, 4, y=6, z=7) + self.assertIn("too many arguments: expected 3, got 4", + str(cm.exception)) + with self.assertRaises(TypeError) as cm: + f() + self.assertIn("not enough arguments: expected at least 1, got 0", + str(cm.exception)) + with self.assertRaises(TypeError) as cm: + f(y=6, z=7) + self.assertIn("missing argument 'x'", str(cm.exception)) + + def test_star_args(self): + """ + Test a compiled function with starargs in the signature. + """ + f, check = self.compile_func(star_defaults) + check(4) + check(4, 5) + check(4, 5, 6) + check(4, 5, 6, 7) + check(4, 5, 6, 7, 8) + check(x=4) + check(x=4, y=5) + check(4, y=5) + with self.assertRaises(TypeError) as cm: + f(4, 5, y=6) + self.assertIn("some keyword arguments unexpected", str(cm.exception)) + with self.assertRaises(TypeError) as cm: + f(4, 5, z=6) + self.assertIn("some keyword arguments unexpected", str(cm.exception)) + with self.assertRaises(TypeError) as cm: + f(4, x=6) + self.assertIn("some keyword arguments unexpected", str(cm.exception)) + + +class TestSignatureHandlingObjectMode(TestSignatureHandling): + """ + Sams as TestSignatureHandling, but in object mode. + """ + + jit_args = dict(forceobj=True) + + +class TestDispatcherMethods(TestCase): + + def test_recompile(self): + closure = 1 + + @jit + def foo(x): + return x + closure + self.assertPreciseEqual(foo(1), 2) + self.assertPreciseEqual(foo(1.5), 2.5) + self.assertEqual(len(foo.signatures), 2) + closure = 2 + self.assertPreciseEqual(foo(1), 2) + # Recompiling takes the new closure into account. + foo.recompile() + # Everything was recompiled + self.assertEqual(len(foo.signatures), 2) + self.assertPreciseEqual(foo(1), 3) + self.assertPreciseEqual(foo(1.5), 3.5) + + def test_recompile_signatures(self): + # Same as above, but with an explicit signature on @jit. + closure = 1 + + @jit("int32(int32)") + def foo(x): + return x + closure + self.assertPreciseEqual(foo(1), 2) + self.assertPreciseEqual(foo(1.5), 2) + closure = 2 + self.assertPreciseEqual(foo(1), 2) + # Recompiling takes the new closure into account. + foo.recompile() + self.assertPreciseEqual(foo(1), 3) + self.assertPreciseEqual(foo(1.5), 3) + + def test_inspect_llvm(self): + # Create a jited function + @jit + def foo(explicit_arg1, explicit_arg2): + return explicit_arg1 + explicit_arg2 + + # Call it in a way to create 3 signatures + foo(1, 1) + foo(1.0, 1) + foo(1.0, 1.0) + + # base call to get all llvm in a dict + llvms = foo.inspect_llvm() + self.assertEqual(len(llvms), 3) + + # make sure the function name shows up in the llvm + for llvm_bc in llvms.values(): + # Look for the function name + self.assertIn("foo", llvm_bc) + + # Look for the argument names + self.assertIn("explicit_arg1", llvm_bc) + self.assertIn("explicit_arg2", llvm_bc) + + def test_inspect_asm(self): + # Create a jited function + @jit + def foo(explicit_arg1, explicit_arg2): + return explicit_arg1 + explicit_arg2 + + # Call it in a way to create 3 signatures + foo(1, 1) + foo(1.0, 1) + foo(1.0, 1.0) + + # base call to get all llvm in a dict + asms = foo.inspect_asm() + self.assertEqual(len(asms), 3) + + # make sure the function name shows up in the llvm + for asm in asms.values(): + # Look for the function name + self.assertTrue("foo" in asm) + + def _check_cfg_display(self, cfg, wrapper=''): + # simple stringify test + if wrapper: + wrapper = "{}{}".format(len(wrapper), wrapper) + module_name = __name__.split('.', 1)[0] + module_len = len(module_name) + prefix = r'^digraph "CFG for \'_ZN{}{}{}'.format(wrapper, + module_len, + module_name) + self.assertRegex(str(cfg), prefix) + # .display() requires an optional dependency on `graphviz`. + # just test for the attribute without running it. + self.assertTrue(callable(cfg.display)) + + def test_inspect_cfg(self): + # Exercise the .inspect_cfg(). These are minimal tests and do not fully + # check the correctness of the function. + @jit + def foo(the_array): + return the_array.sum() + + # Generate 3 overloads + a1 = np.ones(1) + a2 = np.ones((1, 1)) + a3 = np.ones((1, 1, 1)) + foo(a1) + foo(a2) + foo(a3) + + # Call inspect_cfg() without arguments + cfgs = foo.inspect_cfg() + + # Correct count of overloads + self.assertEqual(len(cfgs), 3) + + # Makes sure all the signatures are correct + [s1, s2, s3] = cfgs.keys() + self.assertEqual(set([s1, s2, s3]), + set(map(lambda x: (typeof(x),), [a1, a2, a3]))) + + for cfg in cfgs.values(): + self._check_cfg_display(cfg) + self.assertEqual(len(list(cfgs.values())), 3) + + # Call inspect_cfg(signature) + cfg = foo.inspect_cfg(signature=foo.signatures[0]) + self._check_cfg_display(cfg) + + def test_inspect_cfg_with_python_wrapper(self): + # Exercise the .inspect_cfg() including the python wrapper. + # These are minimal tests and do not fully check the correctness of + # the function. + @jit + def foo(the_array): + return the_array.sum() + + # Generate 3 overloads + a1 = np.ones(1) + a2 = np.ones((1, 1)) + a3 = np.ones((1, 1, 1)) + foo(a1) + foo(a2) + foo(a3) + + # Call inspect_cfg(signature, show_wrapper="python") + cfg = foo.inspect_cfg(signature=foo.signatures[0], + show_wrapper="python") + self._check_cfg_display(cfg, wrapper='cpython') + + def test_inspect_types(self): + @jit + def foo(a, b): + return a + b + + foo(1, 2) + # Exercise the method + foo.inspect_types(StringIO()) + + # Test output + expected = str(foo.overloads[foo.signatures[0]].type_annotation) + with captured_stdout() as out: + foo.inspect_types() + assert expected in out.getvalue() + + def test_inspect_types_with_signature(self): + @jit + def foo(a): + return a + 1 + + foo(1) + foo(1.0) + # Inspect all signatures + with captured_stdout() as total: + foo.inspect_types() + # Inspect first signature + with captured_stdout() as first: + foo.inspect_types(signature=foo.signatures[0]) + # Inspect second signature + with captured_stdout() as second: + foo.inspect_types(signature=foo.signatures[1]) + + self.assertEqual(total.getvalue(), first.getvalue() + second.getvalue()) + + @unittest.skipIf(jinja2 is None, "please install the 'jinja2' package") + @unittest.skipIf(pygments is None, "please install the 'pygments' package") + def test_inspect_types_pretty(self): + @jit + def foo(a, b): + return a + b + + foo(1, 2) + + # Exercise the method, dump the output + with captured_stdout(): + ann = foo.inspect_types(pretty=True) + + # ensure HTML is found in the annotation output + for k, v in ann.ann.items(): + span_found = False + for line in v['pygments_lines']: + if 'span' in line[2]: + span_found = True + self.assertTrue(span_found) + + # check that file+pretty kwarg combo raises + with self.assertRaises(ValueError) as raises: + foo.inspect_types(file=StringIO(), pretty=True) + + self.assertIn("`file` must be None if `pretty=True`", + str(raises.exception)) + + def test_get_annotation_info(self): + @jit + def foo(a): + return a + 1 + + foo(1) + foo(1.3) + + expected = dict(chain.from_iterable(foo.get_annotation_info(i).items() + for i in foo.signatures)) + result = foo.get_annotation_info() + self.assertEqual(expected, result) + + def test_issue_with_array_layout_conflict(self): + """ + This test an issue with the dispatcher when an array that is both + C and F contiguous is supplied as the first signature. + The dispatcher checks for F contiguous first but the compiler checks + for C contiguous first. This results in an C contiguous code inserted + as F contiguous function. + """ + def pyfunc(A, i, j): + return A[i, j] + + cfunc = jit(pyfunc) + + ary_c_and_f = np.array([[1.]]) + ary_c = np.array([[0., 1.], [2., 3.]], order='C') + ary_f = np.array([[0., 1.], [2., 3.]], order='F') + + exp_c = pyfunc(ary_c, 1, 0) + exp_f = pyfunc(ary_f, 1, 0) + + self.assertEqual(1., cfunc(ary_c_and_f, 0, 0)) + got_c = cfunc(ary_c, 1, 0) + got_f = cfunc(ary_f, 1, 0) + + self.assertEqual(exp_c, got_c) + self.assertEqual(exp_f, got_f) + + +class TestDispatcherFunctionBoundaries(TestCase): + def test_pass_dispatcher_as_arg(self): + # Test that a Dispatcher object can be pass as argument + @jit(nopython=True) + def add1(x): + return x + 1 + + @jit(nopython=True) + def bar(fn, x): + return fn(x) + + @jit(nopython=True) + def foo(x): + return bar(add1, x) + + # Check dispatcher as argument inside NPM + inputs = [1, 11.1, np.arange(10)] + expected_results = [x + 1 for x in inputs] + + for arg, expect in zip(inputs, expected_results): + self.assertPreciseEqual(foo(arg), expect) + + # Check dispatcher as argument from python + for arg, expect in zip(inputs, expected_results): + self.assertPreciseEqual(bar(add1, arg), expect) + + def test_dispatcher_as_arg_usecase(self): + @jit(nopython=True) + def maximum(seq, cmpfn): + tmp = seq[0] + for each in seq[1:]: + cmpval = cmpfn(tmp, each) + if cmpval < 0: + tmp = each + return tmp + + got = maximum([1, 2, 3, 4], cmpfn=jit(lambda x, y: x - y)) + self.assertEqual(got, 4) + got = maximum(list(zip(range(5), range(5)[::-1])), + cmpfn=jit(lambda x, y: x[0] - y[0])) + self.assertEqual(got, (4, 0)) + got = maximum(list(zip(range(5), range(5)[::-1])), + cmpfn=jit(lambda x, y: x[1] - y[1])) + self.assertEqual(got, (0, 4)) + + def test_dispatcher_can_return_to_python(self): + @jit(nopython=True) + def foo(fn): + return fn + + fn = jit(lambda x: x) + + self.assertEqual(foo(fn), fn) + + def test_dispatcher_in_sequence_arg(self): + @jit(nopython=True) + def one(x): + return x + 1 + + @jit(nopython=True) + def two(x): + return one(one(x)) + + @jit(nopython=True) + def three(x): + return one(one(one(x))) + + @jit(nopython=True) + def choose(fns, x): + return fns[0](x), fns[1](x), fns[2](x) + + # Tuple case + self.assertEqual(choose((one, two, three), 1), (2, 3, 4)) + # List case + self.assertEqual(choose([one, one, one], 1), (2, 2, 2)) + + +class TestBoxingDefaultError(unittest.TestCase): + # Testing default error at boxing/unboxing + def test_unbox_runtime_error(self): + # Dummy type has no unbox support + def foo(x): + pass + argtys = (types.Dummy("dummy_type"),) + # This needs `compile_isolated`-like behaviour so as to bypass + # dispatcher type checking logic + cres = njit(argtys)(foo).overloads[argtys] + with self.assertRaises(TypeError) as raises: + # Can pass in whatever and the unbox logic will always raise + # without checking the input value. + cres.entry_point(None) + self.assertEqual(str(raises.exception), "can't unbox dummy_type type") + + def test_box_runtime_error(self): + @njit + def foo(): + return unittest # Module type has no boxing logic + with self.assertRaises(TypeError) as raises: + foo() + pat = "cannot convert native Module.* to Python object" + self.assertRegex(str(raises.exception), pat) + + +class TestNoRetryFailedSignature(unittest.TestCase): + """Test that failed-to-compile signatures are not recompiled. + """ + + def run_test(self, func): + fcom = func._compiler + self.assertEqual(len(fcom._failed_cache), 0) + # expected failure because `int` has no `__getitem__` + with self.assertRaises(errors.TypingError): + func(1) + self.assertEqual(len(fcom._failed_cache), 1) + # retry + with self.assertRaises(errors.TypingError): + func(1) + self.assertEqual(len(fcom._failed_cache), 1) + # retry with double + with self.assertRaises(errors.TypingError): + func(1.0) + self.assertEqual(len(fcom._failed_cache), 2) + + def test_direct_call(self): + @jit(nopython=True) + def foo(x): + return x[0] + + self.run_test(foo) + + def test_nested_call(self): + @jit(nopython=True) + def bar(x): + return x[0] + + @jit(nopython=True) + def foobar(x): + bar(x) + + @jit(nopython=True) + def foo(x): + return bar(x) + foobar(x) + + self.run_test(foo) + + @unittest.expectedFailure + # NOTE: @overload does not have an error cache. See PR #9259 for this + # feature and remove the xfail once this is merged. + def test_error_count(self): + def check(field, would_fail): + # Slightly modified from the reproducer in issue #4117. + # Before the patch, the compilation time of the failing case is + # much longer than of the successful case. This can be detected + # by the number of times `trigger()` is visited. + k = 10 + counter = {'c': 0} + + def trigger(x): + assert 0, "unreachable" + + @overload(trigger) + def ol_trigger(x): + # Keep track of every visit + counter['c'] += 1 + if would_fail: + raise errors.TypingError("invoke_failed") + return lambda x: x + + @jit(nopython=True) + def ident(out, x): + pass + + def chain_assign(fs, inner=ident): + tab_head, tab_tail = fs[-1], fs[:-1] + + @jit(nopython=True) + def assign(out, x): + inner(out, x) + out[0] += tab_head(x) + + if tab_tail: + return chain_assign(tab_tail, assign) + else: + return assign + + chain = chain_assign((trigger,) * k) + out = np.ones(2) + if would_fail: + with self.assertRaises(errors.TypingError) as raises: + chain(out, 1) + self.assertIn('invoke_failed', str(raises.exception)) + else: + chain(out, 1) + + # Returns the visit counts + return counter['c'] + + ct_ok = check('a', False) + ct_bad = check('c', True) + # `trigger()` is visited exactly once for both successful and failed + # compilation. + self.assertEqual(ct_ok, 1) + self.assertEqual(ct_bad, 1) + + +@njit +def add_y1(x, y=1): + return x + y + + +@njit +def add_ynone(x, y=None): + return x + (1 if y else 2) + + +@njit +def mult(x, y): + return x * y + + +@njit +def add_func(x, func=mult): + return x + func(x, x) + + +def _checker(f1, arg): + assert f1(arg) == f1.py_func(arg) + + +class TestMultiprocessingDefaultParameters(SerialMixin, unittest.TestCase): + def run_fc_multiproc(self, fc): + try: + ctx = multiprocessing.get_context('spawn') + except AttributeError: + ctx = multiprocessing + + # RE: issue #5973, this doesn't use multiprocessing.Pool.map as doing so + # causes the TBB library to segfault under certain conditions. It's not + # clear whether the cause is something in the complexity of the Pool + # itself, e.g. watcher threads etc, or if it's a problem synonymous with + # a "timing attack". + for a in [1, 2, 3]: + p = ctx.Process(target=_checker, args=(fc, a,)) + p.start() + p.join(_TEST_TIMEOUT) + self.assertEqual(p.exitcode, 0) + + def test_int_def_param(self): + """ Tests issue #4888""" + + self.run_fc_multiproc(add_y1) + + def test_none_def_param(self): + """ Tests None as a default parameter""" + + self.run_fc_multiproc(add_func) + + def test_function_def_param(self): + """ Tests a function as a default parameter""" + + self.run_fc_multiproc(add_func) + + +class TestVectorizeDifferentTargets(unittest.TestCase): + """Test that vectorize can be reapplied if the target is different + """ + + def test_cpu_vs_parallel(self): + @jit + def add(x, y): + return x + y + + custom_vectorize = vectorize([], identity=None, target='cpu') + + custom_vectorize(add) + + custom_vectorize_2 = vectorize([], identity=None, target='parallel') + + custom_vectorize_2(add) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_exceptions.py b/lib/python3.10/site-packages/numba/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..195c963e7af5e3c71f67e9c51bf6aaf5bb253956 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_exceptions.py @@ -0,0 +1,475 @@ +import numpy as np +import sys +import traceback + +from numba import jit, njit +from numba.core import types, errors, utils +from numba.tests.support import (TestCase, expected_failure_py311, + expected_failure_py312, + expected_failure_py313, + ) +import unittest + + +force_pyobj_flags = {'nopython': False, 'forceobj': True} +no_pyobj_flags = {'nopython': True, '_nrt': False} +no_pyobj_flags_w_nrt = {'nopython': True, '_nrt': True} +no_gil_flags = {'nopython': True, 'nogil': True, '_nrt': True} + + +class MyError(Exception): + pass + + +class OtherError(Exception): + pass + + +class UDEArgsToSuper(Exception): + def __init__(self, arg, value0): + super(UDEArgsToSuper, self).__init__(arg) + self.value0 = value0 + + def __eq__(self, other): + if not isinstance(other, self.__class__): + return False + same = True + same |= self.args == other.args + same |= self.value0 == other.value0 + return same + + def __hash__(self): + return hash((super(UDEArgsToSuper).__hash__(), self.value0)) + + +class UDENoArgSuper(Exception): + def __init__(self, arg, value0): + super(UDENoArgSuper, self).__init__() + self.deferarg = arg + self.value0 = value0 + + def __eq__(self, other): + if not isinstance(other, self.__class__): + return False + same = True + same |= self.args == other.args + same |= self.deferarg == other.deferarg + same |= self.value0 == other.value0 + return same + + def __hash__(self): + return hash((super(UDENoArgSuper).__hash__(), self.deferarg, + self.value0)) + + +def raise_class(exc): + def raiser(i): + if i == 1: + raise exc + elif i == 2: + raise ValueError + elif i == 3: + # The exception type is looked up on a module (issue #1624) + raise np.linalg.LinAlgError + return i + return raiser + + +def raise_instance(exc, arg): + def raiser(i): + if i == 1: + raise exc(arg, 1) + elif i == 2: + raise ValueError(arg, 2) + elif i == 3: + raise np.linalg.LinAlgError(arg, 3) + return i + return raiser + + +def raise_instance_runtime_args(exc): + def raiser(i, arg): + if i == 1: + raise exc(arg, 1) + elif i == 2: + raise ValueError(arg, 2) + elif i == 3: + raise np.linalg.LinAlgError(arg, 3) + return i + return raiser + + +def reraise(): + raise + + +def outer_function(inner): + def outer(i): + if i == 3: + raise OtherError("bar", 3) + return inner(i) + return outer + + +def assert_usecase(i): + assert i == 1, "bar" + + +def ude_bug_usecase(): + raise UDEArgsToSuper() # oops user forgot args to exception ctor + + +def raise_runtime_value(arg): + raise ValueError(arg) + + +class TestRaising(TestCase): + + def test_unituple_index_error(self): + def pyfunc(a, i): + return a.shape[i] + + cfunc = njit((types.Array(types.int32, 1, 'A'), types.int32),)(pyfunc) + + a = np.empty(2, dtype=np.int32) + + self.assertEqual(cfunc(a, 0), pyfunc(a, 0)) + + with self.assertRaises(IndexError) as cm: + cfunc(a, 2) + self.assertEqual(str(cm.exception), "tuple index out of range") + + def check_against_python(self, exec_mode, pyfunc, cfunc, + expected_error_class, *args): + + assert exec_mode in (force_pyobj_flags, no_pyobj_flags, + no_pyobj_flags_w_nrt, no_gil_flags) + + # invariant of mode, check the error class and args are the same + with self.assertRaises(expected_error_class) as pyerr: + pyfunc(*args) + with self.assertRaises(expected_error_class) as jiterr: + cfunc(*args) + self.assertEqual(pyerr.exception.args, jiterr.exception.args) + + # special equality check for UDEs + if isinstance(pyerr.exception, (UDEArgsToSuper, UDENoArgSuper)): + self.assertTrue(pyerr.exception == jiterr.exception) + + # in npm check bottom of traceback matches as frame injection with + # location info should ensure this + if exec_mode is no_pyobj_flags: + + # we only care about the bottom two frames, the error and the + # location it was raised. + try: + pyfunc(*args) + except Exception: + py_frames = traceback.format_exception(*sys.exc_info()) + expected_frames = py_frames[-2:] + + try: + cfunc(*args) + except Exception: + c_frames = traceback.format_exception(*sys.exc_info()) + got_frames = c_frames[-2:] + + # check exception and the injected frame are the same + for expf, gotf in zip(expected_frames, got_frames): + # Note use of assertIn not assertEqual, Py 3.11 has markers (^) + # that point to the variable causing the problem, Numba doesn't + # do this so only the start of the string will match. + self.assertIn(gotf, expf) + + def check_raise_class(self, flags): + pyfunc = raise_class(MyError) + cfunc = jit((types.int32,), **flags)(pyfunc) + self.assertEqual(cfunc(0), 0) + self.check_against_python(flags, pyfunc, cfunc, MyError, 1) + self.check_against_python(flags, pyfunc, cfunc, ValueError, 2) + self.check_against_python(flags, pyfunc, cfunc, + np.linalg.linalg.LinAlgError, 3) + + def test_raise_class_nopython(self): + self.check_raise_class(flags=no_pyobj_flags) + + def test_raise_class_objmode(self): + self.check_raise_class(flags=force_pyobj_flags) + + def check_raise_instance(self, flags): + for clazz in [MyError, UDEArgsToSuper, + UDENoArgSuper]: + pyfunc = raise_instance(clazz, "some message") + cfunc = jit((types.int32,), **flags)(pyfunc) + + self.assertEqual(cfunc(0), 0) + self.check_against_python(flags, pyfunc, cfunc, clazz, 1) + self.check_against_python(flags, pyfunc, cfunc, ValueError, 2) + self.check_against_python(flags, pyfunc, cfunc, + np.linalg.linalg.LinAlgError, 3) + + def test_raise_instance_objmode(self): + self.check_raise_instance(flags=force_pyobj_flags) + + def test_raise_instance_nopython(self): + self.check_raise_instance(flags=no_pyobj_flags) + + def check_raise_nested(self, flags, **jit_args): + """ + Check exception propagation from nested functions. + """ + for clazz in [MyError, UDEArgsToSuper, + UDENoArgSuper]: + inner_pyfunc = raise_instance(clazz, "some message") + pyfunc = outer_function(inner_pyfunc) + inner_cfunc = jit(**jit_args)(inner_pyfunc) + cfunc = jit(**jit_args)(outer_function(inner_cfunc)) + + self.check_against_python(flags, pyfunc, cfunc, clazz, 1) + self.check_against_python(flags, pyfunc, cfunc, ValueError, 2) + self.check_against_python(flags, pyfunc, cfunc, OtherError, 3) + + def test_raise_nested_objmode(self): + self.check_raise_nested(force_pyobj_flags, forceobj=True) + + def test_raise_nested_nopython(self): + self.check_raise_nested(no_pyobj_flags, nopython=True) + + def check_reraise(self, flags): + def raise_exc(exc): + raise exc + pyfunc = reraise + cfunc = jit((), **flags)(pyfunc) + for op, err in [(lambda : raise_exc(ZeroDivisionError), + ZeroDivisionError), + (lambda : raise_exc(UDEArgsToSuper("msg", 1)), + UDEArgsToSuper), + (lambda : raise_exc(UDENoArgSuper("msg", 1)), + UDENoArgSuper)]: + def gen_impl(fn): + def impl(): + try: + op() + except err: + fn() + return impl + pybased = gen_impl(pyfunc) + cbased = gen_impl(cfunc) + self.check_against_python(flags, pybased, cbased, err,) + + def test_reraise_objmode(self): + self.check_reraise(flags=force_pyobj_flags) + + def test_reraise_nopython(self): + self.check_reraise(flags=no_pyobj_flags) + + def check_raise_invalid_class(self, cls, flags): + pyfunc = raise_class(cls) + cfunc = jit((types.int32,), **flags)(pyfunc) + with self.assertRaises(TypeError) as cm: + cfunc(1) + self.assertEqual(str(cm.exception), + "exceptions must derive from BaseException") + + def test_raise_invalid_class_objmode(self): + self.check_raise_invalid_class(int, flags=force_pyobj_flags) + self.check_raise_invalid_class(1, flags=force_pyobj_flags) + + def test_raise_invalid_class_nopython(self): + msg = "Encountered unsupported constant type used for exception" + with self.assertRaises(errors.UnsupportedError) as raises: + self.check_raise_invalid_class(int, flags=no_pyobj_flags) + self.assertIn(msg, str(raises.exception)) + with self.assertRaises(errors.UnsupportedError) as raises: + self.check_raise_invalid_class(1, flags=no_pyobj_flags) + self.assertIn(msg, str(raises.exception)) + + def test_raise_bare_string_nopython(self): + @njit + def foo(): + raise "illegal" + msg = ("Directly raising a string constant as an exception is not " + "supported") + with self.assertRaises(errors.UnsupportedError) as raises: + foo() + self.assertIn(msg, str(raises.exception)) + + def check_assert_statement(self, flags): + pyfunc = assert_usecase + cfunc = jit((types.int32,), **flags)(pyfunc) + cfunc(1) + self.check_against_python(flags, pyfunc, cfunc, AssertionError, 2) + + def test_assert_statement_objmode(self): + self.check_assert_statement(flags=force_pyobj_flags) + + def test_assert_statement_nopython(self): + self.check_assert_statement(flags=no_pyobj_flags) + + def check_raise_from_exec_string(self, flags): + # issue #3428 + simple_raise = "def f(a):\n raise exc('msg', 10)" + assert_raise = "def f(a):\n assert a != 1" + py312_pep695_raise = "def f[T: int](a: T) -> T:\n assert a != 1" + py312_pep695_raise_2 = "def f[T: int\n](a: T) -> T:\n assert a != 1" + test_cases = [ + (assert_raise, AssertionError), + (simple_raise, UDEArgsToSuper), + (simple_raise, UDENoArgSuper), + ] + if utils.PYVERSION >= (3, 12): + # Added for https://github.com/numba/numba/issues/9443 + test_cases.append((py312_pep695_raise, AssertionError)) + test_cases.append((py312_pep695_raise_2, AssertionError)) + for f_text, exc in test_cases: + loc = {} + exec(f_text, {'exc': exc}, loc) + pyfunc = loc['f'] + cfunc = jit((types.int32,), **flags)(pyfunc) + self.check_against_python(flags, pyfunc, cfunc, exc, 1) + + def test_assert_from_exec_string_objmode(self): + self.check_raise_from_exec_string(flags=force_pyobj_flags) + + def test_assert_from_exec_string_nopython(self): + self.check_raise_from_exec_string(flags=no_pyobj_flags) + + def check_user_code_error_traceback(self, flags): + # this test checks that if a user tries to compile code that contains + # a bug in exception initialisation (e.g. missing arg) then this also + # has a frame injected with the location information. + pyfunc = ude_bug_usecase + cfunc = jit((), **flags)(pyfunc) + self.check_against_python(flags, pyfunc, cfunc, TypeError) + + def test_user_code_error_traceback_objmode(self): + self.check_user_code_error_traceback(flags=force_pyobj_flags) + + def test_user_code_error_traceback_nopython(self): + self.check_user_code_error_traceback(flags=no_pyobj_flags) + + def check_raise_runtime_value(self, flags): + pyfunc = raise_runtime_value + cfunc = jit((types.string,), **flags)(pyfunc) + self.check_against_python(flags, pyfunc, cfunc, ValueError, 'hello') + + def test_raise_runtime_value_objmode(self): + self.check_raise_runtime_value(flags=force_pyobj_flags) + + def test_raise_runtime_value_nopython(self): + self.check_raise_runtime_value(flags=no_pyobj_flags_w_nrt) + + def test_raise_runtime_value_nogil(self): + self.check_raise_runtime_value(flags=no_gil_flags) + + def check_raise_instance_with_runtime_args(self, flags): + for clazz in [MyError, UDEArgsToSuper, + UDENoArgSuper]: + pyfunc = raise_instance_runtime_args(clazz) + cfunc = jit((types.int32, types.string), **flags)(pyfunc) + + self.assertEqual(cfunc(0, 'test'), 0) + self.check_against_python(flags, pyfunc, cfunc, clazz, 1, 'hello') + self.check_against_python(flags, pyfunc, cfunc, ValueError, 2, + 'world') + self.check_against_python(flags, pyfunc, cfunc, + np.linalg.linalg.LinAlgError, 3, 'linalg') + + def test_raise_instance_with_runtime_args_objmode(self): + self.check_raise_instance_with_runtime_args(flags=force_pyobj_flags) + + def test_raise_instance_with_runtime_args_nopython(self): + self.check_raise_instance_with_runtime_args(flags=no_pyobj_flags_w_nrt) + + def test_raise_instance_with_runtime_args_nogil(self): + self.check_raise_instance_with_runtime_args(flags=no_gil_flags) + + def test_dynamic_raise_bad_args(self): + def raise_literal_dict(): + raise ValueError({'a': 1, 'b': np.ones(4)}) + + def raise_range(): + raise ValueError(range(3)) + + def raise_rng(rng): + raise ValueError(rng.bit_generator) + + funcs = [ + (raise_literal_dict, ()), + (raise_range, ()), + (raise_rng, (types.npy_rng,)), + ] + + for pyfunc, argtypes in funcs: + msg = '.*Cannot convert native .* to a Python object.*' + with self.assertRaisesRegex(errors.TypingError, msg): + njit(argtypes)(pyfunc) + + def test_dynamic_raise_dict(self): + @njit + def raise_literal_dict2(): + raise ValueError({'a': 1, 'b': 3}) + + msg = "{a: 1, b: 3}" + with self.assertRaisesRegex(ValueError, msg): + raise_literal_dict2() + + def test_disable_nrt(self): + @njit(_nrt=False) + def raise_with_no_nrt(i): + raise ValueError(i) + + msg = 'NRT required but not enabled' + with self.assertRaisesRegex(errors.NumbaRuntimeError, msg): + raise_with_no_nrt(123) + + def test_try_raise(self): + + @njit + def raise_(a): + raise ValueError(a) + + @njit + def try_raise(a): + try: + raise_(a) + except Exception: + pass + return a + 1 + + self.assertEqual(try_raise.py_func(3), try_raise(3)) + + @expected_failure_py311 + @expected_failure_py312 + @expected_failure_py313 + def test_dynamic_raise(self): + + @njit + def raise_(a): + raise ValueError(a) + + @njit + def try_raise_(a): + try: + raise_(a) + except Exception: + raise ValueError(a) + + args = [ + 1, + 1.1, + 'hello', + np.ones(3), + [1, 2], + (1, 2), + set([1, 2]), + ] + for fn in (raise_, try_raise_): + for arg in args: + with self.assertRaises(ValueError) as e: + fn(arg) + self.assertEqual((arg,), e.exception.args) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_function_type.py b/lib/python3.10/site-packages/numba/tests/test_function_type.py new file mode 100644 index 0000000000000000000000000000000000000000..dce78c2e701a643d273ab4370f16272f87b31cb2 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_function_type.py @@ -0,0 +1,1408 @@ +import re +import sys +import unittest +import types as pytypes +from numba import jit, njit, cfunc, types, int64, float64, float32, errors +from numba import literal_unroll, typeof +from numba.core.config import IS_WIN32 +import ctypes +import warnings + +from .support import TestCase, MemoryLeakMixin +from .support import redirect_c_stderr, captured_stderr + +import numpy as np + + +def dump(foo): # FOR DEBUGGING, TO BE REMOVED + from numba.core import function + foo_type = function.fromobject(foo) + foo_sig = foo_type.signature() + foo.compile(foo_sig) + print('{" LLVM IR OF "+foo.__name__+" ":*^70}') + print(foo.inspect_llvm(foo_sig.args)) + print('{"":*^70}') + + +# Decorators for transforming a Python function to different kinds of +# functions: + +def mk_cfunc_func(sig): + def cfunc_func(func): + assert isinstance(func, pytypes.FunctionType), repr(func) + f = cfunc(sig)(func) + f.pyfunc = func + return f + return cfunc_func + + +def njit_func(func): + assert isinstance(func, pytypes.FunctionType), repr(func) + f = jit(nopython=True)(func) + f.pyfunc = func + return f + + +def mk_njit_with_sig_func(sig): + def njit_with_sig_func(func): + assert isinstance(func, pytypes.FunctionType), repr(func) + f = jit(sig, nopython=True)(func) + f.pyfunc = func + return f + return njit_with_sig_func + + +def mk_ctypes_func(sig): + def ctypes_func(func, sig=int64(int64)): + assert isinstance(func, pytypes.FunctionType), repr(func) + cfunc = mk_cfunc_func(sig)(func) + addr = cfunc._wrapper_address + if sig == int64(int64): + f = ctypes.CFUNCTYPE(ctypes.c_int64)(addr) + f.pyfunc = func + return f + raise NotImplementedError( + f'ctypes decorator for {func} with signature {sig}') + return ctypes_func + + +class WAP(types.WrapperAddressProtocol): + """An example implementation of wrapper address protocol. + + """ + def __init__(self, func, sig): + self.pyfunc = func + self.cfunc = cfunc(sig)(func) + self.sig = sig + + def __wrapper_address__(self): + return self.cfunc._wrapper_address + + def signature(self): + return self.sig + + def __call__(self, *args, **kwargs): + return self.pyfunc(*args, **kwargs) + + +def mk_wap_func(sig): + def wap_func(func): + return WAP(func, sig) + return wap_func + + +class TestFunctionType(TestCase): + """Test first-class functions in the context of a Numba jit compiled + function. + + """ + + def test_in__(self): + """Function is passed in as an argument. + """ + + def a(i): + return i + 1 + + def foo(f): + return 0 + + sig = int64(int64) + + for decor in [mk_cfunc_func(sig), + njit_func, + mk_njit_with_sig_func(sig), + mk_ctypes_func(sig), + mk_wap_func(sig)]: + for jit_opts in [dict(nopython=True), dict(forceobj=True)]: + jit_ = jit(**jit_opts) + with self.subTest(decor=decor.__name__, jit=jit_opts): + a_ = decor(a) + self.assertEqual(jit_(foo)(a_), foo(a)) + + def test_in_call__(self): + """Function is passed in as an argument and called. + Also test different return values. + """ + + def a_i64(i): + return i + 1234567 + + def a_f64(i): + return i + 1.5 + + def a_str(i): + return "abc" + + def foo(f): + return f(123) + + for f, sig in [(a_i64, int64(int64)), (a_f64, float64(int64))]: + for decor in [mk_cfunc_func(sig), njit_func, + mk_njit_with_sig_func(sig), + mk_wap_func(sig)]: + for jit_opts in [dict(nopython=True), dict(forceobj=True)]: + jit_ = jit(**jit_opts) + with self.subTest( + sig=sig, decor=decor.__name__, jit=jit_opts): + f_ = decor(f) + self.assertEqual(jit_(foo)(f_), foo(f)) + + def test_in_call_out(self): + """Function is passed in as an argument, called, and returned. + """ + + def a(i): + return i + 1 + + def foo(f): + f(123) + return f + + sig = int64(int64) + + for decor in [mk_cfunc_func(sig), njit_func, + mk_njit_with_sig_func(sig), mk_wap_func(sig)]: + for jit_opts in [dict(nopython=True), dict(forceobj=True)]: + jit_ = jit(**jit_opts) + with self.subTest(decor=decor.__name__): + a_ = decor(a) + r1 = jit_(foo)(a_).pyfunc + r2 = foo(a) + self.assertEqual(r1, r2) + + def test_in_seq_call(self): + """Functions are passed in as arguments, used as tuple items, and + called. + + """ + def a(i): + return i + 1 + + def b(i): + return i + 2 + + def foo(f, g): + r = 0 + for f_ in (f, g): + r = r + f_(r) + return r + + sig = int64(int64) + + for decor in [mk_cfunc_func(sig), mk_wap_func(sig), + mk_njit_with_sig_func(sig)]: + for jit_opts in [dict(nopython=True), dict(forceobj=True)]: + jit_ = jit(**jit_opts) + with self.subTest(decor=decor.__name__): + a_ = decor(a) + b_ = decor(b) + self.assertEqual(jit_(foo)(a_, b_), foo(a, b)) + + def test_in_ns_seq_call(self): + """Functions are passed in as an argument and via namespace scoping + (mixed pathways), used as tuple items, and called. + + """ + + def a(i): + return i + 1 + + def b(i): + return i + 2 + + def mkfoo(b_): + def foo(f): + r = 0 + for f_ in (f, b_): + r = r + f_(r) + return r + return foo + + sig = int64(int64) + + for decor in [mk_cfunc_func(sig), + mk_njit_with_sig_func(sig), mk_wap_func(sig), + mk_ctypes_func(sig)][:-1]: + for jit_opts in [dict(nopython=True), dict(forceobj=True)]: + jit_ = jit(**jit_opts) + with self.subTest(decor=decor.__name__): + a_ = decor(a) + b_ = decor(b) + self.assertEqual(jit_(mkfoo(b_))(a_), mkfoo(b)(a)) + + def test_ns_call(self): + """Function is passed in via namespace scoping and called. + + """ + + def a(i): + return i + 1 + + def mkfoo(a_): + def foo(): + return a_(123) + return foo + + sig = int64(int64) + + for decor in [mk_cfunc_func(sig), njit_func, + mk_njit_with_sig_func(sig), mk_wap_func(sig)]: + for jit_opts in [dict(nopython=True), dict(forceobj=True)]: + jit_ = jit(**jit_opts) + with self.subTest(decor=decor.__name__): + a_ = decor(a) + self.assertEqual(jit_(mkfoo(a_))(), mkfoo(a)()) + + def test_ns_out(self): + """Function is passed in via namespace scoping and returned. + + """ + def a(i): + return i + 1 + + def mkfoo(a_): + def foo(): + return a_ + return foo + + sig = int64(int64) + + for decor in [mk_cfunc_func(sig), njit_func, + mk_njit_with_sig_func(sig), mk_wap_func(sig), + mk_ctypes_func(sig)][:-1]: + for jit_opts in [dict(nopython=True), dict(forceobj=True)]: + jit_ = jit(**jit_opts) + with self.subTest(decor=decor.__name__): + a_ = decor(a) + self.assertEqual(jit_(mkfoo(a_))().pyfunc, mkfoo(a)()) + + def test_ns_call_out(self): + """Function is passed in via namespace scoping, called, and then + returned. + + """ + def a(i): + return i + 1 + + def mkfoo(a_): + def foo(): + a_(123) + return a_ + return foo + + sig = int64(int64) + + for decor in [mk_cfunc_func(sig), njit_func, + mk_njit_with_sig_func(sig), mk_wap_func(sig), + mk_ctypes_func(sig)]: + for jit_opts in [dict(nopython=True), dict(forceobj=True)]: + jit_ = jit(**jit_opts) + with self.subTest(decor=decor.__name__): + a_ = decor(a) + self.assertEqual(jit_(mkfoo(a_))().pyfunc, mkfoo(a)()) + + def test_in_overload(self): + """Function is passed in as an argument and called with different + argument types. + + """ + def a(i): + return i + 1 + + def foo(f): + r1 = f(123) + r2 = f(123.45) + return (r1, r2) + + for decor in [njit_func]: + for jit_opts in [dict(nopython=True), dict(forceobj=True)]: + jit_ = jit(**jit_opts) + with self.subTest(decor=decor.__name__): + a_ = decor(a) + self.assertEqual(jit_(foo)(a_), foo(a)) + + def test_ns_overload(self): + """Function is passed in via namespace scoping and called with + different argument types. + + """ + def a(i): + return i + 1 + + def mkfoo(a_): + def foo(): + r1 = a_(123) + r2 = a_(123.45) + return (r1, r2) + return foo + + for decor in [njit_func]: + for jit_opts in [dict(nopython=True), dict(forceobj=True)]: + jit_ = jit(**jit_opts) + with self.subTest(decor=decor.__name__): + a_ = decor(a) + self.assertEqual(jit_(mkfoo(a_))(), mkfoo(a)()) + + def test_in_choose(self): + """Functions are passed in as arguments and called conditionally. + + """ + def a(i): + return i + 1 + + def b(i): + return i + 2 + + def foo(a, b, choose_left): + if choose_left: + r = a(1) + else: + r = b(2) + return r + + sig = int64(int64) + + for decor in [mk_cfunc_func(sig), njit_func, + mk_njit_with_sig_func(sig), mk_wap_func(sig)]: + for jit_opts in [dict(nopython=True), dict(forceobj=True)]: + jit_ = jit(**jit_opts) + with self.subTest(decor=decor.__name__): + a_ = decor(a) + b_ = decor(b) + self.assertEqual(jit_(foo)(a_, b_, True), foo(a, b, True)) + self.assertEqual(jit_(foo)(a_, b_, False), + foo(a, b, False)) + self.assertNotEqual(jit_(foo)(a_, b_, True), + foo(a, b, False)) + + def test_ns_choose(self): + """Functions are passed in via namespace scoping and called + conditionally. + + """ + def a(i): + return i + 1 + + def b(i): + return i + 2 + + def mkfoo(a_, b_): + def foo(choose_left): + if choose_left: + r = a_(1) + else: + r = b_(2) + return r + return foo + + sig = int64(int64) + + for decor in [mk_cfunc_func(sig), njit_func, + mk_njit_with_sig_func(sig), mk_wap_func(sig)]: + for jit_opts in [dict(nopython=True), dict(forceobj=True)]: + jit_ = jit(**jit_opts) + with self.subTest(decor=decor.__name__): + a_ = decor(a) + b_ = decor(b) + self.assertEqual(jit_(mkfoo(a_, b_))(True), + mkfoo(a, b)(True)) + self.assertEqual(jit_(mkfoo(a_, b_))(False), + mkfoo(a, b)(False)) + self.assertNotEqual(jit_(mkfoo(a_, b_))(True), + mkfoo(a, b)(False)) + + def test_in_choose_out(self): + """Functions are passed in as arguments and returned conditionally. + + """ + def a(i): + return i + 1 + + def b(i): + return i + 2 + + def foo(a, b, choose_left): + if choose_left: + return a + else: + return b + + sig = int64(int64) + + for decor in [mk_cfunc_func(sig), njit_func, + mk_njit_with_sig_func(sig), mk_wap_func(sig)]: + for jit_opts in [dict(nopython=True), dict(forceobj=True)]: + jit_ = jit(**jit_opts) + with self.subTest(decor=decor.__name__): + a_ = decor(a) + b_ = decor(b) + self.assertEqual(jit_(foo)(a_, b_, True).pyfunc, + foo(a, b, True)) + self.assertEqual(jit_(foo)(a_, b_, False).pyfunc, + foo(a, b, False)) + self.assertNotEqual(jit_(foo)(a_, b_, True).pyfunc, + foo(a, b, False)) + + def test_in_choose_func_value(self): + """Functions are passed in as arguments, selected conditionally and + called. + + """ + def a(i): + return i + 1 + + def b(i): + return i + 2 + + def foo(a, b, choose_left): + if choose_left: + f = a + else: + f = b + return f(1) + + sig = int64(int64) + + for decor in [mk_cfunc_func(sig), mk_wap_func(sig), njit_func, + mk_njit_with_sig_func(sig)]: + for jit_opts in [dict(nopython=True), dict(forceobj=True)]: + jit_ = jit(**jit_opts) + with self.subTest(decor=decor.__name__): + a_ = decor(a) + b_ = decor(b) + self.assertEqual(jit_(foo)(a_, b_, True), foo(a, b, True)) + self.assertEqual(jit_(foo)(a_, b_, False), + foo(a, b, False)) + self.assertNotEqual(jit_(foo)(a_, b_, True), + foo(a, b, False)) + + def test_in_pick_func_call(self): + """Functions are passed in as items of tuple argument, retrieved via + indexing, and called. + + """ + def a(i): + return i + 1 + + def b(i): + return i + 2 + + def foo(funcs, i): + f = funcs[i] + r = f(123) + return r + + sig = int64(int64) + + for decor in [mk_cfunc_func(sig), mk_wap_func(sig), + mk_njit_with_sig_func(sig)]: + for jit_opts in [dict(nopython=True), dict(forceobj=True)]: + jit_ = jit(**jit_opts) + with self.subTest(decor=decor.__name__): + a_ = decor(a) + b_ = decor(b) + self.assertEqual(jit_(foo)((a_, b_), 0), foo((a, b), 0)) + self.assertEqual(jit_(foo)((a_, b_), 1), foo((a, b), 1)) + self.assertNotEqual(jit_(foo)((a_, b_), 0), foo((a, b), 1)) + + def test_in_iter_func_call(self): + """Functions are passed in as items of tuple argument, retrieved via + indexing, and called within a variable for-loop. + + """ + def a(i): + return i + 1 + + def b(i): + return i + 2 + + def foo(funcs, n): + r = 0 + for i in range(n): + f = funcs[i] + r = r + f(r) + return r + + sig = int64(int64) + + for decor in [mk_cfunc_func(sig), mk_wap_func(sig), + mk_njit_with_sig_func(sig)]: + for jit_opts in [dict(nopython=True), dict(forceobj=True)]: + jit_ = jit(**jit_opts) + with self.subTest(decor=decor.__name__): + a_ = decor(a) + b_ = decor(b) + self.assertEqual(jit_(foo)((a_, b_), 2), foo((a, b), 2)) + + def test_experimental_feature_warning(self): + @jit(nopython=True) + def more(x): + return x + 1 + + @jit(nopython=True) + def less(x): + return x - 1 + + @jit(nopython=True) + def foo(sel, x): + fn = more if sel else less + return fn(x) + + with warnings.catch_warnings(record=True) as ws: + warnings.simplefilter("always") + res = foo(True, 10) + + self.assertEqual(res, 11) + self.assertEqual(foo(False, 10), 9) + + self.assertGreaterEqual(len(ws), 1) + pat = "First-class function type feature is experimental" + for w in ws: + if pat in str(w.message): + break + else: + self.fail("missing warning") + + +class TestFunctionTypeExtensions(TestCase): + """Test calling external library functions within Numba jit compiled + functions. + + """ + + def test_wrapper_address_protocol_libm(self): + """Call cos and sinf from standard math library. + + """ + import ctypes.util + + class LibM(types.WrapperAddressProtocol): + + def __init__(self, fname): + if IS_WIN32: + lib = ctypes.cdll.msvcrt + else: + libpath = ctypes.util.find_library('m') + lib = ctypes.cdll.LoadLibrary(libpath) + self.lib = lib + self._name = fname + if fname == 'cos': + # test for double-precision math function + addr = ctypes.cast(self.lib.cos, ctypes.c_voidp).value + signature = float64(float64) + elif fname == 'sinf': + # test for single-precision math function + # Other 32/64 bit platforms define sinf as the + # single-precision sin function + addr = ctypes.cast(self.lib.sinf, ctypes.c_voidp).value + signature = float32(float32) + else: + raise NotImplementedError( + f'wrapper address of `{fname}`' + f' with signature `{signature}`') + self._signature = signature + self._address = addr + + def __repr__(self): + return f'{type(self).__name__}({self._name!r})' + + def __wrapper_address__(self): + return self._address + + def signature(self): + return self._signature + + mycos = LibM('cos') + mysin = LibM('sinf') + + def myeval(f, x): + return f(x) + + # Not testing forceobj=True as it requires implementing + # LibM.__call__ using ctypes which would be out-of-scope here. + for jit_opts in [dict(nopython=True)]: + jit_ = jit(**jit_opts) + with self.subTest(jit=jit_opts): + if mycos.signature() is not None: + self.assertEqual(jit_(myeval)(mycos, 0.0), 1.0) + if mysin.signature() is not None: + self.assertEqual(jit_(myeval)(mysin, float32(0.0)), 0.0) + + def test_compilation_results(self): + """Turn the existing compilation results of a dispatcher instance to + first-class functions with precise types. + """ + + @jit(nopython=True) + def add_template(x, y): + return x + y + + # Trigger compilations + self.assertEqual(add_template(1, 2), 3) + self.assertEqual(add_template(1.2, 3.4), 4.6) + + cres1, cres2 = add_template.overloads.values() + + # Turn compilation results into first-class functions + iadd = types.CompileResultWAP(cres1) + fadd = types.CompileResultWAP(cres2) + + @jit(nopython=True) + def foo(add, x, y): + return add(x, y) + + @jit(forceobj=True) + def foo_obj(add, x, y): + return add(x, y) + + self.assertEqual(foo(iadd, 3, 4), 7) + self.assertEqual(foo(fadd, 3.4, 4.5), 7.9) + + self.assertEqual(foo_obj(iadd, 3, 4), 7) + self.assertEqual(foo_obj(fadd, 3.4, 4.5), 7.9) + + +class TestMiscIssues(TestCase): + """Test issues of using first-class functions in the context of Numba + jit compiled functions. + + """ + + def test_issue_3405_using_cfunc(self): + + @cfunc('int64()') + def a(): + return 2 + + @cfunc('int64()') + def b(): + return 3 + + def g(arg): + if arg: + f = a + else: + f = b + return f() + + self.assertEqual(jit(nopython=True)(g)(True), 2) + self.assertEqual(jit(nopython=True)(g)(False), 3) + + def test_issue_3405_using_njit(self): + + @jit(nopython=True) + def a(): + return 2 + + @jit(nopython=True) + def b(): + return 3 + + def g(arg): + if not arg: + f = b + else: + f = a + return f() + + self.assertEqual(jit(nopython=True)(g)(True), 2) + self.assertEqual(jit(nopython=True)(g)(False), 3) + + def test_pr4967_example(self): + + @cfunc('int64(int64)') + def a(i): + return i + 1 + + @cfunc('int64(int64)') + def b(i): + return i + 2 + + @jit(nopython=True) + def foo(f, g): + i = f(2) + seq = (f, g) + for fun in seq: + i += fun(i) + return i + + a_ = a._pyfunc + b_ = b._pyfunc + self.assertEqual(foo(a, b), + a_(2) + a_(a_(2)) + b_(a_(2) + a_(a_(2)))) + + def test_pr4967_array(self): + import numpy as np + + @cfunc("intp(intp[:], float64[:])") + def foo1(x, y): + return x[0] + y[0] + + @cfunc("intp(intp[:], float64[:])") + def foo2(x, y): + return x[0] - y[0] + + def bar(fx, fy, i): + a = np.array([10], dtype=np.intp) + b = np.array([12], dtype=np.float64) + if i == 0: + f = fx + elif i == 1: + f = fy + else: + return + return f(a, b) + + r = jit(nopython=True, no_cfunc_wrapper=True)(bar)(foo1, foo2, 0) + self.assertEqual(r, bar(foo1, foo2, 0)) + self.assertNotEqual(r, bar(foo1, foo2, 1)) + + def test_reference_example(self): + import numba + + @numba.njit + def composition(funcs, x): + r = x + for f in funcs[::-1]: + r = f(r) + return r + + @numba.cfunc("double(double)") + def a(x): + return x + 1.0 + + @numba.njit() + def b(x): + return x * x + + r = composition((a, b, b, a), 0.5) + self.assertEqual(r, (0.5 + 1.0) ** 4 + 1.0) + + r = composition((b, a, b, b, a), 0.5) + self.assertEqual(r, ((0.5 + 1.0) ** 4 + 1.0) ** 2) + + def test_apply_function_in_function(self): + + def foo(f, f_inner): + return f(f_inner) + + @cfunc('int64(float64)') + def f_inner(i): + return int64(i * 3) + + @cfunc(int64(types.FunctionType(f_inner._sig))) + def f(f_inner): + return f_inner(123.4) + + self.assertEqual(jit(nopython=True)(foo)(f, f_inner), + foo(f._pyfunc, f_inner._pyfunc)) + + def test_function_with_none_argument(self): + + @cfunc(int64(types.none)) + def a(i): + return 1 + + @jit(nopython=True) + def foo(f): + return f(None) + + self.assertEqual(foo(a), 1) + + def test_constant_functions(self): + + @jit(nopython=True) + def a(): + return 123 + + @jit(nopython=True) + def b(): + return 456 + + @jit(nopython=True) + def foo(): + return a() + b() + + r = foo() + if r != 123 + 456: + print(foo.overloads[()].library.get_llvm_str()) + self.assertEqual(r, 123 + 456) + + def test_generators(self): + + @jit(forceobj=True) + def gen(xs): + for x in xs: + x += 1 + yield x + + @jit(forceobj=True) + def con(gen_fn, xs): + return [it for it in gen_fn(xs)] + + self.assertEqual(con(gen, (1, 2, 3)), [2, 3, 4]) + + @jit(nopython=True) + def gen_(xs): + for x in xs: + x += 1 + yield x + self.assertEqual(con(gen_, (1, 2, 3)), [2, 3, 4]) + + def test_jit_support(self): + + @jit(nopython=True) + def foo(f, x): + return f(x) + + @jit() + def a(x): + return x + 1 + + @jit() + def a2(x): + return x - 1 + + @jit() + def b(x): + return x + 1.5 + + self.assertEqual(foo(a, 1), 2) + a2(5) # pre-compile + self.assertEqual(foo(a2, 2), 1) + self.assertEqual(foo(a2, 3), 2) + self.assertEqual(foo(a, 2), 3) + self.assertEqual(foo(a, 1.5), 2.5) + self.assertEqual(foo(a2, 1), 0) + self.assertEqual(foo(a, 2.5), 3.5) + self.assertEqual(foo(b, 1.5), 3.0) + self.assertEqual(foo(b, 1), 2.5) + + def test_signature_mismatch(self): + @jit(nopython=True) + def f1(x): + return x + + @jit(nopython=True) + def f2(x): + return x + + @jit(nopython=True) + def foo(disp1, disp2, sel): + if sel == 1: + fn = disp1 + else: + fn = disp2 + return fn([1]), fn(2) + + with self.assertRaises(errors.UnsupportedError) as cm: + foo(f1, f2, sel=1) + self.assertRegex( + str(cm.exception), 'mismatch of function types:') + + # this works because `sel == 1` condition is optimized away: + self.assertEqual(foo(f1, f1, sel=1), ([1], 2)) + + def test_unique_dispatcher(self): + # In general, the type of a dispatcher instance is imprecise + # and when used as an input to type-inference, the typing will + # likely fail. However, if a dispatcher instance contains + # exactly one overload and compilation is disabled for the dispatcher, + # then the type of dispatcher instance is interpreted as precise + # and is transformed to a FunctionType instance with the defined + # signature of the single overload. + + def foo_template(funcs, x): + r = x + for f in funcs: + r = f(r) + return r + + a = jit(nopython=True)(lambda x: x + 1) + b = jit(nopython=True)(lambda x: x + 2) + foo = jit(nopython=True)(foo_template) + + # compiling and disabling compilation for `a` is sufficient, + # `b` will inherit its type from the container Tuple type + a(0) + a.disable_compile() + + r = foo((a, b), 0) + self.assertEqual(r, 3) + # the Tuple type of foo's first argument is a precise FunctionType: + self.assertEqual(foo.signatures[0][0].dtype.is_precise(), True) + + def test_zero_address(self): + + sig = int64() + + @cfunc(sig) + def test(): + return 123 + + class Good(types.WrapperAddressProtocol): + """A first-class function type with valid address. + """ + + def __wrapper_address__(self): + return test.address + + def signature(self): + return sig + + class Bad(types.WrapperAddressProtocol): + """A first-class function type with invalid 0 address. + """ + + def __wrapper_address__(self): + return 0 + + def signature(self): + return sig + + class BadToGood(types.WrapperAddressProtocol): + """A first-class function type with invalid address that is + recovered to a valid address. + """ + + counter = -1 + + def __wrapper_address__(self): + self.counter += 1 + return test.address * min(1, self.counter) + + def signature(self): + return sig + + good = Good() + bad = Bad() + bad2good = BadToGood() + + @jit(int64(sig.as_type())) + def foo(func): + return func() + + @jit(int64()) + def foo_good(): + return good() + + @jit(int64()) + def foo_bad(): + return bad() + + @jit(int64()) + def foo_bad2good(): + return bad2good() + + self.assertEqual(foo(good), 123) + + self.assertEqual(foo_good(), 123) + + with self.assertRaises(ValueError) as cm: + foo(bad) + self.assertRegex( + str(cm.exception), + 'wrapper address of <.*> instance must be a positive') + + with self.assertRaises(RuntimeError) as cm: + foo_bad() + self.assertRegex( + str(cm.exception), r'.* function address is null') + + self.assertEqual(foo_bad2good(), 123) + + def test_issue_5470(self): + + @njit() + def foo1(): + return 10 + + @njit() + def foo2(): + return 20 + + formulae_foo = (foo1, foo1) + + @njit() + def bar_scalar(f1, f2): + return f1() + f2() + + @njit() + def bar(): + return bar_scalar(*formulae_foo) + + self.assertEqual(bar(), 20) + + formulae_foo = (foo1, foo2) + + @njit() + def bar(): + return bar_scalar(*formulae_foo) + + self.assertEqual(bar(), 30) + + def test_issue_5540(self): + + @njit(types.int64(types.int64)) + def foo(x): + return x + 1 + + @njit + def bar_bad(foos): + f = foos[0] + return f(x=1) + + @njit + def bar_good(foos): + f = foos[0] + return f(1) + + self.assertEqual(bar_good((foo, )), 2) + + # new/old style error handling + with self.assertRaises((errors.UnsupportedError, + errors.TypingError)) as cm: + bar_bad((foo, )) + + self.assertRegex( + str(cm.exception), + r'.*first-class function call cannot use keyword arguments') + + def test_issue_5615(self): + + @njit + def foo1(x): + return x + 1 + + @njit + def foo2(x): + return x + 2 + + @njit + def bar(fcs): + x = 0 + a = 10 + i, j = fcs[0] + x += i(j(a)) + for t in literal_unroll(fcs): + i, j = t + x += i(j(a)) + return x + + tup = ((foo1, foo2), (foo2, foo1)) + + self.assertEqual(bar(tup), 39) + + def test_issue_5685(self): + + @njit + def foo1(): + return 1 + + @njit + def foo2(x): + return x + 1 + + @njit + def foo3(x): + return x + 2 + + @njit + def bar(fcs): + r = 0 + for pair in literal_unroll(fcs): + f1, f2 = pair + r += f1() + f2(2) + return r + + self.assertEqual(bar(((foo1, foo2),)), 4) + self.assertEqual(bar(((foo1, foo2), (foo1, foo3))), 9) # reproducer + + +class TestBasicSubtyping(TestCase): + def test_basic(self): + """ + Test that a dispatcher object *with* a pre-compiled overload + can be used as input to another function with locked-down signature + """ + a = 1 + + @njit + def foo(x): + return x + 1 + + foo(a) + int_int_fc = types.FunctionType(types.int64(types.int64,)) + + @njit(types.int64(int_int_fc)) + def bar(fc): + return fc(a) + + self.assertEqual(bar(foo), foo(a)) + + def test_basic2(self): + """ + Test that a dispatcher object *without* a pre-compiled overload + can be used as input to another function with locked-down signature + """ + a = 1 + + @njit + def foo(x): + return x + 1 + + int_int_fc = types.FunctionType(types.int64(types.int64,)) + + @njit(types.int64(int_int_fc)) + def bar(fc): + return fc(a) + + self.assertEqual(bar(foo), foo(a)) + + def test_basic3(self): + """ + Test that a dispatcher object *without* a pre-compiled overload + can be used as input to another function with locked-down signature and + that it behaves as a truly generic function (foo1 does not get locked) + """ + a = 1 + + @njit + def foo1(x): + return x + 1 + + @njit + def foo2(x): + return x + 2 + + int_int_fc = types.FunctionType(types.int64(types.int64,)) + + @njit(types.int64(int_int_fc)) + def bar(fc): + return fc(a) + + self.assertEqual(bar(foo1) + 1, bar(foo2)) + + def test_basic4(self): + """ + Test that a dispatcher object can be used as input to another + function with signature as part of a tuple + """ + a = 1 + + @njit + def foo1(x): + return x + 1 + + @njit + def foo2(x): + return x + 2 + + tup = (foo1, foo2) + int_int_fc = types.FunctionType(types.int64(types.int64,)) + + @njit(types.int64(types.UniTuple(int_int_fc, 2))) + def bar(fcs): + x = 0 + for i in range(2): + x += fcs[i](a) + return x + self.assertEqual(bar(tup), foo1(a) + foo2(a)) + + def test_basic5(self): + a = 1 + + @njit + def foo1(x): + return x + 1 + + @njit + def foo2(x): + return x + 2 + + @njit + def bar1(x): + return x / 10 + + @njit + def bar2(x): + return x / 1000 + + tup = (foo1, foo2) + tup_bar = (bar1, bar2) + int_int_fc = types.FunctionType(types.int64(types.int64,)) + + flt_flt_fc = types.FunctionType(types.float64(types.float64,)) + + @njit((types.UniTuple(int_int_fc, 2), types.UniTuple(flt_flt_fc, 2))) + def bar(fcs, ffs): + x = 0 + for i in range(2): + x += fcs[i](a) + for fn in ffs: + x += fn(a) + return x + + got = bar(tup, tup_bar) + expected = foo1(a) + foo2(a) + bar1(a) + bar2(a) + self.assertEqual(got, expected) + + +class TestMultiFunctionType(MemoryLeakMixin, TestCase): + + def test_base(self): + # The test is adapted from https://github.com/numba/numba/issues/9071 + nb_array = typeof(np.ones(2)) + callee_int_type = types.FunctionType(int64(int64)) + sig_int = int64(callee_int_type, int64) + callee_array_type = types.FunctionType(float64(nb_array)) + sig_array = float64(callee_array_type, nb_array) + + @njit([sig_int, sig_array]) + def caller(callee, a): + return callee(a) + + @njit + def callee_int(b): + return b + + @njit + def callee_array(c): + return c.sum() + + b = 1 + c = np.ones(2) + + self.assertEqual(caller(callee_int, b), b) + self.assertEqual(caller(callee_array, c), c.sum()) + + +class TestInliningFunctionType(MemoryLeakMixin, TestCase): + def count_num_bb_in_cfg(self, dispatcher): + dot = dispatcher.inspect_cfg(dispatcher.signatures[0]).dot + num_of_nodes = re.findall(r"Node0x[0-9a-z]+", dot) + return len(num_of_nodes) + + def test_inlining_global_dispatcher(self): + @njit + def add(x, y): + return x + y + + fnty = types.FunctionType(int64(int64, int64)) + + @njit(int64(fnty, int64, int64)) + def callme(fn, x, y): + c = 0 + for i in range(100): + c += fn(x, y) + return c + + @njit + def bar(x, y): + return callme(add, x, y) + + res = bar(123, 321) + self.assertEqual(100 * (123 + 321), res) + # There's only one BB because LLVM will be able to fully optimize + # the reduce-add loop if add() is properly inlined. + self.assertEqual(self.count_num_bb_in_cfg(bar), 1) + + def test_not_inlining_dispatcher_args(self): + @njit + def add(x, y): + return x + y + + fnty = types.FunctionType(int64(int64, int64)) + + @njit(int64(fnty, int64, int64)) + def callme(fn, x, y): + c = 0 + for i in range(100): + c += fn(x, y) + return c + + res = callme(add, 123, 321) + + self.assertEqual(100 * (123 + 321), res) + # Since add() is not inline-able. The number of BB will be greater + # than 1. See test_inlining_global_dispatcher(). + self.assertGreater(self.count_num_bb_in_cfg(callme), 1) + + +class TestExceptionInFunctionType(MemoryLeakMixin, TestCase): + def test_exception_raising(self): + class MyError(Exception): + pass + + @njit + def add(x, y): + res = x + y + if res > 100: + raise MyError(res) + return res + + fnty = types.FunctionType(int64(int64, int64)) + + @njit(int64(fnty)) + def callme(fn): + c = 0 + for i in range(100): + c = fn(c, i) + return c + + @njit + def bar(): + return callme(add) + + # Pass Dispatcher as a global reference + with self.assertRaises(MyError) as exc: + bar() + self.assertEqual(exc.exception.args, (105,)) + + # Pass Dispatcher by argument + with self.assertRaises(MyError) as exc: + callme(add) + self.assertEqual(exc.exception.args, (105,)) + + def test_exception_ignored_in_cfunc(self): + class MyError(Exception): + pass + + @njit + def add(x, y): + res = x + y + if res > 100: + raise MyError(res) + return res + + fnty = types.FunctionType(int64(int64, int64)) + + @njit(int64(fnty, int64, int64)) + def callme(fn, x, y): + return fn(x, y) + + # Cfunc as argument will ignore raised exception + @cfunc(int64(int64, int64)) + def c_add(x, y): + return add(x, y) + + self.assertEqual(callme(c_add, 12, 32), 44) + + # If unittest is buffering (-b), the message goes to Python level stderr + # otherwise, it goes to C stderr. + with redirect_c_stderr() as c_stderr, captured_stderr() as stderr: + # raise ignored and result is garbage + callme(c_add, 100, 1) + sys.stderr.flush() + + err = c_stderr.read() + if not err: + err = stderr.getvalue() + + self.assertIn("Exception ignored in:", err) + self.assertIn(str(MyError(101)), err) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_gdb_bindings.py b/lib/python3.10/site-packages/numba/tests/test_gdb_bindings.py new file mode 100644 index 0000000000000000000000000000000000000000..16d6afc4a301d08c20b129069892f8ff71cafba3 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_gdb_bindings.py @@ -0,0 +1,277 @@ +""" +Tests gdb bindings +""" +import os +import platform +import re +import subprocess +import sys +import threading +from itertools import permutations + +from numba import njit, gdb, gdb_init, gdb_breakpoint, prange +from numba.core import errors +from numba import jit + +from numba.tests.support import (TestCase, captured_stdout, tag, + skip_parfors_unsupported) +from numba.tests.gdb_support import needs_gdb +import unittest + + +_platform = sys.platform + +_unix_like = (_platform.startswith('linux') + or _platform.startswith('darwin') + or ('bsd' in _platform)) + +unix_only = unittest.skipUnless(_unix_like, "unix-like OS is required") +not_unix = unittest.skipIf(_unix_like, "non unix-like OS is required") + +_arch_name = platform.machine() +_is_arm = _arch_name in {'aarch64', 'armv7l'} +not_arm = unittest.skipIf(_is_arm, "testing disabled on ARM") + +_gdb_cond = os.environ.get('GDB_TEST', None) == '1' +needs_gdb_harness = unittest.skipUnless(_gdb_cond, "needs gdb harness") + +long_running = tag('long_running') + +_dbg_njit = njit(debug=True) +_dbg_jit = jit(forceobj=True, debug=True) + + +def impl_gdb_call(a): + gdb('-ex', 'set confirm off', '-ex', 'c', '-ex', 'q') + b = a + 1 + c = a * 2.34 + d = (a, b, c) + print(a, b, c, d) + + +def impl_gdb_call_w_bp(a): + gdb_init('-ex', 'set confirm off', '-ex', 'c', '-ex', 'q') + b = a + 1 + c = a * 2.34 + d = (a, b, c) + gdb_breakpoint() + print(a, b, c, d) + + +def impl_gdb_split_init_and_break_w_parallel(a): + gdb_init('-ex', 'set confirm off', '-ex', 'c', '-ex', 'q') + a += 3 + for i in prange(4): + b = a + 1 + c = a * 2.34 + d = (a, b, c) + gdb_breakpoint() + print(a, b, c, d) + + +@not_arm +@unix_only +class TestGdbBindImpls(TestCase): + """ + Contains unit test implementations for gdb binding testing. Test must be + decorated with `@needs_gdb_harness` to prevent their running under normal + test conditions, the test methods must also end with `_impl` to be + considered for execution. The tests themselves are invoked by the + `TestGdbBinding` test class through the parsing of this class for test + methods and then running the discovered tests in a separate process. Test + names not including the word `quick` will be tagged as @tag('long_running') + """ + + @needs_gdb_harness + def test_gdb_cmd_lang_cpython_quick_impl(self): + with captured_stdout(): + impl_gdb_call(10) + + @needs_gdb_harness + def test_gdb_cmd_lang_nopython_quick_impl(self): + with captured_stdout(): + _dbg_njit(impl_gdb_call)(10) + + @needs_gdb_harness + def test_gdb_cmd_lang_objmode_quick_impl(self): + with captured_stdout(): + _dbg_jit(impl_gdb_call)(10) + + @needs_gdb_harness + def test_gdb_split_init_and_break_cpython_impl(self): + with captured_stdout(): + impl_gdb_call_w_bp(10) + + @needs_gdb_harness + def test_gdb_split_init_and_break_nopython_impl(self): + with captured_stdout(): + _dbg_njit(impl_gdb_call_w_bp)(10) + + @needs_gdb_harness + def test_gdb_split_init_and_break_objmode_impl(self): + with captured_stdout(): + _dbg_jit(impl_gdb_call_w_bp)(10) + + @skip_parfors_unsupported + @needs_gdb_harness + def test_gdb_split_init_and_break_w_parallel_cpython_impl(self): + with captured_stdout(): + impl_gdb_split_init_and_break_w_parallel(10) + + @skip_parfors_unsupported + @needs_gdb_harness + def test_gdb_split_init_and_break_w_parallel_nopython_impl(self): + with captured_stdout(): + _dbg_njit(impl_gdb_split_init_and_break_w_parallel)(10) + + @skip_parfors_unsupported + @needs_gdb_harness + def test_gdb_split_init_and_break_w_parallel_objmode_impl(self): + with captured_stdout(): + _dbg_jit(impl_gdb_split_init_and_break_w_parallel)(10) + + +@not_arm +@unix_only +@needs_gdb +class TestGdbBinding(TestCase): + """ + This test class is used to generate tests which will run the test cases + defined in TestGdbBindImpls in isolated subprocesses, this is for safety + in case something goes awry. + """ + + # test mutates env + _numba_parallel_test_ = False + + _DEBUG = True + + def run_cmd(self, cmdline, env, kill_is_ok=False): + popen = subprocess.Popen(cmdline, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + env=env, + shell=True) + # finish in 20s or kill it, there's no work being done + + def kill(): + popen.stdout.flush() + popen.stderr.flush() + popen.kill() + timeout = threading.Timer(20., kill) + try: + timeout.start() + out, err = popen.communicate() + retcode = popen.returncode + if retcode != 0: + raise AssertionError( + "process failed with code %s: " + "stderr follows\n%s\n" + "stdout :%s" % (retcode, err.decode(), out.decode())) + return out.decode(), err.decode() + finally: + timeout.cancel() + return None, None + + def run_test_in_separate_process(self, test, **kwargs): + env_copy = os.environ.copy() + env_copy['NUMBA_OPT'] = '1' + # Set GDB_TEST to permit the execution of tests decorated with + # @needs_gdb_harness + env_copy['GDB_TEST'] = '1' + cmdline = [sys.executable, "-m", "numba.runtests", test] + return self.run_cmd(' '.join(cmdline), env_copy, **kwargs) + + @classmethod + def _inject(cls, name): + themod = TestGdbBindImpls.__module__ + thecls = TestGdbBindImpls.__name__ + # strip impl + assert name.endswith('_impl') + methname = name.replace('_impl', '') + injected_method = '%s.%s.%s' % (themod, thecls, name) + + def test_template(self): + o, e = self.run_test_in_separate_process(injected_method) + dbgmsg = f'\nSTDOUT={o}\nSTDERR={e}\n' + # If the test was skipped in the subprocess, then mark this as a + # skipped test. + m = re.search(r"\.\.\. skipped '(.*?)'", e) + if m is not None: + self.skipTest(m.group(1)) + self.assertIn('GNU gdb', o, msg=dbgmsg) + self.assertIn('OK', e, msg=dbgmsg) + self.assertNotIn('FAIL', e, msg=dbgmsg) + self.assertNotIn('ERROR', e, msg=dbgmsg) + if 'quick' in name: + setattr(cls, methname, test_template) + else: + setattr(cls, methname, long_running(test_template)) + + @classmethod + def generate(cls): + for name in dir(TestGdbBindImpls): + if name.startswith('test_gdb'): + cls._inject(name) + + +TestGdbBinding.generate() + + +@not_arm +@unix_only +@needs_gdb +class TestGdbMisc(TestCase): + + @long_running + def test_call_gdb_twice(self): + def gen(f1, f2): + @njit + def impl(): + a = 1 + f1() + b = 2 + f2() + return a + b + return impl + + msg_head = "Calling either numba.gdb() or numba.gdb_init() more than" + + def check(func): + with self.assertRaises(errors.UnsupportedError) as raises: + func() + self.assertIn(msg_head, str(raises.exception)) + + for g1, g2 in permutations([gdb, gdb_init]): + func = gen(g1, g2) + check(func) + + @njit + def use_globals(): + a = 1 + gdb() + b = 2 + gdb_init() + return a + b + + check(use_globals) + + +@not_unix +class TestGdbExceptions(TestCase): + + def test_call_gdb(self): + def nop_compiler(x): + return x + for compiler in [nop_compiler, jit(forceobj=True), njit]: + for meth in [gdb, gdb_init]: + def python_func(): + meth() + with self.assertRaises(errors.TypingError) as raises: + compiler(python_func)() + msg = "gdb support is only available on unix-like systems" + self.assertIn(msg, str(raises.exception)) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_gil.py b/lib/python3.10/site-packages/numba/tests/test_gil.py new file mode 100644 index 0000000000000000000000000000000000000000..639ef06eaa4dbcfcce00de02a10a8cfc62807b61 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_gil.py @@ -0,0 +1,182 @@ +import ctypes +import ctypes.util +import os +import sys +import threading +import warnings + +import numpy as np + +import unittest +from numba import jit +from numba.core import errors +from numba.tests.support import TestCase, tag + + +# This CPython API function is a portable way to get the current thread id. +PyThread_get_thread_ident = ctypes.pythonapi.PyThread_get_thread_ident +PyThread_get_thread_ident.restype = ctypes.c_long +PyThread_get_thread_ident.argtypes = [] + +# A way of sleeping from nopython code +if os.name == 'nt': + sleep = ctypes.windll.kernel32.Sleep + sleep.argtypes = [ctypes.c_uint] + sleep.restype = None + sleep_factor = 1 # milliseconds +else: + sleep = ctypes.CDLL(ctypes.util.find_library("c")).usleep + sleep.argtypes = [ctypes.c_uint] + sleep.restype = ctypes.c_int + sleep_factor = 1000 # microseconds + + +def f(a, indices): + # If run from one thread at a time, the function will always fill the + # array with identical values. + # If run from several threads at a time, the function will probably + # fill the array with differing values. + for idx in indices: + # Let another thread run + sleep(10 * sleep_factor) + a[idx] = PyThread_get_thread_ident() + +f_sig = "void(int64[:], intp[:])" + +def lifted_f(a, indices): + """ + Same as f(), but inside a lifted loop + """ + object() # Force object mode + for idx in indices: + # Let another thread run + sleep(10 * sleep_factor) + a[idx] = PyThread_get_thread_ident() + +def object_f(a, indices): + """ + Same as f(), but in object mode + """ + for idx in indices: + # Let another thread run + sleep(10 * sleep_factor) + object() # Force object mode + a[idx] = PyThread_get_thread_ident() + + +class TestGILRelease(TestCase): + + def make_test_array(self, n_members): + return np.arange(n_members, dtype=np.int64) + + def run_in_threads(self, func, n_threads): + # Run the function in parallel over an array and collect results. + threads = [] + # Warm up compilation, since we don't want that to interfere with + # the test proper. + func(self.make_test_array(1), np.arange(1, dtype=np.intp)) + arr = self.make_test_array(50) + for i in range(n_threads): + # Ensure different threads write into the array in different + # orders. + indices = np.arange(arr.size, dtype=np.intp) + np.random.shuffle(indices) + t = threading.Thread(target=func, args=(arr, indices)) + threads.append(t) + for t in threads: + t.start() + for t in threads: + t.join() + return arr + + def check_gil_held(self, func): + arr = self.run_in_threads(func, n_threads=4) + distinct = set(arr) + self.assertEqual(len(distinct), 1, distinct) + + def check_gil_released(self, func): + for n_threads in (4, 12, 32): + # Try harder each time. On an empty machine 4 threads seems + # sufficient, but in some contexts (e.g. Travis CI) we need more. + arr = self.run_in_threads(func, n_threads) + distinct = set(arr) + try: + self.assertGreater(len(distinct), 1, distinct) + except AssertionError as e: + failure = e + else: + return + raise failure + + def test_gil_held(self): + """ + Test the GIL is held by default, by checking serialized runs + produce deterministic results. + """ + cfunc = jit(f_sig, nopython=True)(f) + self.check_gil_held(cfunc) + + def test_gil_released(self): + """ + Test releasing the GIL, by checking parallel runs produce + unpredictable results. + """ + cfunc = jit(f_sig, nopython=True, nogil=True)(f) + self.check_gil_released(cfunc) + + def test_gil_released_inside_lifted_loop(self): + """ + Test the GIL can by released by a lifted loop even though the + surrounding code uses object mode. + """ + cfunc = jit(f_sig, forceobj=True, nogil=True)(lifted_f) + self.check_gil_released(cfunc) + + def test_gil_released_by_caller(self): + """ + Releasing the GIL in the caller is sufficient to have it + released in a callee. + """ + compiled_f = jit(f_sig, nopython=True)(f) + @jit(f_sig, nopython=True, nogil=True) + def caller(a, i): + compiled_f(a, i) + self.check_gil_released(caller) + + def test_gil_released_by_caller_and_callee(self): + """ + Same, but with both caller and callee asking to release the GIL. + """ + compiled_f = jit(f_sig, nopython=True, nogil=True)(f) + @jit(f_sig, nopython=True, nogil=True) + def caller(a, i): + compiled_f(a, i) + self.check_gil_released(caller) + + def test_gil_ignored_by_callee(self): + """ + When only the callee asks to release the GIL, it gets ignored. + """ + compiled_f = jit(f_sig, nopython=True, nogil=True)(f) + @jit(f_sig, nopython=True) + def caller(a, i): + compiled_f(a, i) + self.check_gil_held(caller) + + def test_object_mode(self): + """ + When the function is compiled in object mode, a warning is + printed out. + """ + with warnings.catch_warnings(record=True) as wlist: + warnings.simplefilter('always', errors.NumbaWarning) + cfunc = jit(f_sig, forceobj=True, nogil=True)(object_f) + self.assertTrue(any(w.category is errors.NumbaWarning + and "Code running in object mode won't allow parallel execution" in str(w.message) + for w in wlist), wlist) + # Just check it doesn't crash. + self.run_in_threads(cfunc, 2) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_hashing.py b/lib/python3.10/site-packages/numba/tests/test_hashing.py new file mode 100644 index 0000000000000000000000000000000000000000..4d19f95aa3a5974ea0fd4dfd359fa0d3cd952b48 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_hashing.py @@ -0,0 +1,529 @@ +# -*- coding: utf-8 -*- +""" +Test hashing of various supported types. +""" + +import unittest + +import os +import sys +import subprocess +from collections import defaultdict +from textwrap import dedent + +import numpy as np + +from numba import jit, config, typed, typeof +from numba.core import types, utils +import unittest +from numba.tests.support import (TestCase, skip_unless_py10_or_later, + run_in_subprocess) + +from numba.cpython.unicode import compile_time_get_string_data +from numba.cpython import hashing +from numba.np.numpy_support import numpy_version + + +def hash_usecase(x): + return hash(x) + + +class TestHashingSetup(TestCase): + + def test_warn_on_fnv(self): + # FNV hash alg variant is not supported, check Numba warns + work = """ + import sys + import warnings + from collections import namedtuple + + # hash_info is a StructSequence, mock as a named tuple + fields = ["width", "modulus", "inf", "nan", "imag", "algorithm", + "hash_bits", "seed_bits", "cutoff"] + + hinfo = sys.hash_info + FAKE_HASHINFO = namedtuple('FAKE_HASHINFO', fields) + + fd = dict() + for f in fields: + fd[f] = getattr(hinfo, f) + + fd['algorithm'] = 'fnv' + + fake_hashinfo = FAKE_HASHINFO(**fd) + + # replace the hashinfo with the fnv version + sys.hash_info = fake_hashinfo + with warnings.catch_warnings(record=True) as warns: + # Cause all warnings to always be triggered. + warnings.simplefilter("always") + from numba import njit + @njit + def foo(): + hash(1) + foo() + assert len(warns) > 0 + expect = "FNV hashing is not implemented in Numba. See PEP 456" + for w in warns: + if expect in str(w.message): + break + else: + raise RuntimeError("Expected warning not found") + """ + subprocess.check_call([sys.executable, '-c', dedent(work)]) + + +class TestHashAlgs(TestCase): + # This tests Numba hashing replication against cPython "gold", i.e. the + # actual hash values for given inputs, algs and PYTHONHASHSEEDs + # Test adapted from: + # https://github.com/python/cpython/blob/9dda9020abcf0d51d59b283a89c58c8e1fb0f574/Lib/test/test_hash.py#L197-L264 + # and + # https://github.com/python/cpython/blob/9dda9020abcf0d51d59b283a89c58c8e1fb0f574/Lib/test/test_hash.py#L174-L189 + + # 32bit little, 64bit little, 32bit big, 64bit big + known_hashes = { + 'djba33x': [ # only used for small strings + # seed 0, 'abc' + [193485960, 193485960, 193485960, 193485960], + # seed 42, 'abc' + [-678966196, 573763426263223372, -820489388, -4282905804826039665], + ], + 'siphash13': [ + # NOTE: PyUCS2 layout depends on endianness + # seed 0, 'abc' + [69611762, -4594863902769663758, 69611762, -4594863902769663758], + # seed 42, 'abc' + [-975800855, 3869580338025362921, -975800855, 3869580338025362921], + # seed 42, 'abcdefghijk' + [-595844228, 7764564197781545852, -595844228, 7764564197781545852], + # seed 0, 'äú∑ℇ' + [-1093288643, -2810468059467891395, -1041341092, 4925090034378237276], + # seed 42, 'äú∑ℇ' + [-585999602, -2845126246016066802, -817336969, -2219421378907968137], + ], + 'siphash24': [ + # NOTE: PyUCS2 layout depends on endianness + # seed 0, 'abc' + [1198583518, 4596069200710135518, 1198583518, 4596069200710135518], + # seed 42, 'abc' + [273876886, -4501618152524544106, 273876886, -4501618152524544106], + # seed 42, 'abcdefghijk' + [-1745215313, 4436719588892876975, -1745215313, 4436719588892876975], + # seed 0, 'äú∑ℇ' + [493570806, 5749986484189612790, -1006381564, -5915111450199468540], + # seed 42, 'äú∑ℇ' + [-1677110816, -2947981342227738144, -1860207793, -4296699217652516017], + ], + } + + def get_expected_hash(self, position, length): + if length < sys.hash_info.cutoff: + algorithm = "djba33x" + else: + algorithm = sys.hash_info.algorithm + IS_64BIT = not config.IS_32BITS + if sys.byteorder == 'little': + platform = 1 if IS_64BIT else 0 + else: + assert(sys.byteorder == 'big') + platform = 3 if IS_64BIT else 2 + return self.known_hashes[algorithm][position][platform] + + def get_hash_command(self, repr_): + return 'print(hash(eval(%a)))' % repr_ + + def get_hash(self, repr_, seed=None): + env = os.environ.copy() + if seed is not None: + env['PYTHONHASHSEED'] = str(seed) + else: + env.pop('PYTHONHASHSEED', None) + out, _ = run_in_subprocess(code=self.get_hash_command(repr_), + env=env) + stdout = out.decode().strip() + return int(stdout) + + def test_against_cpython_gold(self): + + args = (('abc', 0, 0), ('abc', 42, 1), ('abcdefghijk', 42, 2), + ('äú∑ℇ', 0, 3), ('äú∑ℇ', 42, 4),) + + for input_str, seed, position in args: + with self.subTest(input_str=input_str, seed=seed): + got = self.get_hash(repr(input_str), seed=seed) + expected = self.get_expected_hash(position, len(input_str)) + self.assertEqual(got, expected) + + +class BaseTest(TestCase): + + def setUp(self): + self.cfunc = jit(nopython=True)(hash_usecase) + + def check_hash_values(self, values): + cfunc = self.cfunc + for val in list(values): + nb_hash = cfunc(val) + self.assertIsInstance(nb_hash, int) + try: + self.assertEqual(nb_hash, hash(val)) + except AssertionError as e: + print("val, nb_hash, hash(val)") + print(val, nb_hash, hash(val)) + print("abs(val), hashing._PyHASH_MODULUS - 1") + print(abs(val), hashing._PyHASH_MODULUS - 1) + raise e + + def int_samples(self, typ=np.int64): + for start in (0, -50, 60000, 1 << 32): + info = np.iinfo(typ) + if not info.min <= start <= info.max: + continue + n = 100 + yield range(start, start + n) + yield range(start, start + 100 * n, 100) + yield range(start, start + 128 * n, 128) + yield [-1] + + def float_samples(self, typ): + info = np.finfo(typ) + + for start in (0, 10, info.max ** 0.5, info.max / 1000.0): + n = 100 + min_step = max(info.tiny, start * info.resolution) + for step in (1.2, min_step ** 0.5, min_step): + if step < min_step: + continue + a = np.linspace(start, start + n * step, n) + a = a.astype(typ) + yield a + yield -a + yield a + a.mean() + + # Infs, nans, zeros, magic -1 + a = [0.0, 0.5, -0.0, -1.0, float('inf'), -float('inf'),] + + # Python 3.10 has a hash for nan based on the pointer to the PyObject + # containing the nan, skip this input and use explicit test instead. + + yield typ(a) + + def complex_samples(self, typ, float_ty): + for real in self.float_samples(float_ty): + for imag in self.float_samples(float_ty): + # Ensure equal sizes + real = real[:len(imag)] + imag = imag[:len(real)] + a = real + typ(1j) * imag + # Python 3.10 has a hash for nan based on the pointer to the + # PyObject containing the nan, skip input that ends up as nan + if not np.any(np.isnan(a)): + yield a + + +class TestNumberHashing(BaseTest): + """ + Test hashing of number types. + """ + + def setUp(self): + if numpy_version >= (2, 0): + # Temporarily set promotions state to legacy, + # to ensure overflow logic works + self.initial_state = np._get_promotion_state() + np._set_promotion_state("legacy") + + return super().setUp() + + def tearDown(self) -> None: + if numpy_version >= (2, 0): + # Reset numpy promotion state to initial state + # since the setting is global + np._set_promotion_state(self.initial_state) + + return super().tearDown() + + def check_floats(self, typ): + for a in self.float_samples(typ): + self.assertEqual(a.dtype, np.dtype(typ)) + self.check_hash_values(a) + + def check_complex(self, typ, float_ty): + for a in self.complex_samples(typ, float_ty): + self.assertEqual(a.dtype, np.dtype(typ)) + self.check_hash_values(a) + + def test_floats(self): + self.check_floats(np.float32) + self.check_floats(np.float64) + + def test_complex(self): + self.check_complex(np.complex64, np.float32) + self.check_complex(np.complex128, np.float64) + + def test_bool(self): + self.check_hash_values([False, True]) + + def test_ints(self): + minmax = [] + + for ty in [np.int8, np.uint8, np.int16, np.uint16, + np.int32, np.uint32, np.int64, np.uint64]: + for a in self.int_samples(ty): + self.check_hash_values(a) + info = np.iinfo(ty) + # check hash(-1) = -2 + # check hash(0) = 0 + self.check_hash_values([ty(-1)]) + self.check_hash_values([ty(0)]) + signed = 'uint' not in str(ty) + # check bit shifting patterns from min through to max + sz = ty().itemsize + for x in [info.min, info.max]: + shifts = 8 * sz + # x is a python int, do shifts etc as a python int and init + # numpy type from that to avoid numpy type rules + y = x + for i in range(shifts): + twiddle1 = 0xaaaaaaaaaaaaaaaa + twiddle2 = 0x5555555555555555 + vals = [y] + for tw in [twiddle1, twiddle2]: + val = y & twiddle1 + if val < sys.maxsize: + vals.append(val) + for v in vals: + self.check_hash_values([ty(v)]) + if signed: # try the same with flipped signs + # negated signed INT_MIN will overflow + for v in vals: + if v != info.min: + self.check_hash_values([ty(-v)]) + if x == 0: # unsigned min is 0, shift up + y = (y | 1) << 1 + else: # everything else shift down + y = y >> 1 + + # these straddle the branch between returning the int as the hash and + # doing the PyLong hash alg + self.check_hash_values([np.int64(0x1ffffffffffffffe)]) + self.check_hash_values([np.int64(0x1fffffffffffffff)]) + self.check_hash_values([np.uint64(0x1ffffffffffffffe)]) + self.check_hash_values([np.uint64(0x1fffffffffffffff)]) + + # check some values near sys int mins + self.check_hash_values([np.int64(-0x7fffffffffffffff)]) + self.check_hash_values([np.int64(-0x7ffffffffffffff6)]) + self.check_hash_values([np.int64(-0x7fffffffffffff9c)]) + self.check_hash_values([np.int32(-0x7fffffff)]) + self.check_hash_values([np.int32(-0x7ffffff6)]) + self.check_hash_values([np.int32(-0x7fffff9c)]) + + @skip_unless_py10_or_later + def test_py310_nan_hash(self): + # On Python 3.10+ nan's hash to a value which is based on the pointer to + # the PyObject containing the nan. Numba cannot replicate as there's no + # object, it instead produces equivalent behaviour, i.e. hashes to + # something "unique". + + # Run 10 hashes, make sure that the "uniqueness" is sufficient that + # there's more than one hash value. Not much more can be done! + x = [float('nan') for i in range(10)] + out = set([self.cfunc(z) for z in x]) + self.assertGreater(len(out), 1) + + +class TestTupleHashing(BaseTest): + """ + Test hashing of tuples. + """ + + def setUp(self): + if numpy_version >= (2, 0): + # Temporarily set promotions state to legacy, + # to ensure overflow logic works + self.initial_state = np._get_promotion_state() + np._set_promotion_state("legacy") + + return super().setUp() + + def tearDown(self) -> None: + if numpy_version >= (2, 0): + # Reset numpy promotion state to initial state + # since the setting is global + np._set_promotion_state(self.initial_state) + + return super().tearDown() + + def check_tuples(self, value_generator, split): + for values in value_generator: + tuples = [split(a) for a in values] + self.check_hash_values(tuples) + + def test_homogeneous_tuples(self): + typ = np.uint64 + + def split2(i): + """ + Split i's bits into 2 integers. + """ + i = typ(i) + return (i & typ(0x5555555555555555), + i & typ(0xaaaaaaaaaaaaaaaa), + ) + + def split3(i): + """ + Split i's bits into 3 integers. + """ + i = typ(i) + return (i & typ(0x2492492492492492), + i & typ(0x4924924924924924), + i & typ(0x9249249249249249), + ) + + self.check_tuples(self.int_samples(), split2) + self.check_tuples(self.int_samples(), split3) + + # Check exact. Sample values from: + # https://github.com/python/cpython/blob/b738237d6792acba85b1f6e6c8993a812c7fd815/Lib/test/test_tuple.py#L80-L93 + # Untypable empty tuples are replaced with (7,). + self.check_hash_values([(7,), (0,), (0, 0), (0.5,), + (0.5, (7,), (-2, 3, (4, 6)))]) + + def test_heterogeneous_tuples(self): + modulo = 2**63 + + def split(i): + a = i & 0x5555555555555555 + b = (i & 0xaaaaaaaa) ^ ((i >> 32) & 0xaaaaaaaa) + return np.int64(a), np.float64(b * 0.0001) + + self.check_tuples(self.int_samples(), split) + + +class TestUnicodeHashing(BaseTest): + + def test_basic_unicode(self): + kind1_string = "abcdefghijklmnopqrstuvwxyz" + for i in range(len(kind1_string)): + self.check_hash_values([kind1_string[:i]]) + + sep = "眼" + kind2_string = sep.join(list(kind1_string)) + for i in range(len(kind2_string)): + self.check_hash_values([kind2_string[:i]]) + + sep = "🐍⚡" + kind4_string = sep.join(list(kind1_string)) + for i in range(len(kind4_string)): + self.check_hash_values([kind4_string[:i]]) + + empty_string = "" + self.check_hash_values(empty_string) + + def test_hash_passthrough(self): + # no `hash` call made, this just checks that `._hash` is correctly + # passed through from an already existing string + kind1_string = "abcdefghijklmnopqrstuvwxyz" + + @jit(nopython=True) + def fn(x): + return x._hash + + hash_value = compile_time_get_string_data(kind1_string)[-1] + self.assertTrue(hash_value != -1) + self.assertEqual(fn(kind1_string), hash_value) + + def test_hash_passthrough_call(self): + # check `x._hash` and hash(x) are the same + kind1_string = "abcdefghijklmnopqrstuvwxyz" + + @jit(nopython=True) + def fn(x): + return x._hash, hash(x) + + hash_value = compile_time_get_string_data(kind1_string)[-1] + self.assertTrue(hash_value != -1) + self.assertEqual(fn(kind1_string), (hash_value, hash_value)) + + @unittest.skip("Needs hash computation at const unpickling time") + def test_hash_literal(self): + # a strconst always seem to have an associated hash value so the hash + # member of the returned value should contain the correct hash + @jit(nopython=True) + def fn(): + x = "abcdefghijklmnopqrstuvwxyz" + return x + val = fn() + tmp = hash("abcdefghijklmnopqrstuvwxyz") + self.assertEqual(tmp, (compile_time_get_string_data(val)[-1])) + + def test_hash_on_str_creation(self): + # In cPython some? new strings do not have a cached hash until hash() is + # called + def impl(do_hash): + const1 = "aaaa" + const2 = "眼眼眼眼" + new = const1 + const2 + if do_hash: + hash(new) + return new + + jitted = jit(nopython=True)(impl) + + # do not compute the hash, cPython will have no cached hash, but Numba + # will + compute_hash = False + expected = impl(compute_hash) + got = jitted(compute_hash) + a = (compile_time_get_string_data(expected)) + b = (compile_time_get_string_data(got)) + self.assertEqual(a[:-1], b[:-1]) + self.assertTrue(a[-1] != b[-1]) + + # now with compute hash enabled, cPython will have a cached hash as will + # Numba + compute_hash = True + expected = impl(compute_hash) + got = jitted(compute_hash) + a = (compile_time_get_string_data(expected)) + b = (compile_time_get_string_data(got)) + self.assertEqual(a, b) + + +class TestUnhashable(TestCase): + # Tests that unhashable types behave correctly and raise a TypeError at + # runtime. + + def test_hash_unhashable(self): + unhashables = (typed.Dict().empty(types.int64, types.int64), + typed.List().empty_list(types.int64), + np.ones(4)) + cfunc = jit(nopython=True)(hash_usecase) + for ty in unhashables: + with self.assertRaises(TypeError) as raises: + cfunc(ty) + expected = f"unhashable type: '{str(typeof(ty))}'" + self.assertIn(expected, str(raises.exception)) + + def test_no_generic_hash(self): + # In CPython, if there's no attr `__hash__` on an object, a hash of the + # object's pointer is returned (see: _Py_HashPointer in the CPython + # source). Numba has no access to such objects and can't create them + # either, so it catches this case and raises an exception. + + @jit(nopython=True) + def foo(): + hash(np.cos) + + with self.assertRaises(TypeError) as raises: + foo() + + expected = ("No __hash__ is defined for object ") + self.assertIn(expected, str(raises.exception)) + + +if __name__ == "__main__": + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_heapq.py b/lib/python3.10/site-packages/numba/tests/test_heapq.py new file mode 100644 index 0000000000000000000000000000000000000000..232fd60121ecd8bd3f7e05b58beeb5ee30d0cf14 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_heapq.py @@ -0,0 +1,484 @@ +import heapq as hq +import itertools + +import numpy as np + +from numba import jit, typed +from numba.tests.support import TestCase, MemoryLeakMixin + + +def heapify(x): + return hq.heapify(x) + + +def heappop(heap): + return hq.heappop(heap) + + +def heappush(heap, item): + return hq.heappush(heap, item) + + +def heappushpop(heap, item): + return hq.heappushpop(heap, item) + + +def heapreplace(heap, item): + return hq.heapreplace(heap, item) + + +def nsmallest(n, iterable): + return hq.nsmallest(n, iterable) + + +def nlargest(n, iterable): + return hq.nlargest(n, iterable) + + +class _TestHeapq(MemoryLeakMixin): + + def setUp(self): + super(_TestHeapq, self).setUp() + self.rnd = np.random.RandomState(42) + + def test_heapify_basic_sanity(self): + pyfunc = heapify + cfunc = jit(nopython=True)(pyfunc) + + a = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0] + b = self.listimpl(a) + + pyfunc(a) + cfunc(b) + self.assertPreciseEqual(a, list(b)) + + # includes non-finite elements + element_pool = [3.142, -10.0, 5.5, np.nan, -np.inf, np.inf] + + # list which may contain duplicate elements + for x in itertools.combinations_with_replacement(element_pool, 6): + a = list(x) + b = self.listimpl(a) + + pyfunc(a) + cfunc(b) + self.assertPreciseEqual(a, list(b)) + + # single element list + for i in range(len(element_pool)): + a = [element_pool[i]] + b = self.listimpl(a) + + pyfunc(a) + cfunc(b) + self.assertPreciseEqual(a, list(b)) + + # elements are tuples + a = [(3, 33), (1, 11), (2, 22)] + b = self.listimpl(a) + pyfunc(a) + cfunc(b) + self.assertPreciseEqual(a, list(b)) + + def check_invariant(self, heap): + for pos, item in enumerate(heap): + if pos: + parentpos = (pos - 1) >> 1 + self.assertTrue(heap[parentpos] <= item) + + def test_push_pop(self): + # inspired by + # https://github.com/python/cpython/blob/e42b7051/Lib/test/test_heapq.py + pyfunc_heappush = heappush + cfunc_heappush = jit(nopython=True)(pyfunc_heappush) + + pyfunc_heappop = heappop + cfunc_heappop = jit(nopython=True)(pyfunc_heappop) + + heap = self.listimpl([-1.0]) + data = self.listimpl([-1.0]) + self.check_invariant(heap) + for i in range(256): + item = self.rnd.randn(1).item(0) + data.append(item) + cfunc_heappush(heap, item) + self.check_invariant(heap) + results = [] + while heap: + item = cfunc_heappop(heap) + self.check_invariant(heap) + results.append(item) + data_sorted = data[:] + data_sorted.sort() + self.assertPreciseEqual(list(data_sorted), results) + self.check_invariant(results) + + def test_heapify(self): + # inspired by + # https://github.com/python/cpython/blob/e42b7051/Lib/test/test_heapq.py + pyfunc = heapify + cfunc = jit(nopython=True)(pyfunc) + + for size in list(range(1, 30)) + [20000]: + heap = self.listimpl(self.rnd.random_sample(size)) + cfunc(heap) + self.check_invariant(heap) + + def test_heapify_exceptions(self): + pyfunc = heapify + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + with self.assertTypingError() as e: + cfunc((1, 5, 4)) + + msg = 'heap argument must be a list' + self.assertIn(msg, str(e.exception)) + + with self.assertTypingError() as e: + cfunc(self.listimpl([1 + 1j, 2 - 3j])) + + msg = ("'<' not supported between instances " + "of 'complex' and 'complex'") + self.assertIn(msg, str(e.exception)) + + def test_heappop_basic_sanity(self): + pyfunc = heappop + cfunc = jit(nopython=True)(pyfunc) + + def a_variations(): + yield [1, 3, 5, 7, 9, 2, 4, 6, 8, 0] + yield [(3, 33), (1, 111), (2, 2222)] + yield np.full(5, fill_value=np.nan).tolist() + yield np.linspace(-10, -5, 100).tolist() + + for a in a_variations(): + heapify(a) + b = self.listimpl(a) + + for i in range(len(a)): + val_py = pyfunc(a) + val_c = cfunc(b) + self.assertPreciseEqual(a, list(b)) + self.assertPreciseEqual(val_py, val_c) + + def test_heappop_exceptions(self): + pyfunc = heappop + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + with self.assertTypingError() as e: + cfunc((1, 5, 4)) + + msg = 'heap argument must be a list' + self.assertIn(msg, str(e.exception)) + + def iterables(self): + yield self.listimpl([1, 3, 5, 7, 9, 2, 4, 6, 8, 0]) + a = np.linspace(-10, 2, 23) + yield self.listimpl(a) + yield self.listimpl(a[::-1]) + self.rnd.shuffle(a) + yield self.listimpl(a) + + def test_heappush_basic(self): + pyfunc_push = heappush + cfunc_push = jit(nopython=True)(pyfunc_push) + + pyfunc_pop = heappop + cfunc_pop = jit(nopython=True)(pyfunc_pop) + + for iterable in self.iterables(): + expected = sorted(iterable) + heap = self.listimpl([iterable.pop(0)]) # must initialise heap + + for value in iterable: + cfunc_push(heap, value) + + got = [cfunc_pop(heap) for _ in range(len(heap))] + self.assertPreciseEqual(expected, got) + + def test_heappush_exceptions(self): + pyfunc = heappush + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + with self.assertTypingError() as e: + cfunc((1, 5, 4), 6) + + msg = 'heap argument must be a list' + self.assertIn(msg, str(e.exception)) + + with self.assertTypingError() as e: + cfunc(self.listimpl([1, 5, 4]), 6.0) + + msg = 'heap type must be the same as item type' + self.assertIn(msg, str(e.exception)) + + def test_nsmallest_basic(self): + pyfunc = nsmallest + cfunc = jit(nopython=True)(pyfunc) + + for iterable in self.iterables(): + for n in range(-5, len(iterable) + 3): + expected = pyfunc(1, iterable) + got = cfunc(1, iterable) + self.assertPreciseEqual(expected, got) + + # n is boolean + out = cfunc(False, self.listimpl([3, 2, 1])) + self.assertPreciseEqual(out, []) + + out = cfunc(True, self.listimpl([3, 2, 1])) + self.assertPreciseEqual(out, [1]) + + # iterable is not a list + out = cfunc(2, (6, 5, 4, 3, 2, 1)) + self.assertPreciseEqual(out, [1, 2]) + + out = cfunc(3, np.arange(6)) + self.assertPreciseEqual(out, [0, 1, 2]) + + def test_nlargest_basic(self): + pyfunc = nlargest + cfunc = jit(nopython=True)(pyfunc) + + for iterable in self.iterables(): + for n in range(-5, len(iterable) + 3): + expected = pyfunc(1, iterable) + got = cfunc(1, iterable) + self.assertPreciseEqual(expected, got) + + # n is boolean + out = cfunc(False, self.listimpl([3, 2, 1])) + self.assertPreciseEqual(out, []) + + out = cfunc(True, self.listimpl([3, 2, 1])) + self.assertPreciseEqual(out, [3]) + + # iterable is not a list + out = cfunc(2, (6, 5, 4, 3, 2, 1)) + self.assertPreciseEqual(out, [6, 5]) + + out = cfunc(3, np.arange(6)) + self.assertPreciseEqual(out, [5, 4, 3]) + + def _assert_typing_error(self, cfunc): + + # Exceptions leak references + self.disable_leak_check() + + with self.assertTypingError() as e: + cfunc(2.2, self.listimpl([3, 2, 1])) + + msg = "First argument 'n' must be an integer" + self.assertIn(msg, str(e.exception)) + + with self.assertTypingError() as e: + cfunc(2, 100) + + msg = "Second argument 'iterable' must be iterable" + self.assertIn(msg, str(e.exception)) + + def test_nsmallest_exceptions(self): + pyfunc = nsmallest + cfunc = jit(nopython=True)(pyfunc) + self._assert_typing_error(cfunc) + + def test_nlargest_exceptions(self): + pyfunc = nlargest + cfunc = jit(nopython=True)(pyfunc) + self._assert_typing_error(cfunc) + + def test_heapreplace_basic(self): + pyfunc = heapreplace + cfunc = jit(nopython=True)(pyfunc) + + a = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0] + + heapify(a) + b = self.listimpl(a) + + for item in [-4, 4, 14]: + pyfunc(a, item) + cfunc(b, item) + self.assertPreciseEqual(a, list(b)) + + a = np.linspace(-3, 13, 20) + a[4] = np.nan + a[-1] = np.inf + a = a.tolist() + + heapify(a) + b = self.listimpl(a) + + for item in [-4.0, 3.142, -np.inf, np.inf]: + pyfunc(a, item) + cfunc(b, item) + self.assertPreciseEqual(a, list(b)) + + def test_heapreplace_exceptions(self): + pyfunc = heapreplace + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + with self.assertTypingError() as e: + cfunc((1, 5, 4), -1) + + msg = 'heap argument must be a list' + self.assertIn(msg, str(e.exception)) + + with self.assertTypingError() as e: + cfunc(self.listimpl([1, 5, 4]), -1.0) + + msg = 'heap type must be the same as item type' + self.assertIn(msg, str(e.exception)) + + def heapiter(self, heap): + try: + while 1: + yield heappop(heap) + except IndexError: + pass + + def test_nbest(self): + # inspired by + # https://github.com/python/cpython/blob/e42b7051/Lib/test/test_heapq.py + cfunc_heapify = jit(nopython=True)(heapify) + cfunc_heapreplace = jit(nopython=True)(heapreplace) + + data = self.rnd.choice(range(2000), 1000).tolist() + heap = self.listimpl(data[:10]) + cfunc_heapify(heap) + + for item in data[10:]: + if item > heap[0]: + cfunc_heapreplace(heap, item) + + self.assertPreciseEqual(list(self.heapiter(list(heap))), + sorted(data)[-10:]) + + def test_heapsort(self): + # inspired by + # https://github.com/python/cpython/blob/e42b7051/Lib/test/test_heapq.py + cfunc_heapify = jit(nopython=True)(heapify) + cfunc_heappush = jit(nopython=True)(heappush) + cfunc_heappop = jit(nopython=True)(heappop) + + for trial in range(100): + # Ensure consistency of typing, use float64 as it's double + # everywhere + values = np.arange(5, dtype=np.float64) + data = self.listimpl(self.rnd.choice(values, 10)) + if trial & 1: + heap = data[:] + cfunc_heapify(heap) + else: + heap = self.listimpl([data[0]]) + for item in data[1:]: + cfunc_heappush(heap, item) + heap_sorted = [cfunc_heappop(heap) for _ in range(10)] + self.assertPreciseEqual(heap_sorted, sorted(data)) + + def test_nsmallest(self): + # inspired by + # https://github.com/python/cpython/blob/e42b7051/Lib/test/test_heapq.py + pyfunc = nsmallest + cfunc = jit(nopython=True)(pyfunc) + + data = self.listimpl(self.rnd.choice(range(2000), 1000)) + + for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): + self.assertPreciseEqual(list(cfunc(n, data)), sorted(data)[:n]) + + def test_nlargest(self): + # inspired by + # https://github.com/python/cpython/blob/e42b7051/Lib/test/test_heapq.py + pyfunc = nlargest + cfunc = jit(nopython=True)(pyfunc) + + data = self.listimpl(self.rnd.choice(range(2000), 1000)) + + for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100): + self.assertPreciseEqual(list(cfunc(n, data)), + sorted(data, reverse=True)[:n]) + + def test_nbest_with_pushpop(self): + # inspired by + # https://github.com/python/cpython/blob/e42b7051/Lib/test/test_heapq.py + pyfunc_heappushpop = heappushpop + cfunc_heappushpop = jit(nopython=True)(pyfunc_heappushpop) + + pyfunc_heapify = heapify + cfunc_heapify = jit(nopython=True)(pyfunc_heapify) + + # Ensure consistency of typing, use float64 as it's double everywhere + values = np.arange(2000, dtype=np.float64) + data = self.listimpl(self.rnd.choice(values, 1000)) + heap = data[:10] + cfunc_heapify(heap) + + for item in data[10:]: + cfunc_heappushpop(heap, item) + + self.assertPreciseEqual(list(self.heapiter(list(heap))), + sorted(data)[-10:]) + + def test_heappushpop(self): + # inspired by + # https://github.com/python/cpython/blob/e42b7051/Lib/test/test_heapq.py + pyfunc = heappushpop + cfunc = jit(nopython=True)(pyfunc) + + h = self.listimpl([1.0]) + x = cfunc(h, 10.0) + self.assertPreciseEqual((list(h), x), ([10.0], 1.0)) + self.assertPreciseEqual(type(h[0]), float) + self.assertPreciseEqual(type(x), float) + + h = self.listimpl([10]) + x = cfunc(h, 9) + self.assertPreciseEqual((list(h), x), ([10], 9)) + + h = self.listimpl([10]) + x = cfunc(h, 11) + self.assertPreciseEqual((list(h), x), ([11], 10)) + + def test_heappushpop_exceptions(self): + pyfunc = heappushpop + cfunc = jit(nopython=True)(pyfunc) + + # Exceptions leak references + self.disable_leak_check() + + with self.assertTypingError() as e: + cfunc((1, 5, 4), -1) + + msg = 'heap argument must be a list' + self.assertIn(msg, str(e.exception)) + + with self.assertTypingError() as e: + cfunc(self.listimpl([1, 5, 4]), False) + + msg = 'heap type must be the same as item type' + self.assertIn(msg, str(e.exception)) + + +class TestHeapqReflectedList(_TestHeapq, TestCase): + """Test heapq with reflected lists""" + + listimpl = list + + +class TestHeapqTypedList(_TestHeapq, TestCase): + """Test heapq with typed lists""" + + listimpl = typed.List diff --git a/lib/python3.10/site-packages/numba/tests/test_inlining.py b/lib/python3.10/site-packages/numba/tests/test_inlining.py new file mode 100644 index 0000000000000000000000000000000000000000..45376a483d515974481212c6454ff5ec1f193136 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_inlining.py @@ -0,0 +1,279 @@ +import re +import numpy as np + +from numba.tests.support import (TestCase, override_config, captured_stdout, + skip_parfors_unsupported) +from numba import jit, njit +from numba.core import types, ir, postproc, compiler +from numba.core.ir_utils import (guard, find_callname, find_const, + get_definition, simplify_CFG) +from numba.core.registry import CPUDispatcher +from numba.core.inline_closurecall import inline_closure_call + +from numba.core.untyped_passes import (ExtractByteCode, TranslateByteCode, FixupArgs, + IRProcessing, DeadBranchPrune, + RewriteSemanticConstants, GenericRewrites, + WithLifting, PreserveIR, InlineClosureLikes) + +from numba.core.typed_passes import (NopythonTypeInference, AnnotateTypes, + NopythonRewrites, PreParforPass, ParforPass, + DumpParforDiagnostics, NativeLowering, + NativeParforLowering, IRLegalization, + NoPythonBackend, NativeLowering, + ParforFusionPass, ParforPreLoweringPass) + +from numba.core.compiler_machinery import FunctionPass, PassManager, register_pass +import unittest + +@register_pass(analysis_only=False, mutates_CFG=True) +class InlineTestPass(FunctionPass): + _name = "inline_test_pass" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + # assuming the function has one block with one call inside + assert len(state.func_ir.blocks) == 1 + block = list(state.func_ir.blocks.values())[0] + for i, stmt in enumerate(block.body): + if guard(find_callname,state.func_ir, stmt.value) is not None: + inline_closure_call(state.func_ir, {}, block, i, lambda: None, + state.typingctx, state.targetctx, (), + state.typemap, state.calltypes) + break + # also fix up the IR + post_proc = postproc.PostProcessor(state.func_ir) + post_proc.run() + post_proc.remove_dels() + return True + + +def gen_pipeline(state, test_pass): + name = 'inline_test' + pm = PassManager(name) + pm.add_pass(TranslateByteCode, "analyzing bytecode") + pm.add_pass(FixupArgs, "fix up args") + pm.add_pass(IRProcessing, "processing IR") + pm.add_pass(WithLifting, "Handle with contexts") + # pre typing + if not state.flags.no_rewrites: + pm.add_pass(GenericRewrites, "nopython rewrites") + pm.add_pass(RewriteSemanticConstants, "rewrite semantic constants") + pm.add_pass(DeadBranchPrune, "dead branch pruning") + pm.add_pass(InlineClosureLikes, + "inline calls to locally defined closures") + # typing + pm.add_pass(NopythonTypeInference, "nopython frontend") + + if state.flags.auto_parallel.enabled: + pm.add_pass(PreParforPass, "Preprocessing for parfors") + if not state.flags.no_rewrites: + pm.add_pass(NopythonRewrites, "nopython rewrites") + if state.flags.auto_parallel.enabled: + pm.add_pass(ParforPass, "convert to parfors") + pm.add_pass(ParforFusionPass, "fuse parfors") + pm.add_pass(ParforPreLoweringPass, "parfor prelowering") + + pm.add_pass(test_pass, "inline test") + + # legalise + pm.add_pass(IRLegalization, "ensure IR is legal prior to lowering") + pm.add_pass(AnnotateTypes, "annotate types") + pm.add_pass(PreserveIR, "preserve IR") + + # lower + if state.flags.auto_parallel.enabled: + pm.add_pass(NativeParforLowering, "native parfor lowering") + else: + pm.add_pass(NativeLowering, "native lowering") + pm.add_pass(NoPythonBackend, "nopython mode backend") + pm.add_pass(DumpParforDiagnostics, "dump parfor diagnostics") + return pm + +class InlineTestPipeline(compiler.CompilerBase): + """compiler pipeline for testing inlining after optimization + """ + def define_pipelines(self): + pm = gen_pipeline(self.state, InlineTestPass) + pm.finalize() + return [pm] + +class TestInlining(TestCase): + """ + Check that jitted inner functions are inlined into outer functions, + in nopython mode. + Note that not all inner functions are guaranteed to be inlined. + We just trust LLVM's inlining heuristics. + """ + + def make_pattern(self, fullname): + """ + Make regexpr to match mangled name + """ + parts = fullname.split('.') + return r'_ZN?' + r''.join([r'\d+{}'.format(p) for p in parts]) + + def assert_has_pattern(self, fullname, text): + pat = self.make_pattern(fullname) + self.assertIsNotNone(re.search(pat, text), + msg='expected {}'.format(pat)) + + def assert_not_has_pattern(self, fullname, text): + pat = self.make_pattern(fullname) + self.assertIsNone(re.search(pat, text), + msg='unexpected {}'.format(pat)) + + def test_inner_function(self): + from numba.tests.inlining_usecases import outer_simple, \ + __name__ as prefix + + with override_config('DUMP_ASSEMBLY', True): + with captured_stdout() as out: + cfunc = jit((types.int32,), nopython=True)(outer_simple) + self.assertPreciseEqual(cfunc(1), 4) + # Check the inner function was elided from the output (which also + # guarantees it was inlined into the outer function). + asm = out.getvalue() + self.assert_has_pattern('%s.outer_simple' % prefix, asm) + self.assert_not_has_pattern('%s.inner' % prefix, asm) + + def test_multiple_inner_functions(self): + from numba.tests.inlining_usecases import outer_multiple, \ + __name__ as prefix + # Same with multiple inner functions, and multiple calls to + # the same inner function (inner()). This checks that linking in + # the same library/module twice doesn't produce linker errors. + with override_config('DUMP_ASSEMBLY', True): + with captured_stdout() as out: + cfunc = jit((types.int32,), nopython=True)(outer_multiple) + self.assertPreciseEqual(cfunc(1), 6) + asm = out.getvalue() + self.assert_has_pattern('%s.outer_multiple' % prefix, asm) + self.assert_not_has_pattern('%s.more' % prefix, asm) + self.assert_not_has_pattern('%s.inner' % prefix, asm) + + @skip_parfors_unsupported + def test_inline_call_after_parfor(self): + from numba.tests.inlining_usecases import __dummy__ + # replace the call to make sure inlining doesn't cause label conflict + # with parfor body + def test_impl(A): + __dummy__() + return A.sum() + j_func = njit(parallel=True, pipeline_class=InlineTestPipeline)( + test_impl) + A = np.arange(10) + self.assertEqual(test_impl(A), j_func(A)) + + @skip_parfors_unsupported + def test_inline_update_target_def(self): + + def test_impl(a): + if a == 1: + b = 2 + else: + b = 3 + return b + + func_ir = compiler.run_frontend(test_impl) + blocks = list(func_ir.blocks.values()) + for block in blocks: + for i, stmt in enumerate(block.body): + # match b = 2 and replace with lambda: 2 + if (isinstance(stmt, ir.Assign) and isinstance(stmt.value, ir.Var) + and guard(find_const, func_ir, stmt.value) == 2): + # replace expr with a dummy call + func_ir._definitions[stmt.target.name].remove(stmt.value) + stmt.value = ir.Expr.call(ir.Var(block.scope, "myvar", loc=stmt.loc), (), (), stmt.loc) + func_ir._definitions[stmt.target.name].append(stmt.value) + #func = g.py_func# + inline_closure_call(func_ir, {}, block, i, lambda: 2) + break + + self.assertEqual(len(func_ir._definitions['b']), 2) + + @skip_parfors_unsupported + def test_inline_var_dict_ret(self): + # make sure inline_closure_call returns the variable replacement dict + # and it contains the original variable name used in locals + @njit(locals={'b': types.float64}) + def g(a): + b = a + 1 + return b + + def test_impl(): + return g(1) + + func_ir = compiler.run_frontend(test_impl) + blocks = list(func_ir.blocks.values()) + for block in blocks: + for i, stmt in enumerate(block.body): + if (isinstance(stmt, ir.Assign) + and isinstance(stmt.value, ir.Expr) + and stmt.value.op == 'call'): + func_def = guard(get_definition, func_ir, stmt.value.func) + if (isinstance(func_def, (ir.Global, ir.FreeVar)) + and isinstance(func_def.value, CPUDispatcher)): + py_func = func_def.value.py_func + _, var_map = inline_closure_call( + func_ir, py_func.__globals__, block, i, py_func) + break + + self.assertTrue('b' in var_map) + + @skip_parfors_unsupported + def test_inline_call_branch_pruning(self): + # branch pruning pass should run properly in inlining to enable + # functions with type checks + @njit + def foo(A=None): + if A is None: + return 2 + else: + return A + + def test_impl(A=None): + return foo(A) + + @register_pass(analysis_only=False, mutates_CFG=True) + class PruningInlineTestPass(FunctionPass): + _name = "pruning_inline_test_pass" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + # assuming the function has one block with one call inside + assert len(state.func_ir.blocks) == 1 + block = list(state.func_ir.blocks.values())[0] + for i, stmt in enumerate(block.body): + if (guard(find_callname, state.func_ir, stmt.value) + is not None): + inline_closure_call(state.func_ir, {}, block, i, + foo.py_func, state.typingctx, state.targetctx, + (state.typemap[stmt.value.args[0].name],), + state.typemap, state.calltypes) + break + return True + + class InlineTestPipelinePrune(compiler.CompilerBase): + + def define_pipelines(self): + pm = gen_pipeline(self.state, PruningInlineTestPass) + pm.finalize() + return [pm] + + # make sure inline_closure_call runs in full pipeline + j_func = njit(pipeline_class=InlineTestPipelinePrune)(test_impl) + A = 3 + self.assertEqual(test_impl(A), j_func(A)) + self.assertEqual(test_impl(), j_func()) + + # make sure IR doesn't have branches + fir = j_func.overloads[(types.Omitted(None),)].metadata['preserved_ir'] + fir.blocks = simplify_CFG(fir.blocks) + self.assertEqual(len(fir.blocks), 1) + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_ir_utils.py b/lib/python3.10/site-packages/numba/tests/test_ir_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..96deeaca0e3f60037938c61d03838f5c22451ddc --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_ir_utils.py @@ -0,0 +1,273 @@ +import numba +from numba.tests.support import TestCase, unittest +from numba.core.registry import cpu_target +from numba.core.compiler import CompilerBase, Flags +from numba.core.compiler_machinery import PassManager +from numba.core import types, ir, bytecode, compiler, ir_utils, registry +from numba.core.untyped_passes import (ExtractByteCode, TranslateByteCode, + FixupArgs, IRProcessing,) + +from numba.core.typed_passes import (NopythonTypeInference, + type_inference_stage, DeadCodeElimination) +from numba.experimental import jitclass + +# global constant for testing find_const +GLOBAL_B = 11 + + +@jitclass([('val', numba.core.types.List(numba.intp))]) +class Dummy(object): + def __init__(self, val): + self.val = val + + +class TestIrUtils(TestCase): + """ + Tests ir handling utility functions like find_callname. + """ + + def test_obj_func_match(self): + """Test matching of an object method (other than Array see #3449) + """ + + def test_func(): + d = Dummy([1]) + d.val.append(2) + + test_ir = compiler.run_frontend(test_func) + typingctx = cpu_target.typing_context + targetctx = cpu_target.target_context + typing_res = type_inference_stage( + typingctx, targetctx, test_ir, (), None) + matched_call = ir_utils.find_callname( + test_ir, test_ir.blocks[0].body[7].value, typing_res.typemap) + self.assertTrue(isinstance(matched_call, tuple) and + len(matched_call) == 2 and + matched_call[0] == 'append') + + def test_dead_code_elimination(self): + + class Tester(CompilerBase): + + @classmethod + def mk_pipeline(cls, args, return_type=None, flags=None, locals={}, + library=None, typing_context=None, + target_context=None): + if not flags: + flags = Flags() + flags.nrt = True + if typing_context is None: + typing_context = registry.cpu_target.typing_context + if target_context is None: + target_context = registry.cpu_target.target_context + return cls(typing_context, target_context, library, args, + return_type, flags, locals) + + def compile_to_ir(self, func, DCE=False): + """ + Compile and return IR + """ + func_id = bytecode.FunctionIdentity.from_function(func) + self.state.func_id = func_id + ExtractByteCode().run_pass(self.state) + state = self.state + + name = "DCE_testing" + pm = PassManager(name) + pm.add_pass(TranslateByteCode, "analyzing bytecode") + pm.add_pass(FixupArgs, "fix up args") + pm.add_pass(IRProcessing, "processing IR") + pm.add_pass(NopythonTypeInference, "nopython frontend") + if DCE is True: + pm.add_pass(DeadCodeElimination, "DCE after typing") + pm.finalize() + pm.run(state) + return state.func_ir + + def check_initial_ir(the_ir): + # dead stuff: + # a const int value 0xdead + # an assign of above into to variable `dead` + # a const int above 0xdeaddead + # an assign of said int to variable `deaddead` + # this is 2 statements to remove + + self.assertEqual(len(the_ir.blocks), 1) + block = the_ir.blocks[0] + deads = [] + for x in block.find_insts(ir.Assign): + if isinstance(getattr(x, 'target', None), ir.Var): + if 'dead' in getattr(x.target, 'name', ''): + deads.append(x) + + self.assertEqual(len(deads), 2) + for d in deads: + # check the ir.Const is the definition and the value is expected + const_val = the_ir.get_definition(d.value) + self.assertTrue(int('0x%s' % d.target.name, 16), + const_val.value) + + return deads + + def check_dce_ir(the_ir): + self.assertEqual(len(the_ir.blocks), 1) + block = the_ir.blocks[0] + deads = [] + consts = [] + for x in block.find_insts(ir.Assign): + if isinstance(getattr(x, 'target', None), ir.Var): + if 'dead' in getattr(x.target, 'name', ''): + deads.append(x) + if isinstance(getattr(x, 'value', None), ir.Const): + consts.append(x) + self.assertEqual(len(deads), 0) + + # check the consts to make sure there's no reference to 0xdead or + # 0xdeaddead + for x in consts: + self.assertTrue(x.value.value not in [0xdead, 0xdeaddead]) + + def foo(x): + y = x + 1 + dead = 0xdead # noqa + z = y + 2 + deaddead = 0xdeaddead # noqa + ret = z * z + return ret + + test_pipeline = Tester.mk_pipeline((types.intp,)) + no_dce = test_pipeline.compile_to_ir(foo) + removed = check_initial_ir(no_dce) + + test_pipeline = Tester.mk_pipeline((types.intp,)) + w_dce = test_pipeline.compile_to_ir(foo, DCE=True) + check_dce_ir(w_dce) + + # check that the count of initial - removed = dce + self.assertEqual(len(no_dce.blocks[0].body) - len(removed), + len(w_dce.blocks[0].body)) + + def test_find_const_global(self): + """ + Test find_const() for values in globals (ir.Global) and freevars + (ir.FreeVar) that are considered constants for compilation. + """ + FREEVAR_C = 12 + + def foo(a): + b = GLOBAL_B + c = FREEVAR_C + return a + b + c + + f_ir = compiler.run_frontend(foo) + block = f_ir.blocks[0] + const_b = None + const_c = None + + for inst in block.body: + if isinstance(inst, ir.Assign) and inst.target.name == 'b': + const_b = ir_utils.guard( + ir_utils.find_const, f_ir, inst.target) + if isinstance(inst, ir.Assign) and inst.target.name == 'c': + const_c = ir_utils.guard( + ir_utils.find_const, f_ir, inst.target) + + self.assertEqual(const_b, GLOBAL_B) + self.assertEqual(const_c, FREEVAR_C) + + def test_flatten_labels(self): + """ tests flatten_labels """ + def foo(a): + acc = 0 + if a > 3: + acc += 1 + if a > 19: + return 53 + elif a < 1000: + if a >= 12: + acc += 1 + for x in range(10): + acc -= 1 + if acc < 2: + break + else: + acc += 7 + else: + raise ValueError("some string") + # prevents inline of return on py310 + py310_defeat1 = 1 # noqa + py310_defeat2 = 2 # noqa + py310_defeat3 = 3 # noqa + py310_defeat4 = 4 # noqa + return acc + + def bar(a): + acc = 0 + z = 12 + if a > 3: + acc += 1 + z += 12 + if a > 19: + z += 12 + return 53 + elif a < 1000: + if a >= 12: + z += 12 + acc += 1 + for x in range(10): + z += 12 + acc -= 1 + if acc < 2: + break + else: + z += 12 + acc += 7 + else: + raise ValueError("some string") + py310_defeat1 = 1 # noqa + py310_defeat2 = 2 # noqa + py310_defeat3 = 3 # noqa + py310_defeat4 = 4 # noqa + return acc + + def baz(a): + acc = 0 + if a > 3: + acc += 1 + if a > 19: + return 53 + else: # extra control flow in comparison to foo + return 55 + elif a < 1000: + if a >= 12: + acc += 1 + for x in range(10): + acc -= 1 + if acc < 2: + break + else: + acc += 7 + else: + raise ValueError("some string") + py310_defeat1 = 1 # noqa + py310_defeat2 = 2 # noqa + py310_defeat3 = 3 # noqa + py310_defeat4 = 4 # noqa + return acc + + def get_flat_cfg(func): + func_ir = ir_utils.compile_to_numba_ir(func, dict()) + flat_blocks = ir_utils.flatten_labels(func_ir.blocks) + self.assertEqual(max(flat_blocks.keys()) + 1, len(func_ir.blocks)) + return ir_utils.compute_cfg_from_blocks(flat_blocks) + + foo_cfg = get_flat_cfg(foo) + bar_cfg = get_flat_cfg(bar) + baz_cfg = get_flat_cfg(baz) + + self.assertEqual(foo_cfg, bar_cfg) + self.assertNotEqual(foo_cfg, baz_cfg) + + +if __name__ == "__main__": + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_jitmethod.py b/lib/python3.10/site-packages/numba/tests/test_jitmethod.py new file mode 100644 index 0000000000000000000000000000000000000000..437c45b6bbdf00b490b49b569e8ebbe05ce63ad3 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_jitmethod.py @@ -0,0 +1,70 @@ +import unittest + +import numpy as np + +from numba import jit +from numba.tests.support import override_config + + +class TestJITMethod(unittest.TestCase): + def test_bound_jit_method_with_loop_lift(self): + class Something(object): + def __init__(self, x0): + self.x0 = x0 + + @jit(forceobj=True) + def method(self, x): + a = np.empty(shape=5, dtype=np.float32) + x0 = self.x0 + + for i in range(a.shape[0]): + a[i] = x0 * x + + return a + + something = Something(3) + np.testing.assert_array_equal(something.method(5), + np.array([15, 15, 15, 15, 15], dtype=np.float32)) + + # Check that loop lifting in nopython mode was successful + [cres] = something.method.overloads.values() + jitloop = cres.lifted[0] + [loopcres] = jitloop.overloads.values() + self.assertTrue(loopcres.fndesc.native) + + def test_unbound_jit_method(self): + class Something(object): + def __init__(self, x0): + self.x0 = x0 + + @jit(forceobj=True) + def method(self): + return self.x0 + + something = Something(3) + self.assertEqual(Something.method(something), 3) + + +class TestDisabledJIT(unittest.TestCase): + def test_decorated_function(self): + with override_config('DISABLE_JIT', True): + def method(x): + return x + jitted = jit(method) + + self.assertEqual(jitted, method) + self.assertEqual(10, method(10)) + self.assertEqual(10, jitted(10)) + + def test_decorated_function_with_kwargs(self): + with override_config('DISABLE_JIT', True): + def method(x): + return x + jitted = jit(nopython=True)(method) + + self.assertEqual(jitted, method) + self.assertEqual(10, method(10)) + self.assertEqual(10, jitted(10)) + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_listimpl.py b/lib/python3.10/site-packages/numba/tests/test_listimpl.py new file mode 100644 index 0000000000000000000000000000000000000000..f55e2369a4208903951ea1b5d2e910028cd1a2a9 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_listimpl.py @@ -0,0 +1,527 @@ +""" +Testing C implementation of the numba typed-list +""" + +import ctypes +import struct + +from numba.tests.support import TestCase +from numba import _helperlib + + +LIST_OK = 0 +LIST_ERR_INDEX = -1 +LIST_ERR_NO_MEMORY = -2 +LIST_ERR_MUTATED = -3 +LIST_ERR_ITER_EXHAUSTED = -4 +LIST_ERR_IMMUTABLE = -5 + + +class List(object): + """A wrapper around the C-API to provide a minimal list object for + testing. + """ + def __init__(self, tc, item_size, allocated): + """ + Parameters + ---------- + tc : TestCase instance + item_size : int + byte size for the items + allocated : int + number of items to allocate for + """ + self.tc = tc + self.item_size = item_size + self.lp = self.list_new(item_size, allocated) + + # The following methods implement part of the list API + + def __del__(self): + self.tc.numba_list_free(self.lp) + + def __len__(self): + return self.list_length() + + def __setitem__(self, i, item): + return self.list_setitem(i, item) + + def __getitem__(self, i): + return self.list_getitem(i) + + def __iter__(self): + return ListIter(self) + + def __delitem__(self, i): + self.list_delitem(i) + + def handle_index(self, i): + # handling negative indices is done at the compiler level, so we only + # support -1 to be last element of the list here + if i < -1 or len(self) == 0: + IndexError("list index out of range") + elif i == -1: + i = len(self) - 1 + return i + + @property + def allocated(self): + return self.list_allocated() + + @property + def is_mutable(self): + return self.list_is_mutable() + + def set_mutable(self): + return self.list_set_is_mutable(1) + + def set_immutable(self): + return self.list_set_is_mutable(0) + + def append(self, item): + self.list_append(item) + + def pop(self, i=-1): + return self.list_pop(i) + + # The methods below are higher-level wrappers for the C-API wrappers + + def list_new(self, item_size, allocated): + lp = ctypes.c_void_p() + status = self.tc.numba_list_new( + ctypes.byref(lp), item_size, allocated, + ) + self.tc.assertEqual(status, LIST_OK) + return lp + + def list_length(self): + return self.tc.numba_list_length(self.lp) + + def list_allocated(self): + return self.tc.numba_list_allocated(self.lp) + + def list_is_mutable(self): + return self.tc.numba_list_is_mutable(self.lp) + + def list_set_is_mutable(self, is_mutable): + return self.tc.numba_list_set_is_mutable(self.lp, is_mutable) + + def list_setitem(self, i, item): + status = self.tc.numba_list_setitem(self.lp, i, item) + if status == LIST_ERR_INDEX: + raise IndexError("list index out of range") + elif status == LIST_ERR_IMMUTABLE: + raise ValueError("list is immutable") + else: + self.tc.assertEqual(status, LIST_OK) + + def list_getitem(self, i): + i = self.handle_index(i) + item_out_buffer = ctypes.create_string_buffer(self.item_size) + status = self.tc.numba_list_getitem(self.lp, i, item_out_buffer) + if status == LIST_ERR_INDEX: + raise IndexError("list index out of range") + else: + self.tc.assertEqual(status, LIST_OK) + return item_out_buffer.raw + + def list_append(self, item): + status = self.tc.numba_list_append(self.lp, item) + if status == LIST_ERR_IMMUTABLE: + raise ValueError("list is immutable") + self.tc.assertEqual(status, LIST_OK) + + def list_pop(self, i): + # pop is getitem and delitem + i = self.handle_index(i) + item = self.list_getitem(i) + self.list_delitem(i) + return item + + def list_delitem(self, i): + # special case slice + if isinstance(i, slice): + status = self.tc.numba_list_delete_slice(self.lp, + i.start, + i.stop, + i.step) + if status == LIST_ERR_IMMUTABLE: + raise ValueError("list is immutable") + self.tc.assertEqual(status, LIST_OK) + # must be an integer, defer to delitem + else: + i = self.handle_index(i) + status = self.tc.numba_list_delitem(self.lp, i) + if status == LIST_ERR_INDEX: + raise IndexError("list index out of range") + elif status == LIST_ERR_IMMUTABLE: + raise ValueError("list is immutable") + self.tc.assertEqual(status, LIST_OK) + + def list_iter(self, itptr): + self.tc.numba_list_iter(itptr, self.lp) + + def list_iter_next(self, itptr): + bi = ctypes.c_void_p(0) + status = self.tc.numba_list_iter_next( + itptr, ctypes.byref(bi), + ) + if status == LIST_ERR_MUTATED: + raise ValueError('list mutated') + elif status == LIST_ERR_ITER_EXHAUSTED: + raise StopIteration + else: + self.tc.assertGreaterEqual(status, 0) + item = (ctypes.c_char * self.item_size).from_address(bi.value) + return item.value + + +class ListIter(object): + """An iterator for the `List`. + """ + def __init__(self, parent): + self.parent = parent + itsize = self.parent.tc.numba_list_iter_sizeof() + self.it_state_buf = (ctypes.c_char_p * itsize)(0) + self.it = ctypes.cast(self.it_state_buf, ctypes.c_void_p) + self.parent.list_iter(self.it) + + def __iter__(self): + return self + + def __next__(self): + return self.parent.list_iter_next(self.it) + + next = __next__ # needed for py2 only + + +class TestListImpl(TestCase): + def setUp(self): + """Bind to the c_helper library and provide the ctypes wrapper. + """ + list_t = ctypes.c_void_p + iter_t = ctypes.c_void_p + + def wrap(name, restype, argtypes=()): + proto = ctypes.CFUNCTYPE(restype, *argtypes) + return proto(_helperlib.c_helpers[name]) + + # numba_test_list() + self.numba_test_list = wrap( + 'test_list', + ctypes.c_int, + ) + + # numba_list_new(NB_List *l, Py_ssize_t item_size, Py_ssize_t allocated) + self.numba_list_new = wrap( + 'list_new', + ctypes.c_int, + [ctypes.POINTER(list_t), ctypes.c_ssize_t, ctypes.c_ssize_t], + ) + # numba_list_free(NB_List *l) + self.numba_list_free = wrap( + 'list_free', + None, + [list_t], + ) + # numba_list_length(NB_List *l) + self.numba_list_length = wrap( + 'list_length', + ctypes.c_int, + [list_t], + ) + # numba_list_allocated(NB_List *l) + self.numba_list_allocated = wrap( + 'list_allocated', + ctypes.c_int, + [list_t], + ) + # numba_list_is_mutable(NB_List *lp) + self.numba_list_is_mutable = wrap( + 'list_is_mutable', + ctypes.c_int, + [list_t], + ) + # numba_list_set_is_mutable(NB_List *lp, int is_mutable) + self.numba_list_set_is_mutable = wrap( + 'list_set_is_mutable', + None, + [list_t, ctypes.c_int], + ) + # numba_list_setitem(NB_List *l, Py_ssize_t i, const char *item) + self.numba_list_setitem = wrap( + 'list_setitem', + ctypes.c_int, + [list_t, ctypes.c_ssize_t, ctypes.c_char_p], + ) + # numba_list_append(NB_List *l, const char *item) + self.numba_list_append = wrap( + 'list_append', + ctypes.c_int, + [list_t, ctypes.c_char_p], + ) + # numba_list_getitem(NB_List *l, Py_ssize_t i, char *out) + self.numba_list_getitem = wrap( + 'list_getitem', + ctypes.c_int, + [list_t, ctypes.c_ssize_t, ctypes.c_char_p], + ) + # numba_list_delitem(NB_List *l, Py_ssize_t i) + self.numba_list_delitem = wrap( + 'list_delitem', + ctypes.c_int, + [list_t, ctypes.c_ssize_t], + ) + # numba_list_delete_slice(NB_List *l, + # Py_ssize_t start, + # Py_ssize_t stop, + # Py_ssize_t step) + self.numba_list_delete_slice = wrap( + 'list_delete_slice', + ctypes.c_int, + [list_t, ctypes.c_ssize_t, ctypes.c_ssize_t, ctypes.c_ssize_t], + ) + # numba_list_iter_sizeof() + self.numba_list_iter_sizeof = wrap( + 'list_iter_sizeof', + ctypes.c_size_t, + ) + # numba_list_iter(NB_ListIter *it, NB_List *l) + self.numba_list_iter = wrap( + 'list_iter', + None, + [ + iter_t, + list_t, + ], + ) + # numba_list_iter_next(NB_ListIter *it, const char **item_ptr) + self.numba_list_iter_next = wrap( + 'list_iter_next', + ctypes.c_int, + [ + iter_t, # it + ctypes.POINTER(ctypes.c_void_p), # item_ptr + ], + ) + + def test_simple_c_test(self): + # Runs the basic test in C. + ret = self.numba_test_list() + self.assertEqual(ret, 0) + + def test_length(self): + l = List(self, 8, 0) + self.assertEqual(len(l), 0) + + def test_allocation(self): + for i in range(16): + l = List(self, 8, i) + self.assertEqual(len(l), 0) + self.assertEqual(l.allocated, i) + + def test_append_get_string(self): + l = List(self, 8, 1) + l.append(b"abcdefgh") + self.assertEqual(len(l), 1) + r = l[0] + self.assertEqual(r, b"abcdefgh") + + def test_append_get_int(self): + l = List(self, 8, 1) + l.append(struct.pack("q", 1)) + self.assertEqual(len(l), 1) + r = struct.unpack("q", l[0])[0] + self.assertEqual(r, 1) + + def test_append_get_string_realloc(self): + l = List(self, 8, 1) + l.append(b"abcdefgh") + self.assertEqual(len(l), 1) + l.append(b"hijklmno") + self.assertEqual(len(l), 2) + r = l[1] + self.assertEqual(r, b"hijklmno") + + def test_set_item_getitem_index_error(self): + l = List(self, 8, 0) + with self.assertRaises(IndexError): + l[0] + with self.assertRaises(IndexError): + l[0] = b"abcdefgh" + + def test_iter(self): + l = List(self, 1, 0) + values = [b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h'] + for i in values: + l.append(i) + received = [] + for j in l: + received.append(j) + self.assertEqual(values, received) + + def test_pop(self): + l = List(self, 1, 0) + values = [b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h'] + for i in values: + l.append(i) + self.assertEqual(len(l), 8) + + received = l.pop() + self.assertEqual(b'h', received) + self.assertEqual(len(l), 7) + received = [j for j in l] + self.assertEqual(received, values[:-1]) + + received = l.pop(0) + self.assertEqual(b'a', received) + self.assertEqual(len(l), 6) + + received = l.pop(2) + self.assertEqual(b'd', received) + self.assertEqual(len(l), 5) + + expected = [b'b', b'c', b'e', b'f', b'g'] + received = [j for j in l] + self.assertEqual(received, expected) + + def test_pop_index_error(self): + l = List(self, 8, 0) + with self.assertRaises(IndexError): + l.pop() + + def test_pop_byte(self): + l = List(self, 4, 0) + values = [b'aaaa', b'bbbb', b'cccc', b'dddd', + b'eeee', b'ffff', b'gggg', b'hhhhh'] + for i in values: + l.append(i) + self.assertEqual(len(l), 8) + + received = l.pop() + self.assertEqual(b'hhhh', received) + self.assertEqual(len(l), 7) + received = [j for j in l] + self.assertEqual(received, values[:-1]) + + received = l.pop(0) + self.assertEqual(b'aaaa', received) + self.assertEqual(len(l), 6) + + received = l.pop(2) + self.assertEqual(b'dddd', received) + self.assertEqual(len(l), 5) + + expected = [b'bbbb', b'cccc', b'eeee', b'ffff', b'gggg'] + received = [j for j in l] + self.assertEqual(received, expected) + + def test_delitem(self): + l = List(self, 1, 0) + values = [b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h'] + for i in values: + l.append(i) + self.assertEqual(len(l), 8) + + # delete first item + del l[0] + self.assertEqual(len(l), 7) + self.assertEqual(list(l), values[1:]) + # delete last item + del l[-1] + self.assertEqual(len(l), 6) + self.assertEqual(list(l), values[1:-1]) + # delete item from middle + del l[2] + self.assertEqual(len(l), 5) + self.assertEqual(list(l), [b'b', b'c', b'e', b'f', b'g']) + + def test_delete_slice(self): + l = List(self, 1, 0) + values = [b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h'] + for i in values: + l.append(i) + self.assertEqual(len(l), 8) + + # delete every second item + # no slice default normalization here, be explicit about start anb stop + del l[0:8:2] + self.assertEqual(len(l), 4) + self.assertEqual(list(l), values[1:8:2]) + + # delete first item + del l[0:1:1] + self.assertEqual(len(l), 3) + self.assertEqual(list(l), [b'd', b'f', b'h']) + + # delete last item + del l[2:3:1] + self.assertEqual(len(l), 2) + self.assertEqual(list(l), [b'd', b'f']) + + # delete all left items + del l[0:2:1] + self.assertEqual(len(l), 0) + self.assertEqual(list(l), []) + + def check_sizing(self, item_size, nmax): + # Helper to verify different item_sizes + l = List(self, item_size, 0) + + def make_item(v): + tmp = "{:0{}}".format(nmax - v - 1, item_size).encode("latin-1") + return tmp[:item_size] + + for i in range(nmax): + l.append(make_item(i)) + + self.assertEqual(len(l), nmax) + + for i in range(nmax): + self.assertEqual(l[i], make_item(i)) + + def test_sizing(self): + # Check different sizes of the key & value. + for i in range(1, 16): + self.check_sizing(item_size=i, nmax=2**i) + + def test_mutability(self): + # setup and populate a singleton + l = List(self, 8, 1) + one = struct.pack("q", 1) + l.append(one) + self.assertTrue(l.is_mutable) + self.assertEqual(len(l), 1) + r = struct.unpack("q", l[0])[0] + self.assertEqual(r, 1) + + # set to immutable and test guards + l.set_immutable() + self.assertFalse(l.is_mutable) + # append + with self.assertRaises(ValueError) as raises: + l.append(one) + self.assertIn("list is immutable", str(raises.exception)) + # setitem + with self.assertRaises(ValueError) as raises: + l[0] = one + self.assertIn("list is immutable", str(raises.exception)) + # pop + with self.assertRaises(ValueError) as raises: + l.pop() + self.assertIn("list is immutable", str(raises.exception)) + # delitem with index + with self.assertRaises(ValueError) as raises: + del l[0] + self.assertIn("list is immutable", str(raises.exception)) + # delitem with slice + with self.assertRaises(ValueError) as raises: + del l[0:1:1] + self.assertIn("list is immutable", str(raises.exception)) + l.set_mutable() + + # check that nothing has changed + self.assertTrue(l.is_mutable) + self.assertEqual(len(l), 1) + r = struct.unpack("q", l[0])[0] + self.assertEqual(r, 1) diff --git a/lib/python3.10/site-packages/numba/tests/test_llvm_version_check.py b/lib/python3.10/site-packages/numba/tests/test_llvm_version_check.py new file mode 100644 index 0000000000000000000000000000000000000000..bea99fed9550a250075811cd8531f6c0b048dd66 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_llvm_version_check.py @@ -0,0 +1,42 @@ +import importlib +import sys + +import unittest + + +class TestLlvmVersion(unittest.TestCase): + + def test_llvmlite_version(self): + # test the system it's running on + import llvmlite + import numba + self.assertTrue(numba.__version__) + + llvmlite_version = llvmlite.__version__ + def cleanup(): + llvmlite.__version__ = llvmlite_version + self.addCleanup(cleanup) + + # explicitly test all 3 cases of version string + ver = numba._min_llvmlite_version + version_pass = '%d.%d.%d' % ver + git_version_pass = '%d.%d.%d-10-g92584ed' % ver + rc_version_pass = '%d.%d.%drc1' % (ver[0], ver[1], ver[2] + 1) + version_fail = '%d.%d.0' % (ver[0], ver[1] - 1) + git_version_fail = '%d.%d.9-10-g92584ed' % (ver[0], ver[1] - 1) + + ver_pass = (version_pass, git_version_pass, rc_version_pass) + ver_fail = (version_fail, git_version_fail) + for v in ver_pass: + llvmlite.__version__ = v + importlib.reload(numba) + self.assertTrue(numba.__version__) + + for v in ver_fail: + with self.assertRaises(ImportError): + llvmlite.__version__ = v + importlib.reload(numba) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_mandelbrot.py b/lib/python3.10/site-packages/numba/tests/test_mandelbrot.py new file mode 100644 index 0000000000000000000000000000000000000000..7a9fc2dd1411e6f52c77654e9dd51e87a612b0a0 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_mandelbrot.py @@ -0,0 +1,28 @@ +import unittest +from numba import njit +from numba.core import types + + +def is_in_mandelbrot(c): + i = 0 + z = 0.0j + for i in range(100): + z = z ** 2 + c + if (z.real * z.real + z.imag * z.imag) >= 4: + return False + return True + + +class TestMandelbrot(unittest.TestCase): + + def test_mandelbrot(self): + pyfunc = is_in_mandelbrot + cfunc = njit((types.complex64,))(pyfunc) + + points = [0+0j, 1+0j, 0+1j, 1+1j, 0.1+0.1j] + for p in points: + self.assertEqual(cfunc(p), pyfunc(p)) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_mathlib.py b/lib/python3.10/site-packages/numba/tests/test_mathlib.py new file mode 100644 index 0000000000000000000000000000000000000000..82863574ef40d4ef75decb7dfe3e4a814e29e568 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_mathlib.py @@ -0,0 +1,559 @@ +import itertools +import math +import sys +import unittest +import warnings + +import numpy as np + +from numba import njit, types +from numba.tests.support import TestCase +from numba.np import numpy_support + + +def sin(x): + return math.sin(x) + + +def cos(x): + return math.cos(x) + + +def tan(x): + return math.tan(x) + + +def sinh(x): + return math.sinh(x) + + +def cosh(x): + return math.cosh(x) + + +def tanh(x): + return math.tanh(x) + + +def asin(x): + return math.asin(x) + + +def acos(x): + return math.acos(x) + + +def atan(x): + return math.atan(x) + + +def atan2(y, x): + return math.atan2(y, x) + + +def asinh(x): + return math.asinh(x) + + +def acosh(x): + return math.acosh(x) + + +def atanh(x): + return math.atanh(x) + + +def sqrt(x): + return math.sqrt(x) + + +def npy_sqrt(x): + return np.sqrt(x) + + +def exp(x): + return math.exp(x) + + +def expm1(x): + return math.expm1(x) + + +def log(x): + return math.log(x) + + +def log1p(x): + return math.log1p(x) + + +def log10(x): + return math.log10(x) + + +def log2(x): + return math.log2(x) + + +def floor(x): + return math.floor(x) + + +def ceil(x): + return math.ceil(x) + + +def trunc(x): + return math.trunc(x) + + +def isnan(x): + return math.isnan(x) + + +def isinf(x): + return math.isinf(x) + + +def isfinite(x): + return math.isfinite(x) + + +def hypot(x, y): + return math.hypot(x, y) + + +def nextafter(x, y): + return math.nextafter(x, y) + + +def degrees(x): + return math.degrees(x) + + +def radians(x): + return math.radians(x) + + +def erf(x): + return math.erf(x) + + +def erfc(x): + return math.erfc(x) + + +def gamma(x): + return math.gamma(x) + + +def lgamma(x): + return math.lgamma(x) + + +def pow(x, y): + return math.pow(x, y) + +def gcd(x, y): + return math.gcd(x, y) + +def copysign(x, y): + return math.copysign(x, y) + + +def frexp(x): + return math.frexp(x) + + +def ldexp(x, e): + return math.ldexp(x, e) + + +def get_constants(): + return math.pi, math.e + + +class TestMathLib(TestCase): + + def test_constants(self): + cfunc = njit(get_constants) + self.assertPreciseEqual(cfunc(), cfunc.py_func()) + + def run_unary(self, pyfunc, x_types, x_values, prec='exact', **kwargs): + cfunc = njit(pyfunc) + for tx, vx in zip(x_types, x_values): + got = cfunc(vx) + expected = pyfunc(vx) + actual_prec = 'single' if tx is types.float32 else prec + msg = 'for input %r' % (vx,) + self.assertPreciseEqual(got, expected, prec=actual_prec, msg=msg, + **kwargs) + + def run_binary(self, pyfunc, x_types, x_values, y_values, prec='exact'): + cfunc = njit(pyfunc) + for ty, x, y in zip(x_types, x_values, y_values): + got = cfunc(x, y) + expected = pyfunc(x, y) + actual_prec = 'single' if ty is types.float32 else prec + msg = 'for inputs (%r, %r)' % (x, y) + self.assertPreciseEqual(got, expected, prec=actual_prec, msg=msg) + + def check_predicate_func(self, pyfunc): + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float32, types.float32, + types.float64, types.float64, types.float64] + x_values = [0, 0, 0, 0, 0, 0, + float('inf'), 0.0, float('nan'), + float('inf'), 0.0, float('nan')] + self.run_unary(pyfunc, x_types, x_values) + + def test_sin(self): + pyfunc = sin + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [-2, -1, -2, 2, 1, 2, .1, .2] + self.run_unary(pyfunc, x_types, x_values) + + @unittest.skipIf(sys.platform == 'win32', + "not exactly equal on win32 (issue #597)") + def test_cos(self): + pyfunc = cos + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [-2, -1, -2, 2, 1, 2, .1, .2] + self.run_unary(pyfunc, x_types, x_values) + + def test_tan(self): + pyfunc = tan + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [-2, -1, -2, 2, 1, 2, .1, .2] + self.run_unary(pyfunc, x_types, x_values) + + def test_sqrt(self): + pyfunc = sqrt + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [2, 1, 2, 2, 1, 2, .1, .2] + self.run_unary(pyfunc, x_types, x_values) + + def test_npy_sqrt(self): + pyfunc = npy_sqrt + x_values = [2, 1, 2, 2, 1, 2, .1, .2] + # XXX poor precision for int16 inputs + x_types = [types.int16, types.uint16] + self.run_unary(pyfunc, x_types, x_values, prec='single') + x_types = [types.int32, types.int64, + types.uint32, types.uint64, + types.float32, types.float64] + self.run_unary(pyfunc, x_types, x_values) + + def test_exp(self): + pyfunc = exp + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [-2, -1, -2, 2, 1, 2, .1, .2] + self.run_unary(pyfunc, x_types, x_values) + + def test_expm1(self): + pyfunc = expm1 + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [-2, -1, -2, 2, 1, 2, .1, .2] + self.run_unary(pyfunc, x_types, x_values) + + def test_log(self): + pyfunc = log + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 10, 100, 1000, 100000, 1000000, 0.1, 1.1] + self.run_unary(pyfunc, x_types, x_values) + + def test_log1p(self): + pyfunc = log1p + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 10, 100, 1000, 100000, 1000000, 0.1, 1.1] + self.run_unary(pyfunc, x_types, x_values) + + def test_log10(self): + pyfunc = log10 + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 10, 100, 1000, 100000, 1000000, 0.1, 1.1] + self.run_unary(pyfunc, x_types, x_values) + + def test_log2(self): + pyfunc = log2 + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 10, 100, 1000, 100000, 1000000, 0.1, 1.1] + self.run_unary(pyfunc, x_types, x_values) + + def test_asin(self): + pyfunc = asin + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 1, 1, 1, 1, 1, 1., 1.] + self.run_unary(pyfunc, x_types, x_values) + + def test_acos(self): + pyfunc = acos + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 1, 1, 1, 1, 1, 1., 1.] + self.run_unary(pyfunc, x_types, x_values) + + def test_atan(self): + pyfunc = atan + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [-2, -1, -2, 2, 1, 2, .1, .2] + self.run_unary(pyfunc, x_types, x_values) + + def test_atan2(self): + pyfunc = atan2 + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [-2, -1, -2, 2, 1, 2, .1, .2] + y_values = [x * 2 for x in x_values] + self.run_binary(pyfunc, x_types, x_values, y_values) + + def test_asinh(self): + pyfunc = asinh + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 1, 1, 1, 1, 1, 1., 1.] + self.run_unary(pyfunc, x_types, x_values, prec='double') + + def test_acosh(self): + pyfunc = acosh + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 1, 1, 1, 1, 1, 1., 1.] + self.run_unary(pyfunc, x_types, x_values) + + def test_atanh(self): + pyfunc = atanh + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [0, 0, 0, 0, 0, 0, 0.1, 0.1] + self.run_unary(pyfunc, x_types, x_values, prec='double') + + def test_sinh(self): + pyfunc = sinh + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 1, 1, 1, 1, 1, 1., 1.] + self.run_unary(pyfunc, x_types, x_values) + + def test_cosh(self): + pyfunc = cosh + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 1, 1, 1, 1, 1, 1., 1.] + self.run_unary(pyfunc, x_types, x_values) + + def test_tanh(self): + pyfunc = tanh + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [0, 0, 0, 0, 0, 0, 0.1, 0.1] + self.run_unary(pyfunc, x_types, x_values) + + def test_floor(self): + pyfunc = floor + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [0, 0, 0, 0, 0, 0, 0.1, 1.9] + self.run_unary(pyfunc, x_types, x_values) + + def test_ceil(self): + pyfunc = ceil + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [0, 0, 0, 0, 0, 0, 0.1, 1.9] + self.run_unary(pyfunc, x_types, x_values) + + def test_trunc(self): + pyfunc = trunc + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [0, 0, 0, 0, 0, 0, 0.1, 1.9] + self.run_unary(pyfunc, x_types, x_values) + + def test_isnan(self): + self.check_predicate_func(isnan) + + def test_isinf(self): + self.check_predicate_func(isinf) + + def test_isfinite(self): + self.check_predicate_func(isfinite) + + def test_hypot(self): + pyfunc = hypot + x_types = [types.int64, types.uint64, + types.float32, types.float64] + x_values = [1, 2, 3, 4, 5, 6, .21, .34] + y_values = [x + 2 for x in x_values] + # Issue #563: precision issues with math.hypot() under Windows. + prec = 'single' + self.run_binary(pyfunc, x_types, x_values, y_values, prec) + # Check that values that overflow in naive implementations do not + # in the numba impl + + def naive_hypot(x, y): + return math.sqrt(x * x + y * y) + + cfunc = njit(pyfunc) + for fltty in (types.float32, types.float64): + dt = numpy_support.as_dtype(fltty).type + val = dt(np.finfo(dt).max / 30.) + nb_ans = cfunc(val, val) + self.assertPreciseEqual(nb_ans, pyfunc(val, val), prec='single') + self.assertTrue(np.isfinite(nb_ans)) + + with warnings.catch_warnings(): + warnings.simplefilter("error", RuntimeWarning) + self.assertRaisesRegex(RuntimeWarning, + 'overflow encountered in .*scalar', + naive_hypot, val, val) + + def test_nextafter(self): + pyfunc = nextafter + x_types = [types.float32, types.float64, + types.int32, types.int64, + types.uint32, types.uint64] + x_values = [0.0, .21, .34, 1005382.042, -25.328] + y1_values = [x + 2 for x in x_values] + y2_values = [x - 2 for x in x_values] + + self.run_binary(pyfunc, x_types, x_values, y1_values) + self.run_binary(pyfunc, x_types, x_values, y2_values) + + # Test using pos/neg inf + self.run_binary(pyfunc, x_types, [0.0, -.5, .5], [math.inf]*3) + self.run_binary(pyfunc, x_types, [0.0, -.5, .5], [-math.inf]*3) + + # if both args to nextafter are equal, then it is returned unchanged. + self.run_binary(pyfunc, x_types, x_values, x_values) + + def test_degrees(self): + pyfunc = degrees + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 1, 1, 1, 1, 1, 1., 1.] + self.run_unary(pyfunc, x_types, x_values) + + def test_radians(self): + pyfunc = radians + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [1, 1, 1, 1, 1, 1, 1., 1.] + self.run_unary(pyfunc, x_types, x_values) + + def test_erf(self): + pyfunc = erf + x_values = [1., 1., -1., -0.0, 0.0, 0.5, 5, float('inf')] + x_types = [types.float32, types.float64] * (len(x_values) // 2) + self.run_unary(pyfunc, x_types, x_values, prec='double', ulps=2) + + def test_erfc(self): + pyfunc = erfc + x_values = [1., 1., -1., -0.0, 0.0, 0.5, 5, float('inf')] + x_types = [types.float32, types.float64] * (len(x_values) // 2) + self.run_unary(pyfunc, x_types, x_values, prec='double', ulps=4) + + def test_gamma(self): + pyfunc = gamma + x_values = [1., -0.9, -0.5, 0.5] + x_types = [types.float32, types.float64] * (len(x_values) // 2) + self.run_unary(pyfunc, x_types, x_values, prec='double', ulps=3) + x_values = [-0.1, 0.1, 2.5, 10.1, 50., float('inf')] + x_types = [types.float64] * len(x_values) + self.run_unary(pyfunc, x_types, x_values, prec='double', ulps=8) + + def test_lgamma(self): + pyfunc = lgamma + x_values = [1., -0.9, -0.1, 0.1, 200., 1e10, 1e30, float('inf')] + x_types = [types.float32, types.float64] * (len(x_values) // 2) + self.run_unary(pyfunc, x_types, x_values, prec='double') + + def test_pow(self): + pyfunc = pow + x_types = [types.int16, types.int32, types.int64, + types.uint16, types.uint32, types.uint64, + types.float32, types.float64] + x_values = [-2, -1, -2, 2, 1, 2, .1, .2] + y_values = [x * 2 for x in x_values] + self.run_binary(pyfunc, x_types, x_values, y_values) + + def test_gcd(self): + from itertools import product, repeat, chain + pyfunc = gcd + signed_args = product( + sorted(types.signed_domain), *repeat((-2, -1, 0, 1, 2, 7, 10), 2) + ) + unsigned_args = product( + sorted(types.unsigned_domain), *repeat((0, 1, 2, 7, 9, 16), 2) + ) + x_types, x_values, y_values = zip(*chain(signed_args, unsigned_args)) + self.run_binary(pyfunc, x_types, x_values, y_values) + + def test_copysign(self): + pyfunc = copysign + value_types = [types.float32, types.float64] + values = [-2, -1, -0.0, 0.0, 1, 2, float('-inf'), float('inf'), + float('nan')] + x_types, x_values, y_values = list(zip( + *itertools.product(value_types, values, values))) + self.run_binary(pyfunc, x_types, x_values, y_values) + + def test_frexp(self): + pyfunc = frexp + x_types = [types.float32, types.float64] + x_values = [-2.5, -0.0, 0.0, 3.5, + float('-inf'), float('inf'), float('nan')] + self.run_unary(pyfunc, x_types, x_values, prec='exact') + + def test_ldexp(self): + pyfunc = ldexp + cfunc = njit(pyfunc) + for fltty in (types.float32, types.float64): + for args in [(2.5, -2), (2.5, 1), (0.0, 0), (0.0, 1), + (-0.0, 0), (-0.0, 1), + (float('inf'), 0), (float('-inf'), 0), + (float('nan'), 0)]: + msg = 'for input %r' % (args,) + self.assertPreciseEqual(cfunc(*args), pyfunc(*args)) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_misc_coverage_support.py b/lib/python3.10/site-packages/numba/tests/test_misc_coverage_support.py new file mode 100644 index 0000000000000000000000000000000000000000..7dee5cdd5054dddbefffee8775fda191e46ab01b --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_misc_coverage_support.py @@ -0,0 +1,75 @@ +import unittest +from unittest.mock import patch + +from numba.tests.support import TestCase + +from numba import njit +from numba.core import ir +from numba.misc.coverage_support import NotifyLocBase, _the_registry + + +class TestMiscCoverageSupport(TestCase): + @TestCase.run_test_in_subprocess(envvars={"NUMBA_JIT_COVERAGE": "1"}) + def test_custom_loc_notifier(self): + class MyNotify(NotifyLocBase): + records = [] + + def notify(self, loc): + self.records.append(("NOTIFY", loc)) + + def close(self): + self.records.append(("CLOSE", None)) + + # Patch to install registry for testing + new_the_registry = _the_registry + [MyNotify] + gv = "numba.misc.coverage_support._the_registry" + with patch(gv, new_the_registry): + + @njit + def foo(): + return 123 + + res = foo() + + self.assertEqual(res, 123) + + # offset by +2 because: + # +1 for the decorator + # +1 for the `def` line + first_offset = 2 + offset = foo.__code__.co_firstlineno + first_offset + loc = ir.Loc(__file__, 1) + self.assertIn(("NOTIFY", loc.with_lineno(offset)), MyNotify.records) + self.assertIn(("CLOSE", None), MyNotify.records) + + # Test dead branch pruned + with patch(gv, new_the_registry): + cond = False + + @njit + def foo(): + if cond: + return 321 + return 123 + + res = foo() + + self.assertEqual(res, 123) + + # `if cond` line is compiled + offset = foo.__code__.co_firstlineno + first_offset + self.assertIn(("NOTIFY", loc.with_lineno(offset)), MyNotify.records) + + # ` return 321` line is not compiled + self.assertNotIn( + ("NOTIFY", loc.with_lineno(offset + 1)), MyNotify.records + ) + + # ` return 123` line is compiled + self.assertIn(("NOTIFY", loc.with_lineno(offset + 2)), MyNotify.records) + + self.assertIn(("CLOSE", None), MyNotify.records) + + +if __name__ == "__main__": + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_nested_calls.py b/lib/python3.10/site-packages/numba/tests/test_nested_calls.py new file mode 100644 index 0000000000000000000000000000000000000000..679bc4af98680e389fc911f544c18b103b468bbe --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_nested_calls.py @@ -0,0 +1,153 @@ +""" +Test problems in nested calls. +Usually due to invalid type conversion between function boundaries. +""" + + +from numba import int32, int64 +from numba import jit +from numba.core import types +from numba.extending import overload +from numba.tests.support import TestCase, tag +import unittest + + +@jit(nopython=True) +def f_inner(a, b, c): + return a, b, c + +def f(x, y, z): + return f_inner(x, c=y, b=z) + +@jit(nopython=True) +def g_inner(a, b=2, c=3): + return a, b, c + +def g(x, y, z): + return g_inner(x, b=y), g_inner(a=z, c=x) + +@jit(nopython=True) +def star_inner(a=5, *b): + return a, b + +def star(x, y, z): + return star_inner(a=x), star_inner(x, y, z) + +def star_call(x, y, z): + return star_inner(x, *y), star_inner(*z) + +@jit(nopython=True) +def argcast_inner(a, b): + if b: + # Here `a` is unified to int64 (from int32 originally) + a = int64(0) + return a + +def argcast(a, b): + return argcast_inner(int32(a), b) + + +def generated_inner(x, y=5, z=6): + assert 0, "unreachable" + + +@overload(generated_inner) +def ol_generated_inner(x, y=5, z=6): + if isinstance(x, types.Complex): + def impl(x, y=5, z=6): + return x + y, z + else: + def impl(x, y=5, z=6): + return x - y, z + return impl + + +def call_generated(a, b): + return generated_inner(a, z=b) + + +class TestNestedCall(TestCase): + + def compile_func(self, pyfunc, objmode=False): + def check(*args, **kwargs): + expected = pyfunc(*args, **kwargs) + result = f(*args, **kwargs) + self.assertPreciseEqual(result, expected) + flags = dict(forceobj=True) if objmode else dict(nopython=True) + f = jit(**flags)(pyfunc) + return f, check + + def test_boolean_return(self): + @jit(nopython=True) + def inner(x): + return not x + + @jit(nopython=True) + def outer(x): + if inner(x): + return True + else: + return False + + self.assertFalse(outer(True)) + self.assertTrue(outer(False)) + + def test_named_args(self, objmode=False): + """ + Test a nested function call with named (keyword) arguments. + """ + cfunc, check = self.compile_func(f, objmode) + check(1, 2, 3) + check(1, y=2, z=3) + + def test_named_args_objmode(self): + self.test_named_args(objmode=True) + + def test_default_args(self, objmode=False): + """ + Test a nested function call using default argument values. + """ + cfunc, check = self.compile_func(g, objmode) + check(1, 2, 3) + check(1, y=2, z=3) + + def test_default_args_objmode(self): + self.test_default_args(objmode=True) + + def test_star_args(self): + """ + Test a nested function call to a function with *args in its signature. + """ + cfunc, check = self.compile_func(star) + check(1, 2, 3) + + def test_star_call(self, objmode=False): + """ + Test a function call with a *args. + """ + cfunc, check = self.compile_func(star_call, objmode) + check(1, (2,), (3,)) + + def test_star_call_objmode(self): + self.test_star_call(objmode=True) + + def test_argcast(self): + """ + Issue #1488: implicitly casting an argument variable should not + break nested calls. + """ + cfunc, check = self.compile_func(argcast) + check(1, 0) + check(1, 1) + + def test_call_generated(self): + """ + Test a nested function call to a generated jit function. + """ + cfunc = jit(nopython=True)(call_generated) + self.assertPreciseEqual(cfunc(1, 2), (-4, 2)) + self.assertPreciseEqual(cfunc(1j, 2), (1j + 5, 2)) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_new_type_system.py b/lib/python3.10/site-packages/numba/tests/test_new_type_system.py new file mode 100644 index 0000000000000000000000000000000000000000..fe1a198b9514b8742076e2ac9fa83b49946ac6d1 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_new_type_system.py @@ -0,0 +1,37 @@ +import numpy as np + +from numba import njit, config +from numba.tests.support import TestCase + + +class TestTypes(TestCase): + + def setUp(self) -> None: + if config.USE_LEGACY_TYPE_SYSTEM: + self.skipTest("This test is only for the new type system") + return super().setUp() + + def test_return_types(self): + @njit + def foo(x): + return x + + cases = [ + # Python types + 1, + 1.2, + (1 + 2j), + True, + # NumPy types + np.int32(1), + np.float64(1.2), + np.complex64(1 + 2j), + np.complex128(1 + 2j), + np.bool_(True), + np.datetime64('2020-01-01'), + np.timedelta64(1, 'D'), + ] + + for case in cases: + self.assertEqual(foo(case), case) + self.assertEqual(type(foo(case)), type(case)) diff --git a/lib/python3.10/site-packages/numba/tests/test_npdatetime.py b/lib/python3.10/site-packages/numba/tests/test_npdatetime.py new file mode 100644 index 0000000000000000000000000000000000000000..4ecff9ad09856a06c82b41e4b36cc470a87e3518 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_npdatetime.py @@ -0,0 +1,1180 @@ +""" +Test np.datetime64 and np.timedelta64 support. +""" + +# NOTE: datetime64 and timedelta64 ufuncs are tested in test_ufuncs. + + +import contextlib +import itertools +import re +import unittest +import warnings + +import numpy as np + +from numba import jit, vectorize, njit +from numba.np.numpy_support import numpy_version +from numba.core import types, config +from numba.core.errors import TypingError +from numba.tests.support import TestCase, tag, skip_parfors_unsupported +from numba.np import npdatetime_helpers, numpy_support + +TIMEDELTA_M = np.dtype('timedelta64[M]') +TIMEDELTA_Y = np.dtype('timedelta64[Y]') + +def value_unit(val): + ty = numpy_support.from_dtype(val.dtype) + return ty.unit + + +date_units = ('Y', 'M') +time_units = ('W', 'D', 'h', 'm', 's', 'ms', 'us', 'ns', 'ps', 'fs', 'as') +# All except generic ("") +all_units = date_units + time_units + + +def add_usecase(x, y): + return x + y + +def sub_usecase(x, y): + return x - y + +def mul_usecase(x, y): + return x * y + +def div_usecase(x, y): + return x / y + +def floordiv_usecase(x, y): + return x // y + +def eq_usecase(x, y): + return x == y + +def ne_usecase(x, y): + return x != y + +def lt_usecase(x, y): + return x < y + +def le_usecase(x, y): + return x <= y + +def gt_usecase(x, y): + return x > y + +def ge_usecase(x, y): + return x >= y + +def pos_usecase(x): + return +x + +def neg_usecase(x): + return -x + +def abs_usecase(x): + return abs(x) + +def hash_usecase(x): + return hash(x) + +def min_usecase(x, y): + return min(x, y) + +def max_usecase(x, y): + return max(x, y) + +def int_cast_usecase(x): + return int(x) + +def make_add_constant(const): + def add_constant(x): + return x + const + return add_constant + + +class TestModuleHelpers(TestCase): + """ + Test the various helpers in numba.npdatetime_helpers. + """ + + def test_can_cast_timedelta(self): + f = npdatetime_helpers.can_cast_timedelta_units + for a, b in itertools.product(date_units, time_units): + self.assertFalse(f(a, b), (a, b)) + self.assertFalse(f(b, a), (a, b)) + for unit in all_units: + self.assertFalse(f(unit, '')) + self.assertTrue(f('', unit)) + for unit in all_units + ('',): + self.assertTrue(f(unit, unit)) + + def check_units_group(group): + for i, a in enumerate(group): + for b in group[:i]: + # large into smaller is ok + self.assertTrue(f(b, a)) + # small into larger is not + self.assertFalse(f(a, b)) + + check_units_group(date_units) + check_units_group(time_units) + + def test_timedelta_conversion(self): + f = npdatetime_helpers.get_timedelta_conversion_factor + for unit in all_units + ('',): + self.assertEqual(f(unit, unit), 1) + for unit in all_units: + self.assertEqual(f('', unit), 1) + for a, b in itertools.product(time_units, date_units): + self.assertIs(f(a, b), None) + self.assertIs(f(b, a), None) + + def check_units_group(group): + for i, a in enumerate(group): + for b in group[:i]: + self.assertGreater(f(b, a), 1, (b, a)) + self.assertIs(f(a, b), None) + + check_units_group(date_units) + check_units_group(time_units) + + # Check some hand-picked values + self.assertEqual(f('Y', 'M'), 12) + self.assertEqual(f('W', 'h'), 24 * 7) + self.assertEqual(f('W', 'm'), 24 * 7 * 60) + self.assertEqual(f('W', 'us'), 24 * 7 * 3600 * 1000 * 1000) + + def test_datetime_timedelta_scaling(self): + f = npdatetime_helpers.get_datetime_timedelta_conversion + def check_error(dt_unit, td_unit): + with self.assertRaises(RuntimeError): + f(dt_unit, td_unit) + # Cannot combine a Y or M timedelta64 with a finer-grained datetime64 + for dt_unit, td_unit in itertools.product(time_units, date_units): + check_error(dt_unit, td_unit) + # Sanity check that all other unit pairs can be converted, we'll + # check individual results below + for dt_unit, td_unit in itertools.product(time_units, time_units): + f(dt_unit, td_unit) + for dt_unit, td_unit in itertools.product(date_units, time_units): + f(dt_unit, td_unit) + for dt_unit, td_unit in itertools.product(date_units, date_units): + f(dt_unit, td_unit) + # No-op conversions + for unit in all_units: + self.assertEqual(f(unit, unit), (unit, 1, 1)) + self.assertEqual(f(unit, ''), (unit, 1, 1)) + self.assertEqual(f('', unit), ('', 1, 1)) + self.assertEqual(f('', ''), ('', 1, 1)) + # "Regular" values + self.assertEqual(f('Y', 'M'), ('M', 12, 1)) + self.assertEqual(f('M', 'Y'), ('M', 1, 12)) + self.assertEqual(f('W', 'D'), ('D', 7, 1)) + self.assertEqual(f('D', 'W'), ('D', 1, 7)) + self.assertEqual(f('W', 's'), ('s', 7 * 24 * 3600, 1)) + self.assertEqual(f('s', 'W'), ('s', 1, 7 * 24 * 3600)) + self.assertEqual(f('s', 'as'), ('as', 1000 ** 6, 1)) + self.assertEqual(f('as', 's'), ('as', 1, 1000 ** 6)) + # "Interesting" values + self.assertEqual(f('Y', 'D'), ('D', 97 + 400 * 365, 400)) + self.assertEqual(f('Y', 'W'), ('W', 97 + 400 * 365, 400 * 7)) + self.assertEqual(f('M', 'D'), ('D', 97 + 400 * 365, 400 * 12)) + self.assertEqual(f('M', 'W'), ('W', 97 + 400 * 365, 400 * 12 * 7)) + self.assertEqual(f('Y', 's'), ('s', (97 + 400 * 365) * 24 * 3600, 400)) + self.assertEqual(f('M', 's'), ('s', (97 + 400 * 365) * 24 * 3600, 400 * 12)) + + def test_combine_datetime_timedelta_units(self): + f = npdatetime_helpers.combine_datetime_timedelta_units + for unit in all_units: + self.assertEqual(f(unit, unit), unit) + self.assertEqual(f('', unit), unit) + self.assertEqual(f(unit, ''), unit) + self.assertEqual(f('', ''), '') + for dt_unit, td_unit in itertools.product(time_units, date_units): + self.assertIs(f(dt_unit, td_unit), None) + for dt_unit, td_unit in itertools.product(date_units, time_units): + self.assertEqual(f(dt_unit, td_unit), td_unit) + + def test_same_kind(self): + f = npdatetime_helpers.same_kind + for u in all_units: + self.assertTrue(f(u, u)) + A = ('Y', 'M', 'W', 'D') + B = ('h', 'm', 's', 'ms', 'us', 'ns', 'ps', 'fs', 'as') + for a, b in itertools.product(A, A): + self.assertTrue(f(a, b)) + for a, b in itertools.product(B, B): + self.assertTrue(f(a, b)) + for a, b in itertools.product(A, B): + self.assertFalse(f(a, b)) + self.assertFalse(f(b, a)) + + +TD = np.timedelta64 +DT = np.datetime64 + + +class TestMiscCompiling(TestCase): + + def test_jit_explicit_signature(self): + def _check_explicit_signature(sig): + f = jit(sig, nopython=True)(add_usecase) + # Just a sanity check + args = DT(1, 'ms'), TD(2, 'us') + expected = add_usecase(*args) + self.assertPreciseEqual(f(*args), expected) + + # Test passing the signature in object form + sig = types.NPDatetime('us')(types.NPDatetime('ms'), types.NPTimedelta('us')) + _check_explicit_signature(sig) + # Same with the signature in string form + sig = "NPDatetime('us')(NPDatetime('ms'), NPTimedelta('us'))" + _check_explicit_signature(sig) + + def test_vectorize_explicit_signature(self): + def _check_explicit_signature(sig): + f = vectorize([sig], nopython=True)(mul_usecase) + # This isn't really right but we can't do better than this, + # since Numpy's ufuncs don't store the metadata of return types. + # Related to https://github.com/numpy/numpy/issues/5429 + self.assertPreciseEqual(f(TD(2), 3), TD(6)) + + # Test passing the signature in object form (issue #917) + sig = types.NPTimedelta('s')(types.NPTimedelta('s'), types.int64) + _check_explicit_signature(sig) + # Same with the signature in string form + sig = "NPTimedelta('s')(NPTimedelta('s'), int64)" + _check_explicit_signature(sig) + + def test_constant_datetime(self): + def check(const): + pyfunc = make_add_constant(const) + f = jit(nopython=True)(pyfunc) + x = TD(4, 'D') + expected = pyfunc(x) + self.assertPreciseEqual(f(x), expected) + check(DT('2001-01-01')) + check(DT('NaT', 'D')) + + def test_constant_timedelta(self): + def check(const): + pyfunc = make_add_constant(const) + f = jit(nopython=True)(pyfunc) + x = TD(4, 'D') + expected = pyfunc(x) + self.assertPreciseEqual(f(x), expected) + check(TD(4, 'D')) + check(TD(-4, 'D')) + check(TD('NaT', 'D')) + + +class TestTimedeltaArithmetic(TestCase): + + jitargs = dict(forceobj=True) + + def jit(self, pyfunc): + return jit(**self.jitargs)(pyfunc) + + def test_add(self): + f = self.jit(add_usecase) + def check(a, b, expected): + self.assertPreciseEqual(f(a, b), expected) + self.assertPreciseEqual(f(b, a), expected) + + check(TD(1), TD(2), TD(3)) + check(TD(1, 's'), TD(2, 's'), TD(3, 's')) + # Implicit unit promotion + check(TD(1, 's'), TD(2, 'us'), TD(1000002, 'us')) + check(TD(1, 'W'), TD(2, 'D'), TD(9, 'D')) + # NaTs + check(TD('NaT'), TD(1), TD('NaT')) + check(TD('NaT', 's'), TD(1, 'D'), TD('NaT', 's')) + check(TD('NaT', 's'), TD(1, 'ms'), TD('NaT', 'ms')) + # Cannot add days and months + with self.assertRaises((TypeError, TypingError)): + f(TD(1, 'M'), TD(1, 'D')) + + def test_sub(self): + f = self.jit(sub_usecase) + def check(a, b, expected): + self.assertPreciseEqual(f(a, b), expected) + self.assertPreciseEqual(f(b, a), -expected) + + check(TD(3), TD(2), TD(1)) + check(TD(3, 's'), TD(2, 's'), TD(1, 's')) + # Implicit unit promotion + check(TD(3, 's'), TD(2, 'us'), TD(2999998, 'us')) + check(TD(1, 'W'), TD(2, 'D'), TD(5, 'D')) + # NaTs + check(TD('NaT'), TD(1), TD('NaT')) + check(TD('NaT', 's'), TD(1, 'D'), TD('NaT', 's')) + check(TD('NaT', 's'), TD(1, 'ms'), TD('NaT', 'ms')) + # Cannot sub days to months + with self.assertRaises((TypeError, TypingError)): + f(TD(1, 'M'), TD(1, 'D')) + + def test_mul(self): + f = self.jit(mul_usecase) + def check(a, b, expected): + self.assertPreciseEqual(f(a, b), expected) + self.assertPreciseEqual(f(b, a), expected) + + # non-int64 int * timedelta64 + check(TD(3), np.uint32(2), TD(6)) + # int * timedelta64 + check(TD(3), 2, TD(6)) + check(TD(3, 'ps'), 2, TD(6, 'ps')) + check(TD('NaT', 'ps'), 2, TD('NaT', 'ps')) + # float * timedelta64 + check(TD(7), 1.5, TD(10)) + check(TD(-7), 1.5, TD(-10)) + check(TD(7, 'ps'), -1.5, TD(-10, 'ps')) + check(TD(-7), -1.5, TD(10)) + check(TD('NaT', 'ps'), -1.5, TD('NaT', 'ps')) + check(TD(7, 'ps'), float('nan'), TD('NaT', 'ps')) + # wraparound on overflow + check(TD(2**62, 'ps'), 16, TD(0, 'ps')) + + def test_div(self): + div = self.jit(div_usecase) + floordiv = self.jit(floordiv_usecase) + def check(a, b, expected): + self.assertPreciseEqual(div(a, b), expected) + self.assertPreciseEqual(floordiv(a, b), expected) + + # timedelta64 / non-int64 int + check(TD(-3, 'ps'), np.uint32(2), TD(-1, 'ps')) + # timedelta64 / int + check(TD(3), 2, TD(1)) + check(TD(-3, 'ps'), 2, TD(-1, 'ps')) + check(TD('NaT', 'ps'), 2, TD('NaT', 'ps')) + check(TD(3, 'ps'), 0, TD('NaT', 'ps')) + check(TD('NaT', 'ps'), 0, TD('NaT', 'ps')) + # timedelta64 / float + check(TD(7), 0.5, TD(14)) + check(TD(-7, 'ps'), 1.5, TD(-4, 'ps')) + check(TD('NaT', 'ps'), 2.5, TD('NaT', 'ps')) + check(TD(3, 'ps'), 0.0, TD('NaT', 'ps')) + check(TD('NaT', 'ps'), 0.0, TD('NaT', 'ps')) + check(TD(3, 'ps'), float('nan'), TD('NaT', 'ps')) + check(TD('NaT', 'ps'), float('nan'), TD('NaT', 'ps')) + + def test_homogeneous_div(self): + div = self.jit(div_usecase) + def check(a, b, expected): + self.assertPreciseEqual(div(a, b), expected) + + # timedelta64 / timedelta64 + check(TD(7), TD(3), 7. / 3.) + check(TD(7, 'us'), TD(3, 'ms'), 7. / 3000.) + check(TD(7, 'ms'), TD(3, 'us'), 7000. / 3.) + check(TD(7), TD(0), float('+inf')) + check(TD(-7), TD(0), float('-inf')) + check(TD(0), TD(0), float('nan')) + # NaTs + check(TD('nat'), TD(3), float('nan')) + check(TD(3), TD('nat'), float('nan')) + check(TD('nat'), TD(0), float('nan')) + # Cannot div months with days + with self.assertRaises((TypeError, TypingError)): + div(TD(1, 'M'), TD(1, 'D')) + + def test_eq_ne(self): + eq = self.jit(eq_usecase) + ne = self.jit(ne_usecase) + def check(a, b, expected): + expected_val = expected + not_expected_val = not expected + + # all NaT comparisons are False, including NaT==NaT, + # conversely != is True + if np.isnat(a) or np.isnat(a): + expected_val = False + not_expected_val = True + + self.assertPreciseEqual(eq(a, b), expected_val) + self.assertPreciseEqual(eq(b, a), expected_val) + self.assertPreciseEqual(ne(a, b), not_expected_val) + self.assertPreciseEqual(ne(b, a), not_expected_val) + + check(TD(1), TD(2), False) + check(TD(1), TD(1), True) + check(TD(1, 's'), TD(2, 's'), False) + check(TD(1, 's'), TD(1, 's'), True) + check(TD(2000, 's'), TD(2, 's'), False) + check(TD(2000, 'ms'), TD(2, 's'), True) + check(TD(1, 'Y'), TD(12, 'M'), True) + # NaTs + check(TD('Nat'), TD('Nat'), True) + check(TD('Nat', 'ms'), TD('Nat', 's'), True) + check(TD('Nat'), TD(1), False) + # Incompatible units => timedeltas compare unequal + if numpy_version < (1, 25): + check(TD(1, 'Y'), TD(365, 'D'), False) + check(TD(1, 'Y'), TD(366, 'D'), False) + # ... except when both are NaT! + check(TD('NaT', 'W'), TD('NaT', 'D'), True) + else: + # incompatible units raise + # The exception is different depending on Python mode + with self.assertRaises((TypeError, TypingError)): + eq(TD(1, 'Y'), TD(365, 'D')) + with self.assertRaises((TypeError, TypingError)): + ne(TD(1, 'Y'), TD(365, 'D')) + + def test_lt_ge(self): + lt = self.jit(lt_usecase) + ge = self.jit(ge_usecase) + def check(a, b, expected): + expected_val = expected + not_expected_val = not expected + + # since np 1.16 all NaT magnitude comparisons including equality + # are False (as NaT == NaT is now False) + if np.isnat(a) or np.isnat(a): + expected_val = False + not_expected_val = False + + self.assertPreciseEqual(lt(a, b), expected_val) + self.assertPreciseEqual(ge(a, b), not_expected_val) + + check(TD(1), TD(2), True) + check(TD(1), TD(1), False) + check(TD(2), TD(1), False) + check(TD(1, 's'), TD(2, 's'), True) + check(TD(1, 's'), TD(1, 's'), False) + check(TD(2, 's'), TD(1, 's'), False) + check(TD(1, 'm'), TD(61, 's'), True) + check(TD(1, 'm'), TD(60, 's'), False) + # NaTs + check(TD('Nat'), TD('Nat'), False) + check(TD('Nat', 'ms'), TD('Nat', 's'), False) + check(TD('Nat'), TD(-(2**63)+1), True) + # Incompatible units => exception raised + with self.assertRaises((TypeError, TypingError)): + lt(TD(1, 'Y'), TD(365, 'D')) + with self.assertRaises((TypeError, TypingError)): + ge(TD(1, 'Y'), TD(365, 'D')) + # ... even when both are NaT + with self.assertRaises((TypeError, TypingError)): + lt(TD('NaT', 'Y'), TD('NaT', 'D')) + with self.assertRaises((TypeError, TypingError)): + ge(TD('NaT', 'Y'), TD('NaT', 'D')) + + def test_le_gt(self): + le = self.jit(le_usecase) + gt = self.jit(gt_usecase) + def check(a, b, expected): + expected_val = expected + not_expected_val = not expected + + # since np 1.16 all NaT magnitude comparisons including equality + # are False (as NaT == NaT is now False) + if np.isnat(a) or np.isnat(a): + expected_val = False + not_expected_val = False + self.assertPreciseEqual(le(a, b), expected_val) + self.assertPreciseEqual(gt(a, b), not_expected_val) + + check(TD(1), TD(2), True) + check(TD(1), TD(1), True) + check(TD(2), TD(1), False) + check(TD(1, 's'), TD(2, 's'), True) + check(TD(1, 's'), TD(1, 's'), True) + check(TD(2, 's'), TD(1, 's'), False) + check(TD(1, 'm'), TD(61, 's'), True) + check(TD(1, 'm'), TD(60, 's'), True) + check(TD(1, 'm'), TD(59, 's'), False) + # NaTs + check(TD('Nat'), TD('Nat'), True) + check(TD('Nat', 'ms'), TD('Nat', 's'), True) + check(TD('Nat'), TD(-(2**63)+1), True) + # Incompatible units => exception raised + with self.assertRaises((TypeError, TypingError)): + le(TD(1, 'Y'), TD(365, 'D')) + with self.assertRaises((TypeError, TypingError)): + gt(TD(1, 'Y'), TD(365, 'D')) + # ... even when both are NaT + with self.assertRaises((TypeError, TypingError)): + le(TD('NaT', 'Y'), TD('NaT', 'D')) + with self.assertRaises((TypeError, TypingError)): + gt(TD('NaT', 'Y'), TD('NaT', 'D')) + + def test_pos(self): + pos = self.jit(pos_usecase) + def check(a): + self.assertPreciseEqual(pos(a), +a) + + check(TD(3)) + check(TD(-4)) + check(TD(3, 'ms')) + check(TD(-4, 'ms')) + check(TD('NaT')) + check(TD('NaT', 'ms')) + + def test_neg(self): + neg = self.jit(neg_usecase) + def check(a): + self.assertPreciseEqual(neg(a), -a) + + check(TD(3)) + check(TD(-4)) + check(TD(3, 'ms')) + check(TD(-4, 'ms')) + check(TD('NaT')) + check(TD('NaT', 'ms')) + + def test_abs(self): + f = self.jit(abs_usecase) + def check(a): + self.assertPreciseEqual(f(a), abs(a)) + + check(TD(3)) + check(TD(-4)) + check(TD(3, 'ms')) + check(TD(-4, 'ms')) + check(TD('NaT')) + check(TD('NaT', 'ms')) + + def test_hash(self): + f = self.jit(hash_usecase) + def check(a): + self.assertPreciseEqual(f(a), hash(a)) + + TD_CASES = ((3,), (-4,), (3, 'ms'), (-4, 'ms'), (27, 'D'), + (2, 'D'), (2, 'W'), (2, 'Y'), (3, 'W'), + (365, 'D'), (10000, 'D'), (-10000, 'D'), + ('NaT',), ('NaT', 'ms'), ('NaT', 'D'), (-1,)) + DT_CASES = (('2014',), ('2016',), ('2000',), ('2014-02',), + ('2014-03',), ('2014-04',), ('2016-02',), ('2000-12-31',), + ('2014-01-16',), ('2014-01-05',), ('2014-01-07',), + ('2014-01-06',), ('2014-02-02',), ('2014-02-27',), + ('2014-02-16',), ('2014-03-01',), ('2000-01-01T01:02:03.002Z',), + ('2000-01-01T01:02:03Z',), ('NaT',)) + + for case, typ in zip(TD_CASES + DT_CASES, + (TD,) * len(TD_CASES) + (DT,) * len(TD_CASES)): + check(typ(*case)) + + def _test_min_max(self, usecase): + f = self.jit(usecase) + def check(a, b): + self.assertPreciseEqual(f(a, b), usecase(a, b)) + + for cases in ( + (TD(0), TD(1), TD(2), TD('NaT')), + (TD(0, 's'), TD(1, 's'), TD(2, 's'), TD('NaT', 's')), + ): + for a, b in itertools.product(cases, cases): + check(a, b) + + def test_min(self): + self._test_min_max(min_usecase) + + def test_max(self): + self._test_min_max(max_usecase) + + +class TestTimedeltaArithmeticNoPython(TestTimedeltaArithmetic): + + jitargs = dict(nopython=True) + + def test_int_cast(self): + f = self.jit(int_cast_usecase) + def check(a): + self.assertPreciseEqual(f(a), int(a)) + + for (delta, unit) in ((3, 'ns'), (-4, 'ns'), (30000, 'ns'), + (-40000000, 'ns'), (1, 'Y')): + check(TD(delta, unit).astype('timedelta64[ns]')) + + for time in ('2014', '2016', '2000', '2014-02', '2014-03', '2014-04', + '2016-02', '2000-12-31', '2014-01-16', '2014-01-05', + '2014-01-07', '2014-01-06', '2014-02-02', '2014-02-27', + '2014-02-16', '2014-03-01', '2000-01-01T01:02:03.002Z', + '2000-01-01T01:02:03Z'): + check(DT(time).astype('datetime64[ns]')) + + with self.assertRaises(TypingError, msg=('Only datetime64[ns] can be ' + + 'converted, but got ' + + 'datetime64[y]')): + f(DT('2014')) + + +class TestDatetimeArithmetic(TestCase): + + jitargs = dict(forceobj=True) + + def jit(self, pyfunc): + return jit(**self.jitargs)(pyfunc) + + @contextlib.contextmanager + def silence_numpy_warnings(self): + # Numpy can raise warnings when combining e.g. a generic timedelta64 + # with a non-generic datetime64. + with warnings.catch_warnings(): + warnings.filterwarnings('ignore', + message='Implicitly casting between incompatible kinds', + category=DeprecationWarning) + yield + + def test_add_sub_timedelta(self): + """ + Test `datetime64 + timedelta64` and `datetime64 - timedelta64`. + """ + add = self.jit(add_usecase) + sub = self.jit(sub_usecase) + def check(a, b, expected): + with self.silence_numpy_warnings(): + self.assertPreciseEqual(add(a, b), expected, (a, b)) + self.assertPreciseEqual(add(b, a), expected, (a, b)) + self.assertPreciseEqual(sub(a, -b), expected, (a, b)) + # Did we get it right? + self.assertPreciseEqual(a + b, expected) + + # Y + ... + check(DT('2014'), TD(2, 'Y'), DT('2016')) + check(DT('2014'), TD(2, 'M'), DT('2014-03')) + check(DT('2014'), TD(3, 'W'), DT('2014-01-16', 'W')) + check(DT('2014'), TD(4, 'D'), DT('2014-01-05')) + check(DT('2000'), TD(365, 'D'), DT('2000-12-31')) + # M + ... + check(DT('2014-02'), TD(2, 'Y'), DT('2016-02')) + check(DT('2014-02'), TD(2, 'M'), DT('2014-04')) + check(DT('2014-02'), TD(2, 'D'), DT('2014-02-03')) + # W + ... + check(DT('2014-01-07', 'W'), TD(2, 'W'), DT('2014-01-16', 'W')) + # D + ... + check(DT('2014-02-02'), TD(27, 'D'), DT('2014-03-01')) + check(DT('2012-02-02'), TD(27, 'D'), DT('2012-02-29')) + check(DT('2012-02-02'), TD(2, 'W'), DT('2012-02-16')) + # s + ... + check(DT('2000-01-01T01:02:03Z'), TD(2, 'h'), DT('2000-01-01T03:02:03Z')) + check(DT('2000-01-01T01:02:03Z'), TD(2, 'ms'), DT('2000-01-01T01:02:03.002Z')) + # More thorough checking with leap years and faraway years + for dt_str in ('600', '601', '604', '801', + '1900', '1904', '2200', '2300', '2304', + '2400', '6001'): + for dt_suffix in ('', '-01', '-12'): + dt = DT(dt_str + dt_suffix) + for td in [TD(2, 'D'), TD(2, 'W'), + TD(100, 'D'), TD(10000, 'D'), + TD(-100, 'D'), TD(-10000, 'D'), + TD(100, 'W'), TD(10000, 'W'), + TD(-100, 'W'), TD(-10000, 'W'), + TD(100, 'M'), TD(10000, 'M'), + TD(-100, 'M'), TD(-10000, 'M')]: + self.assertEqual(add(dt, td), dt + td, (dt, td)) + self.assertEqual(add(td, dt), dt + td, (dt, td)) + self.assertEqual(sub(dt, -td), dt + td, (dt, td)) + + # NaTs + check(DT('NaT'), TD(2), DT('NaT')) + check(DT('NaT', 's'), TD(2, 'h'), DT('NaT', 's')) + check(DT('NaT', 's'), TD(2, 'ms'), DT('NaT', 'ms')) + check(DT('2014'), TD('NaT', 'W'), DT('NaT', 'W')) + check(DT('2014-01-01'), TD('NaT', 'W'), DT('NaT', 'D')) + check(DT('NaT', 's'), TD('NaT', 'ms'), DT('NaT', 'ms')) + + # Cannot add datetime days and timedelta months or years + for f in (add, sub): + with self.assertRaises((TypeError, TypingError)): + f(DT(1, '2014-01-01'), TD(1, 'Y')) + with self.assertRaises((TypeError, TypingError)): + f(DT(1, '2014-01-01'), TD(1, 'M')) + + def datetime_samples(self): + dt_years = ['600', '601', '604', '1968', '1969', '1973', + '2000', '2004', '2005', '2100', '2400', '2401'] + dt_suffixes = ['', '-01', '-12', '-02-28', '-12-31', + '-01-05T12:30:56Z', '-01-05T12:30:56.008Z'] + dts = [DT(a + b) for (a, b) in itertools.product(dt_years, dt_suffixes)] + dts += [DT(s, 'W') for s in dt_years] + return dts + + def test_datetime_difference(self): + """ + Test `datetime64 - datetime64`. + """ + sub = self.jit(sub_usecase) + def check(a, b, expected=None): + with self.silence_numpy_warnings(): + self.assertPreciseEqual(sub(a, b), a - b, (a, b)) + self.assertPreciseEqual(sub(b, a), b - a, (a, b)) + # Did we get it right? + self.assertPreciseEqual(a - b, expected) + + check(DT('2014'), DT('2017'), TD(-3, 'Y')) + check(DT('2014-02'), DT('2017-01'), TD(-35, 'M')) + check(DT('2014-02-28'), DT('2015-03-01'), TD(-366, 'D')) + # NaTs + check(DT('NaT', 'M'), DT('2000'), TD('NaT', 'M')) + check(DT('NaT', 'M'), DT('2000-01-01'), TD('NaT', 'D')) + check(DT('NaT'), DT('NaT'), TD('NaT')) + # Test many more values + with self.silence_numpy_warnings(): + dts = self.datetime_samples() + for a, b in itertools.product(dts, dts): + if (not npdatetime_helpers.same_kind(value_unit(a), value_unit(b))): + continue + self.assertPreciseEqual(sub(a, b), a - b, (a, b)) + + def test_comparisons(self): + # Test all datetime comparisons all at once + eq = self.jit(eq_usecase) + ne = self.jit(ne_usecase) + lt = self.jit(lt_usecase) + le = self.jit(le_usecase) + gt = self.jit(gt_usecase) + ge = self.jit(ge_usecase) + + def check_eq(a, b, expected): + expected_val = expected + not_expected_val = not expected + + # since np 1.16 all NaT comparisons bar != are False, including + # NaT==NaT + if np.isnat(a) or np.isnat(b): + expected_val = False + not_expected_val = True + self.assertFalse(le(a, b), (a, b)) + self.assertFalse(ge(a, b), (a, b)) + self.assertFalse(le(b, a), (a, b)) + self.assertFalse(ge(b, a), (a, b)) + self.assertFalse(lt(a, b), (a, b)) + self.assertFalse(gt(a, b), (a, b)) + self.assertFalse(lt(b, a), (a, b)) + self.assertFalse(gt(b, a), (a, b)) + + with self.silence_numpy_warnings(): + self.assertPreciseEqual(eq(a, b), expected_val, (a, b, expected)) + self.assertPreciseEqual(eq(b, a), expected_val, (a, b, expected)) + self.assertPreciseEqual(ne(a, b), not_expected_val, (a, b, expected)) + self.assertPreciseEqual(ne(b, a), not_expected_val, (a, b, expected)) + if expected_val: + # If equal, then equal-ordered comparisons are true + self.assertTrue(le(a, b), (a, b)) + self.assertTrue(ge(a, b), (a, b)) + self.assertTrue(le(b, a), (a, b)) + self.assertTrue(ge(b, a), (a, b)) + # and strictly ordered comparisons are false + self.assertFalse(lt(a, b), (a, b)) + self.assertFalse(gt(a, b), (a, b)) + self.assertFalse(lt(b, a), (a, b)) + self.assertFalse(gt(b, a), (a, b)) + # Did we get it right? + self.assertPreciseEqual(a == b, expected_val) + + def check_lt(a, b, expected): + expected_val = expected + not_expected_val = not expected + + # since np 1.16 all NaT magnitude comparisons including equality + # are False (as NaT == NaT is now False) + if np.isnat(a) or np.isnat(b): + expected_val = False + not_expected_val = False + + with self.silence_numpy_warnings(): + lt = self.jit(lt_usecase) + self.assertPreciseEqual(lt(a, b), expected_val, (a, b, expected)) + self.assertPreciseEqual(gt(b, a), expected_val, (a, b, expected)) + self.assertPreciseEqual(ge(a, b), not_expected_val, (a, b, expected)) + self.assertPreciseEqual(le(b, a), not_expected_val, (a, b, expected)) + if expected_val: + # If true, then values are not equal + check_eq(a, b, False) + # Did we get it right? + self.assertPreciseEqual(a < b, expected_val) + + check_eq(DT('2014'), DT('2017'), False) + check_eq(DT('2014'), DT('2014-01'), True) + check_eq(DT('2014'), DT('2014-01-01'), True) + check_eq(DT('2014'), DT('2014-01-01', 'W'), True) + check_eq(DT('2014-01'), DT('2014-01-01', 'W'), True) + # Yes, it's not transitive + check_eq(DT('2014-01-01'), DT('2014-01-01', 'W'), False) + check_eq(DT('2014-01-02'), DT('2014-01-06', 'W'), True) + # with times + check_eq(DT('2014-01-01T00:01:00Z', 's'), + DT('2014-01-01T00:01Z', 'm'), True) + check_eq(DT('2014-01-01T00:01:01Z', 's'), + DT('2014-01-01T00:01Z', 'm'), False) + # NaTs + check_lt(DT('NaT', 'Y'), DT('2017'), True) + check_eq(DT('NaT'), DT('NaT'), True) + + # Check comparison between various units + dts = self.datetime_samples() + for a in dts: + # Take a number of smaller units + a_unit = a.dtype.str.split('[')[1][:-1] + i = all_units.index(a_unit) + units = all_units[i:i+6] + for unit in units: + # Force conversion + b = a.astype('M8[%s]' % unit) + if (not npdatetime_helpers.same_kind(value_unit(a), + value_unit(b))): + continue + check_eq(a, b, True) + check_lt(a, b + np.timedelta64(1, unit), True) + check_lt(b - np.timedelta64(1, unit), a, True) + + def _test_min_max(self, usecase): + f = self.jit(usecase) + def check(a, b): + self.assertPreciseEqual(f(a, b), usecase(a, b)) + + for cases in ( + (DT(0, 'ns'), DT(1, 'ns'), DT(2, 'ns'), DT('NaT', 'ns')), + (DT(0, 's'), DT(1, 's'), DT(2, 's'), DT('NaT', 's')), + ): + for a, b in itertools.product(cases, cases): + check(a, b) + + def test_min(self): + self._test_min_max(min_usecase) + + def test_max(self): + self._test_min_max(max_usecase) + +class TestDatetimeArithmeticNoPython(TestDatetimeArithmetic): + + jitargs = dict(nopython=True) + + +class TestMetadataScalingFactor(TestCase): + """ + Tests than non-1 scaling factors are not supported in datetime64 + and timedelta64 dtypes. + """ + + def test_datetime(self, jitargs={'forceobj':True}): + eq = jit(**jitargs)(eq_usecase) + self.assertTrue(eq(DT('2014', '10Y'), DT('2010'))) + + def test_datetime_npm(self): + with self.assertTypingError(): + self.test_datetime(jitargs={'nopython':True}) + + def test_timedelta(self, jitargs={'forceobj':True}): + eq = jit(**jitargs)(eq_usecase) + self.assertTrue(eq(TD(2, '10Y'), TD(20, 'Y'))) + + def test_timedelta_npm(self): + with self.assertTypingError(): + self.test_timedelta(jitargs={'nopython':True}) + + +class TestDatetimeDeltaOps(TestCase): + def test_div(self): + """ + Test the division of a timedelta by numeric types + """ + def arr_div(a, b): + return a / b + + py_func = arr_div + cfunc = njit(arr_div) + test_cases = [ + (np.ones(3, TIMEDELTA_M), np.ones(3, TIMEDELTA_M)), + (np.ones(3, TIMEDELTA_M), np.ones(3, TIMEDELTA_Y)), + (np.ones(3, TIMEDELTA_Y), np.ones(3, TIMEDELTA_M)), + (np.ones(3, TIMEDELTA_Y), np.ones(3, TIMEDELTA_Y)), + (np.ones(3, TIMEDELTA_M), 1), + (np.ones(3, TIMEDELTA_M), np.ones(3, np.int64)), + (np.ones(3, TIMEDELTA_M), np.ones(3, np.float64)), + ] + for a, b in test_cases: + self.assertTrue(np.array_equal(py_func(a, b), cfunc(a, b))) + + +class TestDatetimeArrayOps(TestCase): + + def _test_td_add_or_sub(self, operation, parallel): + """ + Test the addition/subtraction of a datetime array with a timedelta type + """ + def impl(a, b): + return operation(a, b) + + arr_one = np.array([ + np.datetime64("2011-01-01"), + np.datetime64("1971-02-02"), + np.datetime64("2021-03-03"), + np.datetime64("2004-12-07"), + ], dtype="datetime64[ns]") + arr_two = np.array([ + np.datetime64("2011-01-01"), + np.datetime64("1971-02-02"), + np.datetime64("2021-03-03"), + np.datetime64("2004-12-07"), + ], dtype="datetime64[D]") + py_func = impl + cfunc = njit(parallel=parallel)(impl) + test_cases = [ + (arr_one, np.timedelta64(1000)), + (arr_two, np.timedelta64(1000)), + (arr_one, np.timedelta64(-54557)), + (arr_two, np.timedelta64(-54557)), + ] + # np.add is commutative so test the reversed order + if operation is np.add: + test_cases.extend([ + (np.timedelta64(1000), arr_one), + (np.timedelta64(1000), arr_two), + (np.timedelta64(-54557), arr_one), + (np.timedelta64(-54557), arr_two), + ]) + for a, b in test_cases: + self.assertTrue(np.array_equal(py_func(a, b), cfunc(a, b))) + + def test_add_td(self): + self._test_td_add_or_sub(np.add, False) + + @skip_parfors_unsupported + def test_add_td_parallel(self): + self._test_td_add_or_sub(np.add, True) + + def test_sub_td(self): + self._test_td_add_or_sub(np.subtract, False) + + @skip_parfors_unsupported + def test_sub_td_parallel(self): + self._test_td_add_or_sub(np.subtract, True) + + def _test_add_sub_td_no_match(self, operation): + """ + Tests that attempting to add/sub a datetime64 and timedelta64 + with types that cannot be cast raises a reasonable exception. + """ + @njit + def impl(a, b): + return operation(a, b) + + fname = operation.__name__ + expected = re.escape((f"ufunc '{fname}' is not supported between " + "datetime64[ns] and timedelta64[M]")) + with self.assertRaisesRegex((TypingError, TypeError), expected): + impl( + np.array([np.datetime64("2011-01-01"),], + dtype="datetime64[ns]"), + np.timedelta64(1000,'M') + ) + + def test_add_td_no_match(self): + self._test_add_sub_td_no_match(np.add) + + def test_sub_td_no_match(self): + self._test_add_sub_td_no_match(np.subtract) + + def _get_testcases(self): + test_cases = [ + np.array([ + DT(0, "ns"), + DT(1, "ns"), + DT(2, "ns"), + DT(3, "ns"), + ]), + np.array([ + DT("2011-01-01", "ns"), + DT("1971-02-02", "ns"), + DT("1900-01-01", "ns"), + DT("2021-03-03", "ns"), + DT("2004-12-07", "ns"), + ]), + np.array([ + DT("2011-01-01", "D"), + DT("1971-02-02", "D"), + DT("1900-01-01", "D"), + DT("2021-03-03", "D"), + DT("2004-12-07", "D"), + ]), + np.array([ + DT("2011-01-01", "ns"), + DT("1971-02-02", "ns"), + DT("1900-01-01", "ns"), + DT("2021-03-03", "ns"), + DT("2004-12-07", "ns"), + DT("NaT", "ns"), + ]), + np.array([ + DT("NaT", "ns"), + DT("2011-01-01", "ns"), + DT("1971-02-02", "ns"), + DT("1900-01-01", "ns"), + DT("2021-03-03", "ns"), + DT("2004-12-07", "ns"), + ]), + np.array([ + DT("1971-02-02", "ns"), + DT("NaT", "ns"), + ]), + np.array([ + DT("NaT", "ns"), + DT("NaT", "ns"), + DT("NaT", "ns"), + ]), + np.array([ + TD(1, "ns"), + TD(2, "ns"), + TD(3, "ns"), + TD(4, "ns"), + ]), + np.array([ + TD(1, "D"), + TD(2, "D"), + TD(3, "D"), + TD(4, "D"), + ]), + np.array([ + TD("NaT", "ns"), + TD(1, "ns"), + TD(2, "ns"), + TD(3, "ns"), + TD(4, "ns"), + ]), + np.array([ + TD(1, "ns"), + TD(2, "ns"), + TD(3, "ns"), + TD(4, "ns"), + TD("NaT", "ns"), + ]), + np.array([ + TD("NaT", "ns"), + ]), + np.array([ + TD("NaT", "ns"), + TD("NaT", "ns"), + TD("NaT", "ns"), + ]), + ] + return test_cases + + def _test_min_max(self, operation, parallel, method): + if method: + if operation is np.min: + def impl(arr): + return arr.min() + else: + def impl(arr): + return arr.max() + else: + def impl(arr): + return operation(arr) + + py_func = impl + cfunc = njit(parallel=parallel)(impl) + + test_cases = self._get_testcases() + for arr in test_cases: + py_res = py_func(arr) + c_res = cfunc(arr) + if np.isnat(py_res) or np.isnat(c_res): + self.assertTrue(np.isnat(py_res)) + self.assertTrue(np.isnat(c_res)) + else: + self.assertEqual(py_res, c_res) + + def test_min_func(self): + self._test_min_max(min, False, False) + + def test_np_min_func(self): + self._test_min_max(np.min, False, False) + + def test_min_method(self): + self._test_min_max(np.min, False, True) + + def test_max_func(self): + self._test_min_max(max, False, False) + + def test_np_max_func(self): + self._test_min_max(np.max, False, False) + + def test_max_method(self): + self._test_min_max(np.max, False, True) + + @skip_parfors_unsupported + def test_min_func_parallel(self): + self._test_min_max(np.min, True, False) + + @skip_parfors_unsupported + def test_min_method_parallel(self): + self._test_min_max(np.min, True, True) + + @skip_parfors_unsupported + def test_max_func_parallel(self): + self._test_min_max(np.max, True, False) + + @skip_parfors_unsupported + def test_max_method_parallel(self): + self._test_min_max(np.max, True, True) + + def test_searchsorted_datetime(self): + from .test_np_functions import ( + searchsorted, searchsorted_left, searchsorted_right, + ) + pyfunc_list = [searchsorted, searchsorted_left, searchsorted_right] + cfunc_list = [jit(fn) for fn in pyfunc_list] + + def check(pyfunc, cfunc, a, v): + expected = pyfunc(a, v) + got = cfunc(a, v) + self.assertPreciseEqual(expected, got) + + cases = self._get_testcases() + for pyfunc, cfunc in zip(pyfunc_list, cfunc_list): + for arr in cases: + arr = np.sort(arr) + for n in range(1, min(3, arr.size) + 1): + idx = np.random.randint(0, arr.size, n) + vs = arr[idx] + if n == 1: + [v] = vs + check(pyfunc, cfunc, arr, v) + check(pyfunc, cfunc, arr, vs) + + + +class TestDatetimeTypeOps(TestCase): + def test_isinstance_datetime(self): + @njit + def is_complex(a): + return isinstance(a, complex) + @njit + def is_datetime(a): + return isinstance(a, np.datetime64) + @njit + def is_timedelta(a): + return isinstance(a, np.timedelta64) + + dt_a = np.datetime64(1, 'ns') + dt_b = np.datetime64(2, 'ns') + td_c = dt_b - dt_a + + def check(jit_func, x): + with self.subTest(f'{jit_func.__name__}({type(x).__name__})'): + got = jit_func(x) + expect = jit_func.py_func(x) + self.assertEqual(got, expect) + + fns = [ + is_complex, + is_datetime, + is_timedelta, + ] + args = [ + dt_a, + dt_b, + td_c, + ] + for fn, arg in itertools.product(fns, args): + check(fn, arg) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_nrt.py b/lib/python3.10/site-packages/numba/tests/test_nrt.py new file mode 100644 index 0000000000000000000000000000000000000000..f02b48cb711caa7d8c3866c2813342f18d49252e --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_nrt.py @@ -0,0 +1,857 @@ +import math +import os +import platform +import sys +import re + +import numpy as np + +from numba import njit +from numba.core import types +from numba.core.runtime import ( + rtsys, + nrtopt, + _nrt_python, + nrt, +) +from numba.core.extending import intrinsic, include_path +from numba.core.typing import signature +from numba.core.imputils import impl_ret_untracked +from llvmlite import ir +import llvmlite.binding as llvm +from numba.core.unsafe.nrt import NRT_get_api + +from numba.tests.support import (EnableNRTStatsMixin, TestCase, temp_directory, + import_dynamic, skip_if_32bit, + skip_unless_cffi, run_in_subprocess) +from numba.core.registry import cpu_target +import unittest + + +linux_only = unittest.skipIf(not sys.platform.startswith('linux'), + 'linux only test') +x86_only = unittest.skipIf(platform.machine() not in ('i386', 'x86_64'), + 'x86 only test') + + +class Dummy(object): + alive = 0 + + def __init__(self): + type(self).alive += 1 + + def __del__(self): + type(self).alive -= 1 + + +class TestNrtMemInfoNotInitialized(unittest.TestCase): + """ + Unit test for checking the use of the NRT fails if the + initialization sequence has not been run. + """ + _numba_parallel_test_ = False + + def test_init_fail(self): + methods = {'library': (), + 'meminfo_new': ((), ()), + 'meminfo_alloc': ((),), + } + + for meth, args in methods.items(): + try: + with self.assertRaises(RuntimeError) as raises: + rtsys._init = False + fn = getattr(rtsys, meth) + fn(*args) + + msg = "Runtime must be initialized before use." + self.assertIn(msg, str(raises.exception)) + finally: + rtsys._init = True + + +class TestNrtMemInfo(unittest.TestCase): + """ + Unit test for core MemInfo functionality + """ + + def setUp(self): + # Reset the Dummy class + Dummy.alive = 0 + # initialize the NRT (in case the tests are run in isolation) + rtsys.initialize(cpu_target.target_context) + super(TestNrtMemInfo, self).setUp() + + def test_meminfo_refct_1(self): + d = Dummy() + self.assertEqual(Dummy.alive, 1) + addr = 0xdeadcafe # some made up location + + mi = rtsys.meminfo_new(addr, d) + self.assertEqual(mi.refcount, 1) + del d + self.assertEqual(Dummy.alive, 1) + mi.acquire() + self.assertEqual(mi.refcount, 2) + self.assertEqual(Dummy.alive, 1) + mi.release() + self.assertEqual(mi.refcount, 1) + del mi + self.assertEqual(Dummy.alive, 0) + + def test_meminfo_refct_2(self): + d = Dummy() + self.assertEqual(Dummy.alive, 1) + addr = 0xdeadcafe # some made up location + + mi = rtsys.meminfo_new(addr, d) + self.assertEqual(mi.refcount, 1) + del d + self.assertEqual(Dummy.alive, 1) + for ct in range(100): + mi.acquire() + self.assertEqual(mi.refcount, 1 + 100) + self.assertEqual(Dummy.alive, 1) + for _ in range(100): + mi.release() + self.assertEqual(mi.refcount, 1) + del mi + self.assertEqual(Dummy.alive, 0) + + def test_fake_memoryview(self): + d = Dummy() + self.assertEqual(Dummy.alive, 1) + addr = 0xdeadcafe # some made up location + + mi = rtsys.meminfo_new(addr, d) + self.assertEqual(mi.refcount, 1) + mview = memoryview(mi) + self.assertEqual(mi.refcount, 1) + self.assertEqual(addr, mi.data) + self.assertFalse(mview.readonly) + self.assertIs(mi, mview.obj) + self.assertTrue(mview.c_contiguous) + self.assertEqual(mview.itemsize, 1) + self.assertEqual(mview.ndim, 1) + del d + del mi + + self.assertEqual(Dummy.alive, 1) + del mview + self.assertEqual(Dummy.alive, 0) + + def test_memoryview(self): + from ctypes import c_uint32, c_void_p, POINTER, cast + + dtype = np.dtype(np.uint32) + bytesize = dtype.itemsize * 10 + mi = rtsys.meminfo_alloc(bytesize, safe=True) + addr = mi.data + c_arr = cast(c_void_p(mi.data), POINTER(c_uint32 * 10)) + # Check 0xCB-filling + for i in range(10): + self.assertEqual(c_arr.contents[i], 0xcbcbcbcb) + + # Init array with ctypes + for i in range(10): + c_arr.contents[i] = i + 1 + mview = memoryview(mi) + self.assertEqual(mview.nbytes, bytesize) + self.assertFalse(mview.readonly) + self.assertIs(mi, mview.obj) + self.assertTrue(mview.c_contiguous) + self.assertEqual(mview.itemsize, 1) + self.assertEqual(mview.ndim, 1) + del mi + arr = np.ndarray(dtype=dtype, shape=mview.nbytes // dtype.itemsize, + buffer=mview) + del mview + # Modify array with NumPy + np.testing.assert_equal(np.arange(arr.size) + 1, arr) + + arr += 1 + + # Check value reflected in ctypes + for i in range(10): + self.assertEqual(c_arr.contents[i], i + 2) + + self.assertEqual(arr.ctypes.data, addr) + del arr + # At this point the memory is zero filled + # We can't check this deterministically because the memory could be + # consumed by another thread. + + def test_buffer(self): + from ctypes import c_uint32, c_void_p, POINTER, cast + + dtype = np.dtype(np.uint32) + bytesize = dtype.itemsize * 10 + mi = rtsys.meminfo_alloc(bytesize, safe=True) + self.assertEqual(mi.refcount, 1) + addr = mi.data + c_arr = cast(c_void_p(addr), POINTER(c_uint32 * 10)) + # Check 0xCB-filling + for i in range(10): + self.assertEqual(c_arr.contents[i], 0xcbcbcbcb) + + # Init array with ctypes + for i in range(10): + c_arr.contents[i] = i + 1 + + arr = np.ndarray(dtype=dtype, shape=bytesize // dtype.itemsize, + buffer=mi) + self.assertEqual(mi.refcount, 1) + del mi + # Modify array with NumPy + np.testing.assert_equal(np.arange(arr.size) + 1, arr) + + arr += 1 + + # Check value reflected in ctypes + for i in range(10): + self.assertEqual(c_arr.contents[i], i + 2) + + self.assertEqual(arr.ctypes.data, addr) + del arr + # At this point the memory is zero filled + # We can't check this deterministically because the memory could be + # consumed by another thread. + + @skip_if_32bit + def test_allocate_invalid_size(self): + # Checks that attempting to allocate too big a region fails gracefully. + size = types.size_t.maxval // 8 // 2 + for pred in (True, False): + with self.assertRaises(MemoryError) as raises: + rtsys.meminfo_alloc(size, safe=pred) + self.assertIn(f"Requested allocation of {size} bytes failed.", + str(raises.exception)) + + def test_allocate_negative_size(self): + # Checks that attempting to allocate negative number of bytes fails + # gracefully. + size = -10 + for pred in (True, False): + with self.assertRaises(ValueError) as raises: + rtsys.meminfo_alloc(size, safe=pred) + msg = f"Cannot allocate a negative number of bytes: {size}." + self.assertIn(msg, str(raises.exception)) + + +class TestTracemalloc(unittest.TestCase): + """ + Test NRT-allocated memory can be tracked by tracemalloc. + """ + + def measure_memory_diff(self, func): + try: + import tracemalloc + except ImportError: + self.skipTest("tracemalloc not available") + tracemalloc.start() + try: + before = tracemalloc.take_snapshot() + # Keep the result and only delete it after taking a snapshot + res = func() + after = tracemalloc.take_snapshot() + del res + return after.compare_to(before, 'lineno') + finally: + tracemalloc.stop() + + def test_snapshot(self): + N = 1000000 + dtype = np.int8 + + @njit + def alloc_nrt_memory(): + """ + Allocate and return a large array. + """ + return np.empty(N, dtype) + + def keep_memory(): + return alloc_nrt_memory() + + def release_memory(): + alloc_nrt_memory() + + alloc_lineno = keep_memory.__code__.co_firstlineno + 1 + + # Warmup JIT + alloc_nrt_memory() + + # The large NRT-allocated array should appear topmost in the diff + diff = self.measure_memory_diff(keep_memory) + stat = diff[0] + # There is a slight overhead, so the allocated size won't exactly be N + self.assertGreaterEqual(stat.size, N) + self.assertLess(stat.size, N * 1.015, + msg=("Unexpected allocation overhead encountered. " + "May be due to difference in CPython " + "builds or running under coverage")) + frame = stat.traceback[0] + self.assertEqual(os.path.basename(frame.filename), "test_nrt.py") + self.assertEqual(frame.lineno, alloc_lineno) + + # If NRT memory is released before taking a snapshot, it shouldn't + # appear. + diff = self.measure_memory_diff(release_memory) + stat = diff[0] + # Something else appears, but nothing the magnitude of N + self.assertLess(stat.size, N * 0.01) + + +class TestNRTIssue(TestCase): + def test_issue_with_refct_op_pruning(self): + """ + GitHub Issue #1244 https://github.com/numba/numba/issues/1244 + """ + @njit + def calculate_2D_vector_mag(vector): + x, y = vector + + return math.sqrt(x ** 2 + y ** 2) + + @njit + def normalize_2D_vector(vector): + normalized_vector = np.empty(2, dtype=np.float64) + + mag = calculate_2D_vector_mag(vector) + x, y = vector + + normalized_vector[0] = x / mag + normalized_vector[1] = y / mag + + return normalized_vector + + @njit + def normalize_vectors(num_vectors, vectors): + normalized_vectors = np.empty((num_vectors, 2), dtype=np.float64) + + for i in range(num_vectors): + vector = vectors[i] + + normalized_vector = normalize_2D_vector(vector) + + normalized_vectors[i, 0] = normalized_vector[0] + normalized_vectors[i, 1] = normalized_vector[1] + + return normalized_vectors + + num_vectors = 10 + test_vectors = np.random.random((num_vectors, 2)) + got = normalize_vectors(num_vectors, test_vectors) + expected = normalize_vectors.py_func(num_vectors, test_vectors) + + np.testing.assert_almost_equal(expected, got) + + def test_incref_after_cast(self): + # Issue #1427: when casting a value before returning it, the + # cast result should be incref'ed, not the original value. + def f(): + return 0.0, np.zeros(1, dtype=np.int32) + + # Note the return type isn't the same as the tuple type above: + # the first element is a complex rather than a float. + cfunc = njit((types.Tuple((types.complex128, + types.Array(types.int32, 1, 'C') )))())(f) + z, arr = cfunc() + self.assertPreciseEqual(z, 0j) + self.assertPreciseEqual(arr, np.zeros(1, dtype=np.int32)) + + def test_refct_pruning_issue_1511(self): + @njit + def f(): + a = np.ones(10, dtype=np.float64) + b = np.ones(10, dtype=np.float64) + return a, b[:] + + a, b = f() + np.testing.assert_equal(a, b) + np.testing.assert_equal(a, np.ones(10, dtype=np.float64)) + + def test_refct_pruning_issue_1526(self): + @njit + def udt(image, x, y): + next_loc = np.where(image == 1) + + if len(next_loc[0]) == 0: + y_offset = 1 + x_offset = 1 + else: + y_offset = next_loc[0][0] + x_offset = next_loc[1][0] + + next_loc_x = (x - 1) + x_offset + next_loc_y = (y - 1) + y_offset + + return next_loc_x, next_loc_y + + a = np.array([[1, 0, 1, 0, 1, 0, 0, 1, 0, 0]]) + expect = udt.py_func(a, 1, 6) + got = udt(a, 1, 6) + + self.assertEqual(expect, got) + + @TestCase.run_test_in_subprocess + def test_no_nrt_on_njit_decoration(self): + # Checks that the NRT is not initialized/compiled as a result of + # decorating a function with `@njit`. + from numba import njit + + # check the NRT is not initialized. + self.assertFalse(rtsys._init) + + # decorate + @njit + def foo(): + return 123 + + # check the NRT is still not initialized + self.assertFalse(rtsys._init) + + # execute + self.assertEqual(foo(), foo.py_func()) + + # check the NRT is still now initialized as execution has definitely + # occurred. + self.assertTrue(rtsys._init) + + +class TestRefCtPruning(unittest.TestCase): + + sample_llvm_ir = ''' +define i32 @"MyFunction"(i8** noalias nocapture %retptr, { i8*, i32 }** noalias nocapture %excinfo, i8* noalias nocapture readnone %env, double %arg.vt.0, double %arg.vt.1, double %arg.vt.2, double %arg.vt.3, double %arg.bounds.0, double %arg.bounds.1, double %arg.bounds.2, double %arg.bounds.3, i8* %arg.xs.0, i8* nocapture readnone %arg.xs.1, i64 %arg.xs.2, i64 %arg.xs.3, double* nocapture readonly %arg.xs.4, i64 %arg.xs.5.0, i64 %arg.xs.6.0, i8* %arg.ys.0, i8* nocapture readnone %arg.ys.1, i64 %arg.ys.2, i64 %arg.ys.3, double* nocapture readonly %arg.ys.4, i64 %arg.ys.5.0, i64 %arg.ys.6.0, i8* %arg.aggs_and_cols.0.0, i8* nocapture readnone %arg.aggs_and_cols.0.1, i64 %arg.aggs_and_cols.0.2, i64 %arg.aggs_and_cols.0.3, i32* nocapture %arg.aggs_and_cols.0.4, i64 %arg.aggs_and_cols.0.5.0, i64 %arg.aggs_and_cols.0.5.1, i64 %arg.aggs_and_cols.0.6.0, i64 %arg.aggs_and_cols.0.6.1) local_unnamed_addr { +entry: +tail call void @NRT_incref(i8* %arg.xs.0) +tail call void @NRT_incref(i8* %arg.ys.0) +tail call void @NRT_incref(i8* %arg.aggs_and_cols.0.0) +%.251 = icmp sgt i64 %arg.xs.5.0, 0 +br i1 %.251, label %B42.preheader, label %B160 + +B42.preheader: ; preds = %entry +%0 = add i64 %arg.xs.5.0, 1 +br label %B42 + +B42: ; preds = %B40.backedge, %B42.preheader +%lsr.iv3 = phi i64 [ %lsr.iv.next, %B40.backedge ], [ %0, %B42.preheader ] +%lsr.iv1 = phi double* [ %scevgep2, %B40.backedge ], [ %arg.xs.4, %B42.preheader ] +%lsr.iv = phi double* [ %scevgep, %B40.backedge ], [ %arg.ys.4, %B42.preheader ] +%.381 = load double, double* %lsr.iv1, align 8 +%.420 = load double, double* %lsr.iv, align 8 +%.458 = fcmp ole double %.381, %arg.bounds.1 +%not..432 = fcmp oge double %.381, %arg.bounds.0 +%"$phi82.1.1" = and i1 %.458, %not..432 +br i1 %"$phi82.1.1", label %B84, label %B40.backedge + +B84: ; preds = %B42 +%.513 = fcmp ole double %.420, %arg.bounds.3 +%not..487 = fcmp oge double %.420, %arg.bounds.2 +%"$phi106.1.1" = and i1 %.513, %not..487 +br i1 %"$phi106.1.1", label %B108.endif.endif.endif, label %B40.backedge + +B160: ; preds = %B40.backedge, %entry +tail call void @NRT_decref(i8* %arg.ys.0) +tail call void @NRT_decref(i8* %arg.xs.0) +tail call void @NRT_decref(i8* %arg.aggs_and_cols.0.0) +store i8* null, i8** %retptr, align 8 +ret i32 0 + +B108.endif.endif.endif: ; preds = %B84 +%.575 = fmul double %.381, %arg.vt.0 +%.583 = fadd double %.575, %arg.vt.1 +%.590 = fptosi double %.583 to i64 +%.630 = fmul double %.420, %arg.vt.2 +%.638 = fadd double %.630, %arg.vt.3 +%.645 = fptosi double %.638 to i64 +tail call void @NRT_incref(i8* %arg.aggs_and_cols.0.0) ; GONE 1 +tail call void @NRT_decref(i8* null) ; GONE 2 +tail call void @NRT_incref(i8* %arg.aggs_and_cols.0.0), !noalias !0 ; GONE 3 +%.62.i.i = icmp slt i64 %.645, 0 +%.63.i.i = select i1 %.62.i.i, i64 %arg.aggs_and_cols.0.5.0, i64 0 +%.64.i.i = add i64 %.63.i.i, %.645 +%.65.i.i = icmp slt i64 %.590, 0 +%.66.i.i = select i1 %.65.i.i, i64 %arg.aggs_and_cols.0.5.1, i64 0 +%.67.i.i = add i64 %.66.i.i, %.590 +%.84.i.i = mul i64 %.64.i.i, %arg.aggs_and_cols.0.5.1 +%.87.i.i = add i64 %.67.i.i, %.84.i.i +%.88.i.i = getelementptr i32, i32* %arg.aggs_and_cols.0.4, i64 %.87.i.i +%.89.i.i = load i32, i32* %.88.i.i, align 4, !noalias !3 +%.99.i.i = add i32 %.89.i.i, 1 +store i32 %.99.i.i, i32* %.88.i.i, align 4, !noalias !3 +tail call void @NRT_decref(i8* %arg.aggs_and_cols.0.0), !noalias !0 ; GONE 4 +tail call void @NRT_decref(i8* %arg.aggs_and_cols.0.0) ; GONE 5 +br label %B40.backedge + +B40.backedge: ; preds = %B108.endif.endif.endif, %B84, %B42 +%scevgep = getelementptr double, double* %lsr.iv, i64 1 +%scevgep2 = getelementptr double, double* %lsr.iv1, i64 1 +%lsr.iv.next = add i64 %lsr.iv3, -1 +%.294 = icmp sgt i64 %lsr.iv.next, 1 +br i1 %.294, label %B42, label %B160 +} + ''' # noqa + + def test_refct_pruning_op_recognize(self): + input_ir = self.sample_llvm_ir + input_lines = list(input_ir.splitlines()) + before_increfs = [ln for ln in input_lines if 'NRT_incref' in ln] + before_decrefs = [ln for ln in input_lines if 'NRT_decref' in ln] + + # prune + output_ir = nrtopt._remove_redundant_nrt_refct(input_ir) + output_lines = list(output_ir.splitlines()) + after_increfs = [ln for ln in output_lines if 'NRT_incref' in ln] + after_decrefs = [ln for ln in output_lines if 'NRT_decref' in ln] + + # check + self.assertNotEqual(before_increfs, after_increfs) + self.assertNotEqual(before_decrefs, after_decrefs) + + pruned_increfs = set(before_increfs) - set(after_increfs) + pruned_decrefs = set(before_decrefs) - set(after_decrefs) + + # the symm difference == or-combined + combined = pruned_increfs | pruned_decrefs + self.assertEqual(combined, pruned_increfs ^ pruned_decrefs) + pruned_lines = '\n'.join(combined) + + # all GONE lines are pruned + for i in [1, 2, 3, 4, 5]: + gone = '; GONE {}'.format(i) + self.assertIn(gone, pruned_lines) + # no other lines + self.assertEqual(len(list(pruned_lines.splitlines())), len(combined)) + + @unittest.skip("Pass removed as it was buggy. Re-enable when fixed.") + def test_refct_pruning_with_branches(self): + '''testcase from #2350''' + @njit + def _append_non_na(x, y, agg, field): + if not np.isnan(field): + agg[y, x] += 1 + + @njit + def _append(x, y, agg, field): + if not np.isnan(field): + if np.isnan(agg[y, x]): + agg[y, x] = field + else: + agg[y, x] += field + + @njit + def append(x, y, agg, field): + _append_non_na(x, y, agg, field) + _append(x, y, agg, field) + + # Disable python wrapper to avoid detecting necessary + # refcount inside it + @njit(no_cpython_wrapper=True) + def extend(arr, field): + for i in range(arr.shape[0]): + for j in range(arr.shape[1]): + append(j, i, arr, field) + + # Compile + extend.compile("(f4[:,::1], f4)") + + # Test there are no reference count operations + llvmir = str(extend.inspect_llvm(extend.signatures[0])) + refops = list(re.finditer(r'(NRT_incref|NRT_decref)\([^\)]+\)', llvmir)) + self.assertEqual(len(refops), 0) + + @linux_only + @x86_only + def test_inline_asm(self): + """The InlineAsm class from llvmlite.ir has no 'name' attr the refcount + pruning pass should be tolerant to this""" + llvm.initialize() + llvm.initialize_native_target() + llvm.initialize_native_asmprinter() + llvm.initialize_native_asmparser() + + @intrinsic + def bar(tyctx, x, y): + def codegen(cgctx, builder, sig, args): + (arg_0, arg_1) = args + fty = ir.FunctionType(ir.IntType(32), [ir.IntType(32), + ir.IntType(32)]) + mul = builder.asm(fty, "mov $2, $0; imul $1, $0", "=&r,r,r", + (arg_0, arg_1), name="asm_mul", + side_effect=False) + return impl_ret_untracked(cgctx, builder, sig.return_type, mul) + return signature(types.int32, types.int32, types.int32), codegen + + @njit(['int32(int32)']) + def foo(x): + x += 1 + z = bar(x, 2) + return z + + self.assertEqual(foo(10), 22) # expect (10 + 1) * 2 = 22 + + +@skip_unless_cffi +class TestNrtExternalCFFI(EnableNRTStatsMixin, TestCase): + """Testing the use of externally compiled C code that use NRT + """ + def setUp(self): + # initialize the NRT (in case the tests are run in isolation) + cpu_target.target_context + super(TestNrtExternalCFFI, self).setUp() + + def compile_cffi_module(self, name, source, cdef): + from cffi import FFI + + ffi = FFI() + ffi.set_source(name, source, include_dirs=[include_path()]) + ffi.cdef(cdef) + tmpdir = temp_directory("cffi_test_{}".format(name)) + ffi.compile(tmpdir=tmpdir) + sys.path.append(tmpdir) + try: + mod = import_dynamic(name) + finally: + sys.path.remove(tmpdir) + + return ffi, mod + + def get_nrt_api_table(self): + from cffi import FFI + + ffi = FFI() + nrt_get_api = ffi.cast("void* (*)()", _nrt_python.c_helpers['get_api']) + table = nrt_get_api() + return table + + def test_manage_memory(self): + name = "{}_test_manage_memory".format(self.__class__.__name__) + source = r""" +#include +#include "numba/core/runtime/nrt_external.h" + +int status = 0; + +void my_dtor(void *ptr) { + free(ptr); + status = 0xdead; +} + +NRT_MemInfo* test_nrt_api(NRT_api_functions *nrt) { + void * data = malloc(10); + NRT_MemInfo *mi = nrt->manage_memory(data, my_dtor); + nrt->acquire(mi); + nrt->release(mi); + status = 0xa110c; + return mi; +} + """ + cdef = """ +void* test_nrt_api(void *nrt); +extern int status; + """ + + ffi, mod = self.compile_cffi_module(name, source, cdef) + # Init status is 0 + self.assertEqual(mod.lib.status, 0) + table = self.get_nrt_api_table() + out = mod.lib.test_nrt_api(table) + # status is now 0xa110c + self.assertEqual(mod.lib.status, 0xa110c) + mi_addr = int(ffi.cast("size_t", out)) + mi = nrt.MemInfo(mi_addr) + self.assertEqual(mi.refcount, 1) + del mi # force deallocation on mi + # status is now 0xdead + self.assertEqual(mod.lib.status, 0xdead) + + def test_allocate(self): + name = "{}_test_allocate".format(self.__class__.__name__) + source = r""" +#include +#include "numba/core/runtime/nrt_external.h" + +NRT_MemInfo* test_nrt_api(NRT_api_functions *nrt, size_t n) { + size_t *data = NULL; + NRT_MemInfo *mi = nrt->allocate(n); + data = nrt->get_data(mi); + data[0] = 0xded; + data[1] = 0xabc; + data[2] = 0xdef; + return mi; +} + """ + cdef = "void* test_nrt_api(void *nrt, size_t n);" + ffi, mod = self.compile_cffi_module(name, source, cdef) + + table = self.get_nrt_api_table() + + numbytes = 3 * np.dtype(np.intp).itemsize + out = mod.lib.test_nrt_api(table, numbytes) + + mi_addr = int(ffi.cast("size_t", out)) + mi = nrt.MemInfo(mi_addr) + self.assertEqual(mi.refcount, 1) + + buffer = ffi.buffer(ffi.cast("char [{}]".format(numbytes), mi.data)) + arr = np.ndarray(shape=(3,), dtype=np.intp, buffer=buffer) + np.testing.assert_equal(arr, [0xded, 0xabc, 0xdef]) + + def test_get_api(self): + from cffi import FFI + + @njit + def test_nrt_api(): + return NRT_get_api() + + ffi = FFI() + expect = int(ffi.cast('size_t', self.get_nrt_api_table())) + got = test_nrt_api() + self.assertEqual(expect, got) + + +class TestNrtStatistics(TestCase): + + def setUp(self): + # Store the current stats state + self.__stats_state = _nrt_python.memsys_stats_enabled() + + def tearDown(self): + # Set stats state back to whatever it was before the test ran + if self.__stats_state: + _nrt_python.memsys_enable_stats() + else: + _nrt_python.memsys_disable_stats() + + def test_stats_env_var_explicit_on(self): + # Checks that explicitly turning the stats on via the env var works. + src = """if 1: + from numba import njit + import numpy as np + from numba.core.runtime import rtsys, _nrt_python + from numba.core.registry import cpu_target + + @njit + def foo(): + return np.arange(10)[0] + + # initialize the NRT before use + rtsys.initialize(cpu_target.target_context) + assert _nrt_python.memsys_stats_enabled() + orig_stats = rtsys.get_allocation_stats() + foo() + new_stats = rtsys.get_allocation_stats() + total_alloc = new_stats.alloc - orig_stats.alloc + total_free = new_stats.free - orig_stats.free + total_mi_alloc = new_stats.mi_alloc - orig_stats.mi_alloc + total_mi_free = new_stats.mi_free - orig_stats.mi_free + + expected = 1 + assert total_alloc == expected + assert total_free == expected + assert total_mi_alloc == expected + assert total_mi_free == expected + """ + # Check env var explicitly being set works + env = os.environ.copy() + env['NUMBA_NRT_STATS'] = "1" + run_in_subprocess(src, env=env) + + def check_env_var_off(self, env): + + src = """if 1: + from numba import njit + import numpy as np + from numba.core.runtime import rtsys, _nrt_python + + @njit + def foo(): + return np.arange(10)[0] + + assert _nrt_python.memsys_stats_enabled() == False + try: + rtsys.get_allocation_stats() + except RuntimeError as e: + assert "NRT stats are disabled." in str(e) + """ + run_in_subprocess(src, env=env) + + def test_stats_env_var_explicit_off(self): + # Checks that explicitly turning the stats off via the env var works. + env = os.environ.copy() + env['NUMBA_NRT_STATS'] = "0" + self.check_env_var_off(env) + + def test_stats_env_var_default_off(self): + # Checks that the env var not being set is the same as "off", i.e. + # default for Numba is off. + env = os.environ.copy() + env.pop('NUMBA_NRT_STATS', None) + self.check_env_var_off(env) + + def test_stats_status_toggle(self): + + @njit + def foo(): + tmp = np.ones(3) + return np.arange(5 * tmp[0]) + + # Switch on stats + _nrt_python.memsys_enable_stats() + # check the stats are on + self.assertTrue(_nrt_python.memsys_stats_enabled()) + + for i in range(2): + # capture the stats state + stats_1 = rtsys.get_allocation_stats() + # Switch off stats + _nrt_python.memsys_disable_stats() + # check the stats are off + self.assertFalse(_nrt_python.memsys_stats_enabled()) + # run something that would move the counters were they enabled + foo() + # Switch on stats + _nrt_python.memsys_enable_stats() + # check the stats are on + self.assertTrue(_nrt_python.memsys_stats_enabled()) + # capture the stats state (should not have changed) + stats_2 = rtsys.get_allocation_stats() + # run something that will move the counters + foo() + # capture the stats state (should have changed) + stats_3 = rtsys.get_allocation_stats() + # check stats_1 == stats_2 + self.assertEqual(stats_1, stats_2) + # check stats_2 < stats_3 + self.assertLess(stats_2, stats_3) + + def test_rtsys_stats_query_raises_exception_when_disabled(self): + # Checks that the standard rtsys.get_allocation_stats() query raises + # when stats counters are turned off. + + _nrt_python.memsys_disable_stats() + self.assertFalse(_nrt_python.memsys_stats_enabled()) + + with self.assertRaises(RuntimeError) as raises: + rtsys.get_allocation_stats() + + self.assertIn("NRT stats are disabled.", str(raises.exception)) + + def test_nrt_explicit_stats_query_raises_exception_when_disabled(self): + # Checks the various memsys_get_stats functions raise if queried when + # the stats counters are disabled. + method_variations = ('alloc', 'free', 'mi_alloc', 'mi_free') + for meth in method_variations: + stats_func = getattr(_nrt_python, f'memsys_get_stats_{meth}') + with self.subTest(stats_func=stats_func): + # Turn stats off + _nrt_python.memsys_disable_stats() + self.assertFalse(_nrt_python.memsys_stats_enabled()) + with self.assertRaises(RuntimeError) as raises: + stats_func() + self.assertIn("NRT stats are disabled.", str(raises.exception)) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_num_threads.py b/lib/python3.10/site-packages/numba/tests/test_num_threads.py new file mode 100644 index 0000000000000000000000000000000000000000..fdd51ac3dda7056919d9fe1218ffe33c1b97cdbb --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_num_threads.py @@ -0,0 +1,632 @@ +# -*- coding: utf-8 -*- +from __future__ import print_function, absolute_import, division + +import sys +import os +import re +import multiprocessing +import unittest + +import numpy as np + +from numba import (njit, set_num_threads, get_num_threads, prange, config, + threading_layer, guvectorize) +from numba.np.ufunc.parallel import get_thread_id +from numba.core.errors import TypingError +from numba.tests.support import TestCase, skip_parfors_unsupported, tag +from numba.tests.test_parallel_backend import TestInSubprocess + + +class TestNumThreads(TestCase): + _numba_parallel_test_ = False + + def setUp(self): + # Make sure the num_threads is set to the max. This also makes sure + # the threads are launched. + set_num_threads(config.NUMBA_NUM_THREADS) + + def check_mask(self, expected, result): + # There's no guarantee that TBB will use a full mask worth of + # threads if it deems it inefficient to do so + if threading_layer() == 'tbb': + self.assertTrue(np.all(result <= expected)) + elif threading_layer() in ('omp', 'workqueue'): + np.testing.assert_equal(expected, result) + else: + assert 0, 'unreachable' + + @skip_parfors_unsupported + def test_set_num_threads_type(self): + + @njit + def foo(): + set_num_threads('wrong_type') + + expected = "The number of threads specified must be an integer" + for fn, errty in ((foo, TypingError), (foo.py_func, TypeError)): + with self.assertRaises(errty) as raises: + fn() + self.assertIn(expected, str(raises.exception)) + + @skip_parfors_unsupported + @unittest.skipIf(config.NUMBA_NUM_THREADS < 2, "Not enough CPU cores") + def _test_set_num_threads_basic(self): + max_threads = config.NUMBA_NUM_THREADS + + self.assertEqual(get_num_threads(), max_threads) + set_num_threads(2) + self.assertEqual(get_num_threads(), 2) + set_num_threads(max_threads) + self.assertEqual(get_num_threads(), max_threads) + + with self.assertRaises(ValueError): + set_num_threads(0) + + with self.assertRaises(ValueError): + set_num_threads(max_threads + 1) + + @skip_parfors_unsupported + @unittest.skipIf(config.NUMBA_NUM_THREADS < 2, "Not enough CPU cores") + def _test_set_num_threads_basic_jit(self): + max_threads = config.NUMBA_NUM_THREADS + + @njit + def get_n(): + return get_num_threads() + + self.assertEqual(get_n(), max_threads) + set_num_threads(2) + self.assertEqual(get_n(), 2) + set_num_threads(max_threads) + self.assertEqual(get_n(), max_threads) + + @njit + def set_get_n(n): + set_num_threads(n) + return get_num_threads() + + self.assertEqual(set_get_n(2), 2) + self.assertEqual(set_get_n(max_threads), max_threads) + + @skip_parfors_unsupported + @unittest.skipIf(config.NUMBA_NUM_THREADS < 2, "Not enough CPU cores") + def _test_set_num_threads_basic_guvectorize(self): + max_threads = config.NUMBA_NUM_THREADS + + @guvectorize(['void(int64[:])'], + '(n)', + nopython=True, + target='parallel') + def get_n(x): + x[:] = get_num_threads() + + x = np.zeros((5000000,), dtype=np.int64) + get_n(x) + np.testing.assert_equal(x, max_threads) + set_num_threads(2) + x = np.zeros((5000000,), dtype=np.int64) + get_n(x) + np.testing.assert_equal(x, 2) + set_num_threads(max_threads) + x = np.zeros((5000000,), dtype=np.int64) + get_n(x) + np.testing.assert_equal(x, max_threads) + + @guvectorize(['void(int64[:])'], + '(n)', + nopython=True, + target='parallel') + def set_get_n(n): + set_num_threads(n[0]) + n[:] = get_num_threads() + + x = np.zeros((5000000,), dtype=np.int64) + x[0] = 2 + set_get_n(x) + np.testing.assert_equal(x, 2) + x = np.zeros((5000000,), dtype=np.int64) + x[0] = max_threads + set_get_n(x) + np.testing.assert_equal(x, max_threads) + + @skip_parfors_unsupported + @unittest.skipIf(config.NUMBA_NUM_THREADS < 2, "Not enough CPU cores") + def _test_set_num_threads_outside_jit(self): + + # Test set_num_threads outside a jitted function + set_num_threads(2) + + @njit(parallel=True) + def test_func(): + x = 5 + buf = np.empty((x,)) + for i in prange(x): + buf[i] = get_num_threads() + return buf + + @guvectorize(['void(int64[:])'], + '(n)', + nopython=True, + target='parallel') + def test_gufunc(x): + x[:] = get_num_threads() + + out = test_func() + np.testing.assert_equal(out, 2) + + x = np.zeros((5000000,), dtype=np.int64) + test_gufunc(x) + np.testing.assert_equal(x, 2) + + @skip_parfors_unsupported + @unittest.skipIf(config.NUMBA_NUM_THREADS < 2, "Not enough CPU cores") + def _test_set_num_threads_inside_jit(self): + # Test set_num_threads inside a jitted function + @njit(parallel=True) + def test_func(nthreads): + x = 5 + buf = np.empty((x,)) + set_num_threads(nthreads) + for i in prange(x): + buf[i] = get_num_threads() + return buf + + mask = 2 + out = test_func(mask) + np.testing.assert_equal(out, mask) + + @skip_parfors_unsupported + @unittest.skipIf(config.NUMBA_NUM_THREADS < 2, "Not enough CPU cores") + def _test_set_num_threads_inside_guvectorize(self): + # Test set_num_threads inside a jitted guvectorize function + @guvectorize(['void(int64[:])'], + '(n)', + nopython=True, + target='parallel') + def test_func(x): + set_num_threads(x[0]) + x[:] = get_num_threads() + + x = np.zeros((5000000,), dtype=np.int64) + mask = 2 + x[0] = mask + test_func(x) + np.testing.assert_equal(x, mask) + + @skip_parfors_unsupported + @unittest.skipIf(config.NUMBA_NUM_THREADS < 2, "Not enough CPU cores") + def _test_get_num_threads_truth_outside_jit(self): + + for mask in range(2, min(6, config.NUMBA_NUM_THREADS + 1)): + set_num_threads(mask) + + # a lot of work, hopefully will trigger "mask" count of threads to + # join the parallel region (for those backends with dynamic threads) + @njit(parallel=True) + def test_func(): + x = 5000000 + buf = np.empty((x,)) + for i in prange(x): + buf[i] = get_thread_id() + return len(np.unique(buf)), get_num_threads() + + out = test_func() + self.check_mask((mask, mask), out) + + @guvectorize(['void(int64[:], int64[:])'], + '(n), (m)', + nopython=True, + target='parallel') + def test_gufunc(x, out): + x[:] = get_thread_id() + out[0] = get_num_threads() + + # Reshape to force parallelism + x = np.full((5000000,), -1, dtype=np.int64).reshape((100, 50000)) + out = np.zeros((1,), dtype=np.int64) + test_gufunc(x, out) + self.check_mask(mask, out) + self.check_mask(mask, len(np.unique(x))) + + @skip_parfors_unsupported + @unittest.skipIf(config.NUMBA_NUM_THREADS < 2, "Not enough CPU cores") + def _test_get_num_threads_truth_inside_jit(self): + + for mask in range(2, min(6, config.NUMBA_NUM_THREADS + 1)): + + # a lot of work, hopefully will trigger "mask" count of threads to + # join the parallel region (for those backends with dynamic threads) + @njit(parallel=True) + def test_func(): + set_num_threads(mask) + x = 5000000 + buf = np.empty((x,)) + for i in prange(x): + buf[i] = get_thread_id() + return len(np.unique(buf)), get_num_threads() + + out = test_func() + self.check_mask((mask, mask), out) + + @guvectorize(['void(int64[:], int64[:])'], + '(n), (m)', + nopython=True, + target='parallel') + def test_gufunc(x, out): + set_num_threads(mask) + x[:] = get_thread_id() + out[0] = get_num_threads() + + # Reshape to force parallelism + x = np.full((5000000,), -1, dtype=np.int64).reshape((100, 50000)) + out = np.zeros((1,), dtype=np.int64) + test_gufunc(x, out) + self.check_mask(mask, out) + self.check_mask(mask, len(np.unique(x))) + + # this test can only run on OpenMP (providing OMP_MAX_ACTIVE_LEVELS is not + # set or >= 2) and TBB backends + @skip_parfors_unsupported + @unittest.skipIf(config.NUMBA_NUM_THREADS < 2, "Not enough CPU cores") + def _test_nested_parallelism_1(self): + if threading_layer() == 'workqueue': + self.skipTest("workqueue is not threadsafe") + + # check that get_num_threads is ok in nesting + mask = config.NUMBA_NUM_THREADS - 1 + + N = config.NUMBA_NUM_THREADS + M = 2 * config.NUMBA_NUM_THREADS + + @njit(parallel=True) + def child_func(buf, fid): + M, N = buf.shape + for i in prange(N): + buf[fid, i] = get_num_threads() + + def get_test(test_type): + if test_type == 'njit': + def test_func(nthreads, py_func=False): + @njit(parallel=True) + def _test_func(nthreads): + acc = 0 + buf = np.zeros((M, N)) + set_num_threads(nthreads) + for i in prange(M): + local_mask = 1 + i % mask + # set threads in parent function + set_num_threads(local_mask) + if local_mask < N: + child_func(buf, local_mask) + acc += get_num_threads() + return acc, buf + if py_func: + return _test_func.py_func(nthreads) + else: + return _test_func(nthreads) + + elif test_type == 'guvectorize': + def test_func(nthreads, py_func=False): + def _test_func(acc, buf, local_mask): + set_num_threads(nthreads) + # set threads in parent function + set_num_threads(local_mask[0]) + if local_mask[0] < N: + child_func(buf, local_mask[0]) + acc[0] += get_num_threads() + + buf = np.zeros((M, N), dtype=np.int64) + acc = np.zeros((M, 1), dtype=np.int64) + local_mask = (1 + np.arange(M) % mask).reshape((M, 1)) + sig = ['void(int64[:], int64[:, :], int64[:])'] + layout = '(p), (n, m), (p)' + if not py_func: + _test_func = guvectorize(sig, layout, nopython=True, + target='parallel')(_test_func) + else: + _test_func = guvectorize(sig, layout, + forceobj=True)(_test_func) + _test_func(acc, buf, local_mask) + return acc, buf + + return test_func + + for test_type in ['njit', 'guvectorize']: + test_func = get_test(test_type) + got_acc, got_arr = test_func(mask) + exp_acc, exp_arr = test_func(mask, py_func=True) + np.testing.assert_equal(exp_acc, got_acc) + np.testing.assert_equal(exp_arr, got_arr) + + # check the maths reconciles, guvectorize does not reduce, njit does + math_acc_exp = 1 + np.arange(M) % mask + if test_type == 'guvectorize': + math_acc = math_acc_exp.reshape((M, 1)) + else: + math_acc = np.sum(math_acc_exp) + + np.testing.assert_equal(math_acc, got_acc) + + math_arr = np.zeros((M, N)) + for i in range(1, N): + # there's branches on 1, ..., num_threads - 1 + math_arr[i, :] = i + np.testing.assert_equal(math_arr, got_arr) + + # this test can only run on OpenMP (providing OMP_MAX_ACTIVE_LEVELS is not + # set or >= 2) and TBB backends + @skip_parfors_unsupported + @unittest.skipIf(config.NUMBA_NUM_THREADS < 2, "Not enough CPU cores") + def _test_nested_parallelism_2(self): + if threading_layer() == 'workqueue': + self.skipTest("workqueue is not threadsafe") + + # check that get_num_threads is ok in nesting + + N = config.NUMBA_NUM_THREADS + 1 + M = 4 * config.NUMBA_NUM_THREADS + 1 + + def get_impl(child_type, test_type): + + if child_type == 'parallel': + child_dec = njit(parallel=True) + elif child_type == 'njit': + child_dec = njit(parallel=False) + elif child_type == 'none': + def child_dec(x): + return x + + @child_dec + def child(buf, fid): + M, N = buf.shape + set_num_threads(fid) # set threads in child function + for i in prange(N): + buf[fid, i] = get_num_threads() + + if test_type in ['parallel', 'njit', 'none']: + if test_type == 'parallel': + test_dec = njit(parallel=True) + elif test_type == 'njit': + test_dec = njit(parallel=False) + elif test_type == 'none': + def test_dec(x): + return x + + @test_dec + def test_func(nthreads): + buf = np.zeros((M, N)) + set_num_threads(nthreads) + for i in prange(M): + local_mask = 1 + i % mask + # when the threads exit the child functions they should + # have a TLS slot value of the local mask as it was set + # in child + if local_mask < config.NUMBA_NUM_THREADS: + child(buf, local_mask) + assert get_num_threads() == local_mask + return buf + else: + if test_type == 'guvectorize': + test_dec = guvectorize(['int64[:,:], int64[:]'], + '(n, m), (k)', nopython=True, + target='parallel') + elif test_type == 'guvectorize-obj': + test_dec = guvectorize(['int64[:,:], int64[:]'], + '(n, m), (k)', forceobj=True) + + def test_func(nthreads): + @test_dec + def _test_func(buf, local_mask): + set_num_threads(nthreads) + # when the threads exit the child functions they should + # have a TLS slot value of the local mask as it was set + # in child + if local_mask[0] < config.NUMBA_NUM_THREADS: + child(buf, local_mask[0]) + assert get_num_threads() == local_mask[0] + + buf = np.zeros((M, N), dtype=np.int64) + local_mask = (1 + np.arange(M) % mask).reshape((M, 1)) + _test_func(buf, local_mask) + return buf + + return test_func + + mask = config.NUMBA_NUM_THREADS - 1 + + res_arrays = {} + for test_type in ['parallel', 'njit', 'none', + 'guvectorize', 'guvectorize-obj']: + for child_type in ['parallel', 'njit', 'none']: + if child_type == 'none' and test_type != 'none': + continue + set_num_threads(mask) + res_arrays[test_type, child_type] = get_impl( + child_type, test_type)(mask) + + py_arr = res_arrays['none', 'none'] + for arr in res_arrays.values(): + np.testing.assert_equal(arr, py_arr) + + # check the maths reconciles + math_arr = np.zeros((M, N)) + # there's branches on modulo mask but only NUMBA_NUM_THREADS funcs + for i in range(1, config.NUMBA_NUM_THREADS): + math_arr[i, :] = i + + np.testing.assert_equal(math_arr, py_arr) + + # this test can only run on OpenMP (providing OMP_MAX_ACTIVE_LEVELS is not + # set or >= 2) and TBB backends + # This test needs at least 3 threads to run, N>=2 for the launch, M>=N+1 for + # the nested function + @skip_parfors_unsupported + @unittest.skipIf(config.NUMBA_NUM_THREADS < 3, "Not enough CPU cores") + def _test_nested_parallelism_3(self): + if threading_layer() == 'workqueue': + self.skipTest("workqueue is not threadsafe") + + # check that the right number of threads are present in nesting + # this relies on there being a load of cores present + BIG = 1000000 + + @njit(parallel=True) + def work(local_nt): # arg is value 3 + tid = np.zeros(BIG) + acc = 0 + set_num_threads(local_nt) # set to 3 threads + for i in prange(BIG): + acc += 1 + tid[i] = get_thread_id() + return acc, np.unique(tid) + + @njit(parallel=True) + def test_func_jit(nthreads): + set_num_threads(nthreads) # set to 2 threads + lens = np.zeros(nthreads) + total = 0 + for i in prange(nthreads): + my_acc, tids = work(nthreads + 1) # call with value 3 + lens[i] = len(tids) + total += my_acc + return total, np.unique(lens) + + NT = 2 + expected_acc = BIG * NT + expected_thread_count = NT + 1 + + got_acc, got_tc = test_func_jit(NT) + self.assertEqual(expected_acc, got_acc) + self.check_mask(expected_thread_count, got_tc) + + def test_guvectorize(nthreads): + @guvectorize(['int64[:], int64[:]'], + '(n), (n)', + nopython=True, + target='parallel') + def test_func_guvectorize(total, lens): + my_acc, tids = work(nthreads + 1) + lens[0] = len(tids) + total[0] += my_acc + + total = np.zeros((nthreads, 1), dtype=np.int64) + lens = np.zeros(nthreads, dtype=np.int64).reshape((nthreads, 1)) + + test_func_guvectorize(total, lens) + # vectorize does not reduce, so total is summed + return total.sum(), np.unique(lens) + + got_acc, got_tc = test_guvectorize(NT) + + self.assertEqual(expected_acc, got_acc) + self.check_mask(expected_thread_count, got_tc) + + @skip_parfors_unsupported + @unittest.skipIf(config.NUMBA_NUM_THREADS < 2, "Not enough CPU cores") + @unittest.skipIf(not sys.platform.startswith('linux'), "Linux only") + def _test_threadmask_across_fork(self): + forkctx = multiprocessing.get_context('fork') + + @njit + def foo(): + return get_num_threads() + + def wrap(queue): + queue.put(foo()) + + mask = 1 + self.assertEqual(foo(), config.NUMBA_NUM_THREADS) + set_num_threads(mask) + self.assertEqual(foo(), mask) + shared_queue = forkctx.Queue() + # check TLS slot inheritance in fork + p = forkctx.Process(target=wrap, args=(shared_queue,)) + p.start() + p.join() + self.assertEqual(shared_queue.get(), mask) + + def tearDown(self): + set_num_threads(config.NUMBA_NUM_THREADS) + + @skip_parfors_unsupported + def _test_get_thread_id_not_parallel(self): + python_get_thread_id = get_thread_id() + check_array_size = 8 + + @njit(parallel=False) + def par_false(size): + njit_par_false_tid = get_thread_id() + res = np.ones(size) + for i in prange(size): + res[i] = get_thread_id() + return njit_par_false_tid, res + + @njit(parallel=True) + def par_true(size): + njit_par_true_tid = get_thread_id() + res = np.ones(size) + for i in range(size): + res[i] = get_thread_id() + return njit_par_true_tid, res + + self.assertEqual(python_get_thread_id, 0) + njit_par_false_tid, njit_par_false_arr = par_false(check_array_size) + self.assertEqual(njit_par_false_tid, 0) + np.testing.assert_equal(njit_par_false_arr, 0) + njit_par_true_tid, njit_par_true_arr = par_true(check_array_size) + self.assertEqual(njit_par_true_tid, 0) + np.testing.assert_equal(njit_par_true_arr, 0) + + +class TestNumThreadsBackends(TestInSubprocess, TestCase): + _class = TestNumThreads + _DEBUG = False + + # 1 is mainly here to ensure tests skip correctly + num_threads = [i for i in [1, 2, 4, 8, 16] if i <= config.NUMBA_NUM_THREADS] + + def run_test_in_separate_process(self, test, threading_layer, num_threads): + env_copy = os.environ.copy() + env_copy['NUMBA_THREADING_LAYER'] = str(threading_layer) + env_copy['NUMBA_NUM_THREADS'] = str(num_threads) + cmdline = [sys.executable, "-m", "numba.runtests", "-v", test] + return self.run_cmd(cmdline, env_copy) + + @classmethod + def _inject(cls, name, backend, backend_guard, num_threads): + themod = cls.__module__ + thecls = cls._class.__name__ + injected_method = '%s.%s.%s' % (themod, thecls, name) + + def test_template(self): + o, e = self.run_test_in_separate_process(injected_method, backend, + num_threads) + if self._DEBUG: + print('stdout:\n "%s"\n stderr:\n "%s"' % (o, e)) + # If the test was skipped in the subprocess, then mark this as a + # skipped test. + m = re.search(r"\.\.\. skipped '(.*?)'", e) + if m is not None: + self.skipTest(m.group(1)) + self.assertIn('OK', e) + self.assertTrue('FAIL' not in e) + self.assertTrue('ERROR' not in e) + + injected_test = "%s_%s_%s_threads" % (name[1:], backend, num_threads) + setattr(cls, injected_test, + tag('long_running')(backend_guard(test_template))) + + @classmethod + def generate(cls): + for name in cls._class.__dict__.copy(): + for backend, backend_guard in cls.backends.items(): + for num_threads in cls.num_threads: + if not name.startswith('_test_'): + continue + cls._inject(name, backend, backend_guard, num_threads) + + +TestNumThreadsBackends.generate() + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_numbers.py b/lib/python3.10/site-packages/numba/tests/test_numbers.py new file mode 100644 index 0000000000000000000000000000000000000000..1f7c6d4c6e23d8044c6e7374ad893f9896ba19bd --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_numbers.py @@ -0,0 +1,90 @@ +# (Some) Tests for targets/numbers.py + +import numpy as np + +from numba import njit +from numba.core import types +from numba.core.errors import TypingError +from numba.tests.support import TestCase + + +def gen_view(a,b): + def impl(x): + return a(x).view(b) + return impl + + +class TestViewIntFloat(TestCase): + """ This tests the 'view' method on NumPy scalars. """ + + def do_testing(self, inputs, dtypes): + for value, initial_type, expected in inputs: + for target_type, result in zip(dtypes, expected): + view = njit(gen_view(initial_type, target_type)) + if not np.isnan(result): + # check against predefined value + self.assertEqual(view(value), target_type(result)) + # check against numpy + self.assertEqual(view(value), + view.py_func(value)) + else: + # check that our implementation results in nan + self.assertTrue(np.isnan(view(value))) + # check that numpy results in nan + self.assertTrue(np.isnan(view.py_func(value))) + + def test_8_bits(self): + dtypes = (np.uint8, np.int8) + # Value Initial Type Expected answers using dtypes + inputs = ((1, np.uint8, (1, 1)), + (-1, np.int8, (255, -1))) + self.do_testing(inputs, dtypes) + + def test_32_bits(self): + dtypes = (np.uint32, np.int32, np.float32) + # Value Initial Type Expected answers using dtypes + inputs = ((1, np.uint32, (1, 1, 1.401298464324817e-45)), + (-1, np.int32, (4294967295, -1, np.nan)), + (1.0, np.float32, (1065353216, 1065353216, 1.0))) + self.do_testing(inputs, dtypes) + + def test_64_bits(self): + dtypes = (np.uint64, np.int64, np.float64) + # Value Initial Type Expected answers using dtypes + inputs = ((1, np.uint64, (1, 1, 5e-324)), + (-1, np.int64, (18446744073709551615, -1, np.nan)), + (1.0, np.float64, (4607182418800017408, + 4607182418800017408, + 1.0)) + ) + self.do_testing(inputs, dtypes) + + def test_python_scalar_exception(self): + intty = getattr(np, 'int{}'.format(types.intp.bitwidth)) + + @njit + def myview(): + a = 1 + a.view(intty) + + with self.assertRaises(TypingError) as e: + myview() + self.assertIn("'view' can only be called on NumPy dtypes, " + "try wrapping the variable 'a' with 'np.()'", + str(e.exception)) + + def do_testing_exceptions(self, pair): + with self.assertRaises(TypingError) as e: + view = njit(gen_view(pair[0], pair[1])) + view(1) + self.assertIn("Changing the dtype of a 0d array is only supported " + "if the itemsize is unchanged", + str(e.exception)) + + def test_exceptions32(self): + for pair in ((np.int32, np.int8), (np.int8, np.int32)): + self.do_testing_exceptions(pair) + + def test_exceptions64(self): + for pair in ((np.int32, np.int64), (np.int64, np.int32)): + self.do_testing_exceptions(pair) diff --git a/lib/python3.10/site-packages/numba/tests/test_numpyadapt.py b/lib/python3.10/site-packages/numba/tests/test_numpyadapt.py new file mode 100644 index 0000000000000000000000000000000000000000..8df1f028813cee233e67c610e7feddcc8bc14ce2 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_numpyadapt.py @@ -0,0 +1,43 @@ +from ctypes import * + +import numpy as np + +import unittest +from numba import _helperlib + + +class ArrayStruct3D(Structure): + # Mimic the structure defined in numba.targets.arrayobj's make_array() + _fields_ = [ + ("meminfo", c_void_p), + ("parent", c_void_p), + ("nitems", c_ssize_t), + ("itemsize", c_ssize_t), + ("data", c_void_p), + ("shape", (c_ssize_t * 3)), + ("strides", (c_ssize_t * 3)), + ] + + +class TestArrayAdaptor(unittest.TestCase): + def test_array_adaptor(self): + arystruct = ArrayStruct3D() + + adaptorptr = _helperlib.c_helpers['adapt_ndarray'] + adaptor = PYFUNCTYPE(c_int, py_object, c_void_p)(adaptorptr) + + ary = np.arange(60).reshape(2, 3, 10) + status = adaptor(ary, byref(arystruct)) + self.assertEqual(status, 0) + self.assertEqual(arystruct.data, ary.ctypes.data) + self.assertNotEqual(arystruct.meminfo, 0) + self.assertEqual(arystruct.parent, id(ary)) + self.assertEqual(arystruct.nitems, 60) + self.assertEqual(arystruct.itemsize, ary.itemsize) + for i in range(3): + self.assertEqual(arystruct.shape[i], ary.ctypes.shape[i]) + self.assertEqual(arystruct.strides[i], ary.ctypes.strides[i]) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_objects.py b/lib/python3.10/site-packages/numba/tests/test_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..a47f9ca00877ec2dcfc203e7df25b4ddd5da3003 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_objects.py @@ -0,0 +1,57 @@ +""" +Test generic manipulation of objects. +""" + + +import unittest +from numba import jit +from numba.core import types +from numba.tests.support import TestCase + + +class C(object): + pass + + +def setattr_usecase(o, v): + o.x = v + + +def delattr_usecase(o): + del o.x + + +class TestAttributes(TestCase): + def test_setattr(self): + pyfunc = setattr_usecase + cfunc = jit((types.pyobject, types.int32), forceobj=True)(pyfunc) + c = C() + cfunc(c, 123) + self.assertEqual(c.x, 123) + + def test_setattr_attribute_error(self): + pyfunc = setattr_usecase + cfunc = jit((types.pyobject, types.int32), forceobj=True)(pyfunc) + # Can't set undeclared slot + with self.assertRaises(AttributeError): + cfunc(object(), 123) + + def test_delattr(self): + pyfunc = delattr_usecase + cfunc = jit((types.pyobject,), forceobj=True)(pyfunc) + c = C() + c.x = 123 + cfunc(c) + with self.assertRaises(AttributeError): + c.x + + def test_delattr_attribute_error(self): + pyfunc = delattr_usecase + cfunc = jit((types.pyobject,), forceobj=True)(pyfunc) + # Can't delete non-existing attribute + with self.assertRaises(AttributeError): + cfunc(C()) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_operators.py b/lib/python3.10/site-packages/numba/tests/test_operators.py new file mode 100644 index 0000000000000000000000000000000000000000..17f6c4915263519754edc20b22f0357f56b43bc8 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_operators.py @@ -0,0 +1,1622 @@ +import copy +import itertools +import operator +import unittest + +import numpy as np + +from numba import jit, njit +from numba.core import types, utils, errors +from numba.core.types.functions import _header_lead +from numba.tests.support import TestCase, tag, needs_blas +from numba.tests.matmul_usecase import (matmul_usecase, imatmul_usecase, + DumbMatrix,) + +Noflags = {'nopython': True} + +force_pyobj_flags = {'forceobj': True} + + +def make_static_power(exp): + def pow_usecase(x): + return x ** exp + return pow_usecase + + +class LiteralOperatorImpl(object): + + @staticmethod + def add_usecase(x, y): + return x + y + + @staticmethod + def iadd_usecase(x, y): + x += y + return x + + @staticmethod + def sub_usecase(x, y): + return x - y + + @staticmethod + def isub_usecase(x, y): + x -= y + return x + + @staticmethod + def mul_usecase(x, y): + return x * y + + @staticmethod + def imul_usecase(x, y): + x *= y + return x + + @staticmethod + def floordiv_usecase(x, y): + return x // y + + @staticmethod + def ifloordiv_usecase(x, y): + x //= y + return x + + @staticmethod + def truediv_usecase(x, y): + return x / y + + @staticmethod + def itruediv_usecase(x, y): + x /= y + return x + + if matmul_usecase: + matmul_usecase = staticmethod(matmul_usecase) + imatmul_usecase = staticmethod(imatmul_usecase) + + @staticmethod + def mod_usecase(x, y): + return x % y + + @staticmethod + def imod_usecase(x, y): + x %= y + return x + + @staticmethod + def pow_usecase(x, y): + return x ** y + + @staticmethod + def ipow_usecase(x, y): + x **= y + return x + + @staticmethod + def bitshift_left_usecase(x, y): + return x << y + + @staticmethod + def bitshift_ileft_usecase(x, y): + x <<= y + return x + + @staticmethod + def bitshift_right_usecase(x, y): + return x >> y + + @staticmethod + def bitshift_iright_usecase(x, y): + x >>= y + return x + + @staticmethod + def bitwise_and_usecase(x, y): + return x & y + + @staticmethod + def bitwise_iand_usecase(x, y): + x &= y + return x + + @staticmethod + def bitwise_or_usecase(x, y): + return x | y + + @staticmethod + def bitwise_ior_usecase(x, y): + x |= y + return x + + @staticmethod + def bitwise_xor_usecase(x, y): + return x ^ y + + @staticmethod + def bitwise_ixor_usecase(x, y): + x ^= y + return x + + @staticmethod + def bitwise_not_usecase_binary(x, _unused): + return ~x + + @staticmethod + def bitwise_not_usecase(x): + return ~x + + @staticmethod + def not_usecase(x): + return not(x) + + @staticmethod + def negate_usecase(x): + return -x + + @staticmethod + def unary_positive_usecase(x): + return +x + + @staticmethod + def lt_usecase(x, y): + return x < y + + @staticmethod + def le_usecase(x, y): + return x <= y + + @staticmethod + def gt_usecase(x, y): + return x > y + + @staticmethod + def ge_usecase(x, y): + return x >= y + + @staticmethod + def eq_usecase(x, y): + return x == y + + @staticmethod + def ne_usecase(x, y): + return x != y + + @staticmethod + def in_usecase(x, y): + return x in y + + @staticmethod + def not_in_usecase(x, y): + return x not in y + + @staticmethod + def is_usecase(x, y): + return x is y + + +class FunctionalOperatorImpl(object): + + @staticmethod + def add_usecase(x, y): + return operator.add(x, y) + + @staticmethod + def iadd_usecase(x, y): + return operator.iadd(x, y) + + @staticmethod + def sub_usecase(x, y): + return operator.sub(x, y) + + @staticmethod + def isub_usecase(x, y): + return operator.isub(x, y) + + @staticmethod + def mul_usecase(x, y): + return operator.mul(x, y) + + @staticmethod + def imul_usecase(x, y): + return operator.imul(x, y) + + @staticmethod + def floordiv_usecase(x, y): + return operator.floordiv(x, y) + + @staticmethod + def ifloordiv_usecase(x, y): + return operator.ifloordiv(x, y) + + @staticmethod + def truediv_usecase(x, y): + return operator.truediv(x, y) + + @staticmethod + def itruediv_usecase(x, y): + return operator.itruediv(x, y) + + @staticmethod + def mod_usecase(x, y): + return operator.mod(x, y) + + @staticmethod + def imod_usecase(x, y): + return operator.imod(x, y) + + @staticmethod + def pow_usecase(x, y): + return operator.pow(x, y) + + @staticmethod + def ipow_usecase(x, y): + return operator.ipow(x, y) + + @staticmethod + def matmul_usecase(x, y): + return operator.matmul(x, y) + + @staticmethod + def imatmul_usecase(x, y): + return operator.imatmul(x, y) + + @staticmethod + def bitshift_left_usecase(x, y): + return operator.lshift(x, y) + + @staticmethod + def bitshift_ileft_usecase(x, y): + return operator.ilshift(x, y) + + @staticmethod + def bitshift_right_usecase(x, y): + return operator.rshift(x, y) + + @staticmethod + def bitshift_iright_usecase(x, y): + return operator.irshift(x, y) + + @staticmethod + def bitwise_and_usecase(x, y): + return operator.and_(x, y) + + @staticmethod + def bitwise_iand_usecase(x, y): + return operator.iand(x, y) + + @staticmethod + def bitwise_or_usecase(x, y): + return operator.or_(x, y) + + @staticmethod + def bitwise_ior_usecase(x, y): + return operator.ior(x, y) + + @staticmethod + def bitwise_xor_usecase(x, y): + return operator.xor(x, y) + + @staticmethod + def bitwise_ixor_usecase(x, y): + return operator.ixor(x, y) + + @staticmethod + def bitwise_not_usecase_binary(x, _unused): + return operator.invert(x) + + @staticmethod + def bitwise_not_usecase(x): + return operator.invert(x) + + @staticmethod + def not_usecase(x): + return operator.not_(x) + + @staticmethod + def negate_usecase(x): + return operator.neg(x) + + @staticmethod + def unary_positive_usecase(x): + return operator.pos(x) + + @staticmethod + def lt_usecase(x, y): + return operator.lt(x, y) + + @staticmethod + def le_usecase(x, y): + return operator.le(x, y) + + @staticmethod + def gt_usecase(x, y): + return operator.gt(x, y) + + @staticmethod + def ge_usecase(x, y): + return operator.ge(x, y) + + @staticmethod + def eq_usecase(x, y): + return operator.eq(x, y) + + @staticmethod + def ne_usecase(x, y): + return operator.ne(x, y) + + @staticmethod + def in_usecase(x, y): + return operator.contains(y, x) + + @staticmethod + def not_in_usecase(x, y): + return not operator.contains(y, x) + + @staticmethod + def is_usecase(x, y): + return operator.is_(x, y) + + +class TestOperators(TestCase): + """ + Test standard Python operators on scalars. + + NOTE: operators on array are generally tested in test_ufuncs. + """ + + op = LiteralOperatorImpl + + _bitwise_opnames = { + 'bitshift_left_usecase': operator.lshift, + 'bitshift_ileft_usecase': operator.ilshift, + 'bitshift_right_usecase': operator.rshift, + 'bitshift_iright_usecase': operator.irshift, + 'bitwise_and_usecase': operator.and_, + 'bitwise_iand_usecase': operator.iand, + 'bitwise_or_usecase': operator.or_, + 'bitwise_ior_usecase': operator.ior, + 'bitwise_xor_usecase': operator.xor, + 'bitwise_ixor_usecase': operator.ixor, + 'bitwise_not_usecase_binary': operator.invert, + } + + def run_test_ints(self, pyfunc, x_operands, y_operands, types_list, + flags=force_pyobj_flags): + for arg_types in types_list: + cfunc = jit(arg_types, **flags)(pyfunc) + for x, y in itertools.product(x_operands, y_operands): + # For inplace ops, we check that the first operand + # was correctly mutated. + x_got = copy.copy(x) + x_expected = copy.copy(x) + got = cfunc(x_got, y) + expected = pyfunc(x_expected, y) + self.assertPreciseEqual( + got, expected, + msg="mismatch for (%r, %r) with types %s: %r != %r" + % (x, y, arg_types, got, expected)) + self.assertPreciseEqual( + x_got, x_expected, + msg="mismatch for (%r, %r) with types %s: %r != %r" + % (x, y, arg_types, x_got, x_expected)) + + def run_test_floats(self, pyfunc, x_operands, y_operands, types_list, + flags=force_pyobj_flags): + for arg_types in types_list: + cfunc = jit(arg_types, **flags)(pyfunc) + for x, y in itertools.product(x_operands, y_operands): + # For inplace ops, we check that the first operand + # was correctly mutated. + x_got = copy.copy(x) + x_expected = copy.copy(x) + got = cfunc(x_got, y) + expected = pyfunc(x_expected, y) + np.testing.assert_allclose(got, expected, rtol=1e-5) + np.testing.assert_allclose(x_got, x_expected, rtol=1e-5) + + def coerce_operand(self, op, numba_type): + if hasattr(op, "dtype"): + return numba_type.cast_python_value(op) + elif numba_type in types.unsigned_domain: + return abs(int(op.real)) + elif numba_type in types.integer_domain: + return int(op.real) + elif numba_type in types.real_domain: + return float(op.real) + else: + return op + + def run_test_scalar_compare(self, pyfunc, flags=force_pyobj_flags, + ordered=True): + ops = self.compare_scalar_operands + types_list = self.compare_types + if not ordered: + types_list = types_list + self.compare_unordered_types + for typ in types_list: + cfunc = jit((typ, typ), **flags)(pyfunc) + for x, y in itertools.product(ops, ops): + x = self.coerce_operand(x, typ) + y = self.coerce_operand(y, typ) + expected = pyfunc(x, y) + got = cfunc(x, y) + # Scalar ops => scalar result + self.assertIs(type(got), type(expected)) + self.assertEqual(got, expected, + "mismatch with %r (%r, %r)" + % (typ, x, y)) + + + # + # Comparison operators + # + + compare_scalar_operands = [-0.5, -1.0 + 1j, -1.0 + 2j, -0.5 + 1j, 1.5] + compare_types = [types.int32, types.int64, + types.uint32, types.uint64, + types.float32, types.float64] + compare_unordered_types = [types.complex64, types.complex128] + + def test_lt_scalar(self, flags=force_pyobj_flags): + self.run_test_scalar_compare(self.op.lt_usecase, flags) + + def test_lt_scalar_npm(self): + self.test_lt_scalar(flags=Noflags) + + def test_le_scalar(self, flags=force_pyobj_flags): + self.run_test_scalar_compare(self.op.le_usecase, flags) + + def test_le_scalar_npm(self): + self.test_le_scalar(flags=Noflags) + + def test_gt_scalar(self, flags=force_pyobj_flags): + self.run_test_scalar_compare(self.op.gt_usecase, flags) + + def test_gt_scalar_npm(self): + self.test_gt_scalar(flags=Noflags) + + def test_ge_scalar(self, flags=force_pyobj_flags): + self.run_test_scalar_compare(self.op.ge_usecase, flags) + + def test_ge_scalar_npm(self): + self.test_ge_scalar(flags=Noflags) + + def test_eq_scalar(self, flags=force_pyobj_flags): + self.run_test_scalar_compare(self.op.eq_usecase, flags, ordered=False) + + def test_eq_scalar_npm(self): + self.test_eq_scalar(flags=Noflags) + + def test_ne_scalar(self, flags=force_pyobj_flags): + self.run_test_scalar_compare(self.op.ne_usecase, flags, ordered=False) + + def test_ne_scalar_npm(self): + self.test_ne_scalar(flags=Noflags) + + def test_is_ellipsis(self): + cfunc = njit((types.ellipsis, types.ellipsis))(self.op.is_usecase) + self.assertTrue(cfunc(Ellipsis, Ellipsis)) + + def test_is_void_ptr(self): + # can't call this directly from python, as void cannot be unboxed + cfunc_void = jit( + (types.voidptr, types.voidptr), nopython=True + )(self.op.is_usecase) + + # this wrapper performs the casts from int to voidptr for us + @jit(nopython=True) + def cfunc(x, y): + return cfunc_void(x, y) + + self.assertTrue(cfunc(1, 1)) + self.assertFalse(cfunc(1, 2)) + + # + # Arithmetic operators + # + + def run_binop_bools(self, pyfunc, flags=force_pyobj_flags): + x_operands = [False, False, True, True] + y_operands = [False, True, False, True] + + types_list = [(types.boolean, types.boolean)] + + self.run_test_ints(pyfunc, x_operands, y_operands, types_list, + flags=flags) + + def run_binop_ints(self, pyfunc, flags=force_pyobj_flags): + x_operands = [-5, 0, 1, 2] + y_operands = [-3, -1, 1, 3] + + types_list = [(types.int32, types.int32), + (types.int64, types.int64)] + + self.run_test_ints(pyfunc, x_operands, y_operands, types_list, + flags=flags) + + x_operands = [2, 3] + y_operands = [1, 2] + + types_list = [(types.byte, types.byte), + (types.uint32, types.uint32), + (types.uint64, types.uint64)] + + self.run_test_ints(pyfunc, x_operands, y_operands, types_list, + flags=flags) + + def run_binop_floats(self, pyfunc, flags=force_pyobj_flags): + x_operands = [-1.1, 0.0, 1.1] + y_operands = [-1.5, 0.8, 2.1] + + types_list = [(types.float32, types.float32), + (types.float64, types.float64)] + + self.run_test_floats(pyfunc, x_operands, y_operands, types_list, + flags=flags) + + def run_binop_floats_floordiv(self, pyfunc, flags=force_pyobj_flags): + self.run_binop_floats(pyfunc, flags=flags) + + def run_binop_complex(self, pyfunc, flags=force_pyobj_flags): + x_operands = [-1.1 + 0.3j, 0.0 + 0.0j, 1.1j] + y_operands = [-1.5 - 0.7j, 0.8j, 2.1 - 2.0j] + + types_list = [(types.complex64, types.complex64), + (types.complex128, types.complex128)] + + self.run_test_floats(pyfunc, x_operands, y_operands, types_list, + flags=flags) + + def generate_binop_tests(ns, usecases, tp_runners, npm_array=False): + for usecase in usecases: + for tp_name, runner_name in tp_runners.items(): + for nopython in (False, True): + test_name = "test_%s_%s" % (usecase, tp_name) + if nopython: + test_name += "_npm" + flags = Noflags if nopython else force_pyobj_flags + usecase_name = "%s_usecase" % usecase + + def inner(self, runner_name=runner_name, + usecase_name=usecase_name, flags=flags): + runner = getattr(self, runner_name) + op_usecase = getattr(self.op, usecase_name) + runner(op_usecase, flags) + + if nopython and 'array' in tp_name and not npm_array: + def test_meth(self): + with self.assertTypingError(): + inner() + else: + test_meth = inner + + test_meth.__name__ = test_name + + if nopython: + test_meth = tag('important')(test_meth) + + ns[test_name] = test_meth + + + generate_binop_tests(locals(), + ('add', 'iadd', 'sub', 'isub', 'mul', 'imul'), + {'ints': 'run_binop_ints', + 'floats': 'run_binop_floats', + 'complex': 'run_binop_complex', + }) + + generate_binop_tests(locals(), + ('truediv', 'itruediv'), + {'ints': 'run_binop_ints', + 'floats': 'run_binop_floats', + 'complex': 'run_binop_complex', + }) + + # NOTE: floordiv and mod unsupported for complex numbers + generate_binop_tests(locals(), + ('floordiv', 'ifloordiv', 'mod', 'imod'), + {'ints': 'run_binop_ints', + 'floats': 'run_binop_floats_floordiv', + }) + + def check_div_errors(self, usecase_name, msg, flags=force_pyobj_flags, + allow_complex=False): + pyfunc = getattr(self.op, usecase_name) + # Signed and unsigned division can take different code paths, + # test them both. + arg_types = [types.int32, types.uint32, types.float64] + if allow_complex: + arg_types.append(types.complex128) + for tp in arg_types: + cfunc = jit((tp, tp), **flags)(pyfunc) + with self.assertRaises(ZeroDivisionError) as cm: + cfunc(1, 0) + # Test exception message if not in object mode + if flags is not force_pyobj_flags: + self.assertIn(msg, str(cm.exception)) + + def test_truediv_errors(self, flags=force_pyobj_flags): + self.check_div_errors("truediv_usecase", "division by zero", flags=flags, + allow_complex=True) + + def test_truediv_errors_npm(self): + self.test_truediv_errors(flags=Noflags) + + def test_floordiv_errors(self, flags=force_pyobj_flags): + self.check_div_errors("floordiv_usecase", "division by zero", flags=flags) + + def test_floordiv_errors_npm(self): + self.test_floordiv_errors(flags=Noflags) + + def test_mod_errors(self, flags=force_pyobj_flags): + self.check_div_errors("mod_usecase", "modulo by zero", flags=flags) + + def test_mod_errors_npm(self): + self.test_mod_errors(flags=Noflags) + + def run_pow_ints(self, pyfunc, flags=force_pyobj_flags): + x_operands = [-2, -1, 0, 1, 2] + y_operands = [0, 1, 2] + + types_list = [(types.int32, types.int32), + (types.int64, types.int64)] + + self.run_test_ints(pyfunc, x_operands, y_operands, types_list, + flags=flags) + + x_operands = [0, 1, 2] + y_operands = [0, 1, 2] + + types_list = [(types.byte, types.byte), + (types.uint32, types.uint32), + (types.uint64, types.uint64)] + + self.run_test_ints(pyfunc, x_operands, y_operands, types_list, + flags=flags) + + def run_pow_floats(self, pyfunc, flags=force_pyobj_flags): + x_operands = [-222.222, -111.111, 111.111, 222.222] + y_operands = [-2, -1, 0, 1, 2] + + types_list = [(types.float32, types.float32), + (types.float64, types.float64)] + + self.run_test_floats(pyfunc, x_operands, y_operands, types_list, + flags=flags) + + x_operands = [0.0] + y_operands = [0, 1, 2] # TODO native handling of 0 ** negative power + + types_list = [(types.float32, types.float32), + (types.float64, types.float64)] + + self.run_test_floats(pyfunc, x_operands, y_operands, types_list, + flags=flags) + + # XXX power operator is unsupported on complex numbers (see issue #488) + generate_binop_tests(locals(), + ('pow', 'ipow'), + {'ints': 'run_pow_ints', + 'floats': 'run_pow_floats', + }) + + def test_add_complex(self, flags=force_pyobj_flags): + pyfunc = self.op.add_usecase + + x_operands = [1+0j, 1j, -1-1j] + y_operands = x_operands + + types_list = [(types.complex64, types.complex64), + (types.complex128, types.complex128),] + + self.run_test_floats(pyfunc, x_operands, y_operands, types_list, + flags=flags) + + def test_add_complex_npm(self): + self.test_add_complex(flags=Noflags) + + def test_sub_complex(self, flags=force_pyobj_flags): + pyfunc = self.op.sub_usecase + + x_operands = [1+0j, 1j, -1-1j] + y_operands = [1, 2, 3] + + types_list = [(types.complex64, types.complex64), + (types.complex128, types.complex128),] + + self.run_test_floats(pyfunc, x_operands, y_operands, types_list, + flags=flags) + + def test_sub_complex_npm(self): + self.test_sub_complex(flags=Noflags) + + def test_mul_complex(self, flags=force_pyobj_flags): + pyfunc = self.op.mul_usecase + + x_operands = [1+0j, 1j, -1-1j] + y_operands = [1, 2, 3] + + types_list = [(types.complex64, types.complex64), + (types.complex128, types.complex128),] + + self.run_test_floats(pyfunc, x_operands, y_operands, types_list, + flags=flags) + + def test_mul_complex_npm(self): + self.test_mul_complex(flags=Noflags) + + def test_truediv_complex(self, flags=force_pyobj_flags): + pyfunc = self.op.truediv_usecase + + x_operands = [1+0j, 1j, -1-1j] + y_operands = [1, 2, 3] + + types_list = [(types.complex64, types.complex64), + (types.complex128, types.complex128),] + + self.run_test_floats(pyfunc, x_operands, y_operands, types_list, + flags=flags) + + def test_truediv_complex_npm(self): + self.test_truediv_complex(flags=Noflags) + + def test_mod_complex(self, flags=force_pyobj_flags): + pyfunc = self.op.mod_usecase + cres = jit((types.complex64, types.complex64), **flags)(pyfunc) + with self.assertRaises(TypeError) as raises: + cres(4j, 2j) + + # error message depends on Python version. + if utils.PYVERSION in ((3, 10), (3, 11), (3, 12), (3, 13)): + msg = "unsupported operand type(s) for %" + else: + raise NotImplementedError(utils.PYVERSION) + + self.assertIn(msg, str(raises.exception)) + + def test_mod_complex_npm(self): + pyfunc = self.op.mod_usecase + with self.assertTypingError(): + njit((types.complex64, types.complex64))(pyfunc) + + # + # Matrix multiplication + # (just check with simple values; computational tests are in test_linalg) + # + + def check_matmul_objmode(self, pyfunc, inplace): + # Use dummy objects, to work with any NumPy / SciPy version + cfunc = jit((), **force_pyobj_flags)(pyfunc) + a = DumbMatrix(3) + b = DumbMatrix(4) + got = cfunc(a, b) + self.assertEqual(got.value, 12) + if inplace: + self.assertIs(got, a) + else: + self.assertIsNot(got, a) + self.assertIsNot(got, b) + + def test_matmul(self): + self.check_matmul_objmode(self.op.matmul_usecase, inplace=False) + + def test_imatmul(self): + self.check_matmul_objmode(self.op.imatmul_usecase, inplace=True) + + @needs_blas + def check_matmul_npm(self, pyfunc): + arrty = types.Array(types.float32, 1, 'C') + cfunc = njit((arrty, arrty))(pyfunc) + a = np.float32([1, 2]) + b = np.float32([3, 4]) + got = cfunc(a, b) + self.assertPreciseEqual(got, np.dot(a, b)) + # Never inplace + self.assertIsNot(got, a) + self.assertIsNot(got, b) + + def test_matmul_npm(self): + self.check_matmul_npm(self.op.matmul_usecase) + + def test_imatmul_npm(self): + with self.assertTypingError() as raises: + self.check_matmul_npm(self.op.imatmul_usecase) + + # + # Bitwise operators + # + + def run_bitshift_left(self, pyfunc, flags=force_pyobj_flags): + x_operands = [0, 1] + y_operands = [0, 1, 2, 4, 8, 16, 31] + + types_list = [(types.uint32, types.uint32)] + + self.run_test_ints(pyfunc, x_operands, y_operands, types_list, + flags=flags) + + x_operands = [0, 1] + y_operands = [0, 1, 2, 4, 8, 16, 32, 63] + + types_list = [(types.uint64, types.uint64)] + + self.run_test_ints(pyfunc, x_operands, y_operands, types_list, + flags=flags) + + x_operands = [0, -1] + y_operands = [0, 1, 2, 4, 8, 16, 31] + + types_list = [(types.int32, types.int32)] + + self.run_test_ints(pyfunc, x_operands, y_operands, types_list, + flags=flags) + + x_operands = [0, -1] + y_operands = [0, 1, 2, 4, 8, 16, 32, 63] + + types_list = [(types.int64, types.int64)] + + self.run_test_ints(pyfunc, x_operands, y_operands, types_list, + flags=flags) + + generate_binop_tests(locals(), + ('bitshift_left', 'bitshift_ileft'), + {'ints': 'run_bitshift_left', + }) + + def run_bitshift_right(self, pyfunc, flags=force_pyobj_flags): + x_operands = [0, 1, 2**32 - 1] + y_operands = [0, 1, 2, 4, 8, 16, 31] + + types_list = [(types.uint32, types.uint32)] + + self.run_test_ints(pyfunc, x_operands, y_operands, types_list, + flags=flags) + + x_operands = [0, 1, 2**64 - 1] + y_operands = [0, 1, 2, 4, 8, 16, 32, 63] + + types_list = [(types.uint64, types.uint64)] + + self.run_test_ints(pyfunc, x_operands, y_operands, types_list, + flags=flags) + + x_operands = [0, 1, -(2**31)] + y_operands = [0, 1, 2, 4, 8, 16, 31] + + types_list = [(types.int32, types.int32)] + + self.run_test_ints(pyfunc, x_operands, y_operands, types_list, + flags=flags) + + x_operands = [0, -1, -(2**31)] + y_operands = [0, 1, 2, 4, 8, 16, 32, 63] + + types_list = [(types.int64, types.int64)] + + self.run_test_ints(pyfunc, x_operands, y_operands, types_list, + flags=flags) + + generate_binop_tests(locals(), + ('bitshift_right', 'bitshift_iright'), + {'ints': 'run_bitshift_right', + }) + + def run_logical(self, pyfunc, flags=force_pyobj_flags): + x_operands = list(range(0, 8)) + [2**32 - 1] + y_operands = list(range(0, 8)) + [2**32 - 1] + + types_list = [(types.uint32, types.uint32)] + + self.run_test_ints(pyfunc, x_operands, y_operands, types_list, + flags=flags) + + x_operands = list(range(0, 8)) + [2**64 - 1] + y_operands = list(range(0, 8)) + [2**64 - 1] + + types_list = [(types.uint64, types.uint64)] + + self.run_test_ints(pyfunc, x_operands, y_operands, types_list, + flags=flags) + + x_operands = list(range(-4, 4)) + [-(2**31), 2**31 - 1] + y_operands = list(range(-4, 4)) + [-(2**31), 2**31 - 1] + + types_list = [(types.int32, types.int32)] + + self.run_test_ints(pyfunc, x_operands, y_operands, types_list, + flags=flags) + + x_operands = list(range(-4, 4)) + [-(2**63), 2**63 - 1] + y_operands = list(range(-4, 4)) + [-(2**63), 2**63 - 1] + + types_list = [(types.int64, types.int64)] + + self.run_test_ints(pyfunc, x_operands, y_operands, types_list, + flags=flags) + + generate_binop_tests(locals(), + ('bitwise_and', 'bitwise_iand', + 'bitwise_or', 'bitwise_ior', + 'bitwise_xor', 'bitwise_ixor'), + {'ints': 'run_logical', + 'bools': 'run_binop_bools', + }) + + # + # Unary operators + # + + def test_bitwise_not(self, flags=force_pyobj_flags): + pyfunc = self.op.bitwise_not_usecase_binary + + x_operands = list(range(0, 8)) + [2**32 - 1] + x_operands = [np.uint32(x) for x in x_operands] + y_operands = [0] + + types_list = [(types.uint32, types.uint32)] + + self.run_test_ints(pyfunc, x_operands, y_operands, types_list, + flags=flags) + + x_operands = list(range(-4, 4)) + [-(2**31), 2**31 - 1] + y_operands = [0] + + types_list = [(types.int32, types.int32)] + + self.run_test_ints(pyfunc, x_operands, y_operands, types_list, + flags=flags) + + x_operands = list(range(0, 8)) + [2**64 - 1] + x_operands = [np.uint64(x) for x in x_operands] + y_operands = [0] + + types_list = [(types.uint64, types.uint64)] + + self.run_test_ints(pyfunc, x_operands, y_operands, types_list, + flags=flags) + + x_operands = list(range(-4, 4)) + [-(2**63), 2**63 - 1] + y_operands = [0] + + types_list = [(types.int64, types.int64)] + + self.run_test_ints(pyfunc, x_operands, y_operands, types_list, + flags=flags) + + # For booleans, we follow Numpy semantics (i.e. ~True == False, + # not ~True == -2) + values = [False, False, True, True] + values = list(map(np.bool_, values)) + + pyfunc = self.op.bitwise_not_usecase + cfunc = jit((types.boolean,), **flags)(pyfunc) + for val in values: + self.assertPreciseEqual(pyfunc(val), cfunc(val)) + + def test_bitwise_not_npm(self): + self.test_bitwise_not(flags=Noflags) + + def test_bitwise_float(self): + """ + Make sure that bitwise float operations are not allowed + """ + def assert_reject_compile(pyfunc, argtypes, opname): + msg = 'expecting TypingError when compiling {}'.format(pyfunc) + with self.assertRaises(errors.TypingError, msg=msg) as raises: + njit(argtypes)(pyfunc) + # check error message + fmt = _header_lead + ' {}' + expecting = fmt.format(opname + if isinstance(opname, str) + else 'Function({})'.format(opname)) + self.assertIn(expecting, str(raises.exception)) + + methods = [ + 'bitshift_left_usecase', + 'bitshift_ileft_usecase', + 'bitshift_right_usecase', + 'bitshift_iright_usecase', + 'bitwise_and_usecase', + 'bitwise_iand_usecase', + 'bitwise_or_usecase', + 'bitwise_ior_usecase', + 'bitwise_xor_usecase', + 'bitwise_ixor_usecase', + 'bitwise_not_usecase_binary', + ] + + for name in methods: + pyfunc = getattr(self.op, name) + assert_reject_compile(pyfunc, (types.float32, types.float32), + opname=self._bitwise_opnames[name]) + + def test_not(self): + pyfunc = self.op.not_usecase + + values = [ + 1, + 2, + 3, + 1.2, + 3.4j, + ] + + cfunc = jit((), **force_pyobj_flags)(pyfunc) + for val in values: + self.assertEqual(pyfunc(val), cfunc(val)) + + def test_not_npm(self): + pyfunc = self.op.not_usecase + # test native mode + argtys = [ + types.int8, + types.int32, + types.int64, + types.float32, + types.complex128, + ] + values = [ + 1, + 2, + 3, + 1.2, + 3.4j, + ] + for ty, val in zip(argtys, values): + cfunc = njit((ty,))(pyfunc) + self.assertEqual(cfunc.nopython_signatures[0].return_type, + types.boolean) + self.assertEqual(pyfunc(val), cfunc(val)) + + # XXX test_negate should check for negative and positive zeros and infinities + + def test_negate_npm(self): + pyfunc = self.op.negate_usecase + # test native mode + argtys = [ + types.int8, + types.int32, + types.int64, + types.float32, + types.float64, + types.complex128, + types.boolean, + types.boolean, + ] + values = [ + 1, + 2, + 3, + 1.2, + 2.4, + 3.4j, + True, + False, + ] + for ty, val in zip(argtys, values): + cfunc = njit((ty,))(pyfunc) + self.assertAlmostEqual(pyfunc(val), cfunc(val)) + + + def test_negate(self): + pyfunc = self.op.negate_usecase + values = [ + 1, + 2, + 3, + 1.2, + 3.4j, + True, + False, + ] + cfunc = jit((), **force_pyobj_flags)(pyfunc) + for val in values: + self.assertEqual(pyfunc(val), cfunc(val)) + + def test_unary_positive_npm(self): + pyfunc = self.op.unary_positive_usecase + # test native mode + argtys = [ + types.int8, + types.int32, + types.int64, + types.float32, + types.float64, + types.complex128, + types.boolean, + types.boolean, + ] + values = [ + 1, + 2, + 3, + 1.2, + 2.4, + 3.4j, + True, + False + ] + for ty, val in zip(argtys, values): + cfunc = njit((ty,))(pyfunc) + self.assertAlmostEqual(pyfunc(val), cfunc(val)) + + def test_unary_positive(self): + pyfunc = self.op.unary_positive_usecase + values = [ + 1, + 2, + 3, + 1.2, + 3.4j, + True, + False, + ] + cfunc = jit((), **force_pyobj_flags)(pyfunc) + for val in values: + self.assertEqual(pyfunc(val), cfunc(val)) + + def _check_in(self, pyfunc, flags): + dtype = types.int64 + cfunc = jit((dtype, types.UniTuple(dtype, 3)), **flags)(pyfunc) + for i in (3, 4, 5, 6, 42): + tup = (3, 42, 5) + self.assertPreciseEqual(pyfunc(i, tup), cfunc(i, tup)) + + def test_in(self, flags=force_pyobj_flags): + self._check_in(self.op.in_usecase, flags) + + def test_in_npm(self): + self.test_in(flags=Noflags) + + def test_not_in(self, flags=force_pyobj_flags): + self._check_in(self.op.not_in_usecase, flags) + + def test_not_in_npm(self): + self.test_not_in(flags=Noflags) + + +class TestOperatorModule(TestOperators): + + op = FunctionalOperatorImpl + + _bitwise_opnames = { + 'bitshift_left_usecase': operator.lshift, + 'bitshift_ileft_usecase': operator.ilshift, + 'bitshift_right_usecase': operator.rshift, + 'bitshift_iright_usecase': operator.irshift, + 'bitwise_and_usecase': operator.and_, + 'bitwise_iand_usecase': operator.iand, + 'bitwise_or_usecase': operator.or_, + 'bitwise_ior_usecase': operator.ior, + 'bitwise_xor_usecase': operator.xor, + 'bitwise_ixor_usecase': operator.ixor, + 'bitwise_not_usecase_binary': operator.invert, + } + + +class TestMixedInts(TestCase): + """ + Tests for operator calls with mixed integer types. + """ + + op = LiteralOperatorImpl + + int_samples = [0, 1, 3, 10, 42, 127, 10000, -1, -3, -10, -42, -127, -10000] + + int_types = [types.int8, types.uint8, types.int64, types.uint64] + signed_types = [tp for tp in int_types if tp.signed] + unsigned_types = [tp for tp in int_types if not tp.signed] + type_pairs = list(itertools.product(int_types, int_types)) + signed_pairs = [(u, v) for u, v in type_pairs + if u.signed or v.signed] + unsigned_pairs = [(u, v) for u, v in type_pairs + if not (u.signed or v.signed)] + + def int_in_dtype_range(self, val, tp): + tp_info = np.iinfo(tp.key) + return tp_info.min <= val <= tp_info.max + + def get_numpy_signed_upcast(self, *vals): + bitwidth = max(v.dtype.itemsize * 8 for v in vals) + bitwidth = max(bitwidth, types.intp.bitwidth) + return getattr(np, "int%d" % bitwidth) + + def get_numpy_unsigned_upcast(self, *vals): + bitwidth = max(v.dtype.itemsize * 8 for v in vals) + bitwidth = max(bitwidth, types.intp.bitwidth) + return getattr(np, "uint%d" % bitwidth) + + def get_typed_int(self, typ, val): + return getattr(np, typ.name)(val) + + def get_control_signed(self, opname): + op = getattr(operator, opname) + def control_signed(a, b): + tp = self.get_numpy_signed_upcast(a, b) + return op(tp(a), tp(b)) + return control_signed + + def get_control_unsigned(self, opname): + op = getattr(operator, opname) + def control_unsigned(a, b): + tp = self.get_numpy_unsigned_upcast(a, b) + return op(tp(a), tp(b)) + return control_unsigned + + def run_binary(self, pyfunc, control_func, operands, types, + expected_type=int, force_type=lambda x: x, + **assertPreciseEqualArgs): + for xt, yt in types: + cfunc = njit((xt, yt))(pyfunc) + for x, y in itertools.product(operands, operands): + # Check if xt and yt are values with range of dtype x and y + if not self.int_in_dtype_range(x, xt) or not self.int_in_dtype_range(y, yt): + continue + # Get Numpy typed scalars for the given types and values + x = self.get_typed_int(xt, x) + y = self.get_typed_int(yt, y) + expected = control_func(x, y) + got = cfunc(x, y) + self.assertIsInstance(got, expected_type) + msg = ("mismatch for (%r, %r) with types %s" + % (x, y, (xt, yt))) + got, expected = force_type(got), force_type(expected) + self.assertPreciseEqual(got, expected, msg=msg, + **assertPreciseEqualArgs) + + def run_unary(self, pyfunc, control_func, operands, types, + expected_type=int): + for xt in types: + cfunc = njit((xt,))(pyfunc) + for x in operands: + if not self.int_in_dtype_range(x, xt): + continue + x = self.get_typed_int(xt, x) + expected = control_func(x) + got = cfunc(x) + self.assertIsInstance(got, expected_type) + self.assertPreciseEqual( + got, expected, + msg="mismatch for %r with type %s: %r != %r" + % (x, xt, got, expected)) + + def run_arith_binop(self, pyfunc, opname, samples, + expected_type=int, force_type=lambda x: x, + **assertPreciseEqualArgs): + self.run_binary(pyfunc, self.get_control_signed(opname), + samples, self.signed_pairs, expected_type, + force_type=force_type, + **assertPreciseEqualArgs) + self.run_binary(pyfunc, self.get_control_unsigned(opname), + samples, self.unsigned_pairs, expected_type, + force_type=force_type, + **assertPreciseEqualArgs) + + def test_add(self): + self.run_arith_binop(self.op.add_usecase, 'add', self.int_samples) + + def test_sub(self): + self.run_arith_binop(self.op.sub_usecase, 'sub', self.int_samples) + + def test_mul(self): + self.run_arith_binop(self.op.mul_usecase, 'mul', self.int_samples) + + def test_floordiv(self): + samples = [x for x in self.int_samples if x != 0] + self.run_arith_binop(self.op.floordiv_usecase, 'floordiv', samples) + + def test_mod(self): + samples = [x for x in self.int_samples if x != 0] + self.run_arith_binop(self.op.mod_usecase, 'mod', samples) + + def test_pow(self): + extra_cast = {} + if utils.PYVERSION == (3, 11): + extra_cast["force_type"] = float + pyfunc = self.op.pow_usecase + # Only test with positive values, as otherwise trying to write the + # control function in terms of Python or Numpy power turns out insane. + samples = [x for x in self.int_samples if x >= 0] + self.run_arith_binop(pyfunc, 'pow', samples, **extra_cast) + + # Now test all non-zero values, but only with signed types + def control_signed(a, b): + tp = self.get_numpy_signed_upcast(a, b) + if b >= 0: + return tp(a) ** tp(b) + else: + inv = tp(a) ** tp(-b) + if inv == 0: + # Overflow + return 0 + return np.intp(1.0 / inv) + samples = [x for x in self.int_samples if x != 0] + signed_pairs = [(u, v) for u, v in self.type_pairs + if u.signed and v.signed] + self.run_binary(pyfunc, control_signed, + samples, signed_pairs, **extra_cast) + + def test_truediv(self): + + def control(a, b): + return float(a) / float(b) + samples = [x for x in self.int_samples if x != 0] + pyfunc = self.op.truediv_usecase + + # Note: there can be precision issues on x87 + # e.g. for `1 / 18446744073709541616` + # -> 0x1.0000000000002p-64 vs. 0x1.0000000000003p-64. + self.run_binary(pyfunc, control, samples, self.signed_pairs, + expected_type=float, prec='double') + self.run_binary(pyfunc, control, samples, self.unsigned_pairs, + expected_type=float, prec='double') + + def test_and(self): + self.run_arith_binop(self.op.bitwise_and_usecase, 'and_', self.int_samples) + + def test_or(self): + self.run_arith_binop(self.op.bitwise_or_usecase, 'or_', self.int_samples) + + def test_xor(self): + self.run_arith_binop(self.op.bitwise_xor_usecase, 'xor', self.int_samples) + + def run_shift_binop(self, pyfunc, opname): + opfunc = getattr(operator, opname) + def control_signed(a, b): + tp = self.get_numpy_signed_upcast(a, b) + return opfunc(tp(a), tp(b)) + def control_unsigned(a, b): + tp = self.get_numpy_unsigned_upcast(a, b) + return opfunc(tp(a), tp(b)) + + samples = self.int_samples + + def check(xt, yt, control_func): + cfunc = njit((xt, yt))(pyfunc) + for x in samples: + # Avoid shifting by more than the shiftand's bitwidth, as + # we would hit undefined behaviour. + maxshift = xt.bitwidth - 1 + for y in (0, 1, 3, 5, maxshift - 1, maxshift): + if not self.int_in_dtype_range(x, xt) or not self.int_in_dtype_range(y, yt): + continue + # Get Numpy typed scalars for the given types and values + x = self.get_typed_int(xt, x) + y = self.get_typed_int(yt, y) + expected = control_func(x, y) + got = cfunc(x, y) + msg = ("mismatch for (%r, %r) with types %s" + % (x, y, (xt, yt))) + self.assertPreciseEqual(got, expected, msg=msg) + + # For bitshifts, only the first operand's signedness matters + # to choose the operation's signedness. + signed_pairs = [(u, v) for u, v in self.type_pairs + if u.signed] + unsigned_pairs = [(u, v) for u, v in self.type_pairs + if not u.signed] + + for xt, yt in signed_pairs: + check(xt, yt, control_signed) + for xt, yt in unsigned_pairs: + check(xt, yt, control_unsigned) + + def test_lshift(self): + self.run_shift_binop(self.op.bitshift_left_usecase, 'lshift') + + def test_rshift(self): + self.run_shift_binop(self.op.bitshift_right_usecase, 'rshift') + + def test_unary_positive(self): + def control(a): + return a + samples = self.int_samples + pyfunc = self.op.unary_positive_usecase + + self.run_unary(pyfunc, control, samples, self.int_types) + + def test_unary_negative(self): + def control_signed(a): + tp = self.get_numpy_signed_upcast(a) + return tp(-a) + def control_unsigned(a): + tp = self.get_numpy_unsigned_upcast(a) + return tp(-a) + samples = self.int_samples + pyfunc = self.op.negate_usecase + + self.run_unary(pyfunc, control_signed, samples, self.signed_types) + self.run_unary(pyfunc, control_unsigned, samples, self.unsigned_types) + + def test_invert(self): + def control_signed(a): + tp = self.get_numpy_signed_upcast(a) + return tp(~a) + def control_unsigned(a): + tp = self.get_numpy_unsigned_upcast(a) + return tp(~a) + samples = self.int_samples + pyfunc = self.op.bitwise_not_usecase + + self.run_unary(pyfunc, control_signed, samples, self.signed_types) + self.run_unary(pyfunc, control_unsigned, samples, self.unsigned_types) + + +class TestMixedIntsOperatorModule(TestMixedInts): + + op = FunctionalOperatorImpl + + +class TestStaticPower(TestCase): + """ + Test the ** operator with a static exponent, to exercise a + dedicated optimization. + """ + + def _check_pow(self, exponents, values): + for exp in exponents: + # test against non-static version of the @jit-ed function + regular_func = LiteralOperatorImpl.pow_usecase + static_func = make_static_power(exp) + + static_cfunc = jit(nopython=True)(static_func) + regular_cfunc = jit(nopython=True)(regular_func) + for v in values: + try: + expected = regular_cfunc(v, exp) + except ZeroDivisionError: + with self.assertRaises(ZeroDivisionError): + static_cfunc(v) + else: + got = static_cfunc(v) + self.assertPreciseEqual(expected, got, prec='double') + + def test_int_values(self): + exponents = [1, 2, 3, 5, 17, 0, -1, -2, -3] + vals = [0, 1, 3, -1, -4, np.int8(-3), np.uint16(4)] + + self._check_pow(exponents, vals) + + def test_real_values(self): + exponents = [1, 2, 3, 5, 17, 0, -1, -2, -3, 0x111111, -0x111112] + vals = [1.5, 3.25, -1.25, np.float32(-2.0), float('inf'), float('nan')] + + self._check_pow(exponents, vals) + +class TestStringConstComparison(TestCase): + """ + Test comparison of string constants + """ + def test_eq(self): + def test_impl1(): + s = 'test' + return s == 'test' + + def test_impl2(): + s = 'test1' + return s == 'test' + + cfunc1 = jit(nopython=True)(test_impl1) + cfunc2 = jit(nopython=True)(test_impl2) + self.assertEqual(test_impl1(), cfunc1()) + self.assertEqual(test_impl2(), cfunc2()) + + def test_neq(self): + def test_impl1(): + s = 'test' + return s != 'test' + + def test_impl2(): + s = 'test1' + return s != 'test' + + cfunc1 = jit(nopython=True)(test_impl1) + cfunc2 = jit(nopython=True)(test_impl2) + self.assertEqual(test_impl1(), cfunc1()) + self.assertEqual(test_impl2(), cfunc2()) + +class TestBooleanLiteralOperators(TestCase): + """ + Test operators with Boolean constants + """ + def test_eq(self): + + def test_impl1(b): + return a_val == b + + def test_impl2(a): + return a == b_val + + def test_impl3(): + r1 = True == True + r2 = True == False + r3 = False == True + r4 = False == False + return (r1, r2, r3, r4) + + for a_val, b in itertools.product([True, False], repeat=2): + cfunc1 = jit(nopython=True)(test_impl1) + self.assertEqual(test_impl1(b), cfunc1(b)) + + for a, b_val in itertools.product([True, False], repeat=2): + cfunc2 = jit(nopython=True)(test_impl2) + self.assertEqual(test_impl2(a), cfunc2(a)) + + cfunc3 = jit(nopython=True)(test_impl3) + self.assertEqual(test_impl3(), cfunc3()) + + def test_ne(self): + + def test_impl1(b): + return a_val != b + + def test_impl2(a): + return a != b_val + + def test_impl3(): + r1 = True != True + r2 = True != False + r3 = False != True + r4 = False != False + return (r1, r2, r3, r4) + + for a_val, b in itertools.product([True, False], repeat=2): + cfunc1 = jit(nopython=True)(test_impl1) + self.assertEqual(test_impl1(b), cfunc1(b)) + + for a, b_val in itertools.product([True, False], repeat=2): + cfunc2 = jit(nopython=True)(test_impl2) + self.assertEqual(test_impl2(a), cfunc2(a)) + + cfunc3 = jit(nopython=True)(test_impl3) + self.assertEqual(test_impl3(), cfunc3()) + + def test_is(self): + + def test_impl1(b): + return a_val is b + + def test_impl2(): + r1 = True is True + r2 = True is False + r3 = False is True + r4 = False is False + return (r1, r2, r3, r4) + + for a_val, b in itertools.product([True, False], repeat=2): + cfunc1 = jit(nopython=True)(test_impl1) + self.assertEqual(test_impl1(b), cfunc1(b)) + + cfunc2 = jit(nopython=True)(test_impl2) + self.assertEqual(test_impl2(), cfunc2()) + + def test_not(self): + + def test_impl(): + a, b = False, True + return (not a, not b) + + cfunc = jit(nopython=True)(test_impl) + self.assertEqual(test_impl(), cfunc()) + + def test_bool(self): + + def test_impl(): + a, b = False, True + return (bool(a), bool(b)) + + cfunc = jit(nopython=True)(test_impl) + self.assertEqual(test_impl(), cfunc()) + + def test_bool_to_str(self): + + def test_impl(): + a, b = False, True + return (str(a), str(b)) + + cfunc = jit(nopython=True)(test_impl) + self.assertEqual(test_impl(), cfunc()) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_overlap.py b/lib/python3.10/site-packages/numba/tests/test_overlap.py new file mode 100644 index 0000000000000000000000000000000000000000..eecf77c099ce9359a5ed298f84c5eefaa7076883 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_overlap.py @@ -0,0 +1,134 @@ +import numpy as np + +from numba import jit +from numba.core import types +from numba.tests.support import TestCase, tag +import unittest + + +# Array overlaps involving a displacement + +def array_overlap1(src, dest, k=1): + assert src.shape == dest.shape + dest[k:] = src[:-k] + +def array_overlap2(src, dest, k=1): + assert src.shape == dest.shape + dest[:-k] = src[k:] + +def array_overlap3(src, dest, k=1): + assert src.shape == dest.shape + dest[:,:-k] = src[:,k:] + +def array_overlap4(src, dest, k=1): + assert src.shape == dest.shape + dest[:,k:] = src[:,:-k] + +def array_overlap5(src, dest, k=1): + assert src.shape == dest.shape + dest[...,:-k] = src[...,k:] + +def array_overlap6(src, dest, k=1): + assert src.shape == dest.shape + dest[...,k:] = src[...,:-k] + +# Array overlaps involving an in-place reversal + +def array_overlap11(src, dest): + assert src.shape == dest.shape + dest[::-1] = src + +def array_overlap12(src, dest): + assert src.shape == dest.shape + dest[:] = src[::-1] + +def array_overlap13(src, dest): + assert src.shape == dest.shape + dest[:,::-1] = src + +def array_overlap14(src, dest): + assert src.shape == dest.shape + dest[:] = src[:,::-1] + +def array_overlap15(src, dest): + assert src.shape == dest.shape + dest[...,::-1] = src + +def array_overlap16(src, dest): + assert src.shape == dest.shape + dest[:] = src[...,::-1] + + +class TestArrayOverlap(TestCase): + + def check_overlap(self, pyfunc, min_ndim, have_k_argument=False): + N = 4 + + def vary_layouts(orig): + yield orig.copy(order='C') + yield orig.copy(order='F') + a = orig[::-1].copy()[::-1] + assert not a.flags.c_contiguous and not a.flags.f_contiguous + yield a + + def check(pyfunc, cfunc, pydest, cdest, kwargs): + pyfunc(pydest, pydest, **kwargs) + cfunc(cdest, cdest, **kwargs) + self.assertPreciseEqual(pydest, cdest) + + cfunc = jit(nopython=True)(pyfunc) + # Check for up to 3d arrays + for ndim in range(min_ndim, 4): + shape = (N,) * ndim + orig = np.arange(0, N**ndim).reshape(shape) + # Note we cannot copy a 'A' layout array exactly (bitwise), + # so instead we call vary_layouts() twice + for pydest, cdest in zip(vary_layouts(orig), vary_layouts(orig)): + if have_k_argument: + for k in range(1, N): + check(pyfunc, cfunc, pydest, cdest, dict(k=k)) + else: + check(pyfunc, cfunc, pydest, cdest, {}) + + def check_overlap_with_k(self, pyfunc, min_ndim): + self.check_overlap(pyfunc, min_ndim=min_ndim, have_k_argument=True) + + def test_overlap1(self): + self.check_overlap_with_k(array_overlap1, min_ndim=1) + + def test_overlap2(self): + self.check_overlap_with_k(array_overlap2, min_ndim=1) + + def test_overlap3(self): + self.check_overlap_with_k(array_overlap3, min_ndim=2) + + def test_overlap4(self): + self.check_overlap_with_k(array_overlap4, min_ndim=2) + + def test_overlap5(self): + self.check_overlap_with_k(array_overlap5, min_ndim=1) + + def test_overlap6(self): + self.check_overlap_with_k(array_overlap6, min_ndim=1) + + def test_overlap11(self): + self.check_overlap(array_overlap11, min_ndim=1) + + def test_overlap12(self): + self.check_overlap(array_overlap12, min_ndim=1) + + def test_overlap13(self): + self.check_overlap(array_overlap13, min_ndim=2) + + def test_overlap14(self): + self.check_overlap(array_overlap14, min_ndim=2) + + def test_overlap15(self): + self.check_overlap(array_overlap15, min_ndim=1) + + def test_overlap16(self): + self.check_overlap(array_overlap16, min_ndim=1) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_practical_lowering_issues.py b/lib/python3.10/site-packages/numba/tests/test_practical_lowering_issues.py new file mode 100644 index 0000000000000000000000000000000000000000..a069591946a845e3456d4499ca94845025e165c8 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_practical_lowering_issues.py @@ -0,0 +1,212 @@ +""" +Tests for practical lowering specific errors. +""" + +import numpy as np +from numba import njit +from numba.core import types, ir +from numba.core.compiler import CompilerBase, DefaultPassBuilder +from numba.core.typed_passes import NopythonTypeInference +from numba.core.compiler_machinery import register_pass, FunctionPass + +from numba.tests.support import MemoryLeakMixin, TestCase + + +def issue7507_lround(a): + """Dummy function used in test""" + pass + + +class TestLowering(MemoryLeakMixin, TestCase): + def test_issue4156_loop_vars_leak(self): + """Test issues with zero-filling of refct'ed variables inside loops. + + Before the fix, the in-loop variables are always zero-filled at their + definition location. As a result, their state from the previous + iteration is erased. No decref is applied. To fix this, the + zero-filling must only happen once after the alloca at the function + entry block. The loop variables are technically defined once per + function (one alloca per definition per function), but semantically + defined once per assignment. Semantically, their lifetime stop only + when the variable is re-assigned or when the function ends. + """ + @njit + def udt(N): + sum_vec = np.zeros(3) + for n in range(N): + if n >= 0: + # `vec` would leak without the fix. + vec = np.ones(1) + if n >= 0: + sum_vec += vec[0] + + return sum_vec + + got = udt(4) + expect = udt.py_func(4) + self.assertPreciseEqual(got, expect) + + def test_issue4156_loop_vars_leak_variant1(self): + """Variant of test_issue4156_loop_vars_leak. + + Adding an outer loop. + """ + @njit + def udt(N): + sum_vec = np.zeros(3) + for x in range(N): + for y in range(N): + n = x + y + if n >= 0: + # `vec` would leak without the fix. + vec = np.ones(1) + if n >= 0: + sum_vec += vec[0] + + return sum_vec + + got = udt(4) + expect = udt.py_func(4) + self.assertPreciseEqual(got, expect) + + def test_issue4156_loop_vars_leak_variant2(self): + """Variant of test_issue4156_loop_vars_leak. + + Adding deeper outer loop. + """ + @njit + def udt(N): + sum_vec = np.zeros(3) + for z in range(N): + for x in range(N): + for y in range(N): + n = x + y + z + if n >= 0: + # `vec` would leak without the fix. + vec = np.ones(1) + if n >= 0: + sum_vec += vec[0] + + return sum_vec + + got = udt(4) + expect = udt.py_func(4) + self.assertPreciseEqual(got, expect) + + def test_issue4156_loop_vars_leak_variant3(self): + """Variant of test_issue4156_loop_vars_leak. + + Adding inner loop around allocation + """ + @njit + def udt(N): + sum_vec = np.zeros(3) + for z in range(N): + for x in range(N): + n = x + z + if n >= 0: + for y in range(N): + # `vec` would leak without the fix. + vec = np.ones(y) + if n >= 0: + sum_vec += vec[0] + + return sum_vec + + got = udt(4) + expect = udt.py_func(4) + self.assertPreciseEqual(got, expect) + + def test_issue4156_loop_vars_leak_variant4(self): + """Variant of test_issue4156_loop_vars_leak. + + Interleaves loops and allocations + """ + @njit + def udt(N): + sum_vec = 0 + + for n in range(N): + vec = np.zeros(7) + for n in range(N): + z = np.zeros(7) + sum_vec += vec[0] + z[0] + + return sum_vec + + got = udt(4) + expect = udt.py_func(4) + self.assertPreciseEqual(got, expect) + + def test_issue_with_literal_in_static_getitem(self): + """Test an issue with literal type used as index of static_getitem + """ + + @register_pass(mutates_CFG=False, analysis_only=False) + class ForceStaticGetitemLiteral(FunctionPass): + + _name = "force_static_getitem_literal" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + repl = {} + # Force the static_getitem to have a literal type as + # index to replicate the problem. + for inst, sig in state.calltypes.items(): + if (isinstance(inst, ir.Expr) and + inst.op == 'static_getitem'): + [obj, idx] = sig.args + new_sig = sig.replace(args=(obj, + types.literal(inst.index))) + repl[inst] = new_sig + state.calltypes.update(repl) + return True + + class CustomPipeline(CompilerBase): + def define_pipelines(self): + pm = DefaultPassBuilder.define_nopython_pipeline(self.state) + pm.add_pass_after(ForceStaticGetitemLiteral, + NopythonTypeInference) + pm.finalize() + return [pm] + + @njit(pipeline_class=CustomPipeline) + def foo(arr): + return arr[4] # force static_getitem + + arr = np.arange(10) + got = foo(arr) + expect = foo.py_func(arr) + self.assertEqual(got, expect) + + def test_issue7507(self): + """ + Test a problem with BaseContext.get_function() because of changes + related to the new style error handling. + """ + from numba.core.typing.templates import AbstractTemplate, infer_global + from numba.core.imputils import lower_builtin + + @infer_global(issue7507_lround) + class lroundTemplate(AbstractTemplate): + key = issue7507_lround + + def generic(self, args, kws): + signature = types.int64(types.float64) + + # insert a new builtin during the compilation process + @lower_builtin(issue7507_lround, types.float64) + def codegen(context, builder, sig, args): + # Simply truncate with the cast to integer. + return context.cast(builder, args[0], sig.args[0], + sig.return_type) + + return signature + + @njit('int64(float64)') + def foo(a): + return issue7507_lround(a) + + self.assertEqual(foo(3.4), 3) diff --git a/lib/python3.10/site-packages/numba/tests/test_pycc.py b/lib/python3.10/site-packages/numba/tests/test_pycc.py new file mode 100644 index 0000000000000000000000000000000000000000..f9cf92cb8fb08a1fb38a81b70f428ca442007263 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_pycc.py @@ -0,0 +1,359 @@ +import contextlib +import importlib +import os +import shutil +import subprocess +import sys +import tempfile +from unittest import skip +from ctypes import * + +import numpy as np + +import llvmlite.binding as ll + +from numba.core import utils +from numba.tests.support import (TestCase, tag, import_dynamic, temp_directory, + has_blas, needs_setuptools) + +import unittest + + +_skip_reason = 'windows only' +_windows_only = unittest.skipIf(not sys.platform.startswith('win'), + _skip_reason) + + +base_path = os.path.dirname(os.path.abspath(__file__)) + + +def unset_macosx_deployment_target(): + """Unset MACOSX_DEPLOYMENT_TARGET because we are not building portable + libraries + """ + if 'MACOSX_DEPLOYMENT_TARGET' in os.environ: + del os.environ['MACOSX_DEPLOYMENT_TARGET'] + + +@needs_setuptools +class TestCompilerChecks(TestCase): + + # NOTE: THIS TEST MUST ALWAYS RUN ON WINDOWS, DO NOT SKIP + @_windows_only + def test_windows_compiler_validity(self): + # When inside conda-build VSINSTALLDIR should be set and windows should + # have a valid compiler available, `external_compiler_works()` should + # agree with this. If this is not the case then error out to alert devs. + + # This is a local import to avoid deprecation warnings being generated + # through the use of the numba.pycc module. + from numba.pycc.platform import external_compiler_works + is_running_conda_build = os.environ.get('CONDA_BUILD', None) is not None + if is_running_conda_build: + if os.environ.get('VSINSTALLDIR', None) is not None: + self.assertTrue(external_compiler_works()) + + +class BasePYCCTest(TestCase): + + def setUp(self): + unset_macosx_deployment_target() + + self.tmpdir = temp_directory('test_pycc') + # Make sure temporary files and directories created by + # distutils don't clutter the top-level /tmp + tempfile.tempdir = self.tmpdir + + def tearDown(self): + tempfile.tempdir = None + # Since we're executing the module-under-test several times + # from the same process, we must clear the exports registry + # between invocations. + + # This is a local import to avoid deprecation warnings being generated + # through the use of the numba.pycc module. + from numba.pycc.decorators import clear_export_registry + clear_export_registry() + + @contextlib.contextmanager + def check_c_ext(self, extdir, name): + sys.path.append(extdir) + try: + lib = import_dynamic(name) + yield lib + finally: + sys.path.remove(extdir) + sys.modules.pop(name, None) + + +@needs_setuptools +class TestCC(BasePYCCTest): + + def setUp(self): + super(TestCC, self).setUp() + self.skip_if_no_external_compiler() # external compiler needed + from numba.tests import compile_with_pycc + self._test_module = compile_with_pycc + importlib.reload(self._test_module) + + @contextlib.contextmanager + def check_cc_compiled(self, cc): + #cc.verbose = True + cc.output_dir = self.tmpdir + cc.compile() + + with self.check_c_ext(self.tmpdir, cc.name) as lib: + yield lib + + def check_cc_compiled_in_subprocess(self, lib, code): + prolog = """if 1: + import sys + import types + # to disable numba package + sys.modules['numba'] = types.ModuleType('numba') + try: + from numba import njit + except ImportError: + pass + else: + raise RuntimeError('cannot disable numba package') + + sys.path.insert(0, %(path)r) + import %(name)s as lib + """ % {'name': lib.__name__, + 'path': os.path.dirname(lib.__file__)} + code = prolog.strip(' ') + code + subprocess.check_call([sys.executable, '-c', code]) + + def test_cc_properties(self): + cc = self._test_module.cc + self.assertEqual(cc.name, 'pycc_test_simple') + + # Inferred output directory + d = self._test_module.cc.output_dir + self.assertTrue(os.path.isdir(d), d) + + # Inferred output filename + f = self._test_module.cc.output_file + self.assertFalse(os.path.exists(f), f) + self.assertTrue(os.path.basename(f).startswith('pycc_test_simple.'), f) + if sys.platform.startswith('linux'): + self.assertTrue(f.endswith('.so'), f) + # This is a local import to avoid deprecation warnings being + # generated through the use of the numba.pycc module. + from numba.pycc.platform import find_pyext_ending + self.assertIn(find_pyext_ending(), f) + + def test_compile(self): + with self.check_cc_compiled(self._test_module.cc) as lib: + res = lib.multi(123, 321) + self.assertPreciseEqual(res, 123 * 321) + res = lib.multf(987, 321) + self.assertPreciseEqual(res, 987.0 * 321.0) + res = lib.square(5) + self.assertPreciseEqual(res, 25) + self.assertIs(lib.get_none(), None) + with self.assertRaises(ZeroDivisionError): + lib.div(1, 0) + + def check_compile_for_cpu(self, cpu_name): + cc = self._test_module.cc + cc.target_cpu = cpu_name + + with self.check_cc_compiled(cc) as lib: + res = lib.multi(123, 321) + self.assertPreciseEqual(res, 123 * 321) + self.assertEqual(lib.multi.__module__, 'pycc_test_simple') + + def test_compile_for_cpu(self): + # Compiling for the host CPU should always succeed + self.check_compile_for_cpu(ll.get_host_cpu_name()) + + def test_compile_for_cpu_host(self): + # Compiling for the host CPU should always succeed + self.check_compile_for_cpu("host") + + def test_compile_helperlib(self): + with self.check_cc_compiled(self._test_module.cc_helperlib) as lib: + res = lib.power(2, 7) + self.assertPreciseEqual(res, 128) + for val in (-1, -1 + 0j, np.complex128(-1)): + res = lib.sqrt(val) + self.assertPreciseEqual(res, 1j) + for val in (4, 4.0, np.float64(4)): + res = lib.np_sqrt(val) + self.assertPreciseEqual(res, 2.0) + res = lib.spacing(1.0) + self.assertPreciseEqual(res, 2**-52) + # Implicit seeding at startup should guarantee a non-pathological + # start state. + self.assertNotEqual(lib.random(-1), lib.random(-1)) + res = lib.random(42) + expected = np.random.RandomState(42).random_sample() + self.assertPreciseEqual(res, expected) + res = lib.size(np.float64([0] * 3)) + self.assertPreciseEqual(res, 3) + + code = """if 1: + from numpy.testing import assert_equal, assert_allclose + res = lib.power(2, 7) + assert res == 128 + res = lib.random(42) + assert_allclose(res, %(expected)s) + res = lib.spacing(1.0) + assert_allclose(res, 2**-52) + """ % {'expected': expected} + self.check_cc_compiled_in_subprocess(lib, code) + + def test_compile_nrt(self): + with self.check_cc_compiled(self._test_module.cc_nrt) as lib: + # Sanity check + self.assertPreciseEqual(lib.zero_scalar(1), 0.0) + res = lib.zeros(3) + self.assertEqual(list(res), [0, 0, 0]) + if has_blas: + res = lib.vector_dot(4) + self.assertPreciseEqual(res, 30.0) + # test argsort + val = np.float64([2., 5., 1., 3., 4.]) + res = lib.np_argsort(val) + expected = np.argsort(val) + self.assertPreciseEqual(res, expected) + + code = """if 1: + from numpy.testing import assert_equal + from numpy import float64, argsort + res = lib.zero_scalar(1) + assert res == 0.0 + res = lib.zeros(3) + assert list(res) == [0, 0, 0] + if %(has_blas)s: + res = lib.vector_dot(4) + assert res == 30.0 + val = float64([2., 5., 1., 3., 4.]) + res = lib.np_argsort(val) + expected = argsort(val) + assert_equal(res, expected) + """ % dict(has_blas=has_blas) + self.check_cc_compiled_in_subprocess(lib, code) + + def test_hashing(self): + with self.check_cc_compiled(self._test_module.cc_nrt) as lib: + res = lib.hash_literal_str_A() + self.assertPreciseEqual(res, hash("A")) + res = lib.hash_str("A") + self.assertPreciseEqual(res, hash("A")) + + code = """if 1: + from numpy.testing import assert_equal + res = lib.hash_literal_str_A() + assert_equal(res, hash("A")) + res = lib.hash_str("A") + assert_equal(res, hash("A")) + """ + self.check_cc_compiled_in_subprocess(lib, code) + + def test_c_extension_usecase(self): + # Test C-extensions + with self.check_cc_compiled(self._test_module.cc_nrt) as lib: + arr = np.arange(128, dtype=np.intp) + got = lib.dict_usecase(arr) + expect = arr * arr + self.assertPreciseEqual(got, expect) + + +@needs_setuptools +class TestDistutilsSupport(TestCase): + + def setUp(self): + super().setUp() + self.skip_if_no_external_compiler() # external compiler needed + + unset_macosx_deployment_target() + + # Copy the test project into a temp directory to avoid + # keeping any build leftovers in the source tree + self.tmpdir = temp_directory('test_pycc_distutils') + source_dir = os.path.join(base_path, 'pycc_distutils_usecase') + self.usecase_dir = os.path.join(self.tmpdir, 'work') + shutil.copytree(source_dir, self.usecase_dir) + + def check_setup_py(self, setup_py_file): + # Compute PYTHONPATH to ensure the child processes see this Numba + import numba + numba_path = os.path.abspath(os.path.dirname( + os.path.dirname(numba.__file__))) + env = dict(os.environ) + if env.get('PYTHONPATH', ''): + env['PYTHONPATH'] = numba_path + os.pathsep + env['PYTHONPATH'] + else: + env['PYTHONPATH'] = numba_path + + def run_python(args): + p = subprocess.Popen([sys.executable] + args, + cwd=self.usecase_dir, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + env=env) + out, _ = p.communicate() + rc = p.wait() + if rc != 0: + self.fail("python failed with the following output:\n%s" + % out.decode('utf-8', 'ignore')) + + run_python([setup_py_file, "build_ext", "--inplace"]) + code = """if 1: + import pycc_compiled_module as lib + assert lib.get_const() == 42 + res = lib.ones(3) + assert list(res) == [1.0, 1.0, 1.0] + """ + run_python(["-c", code]) + + def check_setup_nested_py(self, setup_py_file): + # Compute PYTHONPATH to ensure the child processes see this Numba + import numba + numba_path = os.path.abspath(os.path.dirname( + os.path.dirname(numba.__file__))) + env = dict(os.environ) + if env.get('PYTHONPATH', ''): + env['PYTHONPATH'] = numba_path + os.pathsep + env['PYTHONPATH'] + else: + env['PYTHONPATH'] = numba_path + + def run_python(args): + p = subprocess.Popen([sys.executable] + args, + cwd=self.usecase_dir, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + env=env) + out, _ = p.communicate() + rc = p.wait() + if rc != 0: + self.fail("python failed with the following output:\n%s" + % out.decode('utf-8', 'ignore')) + + run_python([setup_py_file, "build_ext", "--inplace"]) + code = """if 1: + import nested.pycc_compiled_module as lib + assert lib.get_const() == 42 + res = lib.ones(3) + assert list(res) == [1.0, 1.0, 1.0] + """ + run_python(["-c", code]) + + def test_setup_py_distutils(self): + self.check_setup_py("setup_distutils.py") + + def test_setup_py_distutils_nested(self): + self.check_setup_nested_py("setup_distutils_nested.py") + + def test_setup_py_setuptools(self): + self.check_setup_py("setup_setuptools.py") + + def test_setup_py_setuptools_nested(self): + self.check_setup_nested_py("setup_setuptools_nested.py") + + +if __name__ == "__main__": + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_recursion.py b/lib/python3.10/site-packages/numba/tests/test_recursion.py new file mode 100644 index 0000000000000000000000000000000000000000..346df05720d4d1f53c7806f5b2635518b9e22f34 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_recursion.py @@ -0,0 +1,129 @@ +import math +import warnings + +from numba import jit +from numba.core.errors import TypingError, NumbaWarning +from numba.tests.support import TestCase +import unittest + + +class TestSelfRecursion(TestCase): + + def check_fib(self, cfunc): + self.assertPreciseEqual(cfunc(10), 55) + + def test_global_explicit_sig(self): + from numba.tests.recursion_usecases import fib1 + self.check_fib(fib1) + + def test_inner_explicit_sig(self): + from numba.tests.recursion_usecases import fib2 + self.check_fib(fib2) + + def test_global_implicit_sig(self): + from numba.tests.recursion_usecases import fib3 + self.check_fib(fib3) + + def test_runaway(self): + from numba.tests.recursion_usecases import runaway_self + with self.assertRaises(TypingError) as raises: + runaway_self(123) + self.assertIn("cannot type infer runaway recursion", + str(raises.exception)) + + def test_type_change(self): + from numba.tests.recursion_usecases import make_type_change_self + pfunc = make_type_change_self() + cfunc = make_type_change_self(jit(nopython=True)) + args = 13, 0.125 + self.assertPreciseEqual(pfunc(*args), cfunc(*args)) + + def test_raise(self): + from numba.tests.recursion_usecases import raise_self + with self.assertRaises(ValueError) as raises: + raise_self(3) + + self.assertEqual(str(raises.exception), "raise_self") + + def test_optional_return(self): + from numba.tests.recursion_usecases import make_optional_return_case + pfunc = make_optional_return_case() + cfunc = make_optional_return_case(jit(nopython=True)) + for arg in (0, 5, 10, 15): + self.assertEqual(pfunc(arg), cfunc(arg)) + + def test_growing_return_tuple(self): + from numba.tests.recursion_usecases import make_growing_tuple_case + cfunc = make_growing_tuple_case(jit(nopython=True)) + with self.assertRaises(TypingError) as raises: + cfunc(100) + self.assertIn( + "Return type of recursive function does not converge", + str(raises.exception), + ) + + +class TestMutualRecursion(TestCase): + + def test_mutual_1(self): + from numba.tests.recursion_usecases import outer_fac + expect = math.factorial(10) + self.assertPreciseEqual(outer_fac(10), expect) + + def test_mutual_2(self): + from numba.tests.recursion_usecases import make_mutual2 + pfoo, pbar = make_mutual2() + cfoo, cbar = make_mutual2(jit(nopython=True)) + for x in [-1, 0, 1, 3]: + self.assertPreciseEqual(pfoo(x=x), cfoo(x=x)) + self.assertPreciseEqual(pbar(y=x, z=1), cbar(y=x, z=1)) + + def test_runaway(self): + from numba.tests.recursion_usecases import runaway_mutual + with self.assertRaises(TypingError) as raises: + runaway_mutual(123) + self.assertIn("cannot type infer runaway recursion", + str(raises.exception)) + + def test_type_change(self): + from numba.tests.recursion_usecases import make_type_change_mutual + pfunc = make_type_change_mutual() + cfunc = make_type_change_mutual(jit(nopython=True)) + args = 13, 0.125 + self.assertPreciseEqual(pfunc(*args), cfunc(*args)) + + def test_four_level(self): + from numba.tests.recursion_usecases import make_four_level + pfunc = make_four_level() + cfunc = make_four_level(jit(nopython=True)) + arg = 7 + self.assertPreciseEqual(pfunc(arg), cfunc(arg)) + + def test_inner_error(self): + from numba.tests.recursion_usecases import make_inner_error + # nopython mode + cfunc = make_inner_error(jit(nopython=True)) + with self.assertRaises(TypingError) as raises: + cfunc(2) + errmsg = 'Unknown attribute \'ndim\'' + self.assertIn(errmsg, str(raises.exception)) + # objectmode + # error is never trigger, function return normally + cfunc = make_inner_error(jit(forceobj=True)) + pfunc = make_inner_error() + with warnings.catch_warnings(): + warnings.filterwarnings('ignore', category=NumbaWarning) + got = cfunc(6) + self.assertEqual(got, pfunc(6)) + + def test_raise(self): + from numba.tests.recursion_usecases import make_raise_mutual + cfunc = make_raise_mutual()#jit(nopython=True)) + with self.assertRaises(ValueError) as raises: + cfunc(2) + + self.assertEqual(str(raises.exception), "raise_mutual") + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_remove_dead.py b/lib/python3.10/site-packages/numba/tests/test_remove_dead.py new file mode 100644 index 0000000000000000000000000000000000000000..b1ab55ce2d5e38d36bfffcf05fceb07be1567efc --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_remove_dead.py @@ -0,0 +1,436 @@ +# +# Copyright (c) 2017 Intel Corporation +# SPDX-License-Identifier: BSD-2-Clause +# + +import numba +import numba.parfors.parfor +from numba import njit, jit +from numba.core import ir_utils +from numba.core import types, ir, compiler +from numba.core.registry import cpu_target +from numba.core.ir_utils import (copy_propagate, apply_copy_propagate, + get_name_var_table, remove_dels, remove_dead, + remove_call_handlers, alias_func_extensions) +from numba.core.typed_passes import type_inference_stage +from numba.core.compiler_machinery import FunctionPass, register_pass, PassManager +from numba.core.untyped_passes import (ExtractByteCode, TranslateByteCode, FixupArgs, + IRProcessing, DeadBranchPrune, + RewriteSemanticConstants, GenericRewrites, + WithLifting, PreserveIR, InlineClosureLikes) + +from numba.core.typed_passes import (NopythonTypeInference, AnnotateTypes, + NopythonRewrites, PreParforPass, ParforPass, + DumpParforDiagnostics, NativeLowering, + IRLegalization, NoPythonBackend, NativeLowering) +import numpy as np +from numba.tests.support import skip_parfors_unsupported, needs_blas, TestCase +import unittest + + +def test_will_propagate(b, z, w): + x1 = 3 + x = x1 + if b > 0: + y = z + w + else: + y = 0 + a = 2 * x + return a < b + +def null_func(a,b,c,d): + False + +@numba.njit +def dummy_aliased_func(A): + return A + +def alias_ext_dummy_func(lhs_name, args, alias_map, arg_aliases): + ir_utils._add_alias(lhs_name, args[0].name, alias_map, arg_aliases) + +def findLhsAssign(func_ir, var): + for label, block in func_ir.blocks.items(): + for i, inst in enumerate(block.body): + if isinstance(inst, ir.Assign) and inst.target.name==var: + return True + + return False + +class TestRemoveDead(TestCase): + + _numba_parallel_test_ = False + + def compile_parallel(self, func, arg_types): + return njit(arg_types, parallel=True, fastmath=True)(func) + + def test1(self): + typingctx = cpu_target.typing_context + targetctx = cpu_target.target_context + test_ir = compiler.run_frontend(test_will_propagate) + + typingctx.refresh() + targetctx.refresh() + args = (types.int64, types.int64, types.int64) + typemap, _, calltypes, _ = type_inference_stage(typingctx, targetctx, test_ir, args, None) + remove_dels(test_ir.blocks) + in_cps, out_cps = copy_propagate(test_ir.blocks, typemap) + apply_copy_propagate(test_ir.blocks, in_cps, get_name_var_table(test_ir.blocks), typemap, calltypes) + + remove_dead(test_ir.blocks, test_ir.arg_names, test_ir) + self.assertFalse(findLhsAssign(test_ir, "x")) + + def test2(self): + def call_np_random_seed(): + np.random.seed(2) + + def seed_call_exists(func_ir): + for inst in func_ir.blocks[0].body: + if (isinstance(inst, ir.Assign) and + isinstance(inst.value, ir.Expr) and + inst.value.op == 'call' and + func_ir.get_definition(inst.value.func).attr == 'seed'): + return True + return False + + test_ir = compiler.run_frontend(call_np_random_seed) + remove_dead(test_ir.blocks, test_ir.arg_names, test_ir) + self.assertTrue(seed_call_exists(test_ir)) + + def run_array_index_test(self, func): + A1 = np.arange(6).reshape(2,3) + A2 = A1.copy() + i = 0 + pfunc = self.compile_parallel(func, (numba.typeof(A1), numba.typeof(i))) + + func(A1, i) + pfunc(A2, i) + np.testing.assert_array_equal(A1, A2) + + def test_alias_ravel(self): + def func(A, i): + B = A.ravel() + B[i] = 3 + + self.run_array_index_test(func) + + def test_alias_flat(self): + def func(A, i): + B = A.flat + B[i] = 3 + + self.run_array_index_test(func) + + def test_alias_transpose1(self): + def func(A, i): + B = A.T + B[i,0] = 3 + + self.run_array_index_test(func) + + def test_alias_transpose2(self): + def func(A, i): + B = A.transpose() + B[i,0] = 3 + + self.run_array_index_test(func) + + def test_alias_transpose3(self): + def func(A, i): + B = np.transpose(A) + B[i,0] = 3 + + self.run_array_index_test(func) + + @skip_parfors_unsupported + @needs_blas + def test_alias_ctypes(self): + # use xxnrm2 to test call a C function with ctypes + from numba.np.linalg import _BLAS + xxnrm2 = _BLAS().numba_xxnrm2(types.float64) + + def remove_dead_xxnrm2(rhs, lives, call_list): + if call_list == [xxnrm2]: + return rhs.args[4].name not in lives + return False + + # adding this handler has no-op effect since this function won't match + # anything else but it's a bit cleaner to save the state and recover + old_remove_handlers = remove_call_handlers[:] + remove_call_handlers.append(remove_dead_xxnrm2) + + def func(ret): + a = np.ones(4) + xxnrm2(100, 4, a.ctypes, 1, ret.ctypes) + + A1 = np.zeros(1) + A2 = A1.copy() + + try: + pfunc = self.compile_parallel(func, (numba.typeof(A1),)) + numba.njit(func)(A1) + pfunc(A2) + finally: + # recover global state + remove_call_handlers[:] = old_remove_handlers + + self.assertEqual(A1[0], A2[0]) + + def test_alias_reshape1(self): + def func(A, i): + B = np.reshape(A, (3,2)) + B[i,0] = 3 + + self.run_array_index_test(func) + + def test_alias_reshape2(self): + def func(A, i): + B = A.reshape(3,2) + B[i,0] = 3 + + self.run_array_index_test(func) + + def test_alias_func_ext(self): + def func(A, i): + B = dummy_aliased_func(A) + B[i, 0] = 3 + + # save global state + old_ext_handlers = alias_func_extensions.copy() + try: + alias_func_extensions[('dummy_aliased_func', + 'numba.tests.test_remove_dead')] = alias_ext_dummy_func + self.run_array_index_test(func) + finally: + # recover global state + ir_utils.alias_func_extensions = old_ext_handlers + + def test_rm_dead_rhs_vars(self): + """make sure lhs variable of assignment is considered live if used in + rhs (test for #6715). + """ + def func(): + for i in range(3): + a = (lambda j: j)(i) + a = np.array(a) + return a + + self.assertEqual(func(), numba.njit(func)()) + + @skip_parfors_unsupported + def test_alias_parfor_extension(self): + """Make sure aliases are considered in remove dead extension for + parfors. + """ + def func(): + n = 11 + numba.parfors.parfor.init_prange() + A = np.empty(n) + B = A # create alias to A + for i in numba.prange(n): + A[i] = i + + return B + + @register_pass(analysis_only=False, mutates_CFG=True) + class LimitedParfor(FunctionPass): + _name = "limited_parfor" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + parfor_pass = numba.parfors.parfor.ParforPass( + state.func_ir, + state.typemap, + state.calltypes, + state.return_type, + state.typingctx, + state.flags.auto_parallel, + state.flags, + state.metadata, + state.parfor_diagnostics + ) + remove_dels(state.func_ir.blocks) + parfor_pass.array_analysis.run(state.func_ir.blocks) + parfor_pass._convert_loop(state.func_ir.blocks) + remove_dead(state.func_ir.blocks, + state.func_ir.arg_names, + state.func_ir, + state.typemap) + numba.parfors.parfor.get_parfor_params(state.func_ir.blocks, + parfor_pass.options.fusion, + parfor_pass.nested_fusion_info) + return True + + class TestPipeline(compiler.Compiler): + """Test pipeline that just converts prange() to parfor and calls + remove_dead(). Copy propagation can replace B in the example code + which this pipeline avoids. + """ + def define_pipelines(self): + name = 'test parfor aliasing' + pm = PassManager(name) + pm.add_pass(TranslateByteCode, "analyzing bytecode") + pm.add_pass(FixupArgs, "fix up args") + pm.add_pass(IRProcessing, "processing IR") + pm.add_pass(WithLifting, "Handle with contexts") + # pre typing + if not self.state.flags.no_rewrites: + pm.add_pass(GenericRewrites, "nopython rewrites") + pm.add_pass(RewriteSemanticConstants, "rewrite semantic constants") + pm.add_pass(DeadBranchPrune, "dead branch pruning") + pm.add_pass(InlineClosureLikes, + "inline calls to locally defined closures") + # typing + pm.add_pass(NopythonTypeInference, "nopython frontend") + + # lower + pm.add_pass(NativeLowering, "native lowering") + pm.add_pass(NoPythonBackend, "nopython mode backend") + pm.finalize() + return [pm] + + test_res = numba.jit(pipeline_class=TestPipeline)(func)() + py_res = func() + np.testing.assert_array_equal(test_res, py_res) + + +class TestSSADeadBranchPrune(TestCase): + """ + Test issues that required dead-branch-prune on SSA IR + """ + def test_issue_9706(self): + @njit + def foo(x, y=None): + if y is not None: + return x + y + else: + y = x + return x + y + + @njit + def foo_manual_ssa(x, y=None): + if y is not None: + return x + y + else: + # avoid changing type of `y` + y_ = x + return x + y_ + + self.assertEqual(foo(3, None), foo_manual_ssa(3, None)) + self.assertEqual(foo(3, 10), foo_manual_ssa(3, 10)) + + def test_issue_6541(self): + @njit + def f(xs, out=None): + N, = xs.shape + if out is None: + out = np.arange(N) + else: + assert np.all((0 <= out) & (out < N)) + out[:] = N + return out + + expected = f(np.array([3, 1, 2])) + out = np.arange(3, dtype='i8') + got = f(np.array([3, 1, 2]), out=out) + self.assertIs(got, out) + self.assertPreciseEqual(got, expected) + out = None + got = f(np.array([3, 1, 2]), out=out) + self.assertPreciseEqual(got, expected) + + def test_issue_7482(self): + @njit + def compute(smth, weights, default=0.0): + if weights is None: + return None + + if len(weights) == 0: + return default + + idx = smth > weights + weights = weights[idx] + + return default * weights + + self.assertIsNone(compute(smth=1, weights=None)) + kwargs = dict(smth=1, weights=np.arange(5), default=np.zeros(1)) + self.assertEqual(compute(**kwargs), + compute.py_func(**kwargs)) + + def test_issue_5661(self): + @njit + def foo(a, b=None): + if b is None: + b = 1 + elif b < a: + b += 1 + + return a + b + + args_list = [ + (1, 2), + (2, 1), + (1,), + ] + for args in args_list: + self.assertEqual(foo(*args), foo.py_func(*args)) + + # Variation + # https://github.com/numba/numba/issues/5661#issuecomment-697902475 + def make(decor=njit): + @decor + def inner(state): + if state is None: + state = 0 + else: + state += 1 + return state + + @decor + def fn(): + state = None + for i in range(10): + state = inner(state) + return state + + return fn() + + self.assertEqual(make(), make(lambda x: x)) + + def test_issue_9742(self): + CONST = 32 + + @jit + def foo(): + # This is a prune by value case, conditional is a compile time + # evaluatable constant. + conditional = CONST // 2 + collect = [] + while conditional: + collect.append(conditional) + conditional //= 2 + + return collect + + self.assertEqual(foo(), foo.py_func()) + + def test_issue_9742_variant(self): + CONST = 32 + + @jit + def foo(): + collect = [] + # This is a prune by value case, conditional is a compile time + # evaluatable constant. + x = CONST + 1 + if x: + collect.append(x) + return collect + + self.assertEqual(foo(), foo.py_func()) + + +if __name__ == "__main__": + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_serialize.py b/lib/python3.10/site-packages/numba/tests/test_serialize.py new file mode 100644 index 0000000000000000000000000000000000000000..5aa99e439fcc84d31dd62ca719a0a669d4ef6225 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_serialize.py @@ -0,0 +1,331 @@ +import contextlib +import gc +import pickle +import runpy +import subprocess +import sys +import unittest +from multiprocessing import get_context + +import numba +from numba.core.errors import TypingError +from numba.tests.support import TestCase +from numba.core.target_extension import resolve_dispatcher_from_str +from numba.cloudpickle import dumps, loads + + +class TestDispatcherPickling(TestCase): + + def run_with_protocols(self, meth, *args, **kwargs): + for proto in range(pickle.HIGHEST_PROTOCOL + 1): + meth(proto, *args, **kwargs) + + @contextlib.contextmanager + def simulate_fresh_target(self): + hwstr = 'cpu' + dispatcher_cls = resolve_dispatcher_from_str(hwstr) + old_descr = dispatcher_cls.targetdescr + # Simulate fresh targetdescr + dispatcher_cls.targetdescr = type(dispatcher_cls.targetdescr)(hwstr) + try: + yield + finally: + # Be sure to reinstantiate old descriptor, otherwise other + # objects may be out of sync. + dispatcher_cls.targetdescr = old_descr + + def check_call(self, proto, func, expected_result, args): + def check_result(func): + if (isinstance(expected_result, type) + and issubclass(expected_result, Exception)): + self.assertRaises(expected_result, func, *args) + else: + self.assertPreciseEqual(func(*args), expected_result) + + # Control + check_result(func) + pickled = pickle.dumps(func, proto) + with self.simulate_fresh_target(): + new_func = pickle.loads(pickled) + check_result(new_func) + + def test_call_with_sig(self): + from .serialize_usecases import add_with_sig + self.run_with_protocols(self.check_call, add_with_sig, 5, (1, 4)) + # Compilation has been disabled => float inputs will be coerced to int + self.run_with_protocols(self.check_call, add_with_sig, 5, (1.2, 4.2)) + + def test_call_without_sig(self): + from .serialize_usecases import add_without_sig + self.run_with_protocols(self.check_call, add_without_sig, 5, (1, 4)) + self.run_with_protocols(self.check_call, add_without_sig, 5.5, (1.2, 4.3)) + # Object mode is enabled + self.run_with_protocols(self.check_call, add_without_sig, "abc", ("a", "bc")) + + def test_call_nopython(self): + from .serialize_usecases import add_nopython + self.run_with_protocols(self.check_call, add_nopython, 5.5, (1.2, 4.3)) + # Object mode is disabled + self.run_with_protocols(self.check_call, add_nopython, TypingError, (object(), object())) + + def test_call_nopython_fail(self): + from .serialize_usecases import add_nopython_fail + # Compilation fails + self.run_with_protocols(self.check_call, add_nopython_fail, TypingError, (1, 2)) + + def test_call_objmode_with_global(self): + from .serialize_usecases import get_global_objmode + self.run_with_protocols(self.check_call, get_global_objmode, 7.5, (2.5,)) + + def test_call_closure(self): + from .serialize_usecases import closure + inner = closure(1) + self.run_with_protocols(self.check_call, inner, 6, (2, 3)) + + def check_call_closure_with_globals(self, **jit_args): + from .serialize_usecases import closure_with_globals + inner = closure_with_globals(3.0, **jit_args) + self.run_with_protocols(self.check_call, inner, 7.0, (4.0,)) + + def test_call_closure_with_globals_nopython(self): + self.check_call_closure_with_globals(nopython=True) + + def test_call_closure_with_globals_objmode(self): + self.check_call_closure_with_globals(forceobj=True) + + def test_call_closure_calling_other_function(self): + from .serialize_usecases import closure_calling_other_function + inner = closure_calling_other_function(3.0) + self.run_with_protocols(self.check_call, inner, 11.0, (4.0, 6.0)) + + def test_call_closure_calling_other_closure(self): + from .serialize_usecases import closure_calling_other_closure + inner = closure_calling_other_closure(3.0) + self.run_with_protocols(self.check_call, inner, 8.0, (4.0,)) + + def test_call_dyn_func(self): + from .serialize_usecases import dyn_func + # Check serializing a dynamically-created function + self.run_with_protocols(self.check_call, dyn_func, 36, (6,)) + + def test_call_dyn_func_objmode(self): + from .serialize_usecases import dyn_func_objmode + # Same with an object mode function + self.run_with_protocols(self.check_call, dyn_func_objmode, 36, (6,)) + + def test_renamed_module(self): + from .serialize_usecases import get_renamed_module + # Issue #1559: using a renamed module (e.g. `import numpy as np`) + # should not fail serializing + expected = get_renamed_module(0.0) + self.run_with_protocols(self.check_call, get_renamed_module, + expected, (0.0,)) + + def test_other_process(self): + """ + Check that reconstructing doesn't depend on resources already + instantiated in the original process. + """ + from .serialize_usecases import closure_calling_other_closure + func = closure_calling_other_closure(3.0) + pickled = pickle.dumps(func) + code = """if 1: + import pickle + + data = {pickled!r} + func = pickle.loads(data) + res = func(4.0) + assert res == 8.0, res + """.format(**locals()) + subprocess.check_call([sys.executable, "-c", code]) + + def test_reuse(self): + """ + Check that deserializing the same function multiple times re-uses + the same dispatcher object. + + Note that "same function" is intentionally under-specified. + """ + from .serialize_usecases import closure + func = closure(5) + pickled = pickle.dumps(func) + func2 = closure(6) + pickled2 = pickle.dumps(func2) + + f = pickle.loads(pickled) + g = pickle.loads(pickled) + h = pickle.loads(pickled2) + self.assertIs(f, g) + self.assertEqual(f(2, 3), 10) + g.disable_compile() + self.assertEqual(g(2, 4), 11) + + self.assertIsNot(f, h) + self.assertEqual(h(2, 3), 11) + + # Now make sure the original object doesn't exist when deserializing + func = closure(7) + func(42, 43) + pickled = pickle.dumps(func) + del func + gc.collect() + + f = pickle.loads(pickled) + g = pickle.loads(pickled) + self.assertIs(f, g) + self.assertEqual(f(2, 3), 12) + g.disable_compile() + self.assertEqual(g(2, 4), 13) + + def test_imp_deprecation(self): + """ + The imp module was deprecated in v3.4 in favour of importlib + """ + code = """if 1: + import pickle + import warnings + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always', DeprecationWarning) + from numba import njit + @njit + def foo(x): + return x + 1 + foo(1) + serialized_foo = pickle.dumps(foo) + for x in w: + if 'serialize.py' in x.filename: + assert "the imp module is deprecated" not in x.msg + """ + subprocess.check_call([sys.executable, "-c", code]) + + +class TestSerializationMisc(TestCase): + def test_numba_unpickle(self): + # Test that _numba_unpickle is memorizing its output + from numba.core.serialize import _numba_unpickle + + random_obj = object() + bytebuf = pickle.dumps(random_obj) + hashed = hash(random_obj) + + got1 = _numba_unpickle(id(random_obj), bytebuf, hashed) + # not the original object + self.assertIsNot(got1, random_obj) + got2 = _numba_unpickle(id(random_obj), bytebuf, hashed) + # unpickled results are the same objects + self.assertIs(got1, got2) + + +class TestCloudPickleIssues(TestCase): + """This test case includes issues specific to the cloudpickle implementation. + """ + _numba_parallel_test_ = False + + def test_dynamic_class_reset_on_unpickle(self): + # a dynamic class + class Klass: + classvar = None + + def mutator(): + Klass.classvar = 100 + + def check(): + self.assertEqual(Klass.classvar, 100) + + saved = dumps(Klass) + mutator() + check() + loads(saved) + # Without the patch, each `loads(saved)` will reset `Klass.classvar` + check() + loads(saved) + check() + + @unittest.skipIf(__name__ == "__main__", + "Test cannot run as when module is __main__") + def test_main_class_reset_on_unpickle(self): + mp = get_context('spawn') + proc = mp.Process(target=check_main_class_reset_on_unpickle) + proc.start() + proc.join(timeout=60) + self.assertEqual(proc.exitcode, 0) + + def test_dynamic_class_reset_on_unpickle_new_proc(self): + # a dynamic class + class Klass: + classvar = None + + # serialize Klass in this process + saved = dumps(Klass) + + # Check the reset problem in a new process + mp = get_context('spawn') + proc = mp.Process(target=check_unpickle_dyn_class_new_proc, args=(saved,)) + proc.start() + proc.join(timeout=60) + self.assertEqual(proc.exitcode, 0) + + def test_dynamic_class_issue_7356(self): + cfunc = numba.njit(issue_7356) + self.assertEqual(cfunc(), (100, 100)) + + +class DynClass(object): + # For testing issue #7356 + a = None + + +def issue_7356(): + with numba.objmode(before="intp"): + DynClass.a = 100 + before = DynClass.a + with numba.objmode(after="intp"): + after = DynClass.a + return before, after + + +def check_main_class_reset_on_unpickle(): + # Load module and get its global dictionary + glbs = runpy.run_module( + "numba.tests.cloudpickle_main_class", + run_name="__main__", + ) + # Get the Klass and check it is from __main__ + Klass = glbs['Klass'] + assert Klass.__module__ == "__main__" + assert Klass.classvar != 100 + saved = dumps(Klass) + # mutate + Klass.classvar = 100 + # check + _check_dyn_class(Klass, saved) + + +def check_unpickle_dyn_class_new_proc(saved): + Klass = loads(saved) + assert Klass.classvar != 100 + # mutate + Klass.classvar = 100 + # check + _check_dyn_class(Klass, saved) + + +def _check_dyn_class(Klass, saved): + def check(): + if Klass.classvar != 100: + raise AssertionError("Check failed. Klass reset.") + + check() + loaded = loads(saved) + if loaded is not Klass: + raise AssertionError("Expected reuse") + # Without the patch, each `loads(saved)` will reset `Klass.classvar` + check() + loaded = loads(saved) + if loaded is not Klass: + raise AssertionError("Expected reuse") + check() + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_ssa.py b/lib/python3.10/site-packages/numba/tests/test_ssa.py new file mode 100644 index 0000000000000000000000000000000000000000..49e28c05f2aaa6e1aee6411bba6700784da4d01e --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_ssa.py @@ -0,0 +1,631 @@ +""" +Tests for SSA reconstruction +""" +import sys +import copy +import logging + +import numpy as np + +from numba import njit, jit, types +from numba.core import errors, ir +from numba.core.compiler_machinery import FunctionPass, register_pass +from numba.core.compiler import DefaultPassBuilder, CompilerBase +from numba.core.untyped_passes import ReconstructSSA, PreserveIR +from numba.core.typed_passes import NativeLowering +from numba.extending import overload +from numba.tests.support import MemoryLeakMixin, TestCase, override_config + + +_DEBUG = False + +if _DEBUG: + # Enable debug logger on SSA reconstruction + ssa_logger = logging.getLogger("numba.core.ssa") + ssa_logger.setLevel(level=logging.DEBUG) + ssa_logger.addHandler(logging.StreamHandler(sys.stderr)) + + +class SSABaseTest(TestCase): + + def check_func(self, func, *args): + got = func(*copy.deepcopy(args)) + exp = func.py_func(*copy.deepcopy(args)) + self.assertEqual(got, exp) + + +class TestSSA(SSABaseTest): + """ + Contains tests to help isolate problems in SSA + """ + + def test_argument_name_reused(self): + @njit + def foo(x): + x += 1 + return x + + self.check_func(foo, 123) + + def test_if_else_redefine(self): + @njit + def foo(x, y): + z = x * y + if x < y: + z = x + else: + z = y + return z + + self.check_func(foo, 3, 2) + self.check_func(foo, 2, 3) + + def test_sum_loop(self): + @njit + def foo(n): + c = 0 + for i in range(n): + c += i + return c + + self.check_func(foo, 0) + self.check_func(foo, 10) + + def test_sum_loop_2vars(self): + @njit + def foo(n): + c = 0 + d = n + for i in range(n): + c += i + d += n + return c, d + + self.check_func(foo, 0) + self.check_func(foo, 10) + + def test_sum_2d_loop(self): + @njit + def foo(n): + c = 0 + for i in range(n): + for j in range(n): + c += j + c += i + return c + + self.check_func(foo, 0) + self.check_func(foo, 10) + + def check_undefined_var(self, should_warn): + @njit + def foo(n): + if n: + if n > 0: + c = 0 + return c + else: + # variable c is not defined in this branch + c += 1 + return c + + if should_warn: + with self.assertWarns(errors.NumbaWarning) as warns: + # n=1 so we won't actually run the branch with the uninitialized + self.check_func(foo, 1) + self.assertIn("Detected uninitialized variable c", + str(warns.warning)) + else: + self.check_func(foo, 1) + + with self.assertRaises(UnboundLocalError): + foo.py_func(0) + + def test_undefined_var(self): + with override_config('ALWAYS_WARN_UNINIT_VAR', 0): + self.check_undefined_var(should_warn=False) + with override_config('ALWAYS_WARN_UNINIT_VAR', 1): + self.check_undefined_var(should_warn=True) + + def test_phi_propagation(self): + @njit + def foo(actions): + n = 1 + + i = 0 + ct = 0 + while n > 0 and i < len(actions): + n -= 1 + + while actions[i]: + if actions[i]: + if actions[i]: + n += 10 + actions[i] -= 1 + else: + if actions[i]: + n += 20 + actions[i] += 1 + + ct += n + ct += n + return ct, n + + self.check_func(foo, np.array([1, 2])) + + def test_unhandled_undefined(self): + def function1(arg1, arg2, arg3, arg4, arg5): + # This function is auto-generated. + if arg1: + var1 = arg2 + var2 = arg3 + var3 = var2 + var4 = arg1 + return + else: + if arg2: + if arg4: + var5 = arg4 # noqa: F841 + return + else: + var6 = var4 + return + return var6 + else: + if arg5: + if var1: + if arg5: + var1 = var6 + return + else: + var7 = arg2 # noqa: F841 + return arg2 + return + else: + if var2: + arg5 = arg2 + return arg1 + else: + var6 = var3 + return var4 + return + return + else: + var8 = var1 + return + return var8 + var9 = var3 # noqa: F841 + var10 = arg5 # noqa: F841 + return var1 + + # The argument values is not critical for re-creating the bug + # because the bug is in compile-time. + expect = function1(2, 3, 6, 0, 7) + got = njit(function1)(2, 3, 6, 0, 7) + self.assertEqual(expect, got) + + +class TestReportedSSAIssues(SSABaseTest): + # Tests from issues + # https://github.com/numba/numba/issues?q=is%3Aopen+is%3Aissue+label%3ASSA + + def test_issue2194(self): + + @njit + def foo(): + V = np.empty(1) + s = np.uint32(1) + + for i in range(s): + V[i] = 1 + for i in range(s, 1): + pass + + self.check_func(foo, ) + + def test_issue3094(self): + + @njit + def doit(x): + return x + + @njit + def foo(pred): + if pred: + x = True + else: + x = False + # do something with x + return doit(x) + + self.check_func(foo, False) + + def test_issue3931(self): + + @njit + def foo(arr): + for i in range(1): + arr = arr.reshape(3 * 2) + arr = arr.reshape(3, 2) + return (arr) + + np.testing.assert_allclose(foo(np.zeros((3, 2))), + foo.py_func(np.zeros((3, 2)))) + + def test_issue3976(self): + + def overload_this(a): + return 'dummy' + + @njit + def foo(a): + if a: + s = 5 + s = overload_this(s) + else: + s = 'b' + + return s + + @overload(overload_this) + def ol(a): + return overload_this + + self.check_func(foo, True) + + def test_issue3979(self): + + @njit + def foo(A, B): + x = A[0] + y = B[0] + for i in A: + x = i + for i in B: + y = i + return x, y + + self.check_func(foo, (1, 2), ('A', 'B')) + + def test_issue5219(self): + + def overload_this(a, b=None): + if isinstance(b, tuple): + b = b[0] + return b + + @overload(overload_this) + def ol(a, b=None): + b_is_tuple = isinstance(b, (types.Tuple, types.UniTuple)) + + def impl(a, b=None): + if b_is_tuple is True: + b = b[0] + return b + return impl + + @njit + def test_tuple(a, b): + overload_this(a, b) + + self.check_func(test_tuple, 1, (2, )) + + def test_issue5223(self): + + @njit + def bar(x): + if len(x) == 5: + return x + x = x.copy() + for i in range(len(x)): + x[i] += 1 + return x + + a = np.ones(5) + a.flags.writeable = False + + np.testing.assert_allclose(bar(a), bar.py_func(a)) + + def test_issue5243(self): + + @njit + def foo(q): + lin = np.array((0.1, 0.6, 0.3)) + stencil = np.zeros((3, 3)) + stencil[0, 0] = q[0, 0] + return lin[0] + + self.check_func(foo, np.zeros((2, 2))) + + def test_issue5482_missing_variable_init(self): + # Test error that lowering fails because variable is missing + # a definition before use. + @njit("(intp, intp, intp)") + def foo(x, v, n): + for i in range(n): + if i == 0: + if i == x: + pass + else: + problematic = v + else: + if i == x: + pass + else: + problematic = problematic + v + return problematic + + def test_issue5482_objmode_expr_null_lowering(self): + # Existing pipelines will not have the Expr.null in objmode. + # We have to create a custom pipeline to force a SSA reconstruction + # and stripping. + from numba.core.compiler import CompilerBase, DefaultPassBuilder + from numba.core.untyped_passes import ReconstructSSA, IRProcessing + from numba.core.typed_passes import PreLowerStripPhis + + class CustomPipeline(CompilerBase): + def define_pipelines(self): + pm = DefaultPassBuilder.define_objectmode_pipeline(self.state) + # Force SSA reconstruction and stripping + pm.add_pass_after(ReconstructSSA, IRProcessing) + pm.add_pass_after(PreLowerStripPhis, ReconstructSSA) + pm.finalize() + return [pm] + + @jit("(intp, intp, intp)", looplift=False, + pipeline_class=CustomPipeline) + def foo(x, v, n): + for i in range(n): + if i == n: + if i == x: + pass + else: + problematic = v + else: + if i == x: + pass + else: + problematic = problematic + v + return problematic + + def test_issue5493_unneeded_phi(self): + # Test error that unneeded phi is inserted because variable does not + # have a dominance definition. + data = (np.ones(2), np.ones(2)) + A = np.ones(1) + B = np.ones((1,1)) + + def foo(m, n, data): + if len(data) == 1: + v0 = data[0] + else: + v0 = data[0] + # Unneeded PHI node for `problematic` would be placed here + for _ in range(1, len(data)): + v0 += A + + for t in range(1, m): + for idx in range(n): + t = B + + if idx == 0: + if idx == n - 1: + pass + else: + problematic = t + else: + if idx == n - 1: + pass + else: + problematic = problematic + t + return problematic + + expect = foo(10, 10, data) + res1 = njit(foo)(10, 10, data) + res2 = jit(forceobj=True, looplift=False)(foo)(10, 10, data) + np.testing.assert_array_equal(expect, res1) + np.testing.assert_array_equal(expect, res2) + + def test_issue5623_equal_statements_in_same_bb(self): + + def foo(pred, stack): + i = 0 + c = 1 + + if pred is True: + stack[i] = c + i += 1 + stack[i] = c + i += 1 + + python = np.array([0, 666]) + foo(True, python) + + nb = np.array([0, 666]) + njit(foo)(True, nb) + + expect = np.array([1, 1]) + + np.testing.assert_array_equal(python, expect) + np.testing.assert_array_equal(nb, expect) + + def test_issue5678_non_minimal_phi(self): + # There should be only one phi for variable "i" + + from numba.core.compiler import CompilerBase, DefaultPassBuilder + from numba.core.untyped_passes import ( + ReconstructSSA, FunctionPass, register_pass, + ) + + phi_counter = [] + + @register_pass(mutates_CFG=False, analysis_only=True) + class CheckSSAMinimal(FunctionPass): + # A custom pass to count the number of phis + + _name = self.__class__.__qualname__ + ".CheckSSAMinimal" + + def __init__(self): + super().__init__(self) + + def run_pass(self, state): + ct = 0 + for blk in state.func_ir.blocks.values(): + ct += len(list(blk.find_exprs('phi'))) + phi_counter.append(ct) + return True + + class CustomPipeline(CompilerBase): + def define_pipelines(self): + pm = DefaultPassBuilder.define_nopython_pipeline(self.state) + pm.add_pass_after(CheckSSAMinimal, ReconstructSSA) + pm.finalize() + return [pm] + + @njit(pipeline_class=CustomPipeline) + def while_for(n, max_iter=1): + a = np.empty((n,n)) + i = 0 + while i <= max_iter: + for j in range(len(a)): + for k in range(len(a)): + a[j,k] = j + k + i += 1 + return a + + # Runs fine? + self.assertPreciseEqual(while_for(10), while_for.py_func(10)) + # One phi? + self.assertEqual(phi_counter, [1]) + + def test_issue9242_use_not_dom_def(self): + from numba.core.ir import FunctionIR + from numba.core.compiler_machinery import ( + AnalysisPass, + register_pass, + ) + + def check(fir: FunctionIR): + [blk, *_] = fir.blocks.values() + var = blk.scope.get("d") + defn = fir.get_definition(var) + self.assertEqual(defn.op, "phi") + self.assertIn(ir.UNDEFINED, defn.incoming_values) + + @register_pass(mutates_CFG=False, analysis_only=True) + class SSACheck(AnalysisPass): + """ + Check SSA on variable `d` + """ + + _name = "SSA_Check" + + def __init__(self): + AnalysisPass.__init__(self) + + def run_pass(self, state): + check(state.func_ir) + return False + + class SSACheckPipeline(CompilerBase): + """Inject SSACheck pass into the default pipeline following the SSA + pass + """ + + def define_pipelines(self): + pipeline = DefaultPassBuilder.define_nopython_pipeline( + self.state, "ssa_check_custom_pipeline") + + pipeline._finalized = False + pipeline.add_pass_after(SSACheck, ReconstructSSA) + + pipeline.finalize() + return [pipeline] + + @njit(pipeline_class=SSACheckPipeline) + def py_func(a): + c = a > 0 + if c: + d = a + 5 # d is only defined here; undef in the else branch + + return c and d > 0 + + py_func(10) + + +class TestSROAIssues(MemoryLeakMixin, TestCase): + # This tests issues related to the SROA optimization done in lowering, which + # reduces time spent in the LLVM SROA pass. The optimization is related to + # SSA and tries to reduce the number of alloca statements for variables with + # only a single assignment. + def test_issue7258_multiple_assignment_post_SSA(self): + # This test adds a pass that will duplicate assignment statements to + # variables named "foobar". + # In the reported issue, the bug will cause a memory leak. + cloned = [] + + @register_pass(analysis_only=False, mutates_CFG=True) + class CloneFoobarAssignments(FunctionPass): + # A pass that clones variable assignments into "foobar" + _name = "clone_foobar_assignments_pass" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + mutated = False + for blk in state.func_ir.blocks.values(): + to_clone = [] + # find assignments to "foobar" + for assign in blk.find_insts(ir.Assign): + if assign.target.name == "foobar": + to_clone.append(assign) + # clone + for assign in to_clone: + clone = copy.deepcopy(assign) + blk.insert_after(clone, assign) + mutated = True + # keep track of cloned statements + cloned.append(clone) + return mutated + + class CustomCompiler(CompilerBase): + def define_pipelines(self): + pm = DefaultPassBuilder.define_nopython_pipeline( + self.state, "custom_pipeline", + ) + pm._finalized = False + # Insert the cloning pass after SSA + pm.add_pass_after(CloneFoobarAssignments, ReconstructSSA) + # Capture IR post lowering + pm.add_pass_after(PreserveIR, NativeLowering) + pm.finalize() + return [pm] + + @njit(pipeline_class=CustomCompiler) + def udt(arr): + foobar = arr + 1 # this assignment will be cloned + return foobar + + arr = np.arange(10) + # Verify that the function works as expected + self.assertPreciseEqual(udt(arr), arr + 1) + # Verify that the expected statement is cloned + self.assertEqual(len(cloned), 1) + self.assertEqual(cloned[0].target.name, "foobar") + # Verify in the Numba IR that the expected statement is cloned + nir = udt.overloads[udt.signatures[0]].metadata['preserved_ir'] + self.assertEqual(len(nir.blocks), 1, + "only one block") + [blk] = nir.blocks.values() + assigns = blk.find_insts(ir.Assign) + foobar_assigns = [stmt for stmt in assigns + if stmt.target.name == "foobar"] + self.assertEqual( + len(foobar_assigns), 2, + "expected two assignment statements into 'foobar'", + ) + self.assertEqual( + foobar_assigns[0], foobar_assigns[1], + "expected the two assignment statements to be the same", + ) diff --git a/lib/python3.10/site-packages/numba/tests/test_struct_ref.py b/lib/python3.10/site-packages/numba/tests/test_struct_ref.py new file mode 100644 index 0000000000000000000000000000000000000000..de52fdcf96218af9f3f607ae6fe8078ede521856 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_struct_ref.py @@ -0,0 +1,440 @@ +""" +Test mutable struct, aka, structref +""" +import warnings + +import numpy as np + +from numba import typed, njit, errors, typeof +from numba.core import types +from numba.experimental import structref +from numba.extending import overload_method, overload_attribute +from numba.tests.support import ( + MemoryLeakMixin, TestCase, temp_directory, override_config, +) + + +@structref.register +class MySimplerStructType(types.StructRef): + """ + Test associated with this type represent the lowest level uses of structref. + """ + pass + + +my_struct_ty = MySimplerStructType( + fields=[("values", types.intp[:]), ("counter", types.intp)] +) + +structref.define_boxing(MySimplerStructType, structref.StructRefProxy) + + +class MyStruct(structref.StructRefProxy): + + def __new__(cls, values, counter): + # Define this method to customize the constructor. + # The default takes `*args`. Customizing allow the use of keyword-arg. + # The impl of the method calls `StructRefProxy.__new__` + return structref.StructRefProxy.__new__(cls, values, counter) + + # The below defines wrappers for attributes and methods manually + + @property + def values(self): + return get_values(self) + + @values.setter + def values(self, val): + return set_values(self, val) + + @property + def counter(self): + return get_counter(self) + + def testme(self, arg): + return self.values * arg + self.counter + + @property + def prop(self): + return self.values, self.counter + + def __hash__(self): + return compute_fields(self) + + +@structref.register +class MyStructType(types.StructRef): + """Test associated with this type represent the higher-level uses of + structef. + """ + pass + + +# Call to define_proxy is needed to register the use of `MyStruct` as a +# PyObject proxy for creating a Numba-allocated structref. +# The `MyStruct` class can then be used in both jit-code and interpreted-code. +structref.define_proxy( + MyStruct, + MyStructType, + ['values', 'counter'], +) + + +@njit +def my_struct(values, counter): + st = structref.new(my_struct_ty) + my_struct_init(st, values, counter) + return st + + +@njit +def my_struct_init(self, values, counter): + self.values = values + self.counter = counter + + +@njit +def ctor_by_intrinsic(vs, ctr): + st = my_struct(vs, counter=ctr) + st.values += st.values + st.counter *= ctr + return st + + +@njit +def ctor_by_class(vs, ctr): + return MyStruct(values=vs, counter=ctr) + + +@njit +def get_values(st): + return st.values + + +@njit +def set_values(st, val): + st.values = val + + +@njit +def get_counter(st): + return st.counter + + +@njit +def compute_fields(st): + return st.values + st.counter + + +class TestStructRefBasic(MemoryLeakMixin, TestCase): + def test_structref_type(self): + sr = types.StructRef([('a', types.int64)]) + self.assertEqual(sr.field_dict['a'], types.int64) + sr = types.StructRef([('a', types.int64), ('b', types.float64)]) + self.assertEqual(sr.field_dict['a'], types.int64) + self.assertEqual(sr.field_dict['b'], types.float64) + # bad case + with self.assertRaisesRegex(ValueError, + "expecting a str for field name"): + types.StructRef([(1, types.int64)]) + with self.assertRaisesRegex(ValueError, + "expecting a Numba Type for field type"): + types.StructRef([('a', 123)]) + + def test_invalid_uses(self): + with self.assertRaisesRegex(ValueError, "cannot register"): + structref.register(types.StructRef) + with self.assertRaisesRegex(ValueError, "cannot register"): + structref.define_boxing(types.StructRef, MyStruct) + + def test_MySimplerStructType(self): + vs = np.arange(10, dtype=np.intp) + ctr = 13 + + first_expected = vs + vs + first_got = ctor_by_intrinsic(vs, ctr) + # the returned instance is a structref.StructRefProxy + # but not a MyStruct + self.assertNotIsInstance(first_got, MyStruct) + self.assertPreciseEqual(first_expected, get_values(first_got)) + + second_expected = first_expected + (ctr * ctr) + second_got = compute_fields(first_got) + self.assertPreciseEqual(second_expected, second_got) + + def test_MySimplerStructType_wrapper_has_no_attrs(self): + vs = np.arange(10, dtype=np.intp) + ctr = 13 + wrapper = ctor_by_intrinsic(vs, ctr) + self.assertIsInstance(wrapper, structref.StructRefProxy) + with self.assertRaisesRegex(AttributeError, 'values'): + wrapper.values + with self.assertRaisesRegex(AttributeError, 'counter'): + wrapper.counter + + def test_MyStructType(self): + vs = np.arange(10, dtype=np.float64) + ctr = 11 + + first_expected_arr = vs.copy() + first_got = ctor_by_class(vs, ctr) + self.assertIsInstance(first_got, MyStruct) + self.assertPreciseEqual(first_expected_arr, first_got.values) + + second_expected = first_expected_arr + ctr + second_got = compute_fields(first_got) + self.assertPreciseEqual(second_expected, second_got) + self.assertEqual(first_got.counter, ctr) + + def test_MyStructType_mixed_types(self): + # structref constructor is generic + @njit + def mixed_type(x, y, m, n): + return MyStruct(x, y), MyStruct(m, n) + + a, b = mixed_type(1, 2.3, 3.4j, (4,)) + self.assertEqual(a.values, 1) + self.assertEqual(a.counter, 2.3) + self.assertEqual(b.values, 3.4j) + self.assertEqual(b.counter, (4,)) + + def test_MyStructType_in_dict(self): + td = typed.Dict() + td['a'] = MyStruct(1, 2.3) + self.assertEqual(td['a'].values, 1) + self.assertEqual(td['a'].counter, 2.3) + # overwrite + td['a'] = MyStruct(2, 3.3) + self.assertEqual(td['a'].values, 2) + self.assertEqual(td['a'].counter, 3.3) + # mutate + td['a'].values += 10 + self.assertEqual(td['a'].values, 12) # changed + self.assertEqual(td['a'].counter, 3.3) # unchanged + # insert + td['b'] = MyStruct(4, 5.6) + + def test_MyStructType_in_dict_mixed_type_error(self): + self.disable_leak_check() + + td = typed.Dict() + td['a'] = MyStruct(1, 2.3) + self.assertEqual(td['a'].values, 1) + self.assertEqual(td['a'].counter, 2.3) + + # ERROR: store different types + with self.assertRaisesRegex(errors.TypingError, + r"Cannot cast numba.MyStructType"): + # because first field is not a float; + # the second field is now an integer. + td['b'] = MyStruct(2.3, 1) + + def test_MyStructType_hash_no_typeof_recursion(self): + # Tests that __hash__ is not called prematurely in typeof + # causing infinite recursion (see #8241). + st = MyStruct(1, 2) + typeof(st) + + self.assertEqual(hash(st), 3) + + +@overload_method(MyStructType, "testme") +def _ol_mystructtype_testme(self, arg): + def impl(self, arg): + return self.values * arg + self.counter + return impl + + +@overload_attribute(MyStructType, "prop") +def _ol_mystructtype_prop(self): + def get(self): + return self.values, self.counter + return get + + +class TestStructRefExtending(MemoryLeakMixin, TestCase): + def test_overload_method(self): + @njit + def check(x): + vs = np.arange(10, dtype=np.float64) + ctr = 11 + obj = MyStruct(vs, ctr) + return obj.testme(x) + + x = 3 + got = check(x) + expect = check.py_func(x) + self.assertPreciseEqual(got, expect) + + def test_overload_attribute(self): + @njit + def check(): + vs = np.arange(10, dtype=np.float64) + ctr = 11 + obj = MyStruct(vs, ctr) + return obj.prop + + got = check() + expect = check.py_func() + self.assertPreciseEqual(got, expect) + + +def caching_test_make(x, y): + struct = MyStruct(values=x, counter=y) + return struct + + +def caching_test_use(struct, z): + return struct.testme(z) + + +class TestStructRefCaching(MemoryLeakMixin, TestCase): + def setUp(self): + self._cache_dir = temp_directory(TestStructRefCaching.__name__) + self._cache_override = override_config('CACHE_DIR', self._cache_dir) + self._cache_override.__enter__() + warnings.simplefilter("error") + warnings.filterwarnings(action="ignore", module="typeguard") + + def tearDown(self): + self._cache_override.__exit__(None, None, None) + warnings.resetwarnings() + + def test_structref_caching(self): + def assert_cached(stats): + self.assertEqual(len(stats.cache_hits), 1) + self.assertEqual(len(stats.cache_misses), 0) + + def assert_not_cached(stats): + self.assertEqual(len(stats.cache_hits), 0) + self.assertEqual(len(stats.cache_misses), 1) + + def check(cached): + check_make = njit(cache=True)(caching_test_make) + check_use = njit(cache=True)(caching_test_use) + vs = np.random.random(3) + ctr = 17 + factor = 3 + st = check_make(vs, ctr) + got = check_use(st, factor) + expect = vs * factor + ctr + self.assertPreciseEqual(got, expect) + + if cached: + assert_cached(check_make.stats) + assert_cached(check_use.stats) + else: + assert_not_cached(check_make.stats) + assert_not_cached(check_use.stats) + + check(cached=False) + check(cached=True) + + +@structref.register +class PolygonStructType(types.StructRef): + + def preprocess_fields(self, fields): + # temp name to allow Optional instantiation + self.name = f"numba.PolygonStructType#{id(self)}" + fields = tuple([ + ('value', types.Optional(types.int64)), + ('parent', types.Optional(self)), + ]) + + return fields + + +polygon_struct_type = PolygonStructType(fields=( + ('value', types.Any), + ('parent', types.Any) +)) + + +class PolygonStruct(structref.StructRefProxy): + def __new__(cls, value, parent): + return structref.StructRefProxy.__new__(cls, value, parent) + + @property + def value(self): + return PolygonStruct_get_value(self) + + @property + def parent(self): + return PolygonStruct_get_parent(self) + + +@njit +def PolygonStruct_get_value(self): + return self.value + + +@njit +def PolygonStruct_get_parent(self): + return self.parent + + +structref.define_proxy( + PolygonStruct, + PolygonStructType, + ["value", "parent"] +) + + +@overload_method(PolygonStructType, "flip") +def _ol_polygon_struct_flip(self): + def impl(self): + if self.value is not None: + self.value = -self.value + return impl + + +@overload_attribute(PolygonStructType, "prop") +def _ol_polygon_struct_prop(self): + def get(self): + return self.value, self.parent + return get + + +class TestStructRefForwardTyping(MemoryLeakMixin, TestCase): + def test_same_type_assignment(self): + @njit + def check(x): + poly = PolygonStruct(None, None) + p_poly = PolygonStruct(None, None) + poly.value = x + poly.parent = p_poly + p_poly.value = x + return poly.parent.value + + x = 11 + got = check(x) + expect = x + self.assertPreciseEqual(got, expect) + + def test_overload_method(self): + @njit + def check(x): + poly = PolygonStruct(None, None) + p_poly = PolygonStruct(None, None) + poly.value = x + poly.parent = p_poly + p_poly.value = x + poly.flip() + poly.parent.flip() + return poly.parent.value + + x = 3 + got = check(x) + expect = -x + self.assertPreciseEqual(got, expect) + + def test_overload_attribute(self): + @njit + def check(): + obj = PolygonStruct(5, None) + return obj.prop[0] + + got = check() + expect = 5 + self.assertPreciseEqual(got, expect) diff --git a/lib/python3.10/site-packages/numba/tests/test_support.py b/lib/python3.10/site-packages/numba/tests/test_support.py new file mode 100644 index 0000000000000000000000000000000000000000..e35eda1ff27ff5a97a5db447a36217cbdbcc47a2 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_support.py @@ -0,0 +1,346 @@ +import itertools + +import numpy as np + +from numba import jit +from numba.core import utils +from numba.tests.support import TestCase, forbid_codegen +from .enum_usecases import * +import unittest + +DBL_EPSILON = 2**-52 +FLT_EPSILON = 2**-23 + +INF = float('inf') +NAN = float('nan') + + +class TestAssertPreciseEqual(TestCase): + """ + Tests for TestCase.assertPreciseEqual(). + """ + + int_types = [int] + np_float_types = [np.float32, np.float64] + float_types = [float] + np_float_types + np_complex_types = [np.complex64, np.complex128] + complex_types = [complex] + np_complex_types + bool_types = [bool, np.bool_] + + def eq(self, left, right, **kwargs): + def assert_succeed(left, right): + self.assertPreciseEqual(left, right, **kwargs) + self.assertPreciseEqual(right, left, **kwargs) + assert_succeed(left, right) + assert_succeed((left, left), (right, right)) + assert_succeed([left, left], [right, right]) + + def ne(self, left, right, **kwargs): + def assert_fail(left, right): + try: + self.assertPreciseEqual(left, right, **kwargs) + except AssertionError: + pass + else: + self.fail("%s and %s unexpectedly considered equal" % (left, right)) + assert_fail(left, right) + assert_fail(right, left) + assert_fail((left, left), (right, right)) + assert_fail((right, right), (left, left)) + assert_fail([left, left], [right, right]) + assert_fail([right, right], [left, left]) + + def test_types(self): + # assertPreciseEqual() should test for type compatibility + # int-like, float-like, complex-like are not compatible + for i, f, c in itertools.product(self.int_types, self.float_types, + self.complex_types): + self.ne(i(1), f(1)) + self.ne(f(1), c(1)) + self.ne(i(1), c(1)) + # int and long are compatible between each other + for u, v in itertools.product(self.int_types, self.int_types): + self.eq(u(1), v(1)) + # int and bool are not compatible between each other + for u, v in itertools.product(self.int_types, self.bool_types): + self.ne(u(1), v(1)) + # NumPy float types are not compatible between each other + for u, v in itertools.product(self.np_float_types, self.np_float_types): + if u is v: + self.eq(u(1), v(1)) + else: + self.ne(u(1), v(1)) + # NumPy complex types are not compatible between each other + for u, v in itertools.product(self.np_complex_types, self.np_complex_types): + if u is v: + self.eq(u(1), v(1)) + else: + self.ne(u(1), v(1)) + + def test_int_values(self): + for tp in self.int_types: + for prec in ['exact', 'single', 'double']: + self.eq(tp(0), tp(0), prec=prec) + self.ne(tp(0), tp(1), prec=prec) + self.ne(tp(-1), tp(1), prec=prec) + self.ne(tp(2**80), tp(1+2**80), prec=prec) + + def test_bool_values(self): + for tpa, tpb in itertools.product(self.bool_types, self.bool_types): + self.eq(tpa(True), tpb(True)) + self.eq(tpa(False), tpb(False)) + self.ne(tpa(True), tpb(False)) + + def test_abs_tol_parse(self): + # check invalid values in abs_tol kwarg raises + with self.assertRaises(ValueError): + self.eq(np.float64(1e-17), np.float64(1e-17), abs_tol="invalid") + with self.assertRaises(ValueError): + self.eq(np.float64(1), np.float64(2), abs_tol=int(7)) + + def test_float_values(self): + for tp in self.float_types: + for prec in ['exact', 'single', 'double']: + self.eq(tp(1.5), tp(1.5), prec=prec) + # Signed zeros + self.eq(tp(0.0), tp(0.0), prec=prec) + self.eq(tp(-0.0), tp(-0.0), prec=prec) + self.ne(tp(0.0), tp(-0.0), prec=prec) + self.eq(tp(0.0), tp(-0.0), prec=prec, ignore_sign_on_zero=True) + # Infinities + self.eq(tp(INF), tp(INF), prec=prec) + self.ne(tp(INF), tp(1e38), prec=prec) + self.eq(tp(-INF), tp(-INF), prec=prec) + self.ne(tp(INF), tp(-INF), prec=prec) + # NaNs + self.eq(tp(NAN), tp(NAN), prec=prec) + self.ne(tp(NAN), tp(0), prec=prec) + self.ne(tp(NAN), tp(INF), prec=prec) + self.ne(tp(NAN), tp(-INF), prec=prec) + + def test_float64_values(self): + for tp in [float, np.float64]: + self.ne(tp(1.0 + DBL_EPSILON), tp(1.0)) + + def test_float32_values(self): + tp = np.float32 + self.ne(tp(1.0 + FLT_EPSILON), tp(1.0)) + + def test_float64_values_inexact(self): + for tp in [float, np.float64]: + for scale in [1.0, -2**3, 2**-4, -2**-20]: + a = scale * 1.0 + b = scale * (1.0 + DBL_EPSILON) + c = scale * (1.0 + DBL_EPSILON * 2) + d = scale * (1.0 + DBL_EPSILON * 4) + self.ne(tp(a), tp(b)) + self.ne(tp(a), tp(b), prec='exact') + self.eq(tp(a), tp(b), prec='double') + self.eq(tp(a), tp(b), prec='double', ulps=1) + self.ne(tp(a), tp(c), prec='double') + self.eq(tp(a), tp(c), prec='double', ulps=2) + self.ne(tp(a), tp(d), prec='double', ulps=2) + self.eq(tp(a), tp(c), prec='double', ulps=3) + self.eq(tp(a), tp(d), prec='double', ulps=3) + # test absolute tolerance based on eps + self.eq(tp(1e-16), tp(3e-16), prec='double', abs_tol="eps") + self.ne(tp(1e-16), tp(4e-16), prec='double', abs_tol="eps") + # test absolute tolerance based on value + self.eq(tp(1e-17), tp(1e-18), prec='double', abs_tol=1e-17) + self.ne(tp(1e-17), tp(3e-17), prec='double', abs_tol=1e-17) + + def test_float32_values_inexact(self): + tp = np.float32 + for scale in [1.0, -2**3, 2**-4, -2**-20]: + # About the choice of 0.9: there seem to be issues when + # converting + a = scale * 1.0 + b = scale * (1.0 + FLT_EPSILON) + c = scale * (1.0 + FLT_EPSILON * 2) + d = scale * (1.0 + FLT_EPSILON * 4) + self.ne(tp(a), tp(b)) + self.ne(tp(a), tp(b), prec='exact') + self.ne(tp(a), tp(b), prec='double') + self.eq(tp(a), tp(b), prec='single') + self.ne(tp(a), tp(c), prec='single') + self.eq(tp(a), tp(c), prec='single', ulps=2) + self.ne(tp(a), tp(d), prec='single', ulps=2) + self.eq(tp(a), tp(c), prec='single', ulps=3) + self.eq(tp(a), tp(d), prec='single', ulps=3) + # test absolute tolerance based on eps + self.eq(tp(1e-7), tp(2e-7), prec='single', abs_tol="eps") + self.ne(tp(1e-7), tp(3e-7), prec='single', abs_tol="eps") + # test absolute tolerance based on value + self.eq(tp(1e-7), tp(1e-8), prec='single', abs_tol=1e-7) + self.ne(tp(1e-7), tp(3e-7), prec='single', abs_tol=1e-7) + + def test_complex_values(self): + # Complex literals with signed zeros are confusing, better use + # the explicit constructor. + c_pp, c_pn, c_np, c_nn = [complex(0.0, 0.0), complex(0.0, -0.0), + complex(-0.0, 0.0), complex(-0.0, -0.0)] + for tp in self.complex_types: + for prec in ['exact', 'single', 'double']: + self.eq(tp(1 + 2j), tp(1 + 2j), prec=prec) + self.ne(tp(1 + 1j), tp(1 + 2j), prec=prec) + self.ne(tp(2 + 2j), tp(1 + 2j), prec=prec) + # Signed zeros + self.eq(tp(c_pp), tp(c_pp), prec=prec) + self.eq(tp(c_np), tp(c_np), prec=prec) + self.eq(tp(c_nn), tp(c_nn), prec=prec) + self.ne(tp(c_pp), tp(c_pn), prec=prec) + self.ne(tp(c_pn), tp(c_nn), prec=prec) + # Infinities + self.eq(tp(complex(INF, INF)), tp(complex(INF, INF)), prec=prec) + self.eq(tp(complex(INF, -INF)), tp(complex(INF, -INF)), prec=prec) + self.eq(tp(complex(-INF, -INF)), tp(complex(-INF, -INF)), prec=prec) + self.ne(tp(complex(INF, INF)), tp(complex(INF, -INF)), prec=prec) + self.ne(tp(complex(INF, INF)), tp(complex(-INF, INF)), prec=prec) + self.eq(tp(complex(INF, 0)), tp(complex(INF, 0)), prec=prec) + # NaNs + self.eq(tp(complex(NAN, 0)), tp(complex(NAN, 0)), prec=prec) + self.eq(tp(complex(0, NAN)), tp(complex(0, NAN)), prec=prec) + self.eq(tp(complex(NAN, NAN)), tp(complex(NAN, NAN)), prec=prec) + self.eq(tp(complex(INF, NAN)), tp(complex(INF, NAN)), prec=prec) + self.eq(tp(complex(NAN, -INF)), tp(complex(NAN, -INF)), prec=prec) + # FIXME + #self.ne(tp(complex(NAN, INF)), tp(complex(NAN, -INF))) + #self.ne(tp(complex(NAN, 0)), tp(complex(NAN, 1))) + #self.ne(tp(complex(INF, NAN)), tp(complex(-INF, NAN))) + #self.ne(tp(complex(0, NAN)), tp(complex(1, NAN))) + #self.ne(tp(complex(NAN, 0)), tp(complex(0, NAN))) + # XXX should work with other precisions as well? + self.ne(tp(complex(INF, 0)), tp(complex(INF, 1)), prec='exact') + + def test_complex128_values_inexact(self): + for tp in [complex, np.complex128]: + for scale in [1.0, -2**3, 2**-4, -2**-20]: + a = scale * 1.0 + b = scale * (1.0 + DBL_EPSILON) + c = scale * (1.0 + DBL_EPSILON * 2) + aa = tp(complex(a, a)) + ab = tp(complex(a, b)) + bb = tp(complex(b, b)) + self.ne(tp(aa), tp(ab)) + self.eq(tp(aa), tp(ab), prec='double') + self.eq(tp(ab), tp(bb), prec='double') + self.eq(tp(aa), tp(bb), prec='double') + ac = tp(complex(a, c)) + cc = tp(complex(c, c)) + self.ne(tp(aa), tp(ac), prec='double') + self.ne(tp(ac), tp(cc), prec='double') + self.eq(tp(aa), tp(ac), prec='double', ulps=2) + self.eq(tp(ac), tp(cc), prec='double', ulps=2) + self.eq(tp(aa), tp(cc), prec='double', ulps=2) + self.eq(tp(aa), tp(cc), prec='single') + + def test_complex64_values_inexact(self): + tp = np.complex64 + for scale in [1.0, -2**3, 2**-4, -2**-20]: + a = scale * 1.0 + b = scale * (1.0 + FLT_EPSILON) + c = scale * (1.0 + FLT_EPSILON * 2) + aa = tp(complex(a, a)) + ab = tp(complex(a, b)) + bb = tp(complex(b, b)) + self.ne(tp(aa), tp(ab)) + self.ne(tp(aa), tp(ab), prec='double') + self.eq(tp(aa), tp(ab), prec='single') + self.eq(tp(ab), tp(bb), prec='single') + self.eq(tp(aa), tp(bb), prec='single') + ac = tp(complex(a, c)) + cc = tp(complex(c, c)) + self.ne(tp(aa), tp(ac), prec='single') + self.ne(tp(ac), tp(cc), prec='single') + self.eq(tp(aa), tp(ac), prec='single', ulps=2) + self.eq(tp(ac), tp(cc), prec='single', ulps=2) + self.eq(tp(aa), tp(cc), prec='single', ulps=2) + + def test_enums(self): + values = [Color.red, Color.green, Color.blue, Shake.mint, + Shape.circle, Shape.square, Planet.EARTH, Planet.MERCURY] + for val in values: + self.eq(val, val) + self.ne(val, val.value) + for a, b in itertools.combinations(values, 2): + self.ne(a, b) + + def test_arrays(self): + a = np.arange(1, 7, dtype=np.int16).reshape((2, 3)) + b = a.copy() + self.eq(a, b) + # Different values + self.ne(a, b + 1) + self.ne(a, b[:-1]) + self.ne(a, b.T) + # Different dtypes + self.ne(a, b.astype(np.int32)) + # Different layout + self.ne(a, b.T.copy().T) + # Different ndim + self.ne(a, b.flatten()) + # Different writeability + b.flags.writeable = False + self.ne(a, b) + # Precision + a = np.arange(1, 3, dtype=np.float64) + b = a * (1.0 + DBL_EPSILON) + c = a * (1.0 + DBL_EPSILON * 2) + self.ne(a, b) + self.eq(a, b, prec='double') + self.ne(a, c, prec='double') + + def test_npdatetime(self): + a = np.datetime64('1900', 'Y') + b = np.datetime64('1900', 'Y') + c = np.datetime64('1900-01-01', 'D') + d = np.datetime64('1901', 'Y') + self.eq(a, b) + # Different unit + self.ne(a, c) + # Different value + self.ne(a, d) + + def test_nptimedelta(self): + a = np.timedelta64(1, 'h') + b = np.timedelta64(1, 'h') + c = np.timedelta64(60, 'm') + d = np.timedelta64(2, 'h') + self.eq(a, b) + # Different unit + self.ne(a, c) + # Different value + self.ne(a, d) + + +class TestMisc(TestCase): + + def test_assertRefCount(self): + # Use floats to avoid integer interning + x = 55. + y = 66. + l = [] + with self.assertRefCount(x, y): + pass + with self.assertRaises(AssertionError) as cm: + # y gains a reference + with self.assertRefCount(x, y): + l.append(y) + self.assertIn("66", str(cm.exception)) + + def test_forbid_codegen(self): + """ + Test that forbid_codegen() prevents code generation using the @jit + decorator. + """ + def f(): + return 1 + with forbid_codegen(): + with self.assertRaises(RuntimeError) as raises: + cfunc = jit(nopython=True)(f) + cfunc() + self.assertIn("codegen forbidden by test case", str(raises.exception)) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_svml.py b/lib/python3.10/site-packages/numba/tests/test_svml.py new file mode 100644 index 0000000000000000000000000000000000000000..a047acea529e1cb72b488df3a7117b6f955893ce --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_svml.py @@ -0,0 +1,411 @@ +import math +import numpy as np +import numbers +import re +import traceback +import multiprocessing as mp + +import numba +from numba import njit, prange +from numba.core import config +from numba.tests.support import TestCase, tag, override_env_config +import unittest + +needs_svml = unittest.skipUnless(config.USING_SVML, + "SVML tests need SVML to be present") + +# a map of float64 vector lengths with corresponding CPU architecture +vlen2cpu = {2: 'nehalem', 4: 'haswell', 8: 'skylake-avx512'} +# force LLVM to use AVX512 registers for vectorization +# https://reviews.llvm.org/D67259 +vlen2cpu_features = {2: '', 4: '', 8: '-prefer-256-bit'} + +# env vars to force CPU as skylake-avx512. +# force LLVM to use AVX512 registers for vectorization +# https://reviews.llvm.org/D67259 +_skylake_axv512_envvars = {'NUMBA_CPU_NAME': 'skylake-avx512', + 'NUMBA_CPU_FEATURES': '-prefer-256-bit'} + +# K: SVML functions, V: python functions which are expected to be SIMD-vectorized +# using SVML, explicit references to Python functions here are mostly for sake of +# instant import checks. +# TODO: [] and comments below mean unused/untested SVML function, it's to be +# either enabled or to be replaced with the explanation why the function +# cannot be used in Numba +# TODO: this test does not support functions with more than 1 arguments yet +# The test logic should be modified if there is an SVML function being used under +# different name or module from Python +svml_funcs = { + "sin": [np.sin, math.sin], + "cos": [np.cos, math.cos], + "pow": [], # pow, math.pow], + "exp": [np.exp, math.exp], + "log": [np.log, math.log], + "acos": [math.acos], + "acosh": [math.acosh], + "asin": [math.asin], + "asinh": [math.asinh], + "atan2": [], # math.atan2], + "atan": [math.atan], + "atanh": [math.atanh], + "cbrt": [], # np.cbrt], + "cdfnorm": [], + "cdfnorminv": [], + "ceil": [], # np.ceil, math.ceil], + "cosd": [], + "cosh": [np.cosh, math.cosh], + "erf": [math.erf], # np.erf is available in Intel Distribution + "erfc": [math.erfc], + "erfcinv": [], + "erfinv": [], + "exp10": [], + "exp2": [], # np.exp2], + "expm1": [np.expm1, math.expm1], + "floor": [], # np.floor, math.floor], + "fmod": [], # np.fmod, math.fmod], + "hypot": [], # np.hypot, math.hypot], + "invsqrt": [], # available in Intel Distribution + "log10": [np.log10, math.log10], + "log1p": [np.log1p, math.log1p], + "log2": [], # np.log2], + "logb": [], + "nearbyint": [], + "rint": [], # np.rint], + "round": [], # round], + "sind": [], + "sinh": [np.sinh, math.sinh], + "tan": [np.tan, math.tan], + "tanh": [np.tanh, math.tanh], + "trunc": [], # np.trunc, math.trunc], +} +# TODO: these functions are not vectorizable with complex types +complex_funcs_exclude = ["tan", "log10", "expm1", "log1p", "tanh", "log"] + +# remove untested entries +svml_funcs = {k: v for k, v in svml_funcs.items() if len(v) > 0} +# lists for functions which belong to numpy and math modules correpondently +numpy_funcs = [f for f, v in svml_funcs.items() if "= (3, 12), "needs Python 3.12+") +class TestMonitoring(TestCase): + # Tests the interaction of the Numba dispatcher with `sys.monitoring`. + # + # Note that it looks like a lot of these try..finally type patterns could + # be written using a context manager, this is true, but it is not written + # like that deliberately as a context manager adds implementation details + # onto the stack which makes it harder to debug tests. + + def setUp(self): + # First... check if there's other monitoring stuff registered (e.g. test + # is running under cProfile or coverage), skip if so. + monitor_kinds = [] + for i in range(6): # there are 5 tool IDs + if sys.monitoring.get_tool(i) is not None: + monitor_kinds.append(TOOL2MONITORTYPE[i]) + + if monitor_kinds: + msg = ("Cannot run monitoring tests when other monitors are " + "active, found monitor(s) of type: " + f"{', '.join(monitor_kinds)}") + self.skipTest(msg) + + # set up some standard functions and answers for use throughout + self.foo, self.call_foo = generate_usecase() + self.arg = 10 + self.foo_result = self.arg + 5 + 1 + self.call_foo_result = 2 * self.foo_result + # pretend to be a profiler in the majority of these unit tests + self.tool_id = sys.monitoring.PROFILER_ID + + def check_py_start_calls(self, allcalls): + # Checks that PY_START calls were correctly captured for a + # `self.call_foo(self.arg)` call. + mockcalls = allcalls[PY_START] + self.assertEqual(mockcalls.call_count, 2) + # Find the resume op, this is where the code for `call_foo` "starts" + inst = [x for x in dis.get_instructions(self.call_foo) + if x.opname == "RESUME"] + offset = inst[0].offset + # Numba always reports the start location as offset 0. + calls = (call(self.call_foo.__code__, offset), + call(self.foo.__code__, 0)) + mockcalls.assert_has_calls(calls) + + def check_py_return_calls(self, allcalls): + # Checks that PY_RETURN calls were correctly captured for a + # `self.call_foo(self.arg)` call. + mockcalls = allcalls[PY_RETURN] + self.assertEqual(mockcalls.call_count, 2) + # These are in the order the returns were encountered. Return from `foo` + # occurred first, followed by return from `call_foo`. + # NOTE: it is a known issue that Numba reports the PY_RETURN event as + # occurring at offset 0. At present there's no information about the + # location that the return occurred propagating from the machine code + # back to the dispatcher (where the monitoring events are handled). + offset = [x for x in dis.get_instructions(self.call_foo)][-1].offset + calls = [call(self.foo.__code__, 0, self.foo_result), + call(self.call_foo.__code__, offset, self.call_foo_result)] + mockcalls.assert_has_calls(calls) + + def run_with_events(self, function, args, events, tool_id=None): + # Runs function with args with monitoring set for events on `tool_id` + # (if present, else just uses the default of "PROFILER_ID") returns a + # dictionary event->callback. + try: + if tool_id is None: + _tool_id = self.tool_id + else: + _tool_id = tool_id + sys.monitoring.use_tool_id(_tool_id, "custom_monitor") + callbacks = {} + event_bitmask = 0 + for event in events: + callback = Mock() + sys.monitoring.register_callback(_tool_id, event, callback) + callbacks[event] = callback + event_bitmask |= event + # only start monitoring once callbacks are registered + sys.monitoring.set_events(_tool_id, event_bitmask) + function(*args) + finally: + # clean up state + for event in events: + sys.monitoring.register_callback(_tool_id, event, None) + sys.monitoring.set_events(_tool_id, NO_EVENTS) + sys.monitoring.free_tool_id(_tool_id) + return callbacks + + def test_start_event(self): + # test event PY_START + cb = self.run_with_events(self.call_foo, (self.arg,), (PY_START,)) + # Check... + self.assertEqual(len(cb), 1) + self.check_py_start_calls(cb) + + def test_return_event(self): + # test event PY_RETURN + cb = self.run_with_events(self.call_foo, (self.arg,), (PY_RETURN,)) + # Check... + self.assertEqual(len(cb), 1) + self.check_py_return_calls(cb) + + def test_call_event_chain(self): + # test event PY_START and PY_RETURN monitored at the same time + cb = self.run_with_events(self.call_foo, (self.arg,), + (PY_START, PY_RETURN)) + # Check... + self.assertEqual(len(cb), 2) + self.check_py_return_calls(cb) + self.check_py_start_calls(cb) + + # -------------------------------------------------------------------------- + # NOTE: About the next two tests... + # Numba doesn't support "local event" level monitoring, it's implemented + # in CPython via adjusting the code object bytecode to use + # "instrumented" opcodes. When the interpreter encounters an + # instrumented opcode it triggers the event handling pathways. As Numba + # doesn't interpret the bytecode instruction-at-a-time there's not + # really any way to support this. Two things to check... + # 1. The an instrumented code object doesn't trigger events in + # the dispatcher. + # 2. That Numba can compile instrumented functions (it should be able + # to without any problem as the instrumented bytecode should not + # leak into `.co_code`.). + + def test_instrumented_code_does_not_trigger_numba_events(self): + # 1. from above. + @jit('int64(int64)',) + def foo(x): + return x + 3 + + try: + tool_id = self.tool_id + sys.monitoring.use_tool_id(tool_id, "custom_monitor") + callbacks = {} + event_bitmask = 0 + events = (PY_START, PY_RETURN) + for event in events: + callback = Mock() + sys.monitoring.register_callback(tool_id, event, callback) + callbacks[event] = callback + event_bitmask |= event + + sys.monitoring.set_local_events(tool_id, foo.__code__, + event_bitmask) + result = foo(self.arg) + finally: + for event in events: + sys.monitoring.register_callback(tool_id, event, None) + sys.monitoring.set_local_events(tool_id, foo.__code__, 0) + sys.monitoring.free_tool_id(tool_id) + + # check + self.assertEqual(result, foo.py_func(self.arg)) + self.assertEqual(len(callbacks), 2) + callbacks[PY_START].assert_not_called() + callbacks[PY_RETURN].assert_not_called() + + def test_instrumented_code_can_be_compiled(self): + # 2. from above. + + def foo(x): + return x + 1 + + try: + tool_id = self.tool_id + sys.monitoring.use_tool_id(tool_id, "custom_monitor") + sys.monitoring.set_local_events(tool_id, foo.__code__, PY_START) + sys.monitoring.register_callback(tool_id, PY_START, Mock()) + # test compile + result = jit(foo)(self.arg) + self.assertEqual(result, foo(self.arg)) + finally: + sys.monitoring.register_callback(tool_id, PY_START, None) + sys.monitoring.set_local_events(tool_id, foo.__code__, 0) + sys.monitoring.free_tool_id(tool_id) + + def test_unhandled_events_are_ignored(self): + # Check an unhandled event e.g. PY_YIELD isn't reported. + def generate(dec): + @dec('void()') + def producer(): + yield 10 + + @dec('int64()') + def consumer(): + p = producer() + return next(p) + + return consumer + + event = sys.monitoring.events.PY_YIELD + # check that pure python reports + wrapper = lambda sig: lambda fn: fn + py_consumer = generate(wrapper) + py_cb = self.run_with_events(py_consumer, (), (event,)) + py_cb[event].assert_called_once() + # check the numba does not report + nb_consumer = generate(jit) + nb_cb = self.run_with_events(nb_consumer, (), (event,)) + nb_cb[event].assert_not_called() + + def test_event_with_no_callback_runs(self): + # This checks the situation where an event is being monitored but + # there's no callback associated with the event. In the dispatcher C + # code the loop over tools will be entered, but nothing will get called + # as the "instrument" is missing (NULL). + try: + event = PY_START + tool_id = self.tool_id + sys.monitoring.use_tool_id(tool_id, "custom_monitor") + sys.monitoring.set_events(tool_id, event) + # NO CALLBACK IS REGISTERED! + active_events = sys.monitoring.get_events(tool_id) + self.assertEqual(active_events, event) + result = self.call_foo(self.arg) + active_events = sys.monitoring.get_events(tool_id) + self.assertEqual(active_events, event) + self.assertEqual(result, self.call_foo_result) + finally: + sys.monitoring.set_events(tool_id, NO_EVENTS) + sys.monitoring.free_tool_id(tool_id) + + def test_disable_from_callback(self): + # Event callbacks can disable a _local_ event at a specific location to + # prevent it triggering in the future by returning + # `sys.monitoring.DISABLE`. As this only applies to local events, doing + # this should have absolutely no impact for the global events that Numba + # supports. + + callback = Mock(return_value=sys.monitoring.DISABLE) + + try: + event = PY_START + tool_id = self.tool_id + sys.monitoring.use_tool_id(tool_id, "custom_monitor") + sys.monitoring.set_events(tool_id, event) + sys.monitoring.register_callback(tool_id, event, callback) + active_events = sys.monitoring.get_events(tool_id) + self.assertEqual(active_events, event) + result = self.call_foo(self.arg) + active_events = sys.monitoring.get_events(tool_id) + self.assertEqual(active_events, event) + self.assertEqual(result, self.call_foo_result) + callback.assert_called() + finally: + # It is necessary to restart events that have been disabled. The + # "disabled" state of the `PY_START` event for the tool + # `self.tool_id` "leaks" into subsequent tests. These subsequent + # tests then end up failing as events that should have been + # triggered are not triggered due to the state leak! It's not really + # clear why this happens, if it is part of the design or a side + # effect of the design, or if this behaviour is simply a bug in + # CPython itself. + sys.monitoring.restart_events() + sys.monitoring.register_callback(tool_id, event, None) + sys.monitoring.set_events(tool_id, NO_EVENTS) + sys.monitoring.free_tool_id(tool_id) + + def test_mutation_from_objmode(self): + try: + # Check that it's possible to enable an event (mutate the event + # state)from an `objmode` block. Monitoring for PY_RETURN is set in + # objmode once the function starts executing. + tool_id = self.tool_id + sys.monitoring.use_tool_id(tool_id, "custom_monitor") + event = PY_RETURN + # register the callback... note that the event isn't switched on yet + callback = Mock() + sys.monitoring.register_callback(tool_id, event, callback) + + def objmode_enable_event(switch_on_event): + if switch_on_event: + sys.monitoring.set_events(tool_id, event) + + @_enable_sysmon + @jit('int64(int64)') + def foo(enable): + with objmode: + objmode_enable_event(enable) + return enable + 7 + + # this should not trigger the return callback + foo(0) + callback.assert_not_called() + + # this should trigger the return callback + foo(1) + # switch off the event so the callback mock is protected from + # mutation. + sys.monitoring.set_events(tool_id, NO_EVENTS) + # check what happened + callback.assert_called() + # 2 calls, 1 is the return from the objmode_enable_event, the other + # is the return from foo. + self.assertEqual(callback.call_count, 2) + finally: + sys.monitoring.set_events(tool_id, NO_EVENTS) + sys.monitoring.register_callback(tool_id, event, None) + sys.monitoring.free_tool_id(tool_id) + + def test_multiple_tool_id(self): + # Check that multiple tools will work across different combinations of + # events that Numba dispatcher supports, namely: + # (NO_EVENTS, PY_START, PY_RETURN). + + # the use of NO_EVENTS is superfluous, it is to demonstrate usage. + tool_ids_2_events = {sys.monitoring.DEBUGGER_ID: (NO_EVENTS,), + sys.monitoring.COVERAGE_ID: (PY_START,), + sys.monitoring.PROFILER_ID: (PY_RETURN,), + sys.monitoring.OPTIMIZER_ID: + (PY_START, PY_RETURN,),} + + all_callbacks = {} + try: + for tool_id, events in tool_ids_2_events.items(): + sys.monitoring.use_tool_id(tool_id, f"custom_monitor_{tool_id}") + event_bitmask = 0 + callbacks = {} + all_callbacks[tool_id] = callbacks + for event in events: + callback = Mock() + # Can't set an event for NO_EVENTS! + if event != NO_EVENTS: + sys.monitoring.register_callback(tool_id, event, + callback) + callbacks[event] = callback + event_bitmask |= event + # only start monitoring once callbacks are registered + for tool_id in tool_ids_2_events.keys(): + sys.monitoring.set_events(tool_id, event_bitmask) + self.call_foo(self.arg) + finally: + # clean up state + for tool_id, events in tool_ids_2_events.items(): + for event in events: + # Can't remove an event for NO_EVENTS! + if event != NO_EVENTS: + sys.monitoring.register_callback(tool_id, event, None) + sys.monitoring.set_events(tool_id, NO_EVENTS) + sys.monitoring.free_tool_id(tool_id) + + # Now check all_callbacks... + + # check debugger tool slot + dbg_tool = all_callbacks[sys.monitoring.DEBUGGER_ID] + self.assertEqual(len(dbg_tool), 1) # one event to capture + callback = dbg_tool[NO_EVENTS] + callback.assert_not_called() + + # check coverage tool slot + cov_tool = all_callbacks[sys.monitoring.COVERAGE_ID] + self.assertEqual(len(cov_tool), 1) # one event to capture + self.check_py_start_calls(cov_tool) + + # check profiler tool slot + prof_tool = all_callbacks[sys.monitoring.PROFILER_ID] + self.assertEqual(len(prof_tool), 1) # one event to capture + self.check_py_return_calls(prof_tool) + + # check optimiser tool slot + opt_tool = all_callbacks[sys.monitoring.OPTIMIZER_ID] + self.assertEqual(len(opt_tool), 2) # two events to capture + self.check_py_start_calls(opt_tool) + self.check_py_return_calls(opt_tool) + + def test_raising_under_monitoring(self): + # Check that Numba can raise an exception whilst monitoring is running + # and that 1. `RAISE` is issued 2. `PY_UNWIND` is issued, 3. that + # `PY_RETURN` is not issued. + + ret_callback = Mock() + raise_callback = Mock() + unwind_callback = Mock() + + msg = 'exception raised' + + @_enable_sysmon + @jit('()') + def foo(): + raise ValueError(msg) + + store_raised = None + try: + tool_id = self.tool_id + sys.monitoring.use_tool_id(tool_id, "custom_monitor") + sys.monitoring.register_callback(tool_id, PY_RETURN, ret_callback) + sys.monitoring.register_callback(tool_id, RAISE, raise_callback) + sys.monitoring.register_callback(tool_id, PY_UNWIND, + unwind_callback) + sys.monitoring.set_events(tool_id, PY_RETURN | RAISE | PY_UNWIND) + try: + foo() + except ValueError as raises: + store_raised = raises + # switch off monitoring + sys.monitoring.set_events(tool_id, NO_EVENTS) + # check that the ret_callback was called once (by Numba unpickle to + # fetch the exception info out of the stored bytes). + ret_callback.assert_called_once() + # and that elements that are feasible to check about the call are + # as expected + the_call = ret_callback.call_args_list[0] + self.assertEqual(the_call.args[0], _numba_unpickle.__code__) + self.assertEqual(the_call.args[2][0], ValueError) + self.assertEqual(the_call.args[2][1][0], msg) + + # check that the RAISE event callback was triggered + raise_callback.assert_called() + numba_unpickle_call = raise_callback.call_args_list[0] + self.assertEqual(numba_unpickle_call.args[0], + _numba_unpickle.__code__) + self.assertIsInstance(numba_unpickle_call.args[2], KeyError) + foo_call = raise_callback.call_args_list[1] + self.assertEqual(foo_call.args[0], foo.py_func.__code__) + self.assertIsInstance(foo_call.args[2], ValueError) + self.assertIn(msg, str(foo_call.args[2])) + + # check that PY_UNWIND event callback was called + unwind_callback.assert_called_once() + unwind_call = unwind_callback.call_args_list[0] + self.assertEqual(unwind_call.args[0], foo.py_func.__code__) + self.assertIsInstance(unwind_call.args[2], ValueError) + self.assertIn(msg, str(unwind_call.args[2])) + finally: + sys.monitoring.set_events(tool_id, NO_EVENTS) + sys.monitoring.register_callback(tool_id, PY_RETURN, None) + sys.monitoring.register_callback(tool_id, RAISE, None) + sys.monitoring.register_callback(tool_id, PY_UNWIND, None) + sys.monitoring.free_tool_id(tool_id) + + self.assertIn(msg, str(store_raised)) + + def test_stop_iteration_under_monitoring(self): + # Check that Numba can raise an StopIteration exception whilst + # monitoring is running and that: + # 1. RAISE is issued for an explicitly raised StopIteration exception. + # 2. PY_RETURN is issued appropriately for the unwinding stack + # 3. STOP_ITERATION is not issued as there is no implicit StopIteration + # raised. + + return_callback = Mock() + raise_callback = Mock() + stopiter_callback = Mock() + + msg = 'exception raised' + + @_enable_sysmon + @jit('()') + def foo(): + raise StopIteration(msg) + + store_raised = None + try: + tool_id = self.tool_id + sys.monitoring.use_tool_id(tool_id, "custom_monitor") + sys.monitoring.register_callback(tool_id, PY_RETURN, + return_callback) + sys.monitoring.register_callback(tool_id, RAISE, + raise_callback) + sys.monitoring.register_callback(tool_id, STOP_ITERATION, + stopiter_callback) + sys.monitoring.set_events(tool_id, + PY_RETURN | STOP_ITERATION | RAISE) + try: + foo() + except StopIteration as raises: + store_raised = raises + # switch off monitoring + sys.monitoring.set_events(tool_id, NO_EVENTS) + # check that the return_callback was called once (by Numba unpickle + # to fetch the exception info out of the stored bytes). + return_callback.assert_called_once() + # and that elements that are feasible to check about the call are + # as expected + the_call = return_callback.call_args_list[0] + self.assertEqual(the_call.args[0], _numba_unpickle.__code__) + self.assertEqual(the_call.args[2][0], StopIteration) + self.assertEqual(the_call.args[2][1][0], msg) + + # check that the RAISE event callback was triggered + raise_callback.assert_called() + # check that it's 3 long (numba unpickle, jit(foo), the test method) + self.assertEqual(raise_callback.call_count, 3) + + # check the numba pickle call + numba_unpickle_call = raise_callback.call_args_list[0] + self.assertEqual(numba_unpickle_call.args[0], + _numba_unpickle.__code__) + self.assertIsInstance(numba_unpickle_call.args[2], KeyError) + + # check the jit(foo) call + foo_call = raise_callback.call_args_list[1] + self.assertEqual(foo_call.args[0], foo.py_func.__code__) + self.assertIsInstance(foo_call.args[2], StopIteration) + self.assertIn(msg, str(foo_call.args[2])) + + # check the test method call + meth_call = raise_callback.call_args_list[2] + test_method_code = sys._getframe().f_code + self.assertEqual(meth_call.args[0], test_method_code) + self.assertIsInstance(meth_call.args[2], StopIteration) + self.assertIn(msg, str(meth_call.args[2])) + + # check that the STOP_ITERATION event was not triggered + stopiter_callback.assert_not_called() + finally: + sys.monitoring.set_events(tool_id, NO_EVENTS) + sys.monitoring.register_callback(tool_id, PY_RETURN, None) + sys.monitoring.register_callback(tool_id, STOP_ITERATION, None) + sys.monitoring.register_callback(tool_id, RAISE, None) + sys.monitoring.free_tool_id(tool_id) + + self.assertIn(msg, str(store_raised)) + + def test_raising_callback_unwinds_from_jit_on_success_path(self): + # An event callback can legitimately raise an exception, this test + # makes sure Numba's dispatcher handles it ok on the "successful path", + # i.e. the JIT compiled function didn't raise an exception at runtime. + + msg = "deliberately broken callback" + + callback = Mock(side_effect=ValueError(msg)) + + store_raised = None + try: + event = PY_START + tool_id = self.tool_id + sys.monitoring.use_tool_id(tool_id, "custom_monitor") + sys.monitoring.set_events(tool_id, event) + sys.monitoring.register_callback(tool_id, event, callback) + self.foo(self.arg) + except ValueError as raises: + store_raised = raises + finally: + sys.monitoring.register_callback(tool_id, event, None) + sys.monitoring.set_events(tool_id, NO_EVENTS) + sys.monitoring.free_tool_id(tool_id) + + callback.assert_called_once() + self.assertIn(msg, str(store_raised)) + + def test_raising_callback_unwinds_from_jit_on_raising_path(self): + # An event callback can legitimately raise an exception, this test + # makes sure Numba's dispatcher handles it ok on the + # "unsuccessful path", i.e. the JIT compiled function raised an + # exception at runtime. This test checks the RAISE event, as the + # callback itself raises, it overrides the exception coming from the + # JIT compiled function. + + msg_callback = "deliberately broken callback" + msg_execution = "deliberately broken execution" + + callback = Mock(side_effect=ValueError(msg_callback)) + + class LocalException(Exception): + pass + + @_enable_sysmon + @jit("()") + def raising(): + raise LocalException(msg_execution) + + store_raised = None + try: + event = RAISE + tool_id = self.tool_id + sys.monitoring.use_tool_id(tool_id, "custom_monitor") + sys.monitoring.set_events(tool_id, event) + sys.monitoring.register_callback(tool_id, event, callback) + raising() + except ValueError as raises: + store_raised = raises + finally: + sys.monitoring.register_callback(tool_id, event, None) + sys.monitoring.set_events(tool_id, NO_EVENTS) + sys.monitoring.free_tool_id(tool_id) + + callback.assert_called() + # Called 3x (numba unpickle, ValueError in callback, the test method) + self.assertEqual(callback.call_count, 3) + + # check the numba unpickle call + numba_unpickle_call = callback.call_args_list[0] + self.assertEqual(numba_unpickle_call.args[0], _numba_unpickle.__code__) + self.assertIsInstance(numba_unpickle_call.args[2], KeyError) + + # check the jit(raising) call + raising_call = callback.call_args_list[1] + self.assertEqual(raising_call.args[0], raising.py_func.__code__) + self.assertIs(raising_call.args[2], callback.side_effect) + + # check the test method call + meth_call = callback.call_args_list[2] + test_method_code = sys._getframe().f_code + self.assertEqual(meth_call.args[0], test_method_code) + self.assertIs(meth_call.args[2], callback.side_effect) + + # check the stored exception is the expected exception + self.assertIs(store_raised, callback.side_effect) + + def test_raising_callback_unwinds_from_jit_on_unwind_path(self): + # An event callback can legitimately raise an exception, this test + # makes sure Numba's dispatcher handles it ok on the + # "unsuccessful path", i.e. the JIT compiled function raised an + # exception at runtime. This test checks the PY_UNWIND event. CPython + # seems to not notice the PY_UNWIND coming from the exception arising + # from the raise in the event callback, it just has the PY_UNWIND from + # the raise in the JIT compiled function. + + msg_callback = "deliberately broken callback" + msg_execution = "deliberately broken execution" + + callback = Mock(side_effect=ValueError(msg_callback)) + + class LocalException(Exception): + pass + + @_enable_sysmon + @jit("()") + def raising(): + raise LocalException(msg_execution) + + store_raised = None + try: + event = PY_UNWIND + tool_id = self.tool_id + sys.monitoring.use_tool_id(tool_id, "custom_monitor") + sys.monitoring.set_events(tool_id, event) + sys.monitoring.register_callback(tool_id, event, callback) + raising() + except ValueError as raises: + store_raised = raises + finally: + sys.monitoring.register_callback(tool_id, event, None) + sys.monitoring.set_events(tool_id, NO_EVENTS) + sys.monitoring.free_tool_id(tool_id) + + callback.assert_called_once() + + # check the jit(raising) call + raising_call = callback.call_args_list[0] + self.assertEqual(raising_call.args[0], raising.py_func.__code__) + self.assertEqual(type(raising_call.args[2]), LocalException) + self.assertEqual(str(raising_call.args[2]), msg_execution) + + # check the stored_raise + self.assertIs(store_raised, callback.side_effect) + + def test_monitoring_multiple_threads(self): + # two threads, different tools and events registered on each thread. + + def t1_work(self, q): + try: + # test event PY_START on a "debugger tool" + cb = self.run_with_events(self.call_foo, (self.arg,), + (PY_START,), + tool_id=sys.monitoring.DEBUGGER_ID) + # Check... + self.assertEqual(len(cb), 1) + self.check_py_start_calls(cb) + except Exception as e: + q.put(e) + + def t2_work(self, q): + try: + # test event PY_RETURN on a "coverage tool" + cb = self.run_with_events(self.call_foo, (self.arg,), + (PY_RETURN,), + tool_id=sys.monitoring.COVERAGE_ID) + # Check... + self.assertEqual(len(cb), 1) + self.check_py_return_calls(cb) + except Exception as e: + q.put(e) + + q1 = queue.Queue() + t1 = threading.Thread(target=t1_work, args=(self, q1)) + q2 = queue.Queue() + t2 = threading.Thread(target=t2_work, args=(self, q2)) + + threads = (t1, t2) + for t in threads: + t.start() + for t in threads: + t.join() + + # make sure there were no exceptions + def assert_empty_queue(q): + if q.qsize() != 0: + while not q.empty(): + print(q.get()) + self.fail("queue supposed to be empty") + + assert_empty_queue(q1) + assert_empty_queue(q2) + + +@unittest.skipUnless(PYVERSION >= (3, 12), "needs Python 3.12+") +class TestMonitoringSelfTest(TestCase): + + def test_skipping_of_tests_if_monitoring_in_use(self): + # check that the unit tests in the TestMonitoring class above will skip + # if there are other monitoring tools registered in the thread (in this + # case cProfile is used to cause that effect). + r = self.subprocess_test_runner(TestMonitoring.__module__, + 'TestMonitoring', + 'test_start_event', + flags={'-m': 'cProfile'}) + self.assertIn("skipped=1", str(r)) + + +@unittest.skipUnless(PYVERSION >= (3, 12), "needs Python 3.12+") +class TestMonitoringEnvVarControl(TestCase): + @TestCase.run_test_in_subprocess( + envvars={"NUMBA_ENABLE_SYS_MONITORING": ''}) + def test_default_off(self): + @jit + def foo(x): + return x + 1 + + self.assertFalse(foo._enable_sysmon) + + @TestCase.run_test_in_subprocess( + envvars={"NUMBA_ENABLE_SYS_MONITORING": '0'}) + def test_override_off(self): + @jit + def foo(x): + return x + 1 + + self.assertFalse(foo._enable_sysmon) + + @TestCase.run_test_in_subprocess( + envvars={"NUMBA_ENABLE_SYS_MONITORING": '1'}) + def test_override_on(self): + @jit + def foo(x): + return x + 1 + + self.assertTrue(foo._enable_sysmon) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_sys_stdin_assignment.py b/lib/python3.10/site-packages/numba/tests/test_sys_stdin_assignment.py new file mode 100644 index 0000000000000000000000000000000000000000..f9d88e23547d098ed5c6ffcaaf4f8585b6bbba89 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_sys_stdin_assignment.py @@ -0,0 +1,67 @@ +import sys + +import unittest +from numba import njit + + +@njit +def f0(a, b): + return a + b + + +@njit +def f1(begin1, end1, begin2, end2): + if begin1 > begin2: return f1(begin2, end2, begin1, end1) + return end1 + 1 >= begin2 + + +@njit +def f0_2(a, b): + return a + b + + +@njit +def f1_2(begin1, end1, begin2, end2): + if begin1 > begin2: return f1_2(begin2, end2, begin1, end1) + return end1 + 1 >= begin2 + + +class TestSysStdinAssignment(unittest.TestCase): + + def test_no_reassignment_of_stdout(self): + """ + https://github.com/numba/numba/issues/3027 + Older versions of colorama break stdout/err when recursive functions + are compiled. + + This test should work irrespective of colorama version, or indeed its + presence. If the version is too low, it should be disabled and the test + should work anyway, if it is a sufficiently high version or it is not + present, it should work anyway. + """ + + originally = sys.stdout, sys.stderr + + try: + sys.stdout = None + f0(0, 1) # Not changed stdout? + self.assertEqual(sys.stdout, None) + f1(0, 1, 2, 3) # Not changed stdout? + self.assertEqual(sys.stdout, None) + + sys.stderr = None + f0_2(0, 1) # Not changed stderr? + self.assertEqual(sys.stderr, None) + f1_2(0, 1, 2, 3) # Not changed stderr? + self.assertEqual(sys.stderr, None) + + finally: + sys.stdout, sys.stderr = originally + + self.assertNotEqual(sys.stderr, None) + self.assertNotEqual(sys.stdout, None) + + +if __name__ == '__main__': + unittest.main() + diff --git a/lib/python3.10/site-packages/numba/tests/test_target_overloadselector.py b/lib/python3.10/site-packages/numba/tests/test_target_overloadselector.py new file mode 100644 index 0000000000000000000000000000000000000000..8fa54bccc65057b62b331c24c698d71a8d1caaac --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_target_overloadselector.py @@ -0,0 +1,148 @@ +from itertools import product, permutations +from collections import defaultdict + +import unittest +from numba.core.base import OverloadSelector +from numba.core.registry import cpu_target +from numba.core.imputils import builtin_registry, RegistryLoader +from numba.core import types +from numba.core.errors import NumbaNotImplementedError, NumbaTypeError + + +class TestOverloadSelector(unittest.TestCase): + def test_select_and_sort_1(self): + os = OverloadSelector() + os.append(1, (types.Any, types.Boolean)) + os.append(2, (types.Boolean, types.Integer)) + os.append(3, (types.Boolean, types.Any)) + os.append(4, (types.Boolean, types.Boolean)) + compats = os._select_compatible((types.boolean, types.boolean)) + self.assertEqual(len(compats), 3) + ordered, scoring = os._sort_signatures(compats) + self.assertEqual(len(ordered), 3) + self.assertEqual(len(scoring), 3) + self.assertEqual(ordered[0], (types.Boolean, types.Boolean)) + self.assertEqual(scoring[types.Boolean, types.Boolean], 0) + self.assertEqual(scoring[types.Boolean, types.Any], 1) + self.assertEqual(scoring[types.Any, types.Boolean], 1) + + def test_select_and_sort_2(self): + os = OverloadSelector() + os.append(1, (types.Container,)) + os.append(2, (types.Sequence,)) + os.append(3, (types.MutableSequence,)) + os.append(4, (types.List,)) + compats = os._select_compatible((types.List,)) + self.assertEqual(len(compats), 4) + ordered, scoring = os._sort_signatures(compats) + self.assertEqual(len(ordered), 4) + self.assertEqual(len(scoring), 4) + self.assertEqual(ordered[0], (types.List,)) + self.assertEqual(scoring[(types.List,)], 0) + self.assertEqual(scoring[(types.MutableSequence,)], 1) + self.assertEqual(scoring[(types.Sequence,)], 2) + self.assertEqual(scoring[(types.Container,)], 3) + + def test_match(self): + os = OverloadSelector() + self.assertTrue(os._match(formal=types.Boolean, actual=types.boolean)) + self.assertTrue(os._match(formal=types.Boolean, actual=types.Boolean)) + # test subclass + self.assertTrue(issubclass(types.Sequence, types.Container)) + self.assertTrue(os._match(formal=types.Container, + actual=types.Sequence)) + self.assertFalse(os._match(formal=types.Sequence, + actual=types.Container)) + # test any + self.assertTrue(os._match(formal=types.Any, actual=types.Any)) + self.assertTrue(os._match(formal=types.Any, actual=types.Container)) + self.assertFalse(os._match(formal=types.Container, actual=types.Any)) + + def test_ambiguous_detection(self): + os = OverloadSelector() + # unambiguous signatures + os.append(1, (types.Any, types.Boolean)) + os.append(2, (types.Integer, types.Boolean)) + self.assertEqual(os.find((types.boolean, types.boolean)), 1) + # not implemented + with self.assertRaises(NumbaNotImplementedError) as raises: + os.find((types.boolean, types.int32)) + # generic + os.append(3, (types.Any, types.Any)) + self.assertEqual(os.find((types.boolean, types.int32)), 3) + self.assertEqual(os.find((types.boolean, types.boolean)), 1) + # add ambiguous signature; can match (bool, any) and (any, bool) + os.append(4, (types.Boolean, types.Any)) + with self.assertRaises(NumbaTypeError) as raises: + os.find((types.boolean, types.boolean)) + self.assertIn('2 ambiguous signatures', str(raises.exception)) + # disambiguous + os.append(5, (types.boolean, types.boolean)) + self.assertEqual(os.find((types.boolean, types.boolean)), 5) + + def test_subclass_specialization(self): + os = OverloadSelector() + self.assertTrue(issubclass(types.Sequence, types.Container)) + os.append(1, (types.Container, types.Container,)) + lstty = types.List(types.boolean) + self.assertEqual(os.find((lstty, lstty)), 1) + os.append(2, (types.Container, types.Sequence,)) + self.assertEqual(os.find((lstty, lstty)), 2) + + def test_cache(self): + os = OverloadSelector() + self.assertEqual(len(os._cache), 0) + os.append(1, (types.Any,)) + self.assertEqual(os.find((types.int32,)), 1) + self.assertEqual(len(os._cache), 1) + os.append(2, (types.Integer,)) + self.assertEqual(len(os._cache), 0) + self.assertEqual(os.find((types.int32,)), 2) + self.assertEqual(len(os._cache), 1) + + +class TestAmbiguousOverloads(unittest.TestCase): + + @classmethod + def setUpClass(cls): + # ensure all impls are loaded + cpu_target.target_context.refresh() + + def create_overload_selector(self, kind): + os = OverloadSelector() + loader = RegistryLoader(builtin_registry) + for impl, sig in loader.new_registrations(kind): + os.append(impl, sig) + return os + + def test_ambiguous_casts(self): + os = self.create_overload_selector(kind='casts') + all_types = set(t for sig, impl in os.versions for t in sig) + # ensure there are no ambiguous cast overloads + # note: using permutations to avoid testing cast to the same type + for sig in permutations(all_types, r=2): + try: + os.find(sig) + except NumbaNotImplementedError: + pass # ignore not implemented cast + + def test_ambiguous_functions(self): + loader = RegistryLoader(builtin_registry) + selectors = defaultdict(OverloadSelector) + for impl, fn, sig in loader.new_registrations('functions'): + os = selectors[fn] + os.append(impl, sig) + + for fn, os in selectors.items(): + all_types = set(t for sig, impl in os.versions for t in sig) + # ensure there are no ambiguous overloads + for sig in product(all_types, all_types): + try: + os.find(sig) + except NumbaNotImplementedError: + pass # ignore not implemented cast + + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_tuples.py b/lib/python3.10/site-packages/numba/tests/test_tuples.py new file mode 100644 index 0000000000000000000000000000000000000000..44145197f16185bea8c661eeabc5813d1685a360 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_tuples.py @@ -0,0 +1,764 @@ +import collections +import itertools + +import numpy as np + +from numba import njit, jit, typeof, literally +from numba.core import types, errors, utils +from numba.tests.support import TestCase, MemoryLeakMixin, tag +import unittest + + +Rect = collections.namedtuple('Rect', ('width', 'height')) + +Point = collections.namedtuple('Point', ('x', 'y', 'z')) + +Point2 = collections.namedtuple('Point2', ('x', 'y', 'z')) + +Empty = collections.namedtuple('Empty', ()) + +def tuple_return_usecase(a, b): + return a, b + +def tuple_first(tup): + a, b = tup + return a + +def tuple_second(tup): + a, b = tup + return b + +def tuple_index(tup, idx): + return tup[idx] + +def tuple_index_static(tup): + # Note the negative index + return tup[-2] + +def tuple_slice2(tup): + return tup[1:-1] + +def tuple_slice3(tup): + return tup[1::2] + +def len_usecase(tup): + return len(tup) + +def add_usecase(a, b): + return a + b + +def eq_usecase(a, b): + return a == b + +def ne_usecase(a, b): + return a != b + +def gt_usecase(a, b): + return a > b + +def ge_usecase(a, b): + return a >= b + +def lt_usecase(a, b): + return a < b + +def le_usecase(a, b): + return a <= b + +def in_usecase(a, b): + return a in b + +def bool_usecase(tup): + return bool(tup), (3 if tup else 2) + +def getattr_usecase(tup): + return tup.z, tup.y, tup.x + +def make_point(a, b, c): + return Point(a, b, c) + +def make_point_kws(a, b, c): + return Point(z=c, y=b, x=a) + +def make_point_nrt(n): + r = Rect(list(range(n)), np.zeros(n + 1)) + # This also exercises attribute access + p = Point(r, len(r.width), len(r.height)) + return p + +def type_usecase(tup, *args): + return type(tup)(*args) + +def identity(tup): + return tup + +def index_method_usecase(tup, value): + return tup.index(value) + +def tuple_unpack_static_getitem_err(): + # see issue3895, `c` is imprecise + a, b, c, d = [], [], [], 0.0 + a.append(1) + b.append(1) + return + + +class TestTupleLengthError(unittest.TestCase): + + def test_tuple_length_error(self): + # issue 2195 + # raise an error on tuples greater than 1000 in length + @njit + def eattuple(tup): + return len(tup) + + with self.assertRaises(errors.UnsupportedError) as raises: + tup = tuple(range(1001)) + eattuple(tup) + + expected = "Tuple 'tup' length must be smaller than 1000" + self.assertIn(expected, str(raises.exception)) + +class TestTupleTypeNotIterable(unittest.TestCase): + ''' + issue 4369 + raise an error if 'type' is not iterable + ''' + def test_namedtuple_types_exception(self): + with self.assertRaises(errors.TypingError) as raises: + types.NamedTuple(types.uint32, 'p') + self.assertIn( + "Argument 'types' is not iterable", + str(raises.exception) + ) + + def test_tuple_types_exception(self): + with self.assertRaises(errors.TypingError) as raises: + types.Tuple((types.uint32)) + self.assertIn( + "Argument 'types' is not iterable", + str(raises.exception) + ) + + +class TestTupleReturn(TestCase): + + def test_array_tuple(self): + aryty = types.Array(types.float64, 1, 'C') + cfunc = njit((aryty, aryty))(tuple_return_usecase) + a = b = np.arange(5, dtype='float64') + ra, rb = cfunc(a, b) + self.assertPreciseEqual(ra, a) + self.assertPreciseEqual(rb, b) + del a, b + self.assertPreciseEqual(ra, rb) + + def test_scalar_tuple(self): + scalarty = types.float32 + cfunc = njit((scalarty, scalarty))(tuple_return_usecase) + a = b = 1 + ra, rb = cfunc(a, b) + self.assertEqual(ra, a) + self.assertEqual(rb, b) + + def test_hetero_tuple(self): + alltypes = [] + allvalues = [] + + alltypes.append((types.int32, types.int64)) + allvalues.append((1, 2)) + + alltypes.append((types.float32, types.float64)) + allvalues.append((1.125, .25)) + + alltypes.append((types.int32, types.float64)) + allvalues.append((1231, .5)) + + for (ta, tb), (a, b) in zip(alltypes, allvalues): + cfunc = njit((ta, tb))(tuple_return_usecase) + ra, rb = cfunc(a, b) + self.assertPreciseEqual((ra, rb), (a, b)) + + +class TestTuplePassing(TestCase): + + def test_unituple(self): + tuple_type = types.UniTuple(types.int32, 2) + cf_first = njit((tuple_type,))(tuple_first) + cf_second = njit((tuple_type,))(tuple_second) + self.assertPreciseEqual(cf_first((4, 5)), 4) + self.assertPreciseEqual(cf_second((4, 5)), 5) + + def test_hetero_tuple(self): + tuple_type = types.Tuple((types.int64, types.float32)) + cf_first = njit((tuple_type,))(tuple_first) + cf_second = njit((tuple_type,))(tuple_second) + self.assertPreciseEqual(cf_first((2**61, 1.5)), 2**61) + self.assertPreciseEqual(cf_second((2**61, 1.5)), 1.5) + + def test_size_mismatch(self): + # Issue #1638: tuple size should be checked when unboxing + tuple_type = types.UniTuple(types.int32, 2) + cfunc = njit((tuple_type,))(tuple_first) + entry_point = cfunc.overloads[cfunc.signatures[0]].entry_point + with self.assertRaises(ValueError) as raises: + entry_point((4, 5, 6)) + self.assertEqual(str(raises.exception), + ("size mismatch for tuple, " + "expected 2 element(s) but got 3")) + + +class TestOperations(TestCase): + + def test_len(self): + pyfunc = len_usecase + cfunc = njit((types.Tuple((types.int64, types.float32)),))(pyfunc) + self.assertPreciseEqual(cfunc((4, 5)), 2) + cfunc = njit((types.UniTuple(types.int64, 3),))(pyfunc) + self.assertPreciseEqual(cfunc((4, 5, 6)), 3) + + def test_index_literal(self): + # issue #6023, test non-static getitem with IntegerLiteral index + def pyfunc(tup, idx): + idx = literally(idx) + return tup[idx] + cfunc = njit(pyfunc) + + tup = (4, 3.1, 'sss') + for i in range(len(tup)): + self.assertPreciseEqual(cfunc(tup, i), tup[i]) + + def test_index(self): + pyfunc = tuple_index + cfunc = njit((types.UniTuple(types.int64, 3), types.int64),)(pyfunc) + tup = (4, 3, 6) + for i in range(len(tup)): + self.assertPreciseEqual(cfunc(tup, i), tup[i]) + + # test negative indexing + for i in range(len(tup) + 1): + self.assertPreciseEqual(cfunc(tup, -i), tup[-i]) + + # oob indexes, +ve then -ve + with self.assertRaises(IndexError) as raises: + cfunc(tup, len(tup)) + self.assertEqual("tuple index out of range", str(raises.exception)) + with self.assertRaises(IndexError) as raises: + cfunc(tup, -(len(tup) + 1)) + self.assertEqual("tuple index out of range", str(raises.exception)) + + # Test empty tuple, this is a bit unusual as `njit` will infer the empty + # tuple arg as a types.Tuple and not match the compiled signature, this + # is essentially because the test originally relied on + # `compile_isolated`. + args = (types.UniTuple(types.int64, 0), types.int64,) + cr = njit(args)(pyfunc).overloads[args] + with self.assertRaises(IndexError) as raises: + cr.entry_point((), 0) + self.assertEqual("tuple index out of range", str(raises.exception)) + + # test uintp indexing (because, e.g., parfor generates unsigned prange) + cfunc = njit((types.UniTuple(types.int64, 3), types.uintp,),)(pyfunc) + for i in range(len(tup)): + self.assertPreciseEqual(cfunc(tup, types.uintp(i)), tup[i]) + + # With a compile-time static index (the code generation path is + # different) + pyfunc = tuple_index_static + for typ in (types.UniTuple(types.int64, 4), + types.Tuple((types.int64, types.int32, types.int64, types.int32))): + cfunc = njit((typ,))(pyfunc) + tup = (4, 3, 42, 6) + self.assertPreciseEqual(cfunc(tup), pyfunc(tup)) + + typ = types.UniTuple(types.int64, 1) + with self.assertTypingError(): + njit((typ,))(pyfunc) + + # test unpack, staticgetitem with imprecise type (issue #3895) + pyfunc = tuple_unpack_static_getitem_err + with self.assertTypingError() as raises: + njit((),)(pyfunc) + msg = ("Cannot infer the type of variable 'c', have imprecise type: " + "list(undefined).") + self.assertIn(msg, str(raises.exception)) + + def test_in(self): + pyfunc = in_usecase + cfunc = njit((types.int64, types.UniTuple(types.int64, 3),),)(pyfunc) + tup = (4, 1, 5) + for i in range(5): + self.assertPreciseEqual(cfunc(i, tup), pyfunc(i, tup)) + + # Test the empty case + cfunc = njit((types.int64, types.Tuple([]),),)(pyfunc) + self.assertPreciseEqual(cfunc(1, ()), pyfunc(1, ())) + + def check_slice(self, pyfunc): + tup = (4, 5, 6, 7) + cfunc = njit((types.UniTuple(types.int64, 4),),)(pyfunc) + self.assertPreciseEqual(cfunc(tup), pyfunc(tup)) + args = types.Tuple((types.int64, types.int32, types.int64, types.int32)) + cfunc = njit((args,))(pyfunc) + self.assertPreciseEqual(cfunc(tup), pyfunc(tup)) + + def test_slice2(self): + self.check_slice(tuple_slice2) + + def test_slice3(self): + self.check_slice(tuple_slice3) + + def test_bool(self): + pyfunc = bool_usecase + cfunc = njit((types.Tuple((types.int64, types.int32)),),)(pyfunc) + args = ((4, 5),) + self.assertPreciseEqual(cfunc(*args), pyfunc(*args)) + cfunc = njit((types.UniTuple(types.int64, 3),),)(pyfunc) + args = ((4, 5, 6),) + self.assertPreciseEqual(cfunc(*args), pyfunc(*args)) + cfunc = njit((types.Tuple(()),),)(pyfunc) + self.assertPreciseEqual(cfunc(()), pyfunc(())) + + def test_add(self): + pyfunc = add_usecase + samples = [(types.Tuple(()), ()), + (types.UniTuple(types.int32, 0), ()), + (types.UniTuple(types.int32, 1), (42,)), + (types.Tuple((types.int64, types.float32)), (3, 4.5)), + ] + for (ta, a), (tb, b) in itertools.product(samples, samples): + cfunc = njit((ta, tb),)(pyfunc) + expected = pyfunc(a, b) + got = cfunc(a, b) + self.assertPreciseEqual(got, expected, msg=(ta, tb)) + + def _test_compare(self, pyfunc): + def eq(pyfunc, cfunc, args): + self.assertIs(cfunc(*args), pyfunc(*args), + "mismatch for arguments %s" % (args,)) + + # Same-sized tuples + argtypes = [types.Tuple((types.int64, types.float32)), + types.UniTuple(types.int32, 2)] + for ta, tb in itertools.product(argtypes, argtypes): + cfunc = njit((ta, tb),)(pyfunc) + for args in [((4, 5), (4, 5)), + ((4, 5), (4, 6)), + ((4, 6), (4, 5)), + ((4, 5), (5, 4))]: + eq(pyfunc, cfunc, args) + # Different-sized tuples + argtypes = [types.Tuple((types.int64, types.float32)), + types.UniTuple(types.int32, 3)] + cfunc = njit(tuple(argtypes),)(pyfunc) + for args in [((4, 5), (4, 5, 6)), + ((4, 5), (4, 4, 6)), + ((4, 5), (4, 6, 7))]: + eq(pyfunc, cfunc, args) + + def test_eq(self): + self._test_compare(eq_usecase) + + def test_ne(self): + self._test_compare(ne_usecase) + + def test_gt(self): + self._test_compare(gt_usecase) + + def test_ge(self): + self._test_compare(ge_usecase) + + def test_lt(self): + self._test_compare(lt_usecase) + + def test_le(self): + self._test_compare(le_usecase) + + +class TestNamedTuple(TestCase, MemoryLeakMixin): + + def test_unpack(self): + def check(p): + for pyfunc in tuple_first, tuple_second: + cfunc = jit(nopython=True)(pyfunc) + self.assertPreciseEqual(cfunc(p), pyfunc(p)) + + # Homogeneous + check(Rect(4, 5)) + # Heterogeneous + check(Rect(4, 5.5)) + + def test_len(self): + def check(p): + pyfunc = len_usecase + cfunc = jit(nopython=True)(pyfunc) + self.assertPreciseEqual(cfunc(p), pyfunc(p)) + + # Homogeneous + check(Rect(4, 5)) + check(Point(4, 5, 6)) + # Heterogeneous + check(Rect(4, 5.5)) + check(Point(4, 5.5, 6j)) + + def test_index(self): + pyfunc = tuple_index + cfunc = jit(nopython=True)(pyfunc) + + p = Point(4, 5, 6) + for i in range(len(p)): + self.assertPreciseEqual(cfunc(p, i), pyfunc(p, i)) + + # test uintp indexing (because, e.g., parfor generates unsigned prange) + for i in range(len(p)): + self.assertPreciseEqual(cfunc(p, types.uintp(i)), pyfunc(p, i)) + + def test_bool(self): + def check(p): + pyfunc = bool_usecase + cfunc = jit(nopython=True)(pyfunc) + self.assertPreciseEqual(cfunc(p), pyfunc(p)) + + # Homogeneous + check(Rect(4, 5)) + # Heterogeneous + check(Rect(4, 5.5)) + check(Empty()) + + def _test_compare(self, pyfunc): + def eq(pyfunc, cfunc, args): + self.assertIs(cfunc(*args), pyfunc(*args), + "mismatch for arguments %s" % (args,)) + + cfunc = jit(nopython=True)(pyfunc) + + # Same-sized named tuples + for a, b in [((4, 5), (4, 5)), + ((4, 5), (4, 6)), + ((4, 6), (4, 5)), + ((4, 5), (5, 4))]: + eq(pyfunc, cfunc, (Rect(*a), Rect(*b))) + + # Different-sized named tuples + for a, b in [((4, 5), (4, 5, 6)), + ((4, 5), (4, 4, 6)), + ((4, 5), (4, 6, 7))]: + eq(pyfunc, cfunc, (Rect(*a), Point(*b))) + + def test_eq(self): + self._test_compare(eq_usecase) + + def test_ne(self): + self._test_compare(ne_usecase) + + def test_gt(self): + self._test_compare(gt_usecase) + + def test_ge(self): + self._test_compare(ge_usecase) + + def test_lt(self): + self._test_compare(lt_usecase) + + def test_le(self): + self._test_compare(le_usecase) + + def test_getattr(self): + pyfunc = getattr_usecase + cfunc = jit(nopython=True)(pyfunc) + + for args in (4, 5, 6), (4, 5.5, 6j): + p = Point(*args) + self.assertPreciseEqual(cfunc(p), pyfunc(p)) + + def test_construct(self): + def check(pyfunc): + cfunc = jit(nopython=True)(pyfunc) + for args in (4, 5, 6), (4, 5.5, 6j): + expected = pyfunc(*args) + got = cfunc(*args) + self.assertIs(type(got), type(expected)) + self.assertPreciseEqual(got, expected) + + check(make_point) + check(make_point_kws) + + def test_type(self): + # Test the type() built-in on named tuples + pyfunc = type_usecase + cfunc = jit(nopython=True)(pyfunc) + + arg_tuples = [(4, 5, 6), (4, 5.5, 6j)] + for tup_args, args in itertools.product(arg_tuples, arg_tuples): + tup = Point(*tup_args) + expected = pyfunc(tup, *args) + got = cfunc(tup, *args) + self.assertIs(type(got), type(expected)) + self.assertPreciseEqual(got, expected) + + def test_literal_unification(self): + # Test for #3565. + @jit(nopython=True) + def Data1(value): + return Rect(value, -321) + + @jit(nopython=True) + def call(i, j): + if j == 0: + # In the error, `result` is typed to `Rect(int, LiteralInt)` + # because of the `-321` literal. This doesn't match the + # `result` type in the other branch. + result = Data1(i) + else: + # `result` is typed to be `Rect(int, int)` + result = Rect(i, j) + return result + + r = call(123, 1321) + self.assertEqual(r, Rect(width=123, height=1321)) + r = call(123, 0) + self.assertEqual(r, Rect(width=123, height=-321)) + + def test_string_literal_in_ctor(self): + # Test for issue #3813 + + @jit(nopython=True) + def foo(): + return Rect(10, 'somestring') + + r = foo() + self.assertEqual(r, Rect(width=10, height='somestring')) + + def test_dispatcher_mistreat(self): + # Test for issue #5215 that mistreat namedtuple as tuples + @jit(nopython=True) + def foo(x): + return x + + in1 = (1, 2, 3) + out1 = foo(in1) + self.assertEqual(in1, out1) + + in2 = Point(1, 2, 3) + out2 = foo(in2) + self.assertEqual(in2, out2) + + # Check the signatures + self.assertEqual(len(foo.nopython_signatures), 2) + self.assertEqual(foo.nopython_signatures[0].args[0], typeof(in1)) + self.assertEqual(foo.nopython_signatures[1].args[0], typeof(in2)) + + # Differently named + in3 = Point2(1, 2, 3) + out3 = foo(in3) + self.assertEqual(in3, out3) + self.assertEqual(len(foo.nopython_signatures), 3) + self.assertEqual(foo.nopython_signatures[2].args[0], typeof(in3)) + + +class TestTupleNRT(TestCase, MemoryLeakMixin): + def test_tuple_add(self): + def pyfunc(x): + a = np.arange(3) + return (a,) + (x,) + + cfunc = jit(nopython=True)(pyfunc) + x = 123 + expect_a, expect_x = pyfunc(x) + got_a, got_x = cfunc(x) + np.testing.assert_equal(got_a, expect_a) + self.assertEqual(got_x, expect_x) + + +class TestNamedTupleNRT(TestCase, MemoryLeakMixin): + + def test_return(self): + # Check returning a namedtuple with a list inside it + pyfunc = make_point_nrt + cfunc = jit(nopython=True)(pyfunc) + + for arg in (3, 0): + expected = pyfunc(arg) + got = cfunc(arg) + self.assertIs(type(got), type(expected)) + self.assertPreciseEqual(got, expected) + + +class TestConversions(TestCase): + """ + Test implicit conversions between tuple types. + """ + + def check_conversion(self, fromty, toty, val): + pyfunc = identity + cfunc = njit(toty(fromty))(pyfunc) + res = cfunc(val) + self.assertEqual(res, val) + + def test_conversions(self): + check = self.check_conversion + fromty = types.UniTuple(types.int32, 2) + check(fromty, types.UniTuple(types.float32, 2), (4, 5)) + check(fromty, types.Tuple((types.float32, types.int16)), (4, 5)) + aty = types.UniTuple(types.int32, 0) + bty = types.Tuple(()) + check(aty, bty, ()) + check(bty, aty, ()) + + with self.assertRaises(errors.TypingError) as raises: + check(fromty, types.Tuple((types.float32,)), (4, 5)) + msg = "No conversion from UniTuple(int32 x 2) to UniTuple(float32 x 1)" + self.assertIn(msg, str(raises.exception)) + + +class TestMethods(TestCase): + + def test_index(self): + pyfunc = index_method_usecase + cfunc = jit(nopython=True)(pyfunc) + self.assertEqual(cfunc((1, 2, 3), 2), 1) + + with self.assertRaises(ValueError) as raises: + cfunc((1, 2, 3), 4) + msg = 'tuple.index(x): x not in tuple' + self.assertEqual(msg, str(raises.exception)) + + +class TestTupleBuild(TestCase): + + def test_build_unpack(self): + def check(p): + pyfunc = lambda a: (1, *a) + cfunc = jit(nopython=True)(pyfunc) + self.assertPreciseEqual(cfunc(p), pyfunc(p)) + + # Homogeneous + check((4, 5)) + # Heterogeneous + check((4, 5.5)) + + def test_build_unpack_assign_like(self): + # see #6534 + def check(p): + pyfunc = lambda a: (*a,) + cfunc = jit(nopython=True)(pyfunc) + self.assertPreciseEqual(cfunc(p), pyfunc(p)) + + # Homogeneous + check((4, 5)) + # Heterogeneous + check((4, 5.5)) + + def test_build_unpack_fail_on_list_assign_like(self): + # see #6534 + def check(p): + pyfunc = lambda a: (*a,) + cfunc = jit(nopython=True)(pyfunc) + self.assertPreciseEqual(cfunc(p), pyfunc(p)) + + with self.assertRaises(errors.TypingError) as raises: + check([4, 5]) + + # Python 3.9 has a peephole rewrite due to large changes in tuple + # unpacking. It results in a tuple + list situation from the above + # so the error message reflects that. Catching this specific and + # seemingly rare sequence in the peephole rewrite is prohibitively + # hard. Should it be reported numerous times, revisit then. + msg1 = "No implementation of function" + self.assertIn(msg1, str(raises.exception)) + msg2 = "tuple(reflected list(" # ignore the rest of reflected list + # part, it's repr is quite volatile. + self.assertIn(msg2, str(raises.exception)) + + def test_build_unpack_more(self): + def check(p): + pyfunc = lambda a: (1, *a, (1, 2), *a) + cfunc = jit(nopython=True)(pyfunc) + self.assertPreciseEqual(cfunc(p), pyfunc(p)) + + # Homogeneous + check((4, 5)) + # Heterogeneous + check((4, 5.5)) + + def test_build_unpack_call(self): + def check(p): + @jit + def inner(*args): + return args + pyfunc = lambda a: inner(1, *a) + cfunc = jit(nopython=True)(pyfunc) + self.assertPreciseEqual(cfunc(p), pyfunc(p)) + + # Homogeneous + check((4, 5)) + # Heterogeneous + check((4, 5.5)) + + def test_build_unpack_call_more(self): + def check(p): + @jit + def inner(*args): + return args + pyfunc = lambda a: inner(1, *a, *(1, 2), *a) + cfunc = jit(nopython=True)(pyfunc) + self.assertPreciseEqual(cfunc(p), pyfunc(p)) + + # Homogeneous + check((4, 5)) + # Heterogeneous + check((4, 5.5)) + + def test_tuple_constructor(self): + def check(pyfunc, arg): + cfunc = jit(nopython=True)(pyfunc) + self.assertPreciseEqual(cfunc(arg), pyfunc(arg)) + + # empty + check(lambda _: tuple(), ()) + # Homogeneous + check(lambda a: tuple(a), (4, 5)) + # Heterogeneous + check(lambda a: tuple(a), (4, 5.5)) + + def test_unpack_with_predicate_fails(self): + # this fails as the list_to_tuple/list_extend peephole bytecode + # rewriting needed for Python 3.9+ cannot yet traverse the CFG. + @njit + def foo(): + a = (1,) + b = (3,2, 4) + return (*(b if a[0] else (5, 6)),) + + with self.assertRaises(errors.UnsupportedBytecodeError) as raises: + foo() + msg = "op_LIST_EXTEND at the start of a block" + self.assertIn(msg, str(raises.exception)) + + def test_build_unpack_with_calls_in_unpack(self): + def check(p): + def pyfunc(a): + z = [1, 2] + return (*a, z.append(3), z.extend(a), np.ones(3)), z + + cfunc = jit(nopython=True)(pyfunc) + self.assertPreciseEqual(cfunc(p), pyfunc(p)) + + check((4, 5)) + + def test_build_unpack_complicated(self): + def check(p): + def pyfunc(a): + z = [1, 2] + return (*a, *(*a, a), *(a, (*(a, (1, 2), *(3,), *a), + (a, 1, (2, 3), *a, 1), (1,))), + *(z.append(4), z.extend(a))), z + + cfunc = jit(nopython=True)(pyfunc) + self.assertPreciseEqual(cfunc(p), pyfunc(p)) + + check((10, 20)) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_typedlist.py b/lib/python3.10/site-packages/numba/tests/test_typedlist.py new file mode 100644 index 0000000000000000000000000000000000000000..79098980158c59ae4930d8b7b885ee04c74aa2d6 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_typedlist.py @@ -0,0 +1,1689 @@ +import sys +import subprocess +from itertools import product +from textwrap import dedent + +import numpy as np + +from numba import config +from numba import njit +from numba import int32, float32, prange, uint8 +from numba.core import types +from numba import typeof +from numba.typed import List, Dict +from numba.core.errors import TypingError +from numba.tests.support import (TestCase, MemoryLeakMixin, override_config, + forbid_codegen, skip_parfors_unsupported) +from numba.core.unsafe.refcount import get_refcount +from numba.experimental import jitclass + + +def to_tl(l): + """ Convert cpython list to typed-list. """ + tl = List.empty_list(int32) + for k in l: + tl.append(k) + return tl + + +class TestTypedList(MemoryLeakMixin, TestCase): + + def test_basic(self): + l = List.empty_list(int32) + # len + self.assertEqual(len(l), 0) + # append + l.append(0) + # len + self.assertEqual(len(l), 1) + # setitem + l.append(0) + l.append(0) + l[0] = 10 + l[1] = 11 + l[2] = 12 + # getitem + self.assertEqual(l[0], 10) + self.assertEqual(l[1], 11) + self.assertEqual(l[2], 12) + self.assertEqual(l[-3], 10) + self.assertEqual(l[-2], 11) + self.assertEqual(l[-1], 12) + # __iter__ + # the default __iter__ from MutableSequence will raise an IndexError + # via __getitem__ and thus leak an exception, so this shouldn't + for i in l: + pass + # contains + self.assertTrue(10 in l) + self.assertFalse(0 in l) + # count + l.append(12) + self.assertEqual(l.count(0), 0) + self.assertEqual(l.count(10), 1) + self.assertEqual(l.count(12), 2) + # pop + self.assertEqual(len(l), 4) + self.assertEqual(l.pop(), 12) + self.assertEqual(len(l), 3) + self.assertEqual(l.pop(1), 11) + self.assertEqual(len(l), 2) + # extend + l.extend((100, 200, 300)) + self.assertEqual(len(l), 5) + self.assertEqual(list(l), [10, 12, 100, 200, 300]) + # insert + l.insert(0, 0) + self.assertEqual(list(l), [0, 10, 12, 100, 200, 300]) + l.insert(3, 13) + self.assertEqual(list(l), [0, 10, 12, 13, 100, 200, 300]) + l.insert(100, 400) + self.assertEqual(list(l), [0, 10, 12, 13, 100, 200, 300, 400]) + # remove + l.remove(0) + l.remove(400) + l.remove(13) + self.assertEqual(list(l), [10, 12, 100, 200, 300]) + # clear + l.clear() + self.assertEqual(len(l), 0) + self.assertEqual(list(l), []) + # reverse + l.extend(tuple(range(10, 20))) + l.reverse() + self.assertEqual(list(l), list(range(10, 20))[::-1]) + # copy + new = l.copy() + self.assertEqual(list(new), list(range(10, 20))[::-1]) + # equal + self.assertEqual(l, new) + # not equal + new[-1] = 42 + self.assertNotEqual(l, new) + # index + self.assertEqual(l.index(15), 4) + + def test_list_extend_refines_on_unicode_type(self): + @njit + def foo(string): + l = List() + l.extend(string) + return l + + for func in (foo, foo.py_func): + for string in ("a", "abc", "\nabc\t"): + self.assertEqual(list(func(string)), list(string)) + + def test_unsigned_access(self): + L = List.empty_list(int32) + ui32_0 = types.uint32(0) + ui32_1 = types.uint32(1) + ui32_2 = types.uint32(2) + + # insert + L.append(types.uint32(10)) + L.append(types.uint32(11)) + L.append(types.uint32(12)) + self.assertEqual(len(L), 3) + + # getitem + self.assertEqual(L[ui32_0], 10) + self.assertEqual(L[ui32_1], 11) + self.assertEqual(L[ui32_2], 12) + + # setitem + L[ui32_0] = 123 + L[ui32_1] = 456 + L[ui32_2] = 789 + self.assertEqual(L[ui32_0], 123) + self.assertEqual(L[ui32_1], 456) + self.assertEqual(L[ui32_2], 789) + + # index + ui32_123 = types.uint32(123) + ui32_456 = types.uint32(456) + ui32_789 = types.uint32(789) + self.assertEqual(L.index(ui32_123), 0) + self.assertEqual(L.index(ui32_456), 1) + self.assertEqual(L.index(ui32_789), 2) + + # delitem + L.__delitem__(ui32_2) + del L[ui32_1] + self.assertEqual(len(L), 1) + self.assertEqual(L[ui32_0], 123) + + # pop + L.append(2) + L.append(3) + L.append(4) + self.assertEqual(len(L), 4) + self.assertEqual(L.pop(), 4) + self.assertEqual(L.pop(ui32_2), 3) + self.assertEqual(L.pop(ui32_1), 2) + self.assertEqual(L.pop(ui32_0), 123) + + def test_dtype(self): + + L = List.empty_list(int32) + self.assertEqual(L._dtype, int32) + + L = List.empty_list(float32) + self.assertEqual(L._dtype, float32) + + @njit + def foo(): + li, lf = List(), List() + li.append(int32(1)) + lf.append(float32(1.0)) + return li._dtype, lf._dtype + + self.assertEqual(foo(), (np.dtype('int32'), np.dtype('float32'))) + self.assertEqual(foo.py_func(), (int32, float32)) + + def test_dtype_raises_exception_on_untyped_list(self): + + with self.assertRaises(RuntimeError) as raises: + L = List() + L._dtype + self.assertIn( + "invalid operation on untyped list", + str(raises.exception), + ) + + @skip_parfors_unsupported + def test_unsigned_prange(self): + @njit(parallel=True) + def foo(a): + r = types.uint64(3) + s = types.uint64(0) + for i in prange(r): + s = s + a[i] + return s + + a = List.empty_list(types.uint64) + a.append(types.uint64(12)) + a.append(types.uint64(1)) + a.append(types.uint64(7)) + self.assertEqual(foo(a), 20) + + def test_compiled(self): + @njit + def producer(): + l = List.empty_list(int32) + l.append(23) + return l + + @njit + def consumer(l): + return l[0] + + l = producer() + val = consumer(l) + self.assertEqual(val, 23) + + def test_getitem_slice(self): + """ Test getitem using a slice. + + This tests suffers from combinatorial explosion, so we parametrize it + and compare results against the regular list in a quasi fuzzing + approach. + + """ + # initialize regular list + rl = list(range(10, 20)) + # initialize typed list + tl = List.empty_list(int32) + for i in range(10, 20): + tl.append(i) + # define the ranges + start_range = list(range(-20, 30)) + stop_range = list(range(-20, 30)) + step_range = [-5, -4, -3, -2, -1, 1, 2, 3, 4, 5] + + # check that they are the same initially + self.assertEqual(rl, list(tl)) + # check that copy by slice works, no start, no stop, no step + self.assertEqual(rl[:], list(tl[:])) + + # start only + for sa in start_range: + self.assertEqual(rl[sa:], list(tl[sa:])) + # stop only + for so in stop_range: + self.assertEqual(rl[:so], list(tl[:so])) + # step only + for se in step_range: + self.assertEqual(rl[::se], list(tl[::se])) + + # start and stop + for sa, so in product(start_range, stop_range): + self.assertEqual(rl[sa:so], list(tl[sa:so])) + # start and step + for sa, se in product(start_range, step_range): + self.assertEqual(rl[sa::se], list(tl[sa::se])) + # stop and step + for so, se in product(stop_range, step_range): + self.assertEqual(rl[:so:se], list(tl[:so:se])) + + # start, stop and step + for sa, so, se in product(start_range, stop_range, step_range): + self.assertEqual(rl[sa:so:se], list(tl[sa:so:se])) + + def test_setitem_slice(self): + """ Test setitem using a slice. + + This tests suffers from combinatorial explosion, so we parametrize it + and compare results against the regular list in a quasi fuzzing + approach. + + """ + + def setup(start=10, stop=20): + # initialize regular list + rl_ = list(range(start, stop)) + # initialize typed list + tl_ = List.empty_list(int32) + # populate typed list + for i in range(start, stop): + tl_.append(i) + # check they are the same + self.assertEqual(rl_, list(tl_)) + return rl_, tl_ + + ### Simple slicing ### + + # assign to itself + rl, tl = setup() + rl[:], tl[:] = rl, tl + self.assertEqual(rl, list(tl)) + + # extend self + rl, tl = setup() + rl[len(rl):], tl[len(tl):] = rl, tl + self.assertEqual(rl, list(tl)) + # prepend self + rl, tl = setup() + rl[:0], tl[:0] = rl, tl + self.assertEqual(rl, list(tl)) + # partial assign to self, with equal length + rl, tl = setup() + rl[3:5], tl[3:5] = rl[6:8], tl[6:8] + self.assertEqual(rl, list(tl)) + # partial assign to self, with larger slice + rl, tl = setup() + rl[3:5], tl[3:5] = rl[6:9], tl[6:9] + self.assertEqual(rl, list(tl)) + # partial assign to self, with smaller slice + rl, tl = setup() + rl[3:5], tl[3:5] = rl[6:7], tl[6:7] + self.assertEqual(rl, list(tl)) + + # extend + rl, tl = setup() + rl[len(rl):] = list(range(110, 120)) + tl[len(tl):] = to_tl(range(110,120)) + self.assertEqual(rl, list(tl)) + # extend empty + rl, tl = setup(0, 0) + rl[len(rl):] = list(range(110, 120)) + tl[len(tl):] = to_tl(range(110,120)) + self.assertEqual(rl, list(tl)) + # extend singleton + rl, tl = setup(0, 1) + rl[len(rl):] = list(range(110, 120)) + tl[len(tl):] = to_tl(range(110,120)) + self.assertEqual(rl, list(tl)) + + # prepend + rl, tl = setup() + rl[:0], tl[:0] = list(range(110, 120)), to_tl(range(110,120)) + self.assertEqual(rl, list(tl)) + # prepend empty + rl, tl = setup(0,0) + rl[:0], tl[:0] = list(range(110, 120)), to_tl(range(110,120)) + self.assertEqual(rl, list(tl)) + # prepend singleton + rl, tl = setup(0,1) + rl[:0], tl[:0] = list(range(110, 120)), to_tl(range(110,120)) + self.assertEqual(rl, list(tl)) + + # simple equal length assignment, just replace + rl, tl = setup() + rl[1:3], tl[1:3] = [100, 200], to_tl([100, 200]) + self.assertEqual(rl, list(tl)) + + # slice for assignment is larger, need to replace and insert + rl, tl = setup() + rl[1:3], tl[1:3] = [100, 200, 300, 400], to_tl([100, 200, 300, 400]) + self.assertEqual(rl, list(tl)) + + # slice for assignment is smaller, need to replace and delete + rl, tl = setup() + rl[1:3], tl[1:3] = [100], to_tl([100]) + self.assertEqual(rl, list(tl)) + + # slice for assignment is smaller and item is empty, need to delete + rl, tl = setup() + rl[1:3], tl[1:3] = [], to_tl([]) + self.assertEqual(rl, list(tl)) + + # Synonym for clear + rl, tl = setup() + rl[:], tl[:] = [], to_tl([]) + self.assertEqual(rl, list(tl)) + + ### Extended slicing ### + + # replace every second element + rl, tl = setup() + rl[::2], tl[::2] = [100,200,300,400,500], to_tl([100,200,300,400,500]) + self.assertEqual(rl, list(tl)) + # replace every second element, backwards + rl, tl = setup() + rl[::-2], tl[::-2] = [100,200,300,400,500], to_tl([100,200,300,400,500]) + self.assertEqual(rl, list(tl)) + + # reverse assign to itself + rl, tl = setup() + rl[::-1], tl[::-1] = rl, tl + self.assertEqual(rl, list(tl)) + + def test_setitem_slice_value_error(self): + self.disable_leak_check() + + tl = List.empty_list(int32) + for i in range(10,20): + tl.append(i) + + assignment = List.empty_list(int32) + for i in range(1, 4): + assignment.append(i) + + with self.assertRaises(ValueError) as raises: + tl[8:3:-1] = assignment + self.assertIn( + "length mismatch for extended slice and sequence", + str(raises.exception), + ) + + def test_delitem_slice(self): + """ Test delitem using a slice. + + This tests suffers from combinatorial explosion, so we parametrize it + and compare results against the regular list in a quasi fuzzing + approach. + + """ + + def setup(start=10, stop=20): + # initialize regular list + rl_ = list(range(start, stop)) + # initialize typed list + tl_ = List.empty_list(int32) + # populate typed list + for i in range(start, stop): + tl_.append(i) + # check they are the same + self.assertEqual(rl_, list(tl_)) + return rl_, tl_ + + # define the ranges + start_range = list(range(-20, 30)) + stop_range = list(range(-20, 30)) + step_range = [-5, -4, -3, -2, -1, 1, 2, 3, 4, 5] + + rl, tl = setup() + # check that they are the same initially + self.assertEqual(rl, list(tl)) + # check that deletion of the whole list by slice works + del rl[:] + del tl[:] + self.assertEqual(rl, list(tl)) + + # start only + for sa in start_range: + rl, tl = setup() + del rl[sa:] + del tl[sa:] + self.assertEqual(rl, list(tl)) + # stop only + for so in stop_range: + rl, tl = setup() + del rl[:so] + del tl[:so] + self.assertEqual(rl, list(tl)) + # step only + for se in step_range: + rl, tl = setup() + del rl[::se] + del tl[::se] + self.assertEqual(rl, list(tl)) + + # start and stop + for sa, so in product(start_range, stop_range): + rl, tl = setup() + del rl[sa:so] + del tl[sa:so] + self.assertEqual(rl, list(tl)) + # start and step + for sa, se in product(start_range, step_range): + rl, tl = setup() + del rl[sa::se] + del tl[sa::se] + self.assertEqual(rl, list(tl)) + # stop and step + for so, se in product(stop_range, step_range): + rl, tl = setup() + del rl[:so:se] + del tl[:so:se] + self.assertEqual(rl, list(tl)) + + # start, stop and step + for sa, so, se in product(start_range, stop_range, step_range): + rl, tl = setup() + del rl[sa:so:se] + del tl[sa:so:se] + self.assertEqual(rl, list(tl)) + + def test_list_create_no_jit_using_empty_list(self): + with override_config('DISABLE_JIT', True): + with forbid_codegen(): + l = List.empty_list(types.int32) + self.assertEqual(type(l), list) + + def test_list_create_no_jit_using_List(self): + with override_config('DISABLE_JIT', True): + with forbid_codegen(): + l = List() + self.assertEqual(type(l), list) + + def test_catch_global_typed_list(self): + from numba.tests.typedlist_usecases import catch_global + + expected_message = ("The use of a ListType[int32] type, assigned to " + "variable 'global_typed_list' in globals, is not " + "supported as globals are considered compile-time " + "constants and there is no known way to compile " + "a ListType[int32] type as a constant.") + with self.assertRaises(TypingError) as raises: + njit(catch_global)() + self.assertIn( + expected_message, + str(raises.exception), + ) + self.disable_leak_check() + + def test_repr(self): + l = List() + expected = "ListType[Undefined]([])" + self.assertEqual(expected, repr(l)) + + l = List([int32(i) for i in (1, 2, 3)]) + expected = "ListType[int32]([1, 2, 3])" + self.assertEqual(expected, repr(l)) + + def test_repr_long_list(self): + l = List(range(1005)) + expected = f"{typeof(l)}([{', '.join(map(str, l))}])" + self.assertEqual(expected, repr(l)) + + def test_repr_long_list_ipython(self): + + # Test repr of long typed Lists in an IPython session + args = ["-m", "IPython", "--quiet", "--quick", "--no-banner", + "--colors=NoColor", "-c"] + base_cmd = [sys.executable] + args + try: + subprocess.check_output(base_cmd + ["--version"]) + except subprocess.CalledProcessError as e: + self.skipTest("ipython not found: return code %d" % e.returncode) + + def run_repr_cmd(repr_cmd_str): + cmd = base_cmd + [repr_cmd_str] + p = subprocess.Popen( + cmd, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + universal_newlines=True, + ) + out, err = p.communicate() + return err + + l = List(range(1000)) + expected = f"{typeof(l)}([{', '.join(map(str, l))}])" + actual = run_repr_cmd(" ".join( + [ + "import sys;", + "from numba.typed import List;", + "res = repr(List(range(1000)));", + "sys.stderr.write(res);" + ] + )) + self.assertEqual(expected, actual) + + l = List(range(1005)) + # Assert that the long list is truncated + expected = f"{typeof(l)}([{', '.join(map(str, l[:1000]))}, ...])" + actual = run_repr_cmd(" ".join( + [ + "import sys;", + "from numba.typed import List;", + "res = repr(List(range(1005)));", + "sys.stderr.write(res);" + ] + )) + self.assertEqual(expected, actual) + + def test_iter_mutates_self(self): + self.disable_leak_check() + + @njit + def foo(x): + count = 0 + for i in x: + if count > 1: + x.append(2.) + count += 1 + + l = List() + l.append(1.) + l.append(1.) + l.append(1.) + with self.assertRaises(RuntimeError) as raises: + foo(l) + + msg = "list was mutated during iteration" + self.assertIn(msg, str(raises.exception)) + + +class TestNoneType(MemoryLeakMixin, TestCase): + + def test_append_none(self): + @njit + def impl(): + l = List() + l.append(None) + return l + + self.assertEqual(impl.py_func(), impl()) + + def test_len_none(self): + @njit + def impl(): + l = List() + l.append(None) + return len(l) + + self.assertEqual(impl.py_func(), impl()) + + def test_getitem_none(self): + @njit + def impl(): + l = List() + l.append(None) + return l[0] + + self.assertEqual(impl.py_func(), impl()) + + def test_setitem_none(self): + @njit + def impl(): + l = List() + l.append(None) + l[0] = None + return l + + self.assertEqual(impl.py_func(), impl()) + + def test_equals_none(self): + @njit + def impl(): + l = List() + l.append(None) + m = List() + m.append(None) + return l == m, l != m, l < m, l <= m, l > m, l >= m + + self.assertEqual(impl.py_func(), impl()) + + def test_not_equals_none(self): + @njit + def impl(): + l = List() + l.append(None) + m = List() + m.append(1) + return l == m, l != m, l < m, l <= m, l > m, l >= m + + self.assertEqual(impl.py_func(), impl()) + + def test_iter_none(self): + @njit + def impl(): + l = List() + l.append(None) + l.append(None) + l.append(None) + count = 0 + for i in l: + count += 1 + return count + + self.assertEqual(impl.py_func(), impl()) + + def test_none_typed_method_fails(self): + """ Test that unsupported operations on List[None] raise. """ + def generate_function(line1, line2): + context = {} + exec(dedent(""" + from numba.typed import List + def bar(): + lst = List() + {} + {} + """.format(line1, line2)), context) + return njit(context["bar"]) + for line1, line2 in ( + ("lst.append(None)", "lst.pop()"), + ("lst.append(None)", "del lst[0]"), + ("lst.append(None)", "lst.count(None)"), + ("lst.append(None)", "lst.index(None)"), + ("lst.append(None)", "lst.insert(0, None)"), + ("" , "lst.insert(0, None)"), + ("lst.append(None)", "lst.clear()"), + ("lst.append(None)", "lst.copy()"), + ("lst.append(None)", "lst.extend([None])"), + ("", "lst.extend([None])"), + ("lst.append(None)", "lst.remove(None)"), + ("lst.append(None)", "lst.reverse()"), + ("lst.append(None)", "None in lst"), + ): + with self.assertRaises(TypingError) as raises: + foo = generate_function(line1, line2) + foo() + self.assertIn( + "method support for List[None] is limited", + str(raises.exception), + ) + + +class TestAllocation(MemoryLeakMixin, TestCase): + + def test_allocation(self): + # kwarg version + for i in range(16): + tl = List.empty_list(types.int32, allocated=i) + self.assertEqual(tl._allocated(), i) + + # posarg version + for i in range(16): + tl = List.empty_list(types.int32, i) + self.assertEqual(tl._allocated(), i) + + def test_allocation_njit(self): + # kwarg version + @njit + def foo(i): + tl = List.empty_list(types.int32, allocated=i) + return tl._allocated() + + for j in range(16): + self.assertEqual(foo(j), j) + + # posarg version + @njit + def foo(i): + tl = List.empty_list(types.int32, i) + return tl._allocated() + + for j in range(16): + self.assertEqual(foo(j), j) + + def test_growth_and_shrinkage(self): + tl = List.empty_list(types.int32) + growth_before = {0: 0, 4:4, 8:8, 16:16} + growth_after = {0: 4, 4:8, 8:16, 16:25} + for i in range(17): + if i in growth_before: + self.assertEqual(growth_before[i], tl._allocated()) + tl.append(i) + if i in growth_after: + self.assertEqual(growth_after[i], tl._allocated()) + + shrink_before = {17: 25, 12:25, 9:18, 6:12, 4:8, 3:6, 2:5, 1:4} + shrink_after = {17: 25, 12:18, 9:12, 6:8, 4:6, 3:5, 2:4, 1:0} + for i in range(17, 0, -1): + if i in shrink_before: + self.assertEqual(shrink_before[i], tl._allocated()) + tl.pop() + if i in shrink_after: + self.assertEqual(shrink_after[i], tl._allocated()) + + +class TestExtend(MemoryLeakMixin, TestCase): + + def test_extend_other(self): + @njit + def impl(other): + l = List.empty_list(types.int32) + for x in range(10): + l.append(x) + l.extend(other) + return l + + other = List.empty_list(types.int32) + for x in range(10): + other.append(x) + + expected = impl.py_func(other) + got = impl(other) + self.assertEqual(expected, got) + + def test_extend_self(self): + @njit + def impl(): + l = List.empty_list(types.int32) + for x in range(10): + l.append(x) + l.extend(l) + return l + + expected = impl.py_func() + got = impl() + self.assertEqual(expected, got) + + def test_extend_tuple(self): + @njit + def impl(): + l = List.empty_list(types.int32) + for x in range(10): + l.append(x) + l.extend((100,200,300)) + return l + + expected = impl.py_func() + got = impl() + self.assertEqual(expected, got) + + def test_extend_single_value_container(self): + @njit + def impl(): + l = List() + l.extend((100,)) + return l + + expected = impl.py_func() + got = impl() + self.assertEqual(expected, got) + + def test_extend_empty_unrefined(self): + # Extending an unrefined list with an empty iterable doesn't work in a + # jit compiled function as the list remains untyped. + l = List() + ret = l.extend(tuple()) + self.assertIsNone(ret) + self.assertEqual(len(l), 0) + self.assertFalse(l._typed) + + def test_extend_empty_refiend(self): + # Extending a refined list with an empty iterable doesn't work in a + # jit compiled function as the (empty) argument can't be typed + l = List((1,)) + l.extend(tuple()) + self.assertEqual(len(l), 1) + self.assertTrue(l._typed) + + +@njit +def cmp(a, b): + return a < b, a <= b, a == b, a != b, a >= b, a > b + + +class TestComparisons(MemoryLeakMixin, TestCase): + + def _cmp_dance(self, expected, pa, pb, na, nb): + # interpreter with regular list + self.assertEqual(cmp.py_func(pa, pb), expected) + + # interpreter with typed-list + py_got = cmp.py_func(na, nb) + self.assertEqual(py_got, expected) + + # compiled with typed-list + jit_got = cmp(na, nb) + self.assertEqual(jit_got, expected) + + def test_empty_vs_empty(self): + pa, pb = [], [] + na, nb = to_tl(pa), to_tl(pb) + expected = False, True, True, False, True, False + self._cmp_dance(expected, pa, pb, na, nb) + + def test_empty_vs_singleton(self): + pa, pb = [], [0] + na, nb = to_tl(pa), to_tl(pb) + expected = True, True, False, True, False, False + self._cmp_dance(expected, pa, pb, na, nb) + + def test_singleton_vs_empty(self): + pa, pb = [0], [] + na, nb = to_tl(pa), to_tl(pb) + expected = False, False, False, True, True, True + self._cmp_dance(expected, pa, pb, na, nb) + + def test_singleton_vs_singleton_equal(self): + pa, pb = [0], [0] + na, nb = to_tl(pa), to_tl(pb) + expected = False, True, True, False, True, False + self._cmp_dance(expected, pa, pb, na, nb) + + def test_singleton_vs_singleton_less_than(self): + pa, pb = [0], [1] + na, nb = to_tl(pa), to_tl(pb) + expected = True, True, False, True, False, False + self._cmp_dance(expected, pa, pb, na, nb) + + def test_singleton_vs_singleton_greater_than(self): + pa, pb = [1], [0] + na, nb = to_tl(pa), to_tl(pb) + expected = False, False, False, True, True, True + self._cmp_dance(expected, pa, pb, na, nb) + + def test_equal(self): + pa, pb = [1, 2, 3], [1, 2, 3] + na, nb = to_tl(pa), to_tl(pb) + expected = False, True, True, False, True, False + self._cmp_dance(expected, pa, pb, na, nb) + + def test_first_shorter(self): + pa, pb = [1, 2], [1, 2, 3] + na, nb = to_tl(pa), to_tl(pb) + expected = True, True, False, True, False, False + self._cmp_dance(expected, pa, pb, na, nb) + + def test_second_shorter(self): + pa, pb = [1, 2, 3], [1, 2] + na, nb = to_tl(pa), to_tl(pb) + expected = False, False, False, True, True, True + self._cmp_dance(expected, pa, pb, na, nb) + + def test_first_less_than(self): + pa, pb = [1, 2, 2], [1, 2, 3] + na, nb = to_tl(pa), to_tl(pb) + expected = True, True, False, True, False, False + self._cmp_dance(expected, pa, pb, na, nb) + + def test_first_greater_than(self): + pa, pb = [1, 2, 3], [1, 2, 2] + na, nb = to_tl(pa), to_tl(pb) + expected = False, False, False, True, True, True + self._cmp_dance(expected, pa, pb, na, nb) + + def test_equals_non_list(self): + l = to_tl([1, 2, 3]) + self.assertFalse(any(cmp.py_func(l, 1))) + self.assertFalse(any(cmp(l, 1))) + + +class TestListInferred(TestCase): + + def test_simple_refine_append(self): + @njit + def foo(): + l = List() + l.append(1) + return l + + expected = foo.py_func() + got = foo() + self.assertEqual(expected, got) + self.assertEqual(list(got), [1]) + self.assertEqual(typeof(got).item_type, typeof(1)) + + def test_simple_refine_insert(self): + @njit + def foo(): + l = List() + l.insert(0, 1) + return l + + expected = foo.py_func() + got = foo() + self.assertEqual(expected, got) + self.assertEqual(list(got), [1]) + self.assertEqual(typeof(got).item_type, typeof(1)) + + def test_refine_extend_list(self): + @njit + def foo(): + a = List() + b = List() + for i in range(3): + b.append(i) + a.extend(b) + return a + + expected = foo.py_func() + got = foo() + self.assertEqual(expected, got) + self.assertEqual(list(got), [0, 1, 2]) + self.assertEqual(typeof(got).item_type, typeof(1)) + + def test_refine_extend_set(self): + @njit + def foo(): + l = List() + l.extend((0, 1, 2)) + return l + + expected = foo.py_func() + got = foo() + self.assertEqual(expected, got) + self.assertEqual(list(got), [0, 1, 2]) + self.assertEqual(typeof(got).item_type, typeof(1)) + + def test_refine_list_extend_iter(self): + @njit + def foo(): + l = List() + d = Dict() + d[0] = 0 + # d.keys() provides a DictKeysIterableType + l.extend(d.keys()) + return l + + got = foo() + self.assertEqual(0, got[0]) + + +class TestListRefctTypes(MemoryLeakMixin, TestCase): + + def test_str_item(self): + @njit + def foo(): + l = List.empty_list(types.unicode_type) + for s in ("a", "ab", "abc", "abcd"): + l.append(s) + return l + + l = foo() + expected = ["a", "ab", "abc", "abcd"] + for i, s in enumerate(expected): + self.assertEqual(l[i], s) + self.assertEqual(list(l), expected) + # Test insert replacement + l[3] = 'uxyz' + self.assertEqual(l[3], 'uxyz') + # Test list growth + nelem = 100 + for i in range(4, nelem): + l.append(str(i)) + self.assertEqual(l[i], str(i)) + + def test_str_item_refcount_replace(self): + @njit + def foo(): + # use some tricks to make ref-counted unicode + i, j = 'ab', 'c' + a = i + j + m, n = 'zy', 'x' + z = m + n + l = List.empty_list(types.unicode_type) + l.append(a) + # This *should* dec' a and inc' z thus tests that items that are + # replaced are also dec'ed. + l[0] = z + ra, rz = get_refcount(a), get_refcount(z) + return l, ra, rz + + l, ra, rz = foo() + self.assertEqual(l[0], "zyx") + self.assertEqual(ra, 1) + self.assertEqual(rz, 2) + + def test_dict_as_item_in_list(self): + @njit + def foo(): + l = List.empty_list(Dict.empty(int32, int32)) + d = Dict.empty(int32, int32) + d[0] = 1 + # This increments the refcount for d + l.append(d) + return get_refcount(d) + + c = foo() + if config.LLVM_REFPRUNE_PASS: + # Because the pruner cleared all other increfs + self.assertEqual(1, c) + else: + self.assertEqual(2, c) + + def test_dict_as_item_in_list_multi_refcount(self): + @njit + def foo(): + l = List.empty_list(Dict.empty(int32, int32)) + d = Dict.empty(int32, int32) + d[0] = 1 + # This increments the refcount for d, twice + l.append(d) + l.append(d) + return get_refcount(d) + + c = foo() + if config.LLVM_REFPRUNE_PASS: + # Because the pruner cleared all other increfs + self.assertEqual(1, c) + else: + self.assertEqual(3, c) + + def test_list_as_value_in_dict(self): + @njit + def foo(): + d = Dict.empty(int32, List.empty_list(int32)) + l = List.empty_list(int32) + l.append(0) + # This increments the refcount for l + d[0] = l + return get_refcount(l) + + c = foo() + if config.LLVM_REFPRUNE_PASS: + # Because the pruner cleared all other increfs + self.assertEqual(1, c) + else: + self.assertEqual(2, c) + + def test_list_as_item_in_list(self): + nested_type = types.ListType(types.int32) + + @njit + def foo(): + la = List.empty_list(nested_type) + lb = List.empty_list(types.int32) + lb.append(1) + la.append(lb) + return la + + expected = foo.py_func() + got = foo() + self.assertEqual(expected, got) + + def test_array_as_item_in_list(self): + nested_type = types.Array(types.float64, 1, 'C') + + @njit + def foo(): + l = List.empty_list(nested_type) + a = np.zeros((1,)) + l.append(a) + return l + + expected = foo.py_func() + got = foo() + # Need to compare the nested arrays + self.assertTrue(np.all(expected[0] == got[0])) + + def test_array_pop_from_single_value_list(self): + @njit + def foo(): + l = List((np.zeros((1,)),)) + l.pop() + return l + + expected, got = foo.py_func(), foo() + # Need to compare the nested arrays + self.assertEqual(len(expected), 0) + self.assertEqual(len(got), 0) + # FIXME comparison of empty array-typed lists fails + # self.assertEqual(expected, got) + + def test_5264(self): + # Test the reproducer from #5264 and make sure it doesn't segfault + float_array = types.float64[:] + l = List.empty_list(float_array) + l.append(np.ones(3,dtype=np.float64)) + l.pop() + self.assertEqual(0, len(l)) + + def test_jitclass_as_item_in_list(self): + + spec = [ + ('value', int32), # a simple scalar field + ('array', float32[:]), # an array field + ] + + @jitclass(spec) + class Bag(object): + def __init__(self, value): + self.value = value + self.array = np.zeros(value, dtype=np.float32) + + @property + def size(self): + return self.array.size + + def increment(self, val): + for i in range(self.size): + self.array[i] += val + return self.array + + @njit + def foo(): + l = List() + l.append(Bag(21)) + l.append(Bag(22)) + l.append(Bag(23)) + return l + + expected = foo.py_func() + got = foo() + + def bag_equal(one, two): + # jitclasses couldn't override __eq__ at time of writing + self.assertEqual(one.value, two.value) + np.testing.assert_allclose(one.array, two.array) + + [bag_equal(a, b) for a, b in zip(expected, got)] + + def test_4960(self): + # Test the reproducer from #4960 and make sure it doesn't segfault + @jitclass([('value', int32)]) + class Simple(object): + def __init__(self, value): + self.value = value + + @njit + def foo(): + l = List((Simple(23),Simple(24))) + l.pop() + return l + + l = foo() + self.assertEqual(1, len(l)) + + def test_storage_model_mismatch(self): + # https://github.com/numba/numba/issues/4520 + # check for storage model mismatch in refcount ops generation + lst = List() + ref = [ + ("a", True, "a"), + ("b", False, "b"), + ("c", False, "c"), + ] + # populate + for x in ref: + lst.append(x) + # test + for i, x in enumerate(ref): + self.assertEqual(lst[i], ref[i]) + + def test_equals_on_list_with_dict_for_equal_lists(self): + # https://github.com/numba/numba/issues/4879 + a, b = List(), Dict() + b["a"] = 1 + a.append(b) + + c, d = List(), Dict() + d["a"] = 1 + c.append(d) + + self.assertEqual(a, c) + + def test_equals_on_list_with_dict_for_unequal_dicts(self): + # https://github.com/numba/numba/issues/4879 + a, b = List(), Dict() + b["a"] = 1 + a.append(b) + + c, d = List(), Dict() + d["a"] = 2 + c.append(d) + + self.assertNotEqual(a, c) + + def test_equals_on_list_with_dict_for_unequal_lists(self): + # https://github.com/numba/numba/issues/4879 + a, b = List(), Dict() + b["a"] = 1 + a.append(b) + + c, d, e = List(), Dict(), Dict() + d["a"] = 1 + e["b"] = 2 + c.append(d) + c.append(e) + + self.assertNotEqual(a, c) + + +class TestListSort(MemoryLeakMixin, TestCase): + def setUp(self): + super(TestListSort, self).setUp() + np.random.seed(0) + + def make(self, ctor, data): + lst = ctor() + lst.extend(data) + return lst + + def make_both(self, data): + return { + 'py': self.make(list, data), + 'nb': self.make(List, data), + } + + def test_sort_no_args(self): + def udt(lst): + lst.sort() + return lst + + for nelem in [13, 29, 127]: + my_lists = self.make_both(np.random.randint(0, nelem, nelem)) + self.assertEqual(list(udt(my_lists['nb'])), udt(my_lists['py'])) + + def test_sort_all_args(self): + def udt(lst, key, reverse): + lst.sort(key=key, reverse=reverse) + return lst + + possible_keys = [ + lambda x: -x, # negative + lambda x: 1 / (1 + x), # make float + lambda x: (x, -x), # tuple + lambda x: x, # identity + ] + possible_reverse = [True, False] + for key, reverse in product(possible_keys, possible_reverse): + my_lists = self.make_both(np.random.randint(0, 100, 23)) + msg = "case for key={} reverse={}".format(key, reverse) + self.assertEqual( + list(udt(my_lists['nb'], key=key, reverse=reverse)), + udt(my_lists['py'], key=key, reverse=reverse), + msg=msg, + ) + + def test_sort_dispatcher_key(self): + def udt(lst, key): + lst.sort(key=key) + return lst + + my_lists = self.make_both(np.random.randint(0, 100, 31)) + py_key = lambda x: x + 1 + nb_key = njit(lambda x: x + 1) + # test typedlist with jitted function + self.assertEqual( + list(udt(my_lists['nb'], key=nb_key)), + udt(my_lists['py'], key=py_key), + ) + # test typedlist with and without jitted function + self.assertEqual( + list(udt(my_lists['nb'], key=nb_key)), + list(udt(my_lists['nb'], key=py_key)), + ) + + def test_sort_in_jit_w_lambda_key(self): + @njit + def udt(lst): + lst.sort(key=lambda x: -x) + return lst + + lst = self.make(List, np.random.randint(0, 100, 31)) + self.assertEqual(udt(lst), udt.py_func(lst)) + + def test_sort_in_jit_w_global_key(self): + @njit + def keyfn(x): + return -x + + @njit + def udt(lst): + lst.sort(key=keyfn) + return lst + + lst = self.make(List, np.random.randint(0, 100, 31)) + self.assertEqual(udt(lst), udt.py_func(lst)) + + def test_sort_on_arrays(self): + @njit + def foo(lst): + lst.sort(key=lambda arr: np.sum(arr)) + return lst + + arrays = [np.random.random(3) for _ in range(10)] + my_lists = self.make_both(arrays) + self.assertEqual( + list(foo(my_lists['nb'])), + foo.py_func(my_lists['py']), + ) + + +class TestImmutable(MemoryLeakMixin, TestCase): + + def test_is_immutable(self): + @njit + def foo(): + l = List() + l.append(1) + return l._is_mutable() + self.assertTrue(foo()) + self.assertTrue(foo.py_func()) + + def test_make_immutable_is_immutable(self): + @njit + def foo(): + l = List() + l.append(1) + l._make_immutable() + return l._is_mutable() + self.assertFalse(foo()) + self.assertFalse(foo.py_func()) + + def test_length_still_works_when_immutable(self): + @njit + def foo(): + l = List() + l.append(1) + l._make_immutable() + return len(l),l._is_mutable() + length, mutable = foo() + self.assertEqual(length, 1) + self.assertFalse(mutable) + + def test_getitem_still_works_when_immutable(self): + @njit + def foo(): + l = List() + l.append(1) + l._make_immutable() + return l[0], l._is_mutable() + test_item, mutable = foo() + self.assertEqual(test_item, 1) + self.assertFalse(mutable) + + def test_append_fails(self): + self.disable_leak_check() + + @njit + def foo(): + l = List() + l.append(1) + l._make_immutable() + l.append(1) + + for func in (foo, foo.py_func): + with self.assertRaises(ValueError) as raises: + func() + self.assertIn( + 'list is immutable', + str(raises.exception), + ) + + def test_mutation_fails(self): + """ Test that any attempt to mutate an immutable typed list fails. """ + self.disable_leak_check() + + def generate_function(line): + context = {} + exec(dedent(""" + from numba.typed import List + def bar(): + lst = List() + lst.append(1) + lst._make_immutable() + {} + """.format(line)), context) + return njit(context["bar"]) + for line in ("lst.append(0)", + "lst[0] = 0", + "lst.pop()", + "del lst[0]", + "lst.extend((0,))", + "lst.insert(0, 0)", + "lst.clear()", + "lst.reverse()", + "lst.sort()", + ): + foo = generate_function(line) + for func in (foo, foo.py_func): + with self.assertRaises(ValueError) as raises: + func() + self.assertIn( + "list is immutable", + str(raises.exception), + ) + + +class TestGetItemIndexType(MemoryLeakMixin, TestCase): + + def test_indexing_with_uint8(self): + """ Test for reproducer at https://github.com/numba/numba/issues/7250 + """ + @njit + def foo(): + l = List.empty_list(uint8) + for i in range(129): + l.append(uint8(i)) + a = uint8(128) + return l[a] + + self.assertEqual(foo(), 128) + + +class TestListFromIter(MemoryLeakMixin, TestCase): + + def test_simple_iterable_types(self): + """Test all simple iterables that a List can be constructed from.""" + + def generate_function(line): + context = {} + code = dedent(""" + from numba.typed import List + def bar(): + {} + return l + """).format(line) + exec(code, context) + return njit(context["bar"]) + for line in ("l = List([0, 1, 2])", + "l = List(range(3))", + "l = List(List([0, 1, 2]))", + "l = List((0, 1, 2))", + "l = List(set([0, 1, 2]))", + ): + foo = generate_function(line) + cf_received, py_received = foo(), foo.py_func() + for result in (cf_received, py_received): + for i in range(3): + self.assertEqual(i, result[i]) + + def test_unicode(self): + """Test that a List can be created from a unicode string.""" + @njit + def foo(): + l = List("abc") + return l + expected = List() + for i in ("a", "b", "c"): + expected.append(i) + self.assertEqual(foo.py_func(), expected) + self.assertEqual(foo(), expected) + + def test_dict_iters(self): + """Test that a List can be created from Dict iterators.""" + + def generate_function(line): + context = {} + code = dedent(""" + from numba.typed import List, Dict + def bar(): + d = Dict() + d[0], d[1], d[2] = "a", "b", "c" + {} + return l + """).format(line) + exec(code, context) + return njit(context["bar"]) + + def generate_expected(values): + expected = List() + for i in values: + expected.append(i) + return expected + + for line, values in ( + ("l = List(d)", (0, 1, 2)), + ("l = List(d.keys())", (0, 1, 2)), + ("l = List(d.values())", ("a", "b", "c")), + ("l = List(d.items())", ((0, "a"), (1, "b"), (2, "c"))), + ): + foo, expected = generate_function(line), generate_expected(values) + for func in (foo, foo.py_func): + self.assertEqual(func(), expected) + + def test_ndarray_scalar(self): + + @njit + def foo(): + return List(np.ones(3)) + + expected = List() + for i in range(3): + expected.append(1) + + self.assertEqual(expected, foo()) + self.assertEqual(expected, foo.py_func()) + + def test_ndarray_oned(self): + + @njit + def foo(): + return List(np.array(1)) + + expected = List() + expected.append(1) + + self.assertEqual(expected, foo()) + self.assertEqual(expected, foo.py_func()) + + def test_ndarray_twod(self): + + @njit + def foo(x): + return List(x) + + carr = np.array([[1, 2], [3, 4]]) + farr = np.asfortranarray(carr) + aarr = np.arange(8).reshape((2, 4))[:, ::2] + + for layout, arr in zip('CFA', (carr, farr, aarr)): + self.assertEqual(typeof(arr).layout, layout) + expected = List() + expected.append(arr[0, :]) + expected.append(arr[1, :]) + received = foo(arr) + + np.testing.assert_equal(expected[0], received[0]) + np.testing.assert_equal(expected[1], received[1]) + + pyreceived = foo.py_func(arr) + + np.testing.assert_equal(expected[0], pyreceived[0]) + np.testing.assert_equal(expected[1], pyreceived[1]) + + def test_exception_on_plain_int(self): + @njit + def foo(): + l = List(23) + return l + + with self.assertRaises(TypingError) as raises: + foo() + self.assertIn( + "List() argument must be iterable", + str(raises.exception), + ) + + with self.assertRaises(TypeError) as raises: + List(23) + self.assertIn( + "List() argument must be iterable", + str(raises.exception), + ) + + def test_exception_on_inhomogeneous_tuple(self): + @njit + def foo(): + l = List((1, 1.0)) + return l + + with self.assertRaises(TypingError) as raises: + foo() + self.assertIn( + "List() argument must be iterable", + str(raises.exception), + ) + + with self.assertRaises(TypingError) as raises: + List((1, 1.0)) + # FIXME this bails with a length casting error when we attempt to + # append 1.0 to an int typed list. + + def test_exception_on_too_many_args(self): + @njit + def foo(): + l = List((0, 1, 2), (3, 4, 5)) + return l + + with self.assertRaises(TypingError) as raises: + foo() + self.assertIn( + "List() expected at most 1 argument, got 2", + str(raises.exception), + ) + + with self.assertRaises(TypeError) as raises: + List((0, 1, 2), (3, 4, 5)) + self.assertIn( + "List() expected at most 1 argument, got 2", + str(raises.exception), + ) + + @njit + def foo(): + l = List((0, 1, 2), (3, 4, 5), (6, 7, 8)) + return l + + with self.assertRaises(TypingError) as raises: + foo() + self.assertIn( + "List() expected at most 1 argument, got 3", + str(raises.exception), + ) + + with self.assertRaises(TypeError) as raises: + List((0, 1, 2), (3, 4, 5), (6, 7, 8)) + self.assertIn( + "List() expected at most 1 argument, got 3", + str(raises.exception), + ) + + def test_exception_on_kwargs(self): + @njit + def foo(): + l = List(iterable=(0, 1, 2)) + return l + + with self.assertRaises(TypingError) as raises: + foo() + self.assertIn( + "List() takes no keyword arguments", + str(raises.exception), + ) + + with self.assertRaises(TypeError) as raises: + List(iterable=(0, 1, 2)) + self.assertIn( + "List() takes no keyword arguments", + str(raises.exception), + ) diff --git a/lib/python3.10/site-packages/numba/tests/test_typeguard.py b/lib/python3.10/site-packages/numba/tests/test_typeguard.py new file mode 100644 index 0000000000000000000000000000000000000000..37ab82dd8fc321fe560b87ed10f62fcfba36b277 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_typeguard.py @@ -0,0 +1,44 @@ +""" +Tests to ensure that typeguard is working as expected. +This mostly contains negative tests as proof that typeguard can catch errors. +""" +import unittest +from numba.tests.support import TestCase, skip_unless_typeguard + + +def guard_args(val: int): + return + + +def guard_ret(val) -> int: + return val + + +@skip_unless_typeguard +class TestTypeGuard(TestCase): + + def setUp(self): + super().setUp() + import typeguard + # This is a test class invariant but the Numba multiprocesses test + # runner doesn't respect `setUpClass` so just use `setUp`. + # typeguard 3+ uses typeguard.TypeCheckError, 2.x uses TypeError + self._exception_type = getattr(typeguard, 'TypeCheckError', TypeError) + + def test_check_args(self): + with self.assertRaises(self._exception_type): + guard_args(float(1.2)) + + def test_check_ret(self): + with self.assertRaises(self._exception_type): + guard_ret(float(1.2)) + + def test_check_does_not_work_with_inner_func(self): + def guard(val: int) -> int: + return + + guard(float(1.2)) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_types.py b/lib/python3.10/site-packages/numba/tests/test_types.py new file mode 100644 index 0000000000000000000000000000000000000000..ce05fab65a4992a87cfd4b39a6e360b04a150a2c --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_types.py @@ -0,0 +1,879 @@ +""" +Tests for numba.types. +""" + + +from collections import namedtuple +import gc +import os +import operator +import sys +import weakref + +import numpy as np + +from numba.core import types, typing, errors, sigutils +from numba.core.types.abstract import _typecache +from numba.core.types.functions import _header_lead +from numba.core.typing.templates import make_overload_template +from numba import jit, njit, typeof +from numba.core.extending import (overload, register_model, models, unbox, + NativeValue, typeof_impl) +from numba.tests.support import TestCase, create_temp_module +from numba.tests.enum_usecases import Color, Shake, Shape +import unittest +from numba.np import numpy_support + + +try: + import cPickle as pickle +except ImportError: + import pickle + + +Point = namedtuple('Point', ('x', 'y')) + +Rect = namedtuple('Rect', ('width', 'height')) + + +def gen(x): + yield x + 1 + + +class Dummy(object): + pass + + +class TestTypes(TestCase): + + def test_equality(self): + self.assertEqual(types.int32, types.int32) + self.assertEqual(types.uint32, types.uint32) + self.assertEqual(types.complex64, types.complex64) + self.assertEqual(types.float32, types.float32) + # Different signedness + self.assertNotEqual(types.int32, types.uint32) + # Different width + self.assertNotEqual(types.int64, types.int32) + self.assertNotEqual(types.float64, types.float32) + self.assertNotEqual(types.complex64, types.complex128) + # Different domain + self.assertNotEqual(types.int64, types.float64) + self.assertNotEqual(types.uint64, types.float64) + self.assertNotEqual(types.complex64, types.float64) + # Same arguments but different return types + get_pointer = None + sig_a = typing.signature(types.intp, types.intp) + sig_b = typing.signature(types.voidptr, types.intp) + a = types.ExternalFunctionPointer(sig=sig_a, get_pointer=get_pointer) + b = types.ExternalFunctionPointer(sig=sig_b, get_pointer=get_pointer) + self.assertNotEqual(a, b) + # Different call convention + a = types.ExternalFunctionPointer(sig=sig_a, get_pointer=get_pointer) + b = types.ExternalFunctionPointer(sig=sig_a, get_pointer=get_pointer, + cconv='stdcall') + self.assertNotEqual(a, b) + # Different get_pointer + a = types.ExternalFunctionPointer(sig=sig_a, get_pointer=get_pointer) + b = types.ExternalFunctionPointer(sig=sig_a, get_pointer=object()) + self.assertNotEqual(a, b) + + # Different template classes bearing the same name + class DummyTemplate(object): + key = "foo" + a = types.BoundFunction(DummyTemplate, types.int32) + + class DummyTemplate(object): + key = "bar" + b = types.BoundFunction(DummyTemplate, types.int32) + self.assertNotEqual(a, b) + + # Different dtypes + self.assertNotEqual(types.DType(types.int32), types.DType(types.int64)) + + # CPointer with same addrspace + self.assertEqual(types.CPointer(types.float32), + types.CPointer(types.float32)) + + # CPointer with different addrspace + self.assertNotEqual(types.CPointer(types.float32, 0), + types.CPointer(types.float32, 1)) + + def test_weaktype(self): + d = Dummy() + e = Dummy() + a = types.Dispatcher(d) + b = types.Dispatcher(d) + c = types.Dispatcher(e) + self.assertIs(a.dispatcher, d) + self.assertIs(b.dispatcher, d) + self.assertIs(c.dispatcher, e) + # Equality of alive references + self.assertTrue(a == b) + self.assertFalse(a != b) + self.assertTrue(a != c) + self.assertFalse(a == c) + z = types.int8 + self.assertFalse(a == z) + self.assertFalse(b == z) + self.assertFalse(c == z) + self.assertTrue(a != z) + self.assertTrue(b != z) + self.assertTrue(c != z) + # Hashing and mappings + s = set([a, b, c]) + self.assertEqual(len(s), 2) + self.assertIn(a, s) + self.assertIn(b, s) + self.assertIn(c, s) + # Kill the references + d = e = None + gc.collect() + with self.assertRaises(ReferenceError): + a.dispatcher + with self.assertRaises(ReferenceError): + b.dispatcher + with self.assertRaises(ReferenceError): + c.dispatcher + # Dead references are always unequal + self.assertFalse(a == b) + self.assertFalse(a == c) + self.assertFalse(b == c) + self.assertFalse(a == z) + self.assertTrue(a != b) + self.assertTrue(a != c) + self.assertTrue(b != c) + self.assertTrue(a != z) + + def test_interning(self): + # Test interning and lifetime of dynamic types. + a = types.Dummy('xyzzyx') + code = a._code + b = types.Dummy('xyzzyx') + self.assertIs(b, a) + wr = weakref.ref(a) + del a + gc.collect() + c = types.Dummy('xyzzyx') + self.assertIs(c, b) + # The code is always the same + self.assertEqual(c._code, code) + del b, c + gc.collect() + self.assertIs(wr(), None) + d = types.Dummy('xyzzyx') + # The original code wasn't reused. + self.assertNotEqual(d._code, code) + + def test_cache_trimming(self): + # Test that the cache doesn't grow in size when types are + # created and disposed of. + cache = _typecache + gc.collect() + # Keep strong references to existing types, to avoid spurious failures + existing_types = [wr() for wr in cache] # noqa: F841 + cache_len = len(cache) + a = types.Dummy('xyzzyx') + b = types.Dummy('foox') + self.assertEqual(len(cache), cache_len + 2) + del a, b + gc.collect() + self.assertEqual(len(cache), cache_len) + + def test_array_notation(self): + def check(arrty, scalar, ndim, layout): + self.assertIs(arrty.dtype, scalar) + self.assertEqual(arrty.ndim, ndim) + self.assertEqual(arrty.layout, layout) + + def check_index_error(callable): + with self.assertRaises(KeyError) as raises: + callable() + self.assertIn( + "Can only index numba types with slices with no start or " + "stop, got", str(raises.exception)) + + scalar = types.int32 + check(scalar[:], scalar, 1, 'A') + check(scalar[::1], scalar, 1, 'C') + check(scalar[:, :], scalar, 2, 'A') + check(scalar[:, ::1], scalar, 2, 'C') + check(scalar[::1, :], scalar, 2, 'F') + + check_index_error(lambda: scalar[0]) + check_index_error(lambda: scalar[:, 4]) + check_index_error(lambda: scalar[::1, 1:]) + check_index_error(lambda: scalar[:2]) + check_index_error(lambda: list(scalar)) + + def test_array_notation_for_dtype(self): + def check(arrty, scalar, ndim, layout): + self.assertIs(arrty.dtype, scalar) + self.assertEqual(arrty.ndim, ndim) + self.assertEqual(arrty.layout, layout) + scalar = types.int32 + dtyped = types.DType(scalar) + check(dtyped[:], scalar, 1, 'A') + check(dtyped[::1], scalar, 1, 'C') + check(dtyped[:, :], scalar, 2, 'A') + check(dtyped[:, ::1], scalar, 2, 'C') + check(dtyped[::1, :], scalar, 2, 'F') + + def test_call_notation(self): + # Function call signature + i = types.int32 + d = types.double + self.assertEqual(i(), typing.signature(i)) + self.assertEqual(i(d), typing.signature(i, d)) + self.assertEqual(i(d, d), typing.signature(i, d, d)) + # Value cast + self.assertPreciseEqual(i(42.5), 42) + self.assertPreciseEqual(d(-5), -5.0) + ty = types.NPDatetime('Y') + self.assertPreciseEqual(ty('1900'), np.datetime64('1900', 'Y')) + self.assertPreciseEqual(ty('NaT'), np.datetime64('NaT', 'Y')) + ty = types.NPTimedelta('s') + self.assertPreciseEqual(ty(5), np.timedelta64(5, 's')) + self.assertPreciseEqual(ty('NaT'), np.timedelta64('NaT', 's')) + ty = types.NPTimedelta('') + self.assertPreciseEqual(ty(5), np.timedelta64(5)) + self.assertPreciseEqual(ty('NaT'), np.timedelta64('NaT')) + + def test_list_type_getitem(self): + for listty in (types.int64, types.Array(types.float64, 1, 'C')): + l_int = types.List(listty) + self.assertTrue(isinstance(l_int, types.List)) + self.assertTrue(isinstance(l_int[0], type(listty))) + + def test_function_incompatible_templates(self): + # issue 4345 + def func_stub(): + pass + + def func_stub2(): + pass + + def ol(): + pass + + template1 = make_overload_template(func_stub, ol, {}, True, 'never') + template2 = make_overload_template(func_stub2, ol, {}, True, 'never') + + with self.assertRaises(ValueError) as raises: + types.Function((template1, template2)) + self.assertIn("incompatible templates:", str(raises.exception)) + + +class TestNumbers(TestCase): + """ + Tests for number types. + """ + + def test_bitwidth(self): + """ + All numeric types have bitwidth attribute + """ + for ty in types.number_domain: + self.assertTrue(hasattr(ty, "bitwidth")) + + def test_minval_maxval(self): + self.assertEqual(types.int8.maxval, 127) + self.assertEqual(types.int8.minval, -128) + self.assertEqual(types.uint8.maxval, 255) + self.assertEqual(types.uint8.minval, 0) + self.assertEqual(types.int64.maxval, (1 << 63) - 1) + self.assertEqual(types.int64.minval, -(1 << 63)) + self.assertEqual(types.uint64.maxval, (1 << 64) - 1) + self.assertEqual(types.uint64.minval, 0) + + def test_from_bidwidth(self): + f = types.Integer.from_bitwidth + self.assertIs(f(32), types.int32) + self.assertIs(f(8, signed=False), types.uint8) + + def test_ordering(self): + def check_order(values): + for i in range(len(values)): + self.assertLessEqual(values[i], values[i]) + self.assertGreaterEqual(values[i], values[i]) + self.assertFalse(values[i] < values[i]) + self.assertFalse(values[i] > values[i]) + for j in range(i): + self.assertLess(values[j], values[i]) + self.assertLessEqual(values[j], values[i]) + self.assertGreater(values[i], values[j]) + self.assertGreaterEqual(values[i], values[j]) + self.assertFalse(values[i] < values[j]) + self.assertFalse(values[i] <= values[j]) + self.assertFalse(values[j] > values[i]) + self.assertFalse(values[j] >= values[i]) + + check_order([types.int8, types.int16, types.int32, types.int64]) + check_order([types.uint8, types.uint16, types.uint32, types.uint64]) + check_order([types.float32, types.float64]) + check_order([types.complex64, types.complex128]) + + with self.assertRaises(TypeError): + types.int8 <= types.uint32 + with self.assertRaises(TypeError): + types.int8 <= types.float32 + with self.assertRaises(TypeError): + types.float64 <= types.complex128 + + +class TestNdIter(TestCase): + + def test_properties(self): + def check(ty, dtypes, ndim, layout, indexers=None): + self.assertEqual(ty.ndim, ndim) + self.assertEqual(ty.layout, layout) + self.assertEqual(ty.dtypes, dtypes) + views = [types.Array(dtype, 0, "C") for dtype in dtypes] + if len(views) > 1: + self.assertEqual( + ty.yield_type, + types.BaseTuple.from_types(views)) + else: + self.assertEqual(ty.yield_type, views[0]) + if indexers is not None: + self.assertEqual(ty.indexers, indexers) + + f32 = types.float32 + c64 = types.complex64 + i16 = types.int16 + a = types.Array(f32, 1, "C") + b = types.Array(f32, 2, "C") + c = types.Array(c64, 2, "F") + d = types.Array(i16, 2, "A") + e = types.Array(i16, 0, "C") + f = types.Array(f32, 1, "A") + g = types.Array(f32, 0, "C") + + # 0-dim iterator + ty = types.NumpyNdIterType((e,)) + check(ty, (i16,), 0, "C", [('0d', 0, 0, [0])]) + self.assertFalse(ty.need_shaped_indexing) + ty = types.NumpyNdIterType((e, g)) + check(ty, (i16, f32), 0, "C", [('0d', 0, 0, [0, 1])]) + self.assertFalse(ty.need_shaped_indexing) + ty = types.NumpyNdIterType((e, c64)) + check(ty, (i16, c64), 0, "C", + [('0d', 0, 0, [0]), ('scalar', 0, 0, [1])]) + self.assertFalse(ty.need_shaped_indexing) + + # 1-dim iterator + ty = types.NumpyNdIterType((a,)) + check(ty, (f32,), 1, "C", + [('flat', 0, 1, [0])]) + self.assertFalse(ty.need_shaped_indexing) + ty = types.NumpyNdIterType((a, a)) + check(ty, (f32, f32), 1, "C", + [('flat', 0, 1, [0, 1])]) + self.assertFalse(ty.need_shaped_indexing) + ty = types.NumpyNdIterType((a, e, e, c64)) + check(ty, (f32, i16, i16, c64), 1, "C", + [('flat', 0, 1, [0]), # a + ('0d', 0, 0, [1, 2]), # e, e + ('scalar', 0, 0, [3]), # c64 + ]) + self.assertFalse(ty.need_shaped_indexing) + ty = types.NumpyNdIterType((a, f)) + check(ty, (f32, f32), 1, "C", + [('flat', 0, 1, [0]), ('indexed', 0, 1, [1])]) + self.assertTrue(ty.need_shaped_indexing) + ty = types.NumpyNdIterType((f,)) + check(ty, (f32,), 1, "C", [('indexed', 0, 1, [0])]) + self.assertTrue(ty.need_shaped_indexing) + + # 2-dim C-order iterator + ty = types.NumpyNdIterType((b,)) + check(ty, (f32,), 2, "C", [('flat', 0, 2, [0])]) + self.assertFalse(ty.need_shaped_indexing) + ty = types.NumpyNdIterType((b, c)) + check( + ty, (f32, c64), 2, "C", [ + ('flat', 0, 2, [0]), ('indexed', 0, 2, [1])]) + self.assertTrue(ty.need_shaped_indexing) + ty = types.NumpyNdIterType((d,)) + check(ty, (i16,), 2, "C", [('indexed', 0, 2, [0])]) + self.assertTrue(ty.need_shaped_indexing) + ty = types.NumpyNdIterType((b, c, d, d, e)) + check(ty, (f32, c64, i16, i16, i16), 2, "C", + [('flat', 0, 2, [0]), # b + ('indexed', 0, 2, [1, 2, 3]), # c, d, d + ('0d', 0, 0, [4]), # e + ]) + self.assertTrue(ty.need_shaped_indexing) + ty = types.NumpyNdIterType((a, b, c, d, d, f)) + check(ty, (f32, f32, c64, i16, i16, f32), 2, "C", + [('flat', 1, 2, [0]), # a + ('flat', 0, 2, [1]), # b + ('indexed', 0, 2, [2, 3, 4]), # c, d, d + ('indexed', 1, 2, [5]), # f + ]) + self.assertTrue(ty.need_shaped_indexing) + + # 2-dim F-order iterator + ty = types.NumpyNdIterType((c,)) + check(ty, (c64,), 2, "F", [('flat', 0, 2, [0])]) + self.assertFalse(ty.need_shaped_indexing) + ty = types.NumpyNdIterType((c, b, c, f)) + check(ty, (c64, f32, c64, f32), 2, "F", + [('flat', 0, 2, [0, 2]), # c, c + ('indexed', 0, 2, [1]), # b + ('indexed', 0, 1, [3]), # f + ]) + self.assertTrue(ty.need_shaped_indexing) + ty = types.NumpyNdIterType((b, c, c, d, d, a, e)) + check(ty, (f32, c64, c64, i16, i16, f32, i16), 2, "F", + [('indexed', 0, 2, [0, 3, 4]), # b, d, d + ('flat', 0, 2, [1, 2]), # c, c + ('flat', 0, 1, [5]), # a + ('0d', 0, 0, [6]), # e + ]) + self.assertTrue(ty.need_shaped_indexing) + + +class TestPickling(TestCase): + """ + Pickling and unpickling should preserve type identity (singleton-ness) + and the _code attribute. This is only a requirement for types that + can be part of function signatures. + """ + + def predefined_types(self): + """ + Yield all predefined type instances + """ + for ty in types.__dict__.values(): + if isinstance(ty, types.Type): + yield ty + + def check_pickling(self, orig): + pickled = pickle.dumps(orig, protocol=-1) + ty = pickle.loads(pickled) + self.assertIs(ty, orig) + self.assertGreaterEqual(ty._code, 0) + + def test_predefined_types(self): + tys = list(self.predefined_types()) + self.assertIn(types.int16, tys) + for ty in tys: + self.check_pickling(ty) + + def test_atomic_types(self): + for unit in ('M', 'ms'): + ty = types.NPDatetime(unit) + self.check_pickling(ty) + ty = types.NPTimedelta(unit) + self.check_pickling(ty) + + def test_arrays(self): + for ndim in (0, 1, 2): + for layout in ('A', 'C', 'F'): + ty = types.Array(types.int16, ndim, layout) + self.check_pickling(ty) + + def test_records(self): + recordtype = np.dtype([('a', np.float64), + ('b', np.int32), + ('c', np.complex64), + ('d', (np.str_, 5))]) + ty = numpy_support.from_dtype(recordtype) + self.check_pickling(ty) + self.check_pickling(types.Array(ty, 1, 'A')) + + def test_optional(self): + ty = types.Optional(types.int32) + self.check_pickling(ty) + + def test_tuples(self): + ty1 = types.UniTuple(types.int32, 3) + self.check_pickling(ty1) + ty2 = types.Tuple((types.int32, ty1)) + self.check_pickling(ty2) + + def test_namedtuples(self): + ty1 = types.NamedUniTuple(types.intp, 2, Point) + self.check_pickling(ty1) + ty2 = types.NamedTuple((types.intp, types.float64), Point) + self.check_pickling(ty2) + + def test_enums(self): + ty1 = types.EnumMember(Color, types.int32) + self.check_pickling(ty1) + ty2 = types.EnumMember(Shake, types.int64) + self.check_pickling(ty2) + ty3 = types.IntEnumMember(Shape, types.int64) + self.check_pickling(ty3) + + def test_lists(self): + ty = types.List(types.int32) + self.check_pickling(ty) + + def test_generator(self): + cfunc = jit("(int32,)", nopython=True)(gen) + sigs = list(cfunc.nopython_signatures) + ty = sigs[0].return_type + self.assertIsInstance(ty, types.Generator) + self.check_pickling(ty) + + # call templates are not picklable + @unittest.expectedFailure + def test_external_function_pointers(self): + from numba.core.typing import ctypes_utils + from numba.tests.ctypes_usecases import c_sin, c_cos + for fnptr in (c_sin, c_cos): + ty = ctypes_utils.make_function_type(fnptr) + self.assertIsInstance(ty, types.ExternalFunctionPointer) + self.check_pickling(ty) + + +class TestSignatures(TestCase): + + def test_normalize_signature(self): + f = sigutils.normalize_signature + + def check(sig, args, return_type): + self.assertEqual(f(sig), (args, return_type)) + + def check_error(sig, msg): + with self.assertRaises(TypeError) as raises: + f(sig) + self.assertIn(msg, str(raises.exception)) + + f32 = types.float32 + c64 = types.complex64 + i16 = types.int16 + a = types.Array(f32, 1, "C") + + check((c64,), (c64,), None) + check((f32, i16), (f32, i16), None) + check(a(i16), (i16,), a) + check("int16(complex64)", (c64,), i16) + check("(complex64, int16)", (c64, i16), None) + check(typing.signature(i16, c64), (c64,), i16) + + msg = "invalid type in signature: expected a type instance" + check_error((types.Integer,), msg) + check_error((None,), msg) + check_error([], "invalid signature") + + +class TestRecordDtype(unittest.TestCase): + def test_record_type_equiv(self): + rec_dt = np.dtype([('a', np.int32), ('b', np.float32)]) + rec_ty = typeof(rec_dt) + art1 = rec_ty[::1] + arr = np.zeros(5, dtype=rec_dt) + art2 = typeof(arr) + self.assertEqual(art2.dtype.dtype, rec_ty) + self.assertEqual(art1, art2) + + def test_user_specified(self): + rec_dt = np.dtype([('a', np.int32), ('b', np.float32)]) + rec_type = typeof(rec_dt) + + @jit((rec_type[:],), nopython=True) + def foo(x): + return x['a'], x['b'] + + arr = np.zeros(1, dtype=rec_dt) + arr[0]['a'] = 123 + arr[0]['b'] = 32.1 + + a, b = foo(arr) + + self.assertEqual(a, arr[0]['a']) + self.assertEqual(b, arr[0]['b']) + + +class TestDType(TestCase): + def test_type_attr(self): + # Test .type attribute of dtype + def conv(arr, val): + return arr.dtype.type(val) + + jit_conv = jit(nopython=True)(conv) + + def assert_matches(arr, val, exact): + expect = conv(arr, val) + got = jit_conv(arr, val) + self.assertPreciseEqual(expect, exact) + self.assertPreciseEqual(typeof(expect), typeof(got)) + self.assertPreciseEqual(expect, got) + + arr = np.zeros(5) + assert_matches(arr.astype(np.intp), 1.2, 1) + assert_matches(arr.astype(np.float64), 1.2, 1.2) + assert_matches(arr.astype(np.complex128), 1.2, (1.2 + 0j)) + assert_matches(arr.astype(np.complex128), 1.2j, 1.2j) + + def test_kind(self): + def tkind(A): + return A.dtype.kind == 'f' + jit_tkind = jit(nopython=True)(tkind) + self.assertEqual(tkind(np.ones(3)), jit_tkind(np.ones(3))) + self.assertEqual(tkind(np.ones(3, dtype=np.intp)), + jit_tkind(np.ones(3, dtype=np.intp))) + + def test_dtype_with_type(self): + def impl(): + a = np.dtype(np.float64) + return a.type(0) + jit_impl = jit(nopython=True)(impl) + self.assertEqual(impl(), jit_impl()) + + def test_dtype_with_string(self): + def impl(): + a = np.dtype('float64') + return a.type(0) + jit_impl = jit(nopython=True)(impl) + self.assertEqual(impl(), jit_impl()) + + +class TestIsInternalTypeMarker(TestCase): + """Tests the use of the Type metaclass init correctly setting the flag on + the `is_internal` attr of a concrete Type class + """ + source_lines = """ +from numba.core import types + +class FooType(types.Type): + def __init__(self): + super(FooType, self).__init__(name='Foo') +""" + + def test_create_temp_module(self): + sys_path_original = list(sys.path) + sys_modules_original = dict(sys.modules) + with create_temp_module(self.source_lines) as test_module: + temp_module_dir = os.path.dirname(test_module.__file__) + self.assertEqual(temp_module_dir, sys.path[0]) + self.assertEqual(sys.path[1:], sys_path_original) + self.assertTrue(test_module.__name__ in sys.modules) + # Test that modifications to sys.path / sys.modules are reverted + self.assertEqual(sys.path, sys_path_original) + self.assertEqual(sys.modules, sys_modules_original) + + def test_create_temp_module_with_exception(self): + try: + sys_path_original = list(sys.path) + sys_modules_original = dict(sys.modules) + with create_temp_module(self.source_lines): + raise ValueError("Something went wrong!") + except ValueError: + # Test that modifications to sys.path / sys.modules are reverted + self.assertEqual(sys.path, sys_path_original) + self.assertEqual(sys.modules, sys_modules_original) + + def test_externally_defined_type_is_external(self): + + with create_temp_module(self.source_lines) as test_module: + FooType = test_module.FooType + self.assertFalse(FooType().is_internal) + + # set up an extension type + class Foo(object): + pass + + register_model(FooType)(models.OpaqueModel) + + @typeof_impl.register(Foo) + def _typ_foo(val, c): + return FooType() + + @unbox(FooType) + def unbox_foo(typ, obj, c): + return NativeValue(c.context.get_dummy_value()) + + # function to overload + def false_if_not_array(a): + pass + + # Set up an overload which will accept all types irrespective of + # whether they are from Numba's closed type system + @overload(false_if_not_array) + def ol_false_if_not_array(a): + if isinstance(a, types.Array): + return lambda a : True + else: + return lambda a : False + + @njit + def call_false_if_not_array(a): + return false_if_not_array(a) + + self.assertTrue(call_false_if_not_array(np.zeros(10))) + self.assertFalse(call_false_if_not_array(10)) + + # The extension type was accepted + self.assertFalse(call_false_if_not_array(Foo())) + + # Now do the same sort of overload but put in a guard based on the + # use of internal types + + def false_if_not_array_closed_system(a): + pass + + @overload(false_if_not_array_closed_system) + def ol_false_if_not_array_closed_system(a): + if a.is_internal: # guard + if isinstance(a, types.Array): + return lambda a : True + else: + return lambda a : False + + @njit + def call_false_if_not_array_closed_system(a): + return false_if_not_array_closed_system(a) + + self.assertTrue(call_false_if_not_array_closed_system(np.zeros(10))) + self.assertFalse(call_false_if_not_array_closed_system(10)) + + with self.assertRaises(errors.TypingError) as raises: + call_false_if_not_array_closed_system(Foo()) + estr = str(raises.exception) + self.assertIn(_header_lead, estr) + self.assertIn("false_if_not_array_closed_system", estr) + self.assertIn("(Foo)", estr) + + def test_mixin_against_real_example(self): + # See issue #4970, this checks that unicode eq/ne now ignores extension + # types. + + with create_temp_module(self.source_lines) as test_module: + FooType = test_module.FooType + self.assertFalse(FooType().is_internal) + + # set up an extension type + class Foo(object): + pass + + register_model(FooType)(models.OpaqueModel) + + @typeof_impl.register(Foo) + def _typ_foo(val, c): + return FooType() + + @unbox(FooType) + def unbox_foo(typ, obj, c): + return NativeValue(c.context.get_dummy_value()) + + @overload(operator.eq) + def foo_eq(a, b): + if a == FooType(): + return lambda a, b: "RAN CUSTOM EQ OVERLOAD" + + @overload(operator.ne) + def foo_ne(a, b): + if a == FooType(): + return lambda a, b: "RAN CUSTOM NE OVERLOAD" + + @njit + def f(a): + return a == "A", a != "A" + + self.assertEqual(("RAN CUSTOM EQ OVERLOAD", + "RAN CUSTOM NE OVERLOAD"), + f(Foo())) + + +class TestIssues(TestCase): + def test_omitted_type(self): + # issue https://github.com/numba/numba/issues/5471 + def inner(a): + pass + + @overload(inner) + def inner_overload(a): + if not isinstance(a, types.Literal): + return + return lambda a: a + + @njit + def my_func(a='a'): + return inner(a) + + @njit + def f(): + return my_func() + + @njit + def g(): + return my_func('b') + + self.assertEqual(f(), 'a') + self.assertEqual(g(), 'b') + + def test_type_of_literal(self): + # type(val) where val is a literal should not give a literal type. + def inner(a): + pass + + @overload(inner) + def inner_overload(a): + if not isinstance(a, types.Literal): + return + self.assertIsInstance(a, types.Literal) + # NOTE: using 1.23 to ensure that the result is indeed an int. + return lambda a: type(a)(a + 1.23) + + @njit + def my_func(a=1): + return inner(a) + + @njit + def f(): + return my_func() + + @njit + def g(): + return my_func(100) + + self.assertEqual(f(), 2) + self.assertEqual(g(), 101) + + def test_issue_typeref_key(self): + # issue https://github.com/numba/numba/issues/6336 + class NoUniqueNameType(types.Dummy): + def __init__(self, param): + super(NoUniqueNameType, self).__init__('NoUniqueNameType') + self.param = param + + @property + def key(self): + return self.param + + no_unique_name_type_1 = NoUniqueNameType(1) + no_unique_name_type_2 = NoUniqueNameType(2) + + for ty1 in (no_unique_name_type_1, no_unique_name_type_2): + for ty2 in (no_unique_name_type_1, no_unique_name_type_2): + self.assertIs( + types.TypeRef(ty1) == types.TypeRef(ty2), ty1 == ty2) + + def test_issue_list_type_key(self): + # https://github.com/numba/numba/issues/6397 + class NoUniqueNameType(types.Dummy): + def __init__(self, param): + super(NoUniqueNameType, self).__init__('NoUniqueNameType') + self.param = param + + @property + def key(self): + return self.param + + no_unique_name_type_1 = NoUniqueNameType(1) + no_unique_name_type_2 = NoUniqueNameType(2) + + for ty1 in (no_unique_name_type_1, no_unique_name_type_2): + for ty2 in (no_unique_name_type_1, no_unique_name_type_2): + self.assertIs( + types.ListType(ty1) == types.ListType(ty2), # noqa: E721 + ty1 == ty2 + ) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_typingerror.py b/lib/python3.10/site-packages/numba/tests/test_typingerror.py new file mode 100644 index 0000000000000000000000000000000000000000..ce6b6cd3e0e9f6a93e1b508699fbddbe35dd85ab --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_typingerror.py @@ -0,0 +1,236 @@ +import math +import re +import textwrap +import operator + +import numpy as np + +import unittest +from numba import jit, njit +from numba.core import types +from numba.core.errors import TypingError +from numba.core.types.functions import _header_lead +from numba.tests.support import TestCase + + +def what(): + pass + +def foo(): + return what() + +def bar(x): + return x.a + +def issue_868(a): + return a.shape * 2 + +def impossible_return_type(x): + if x > 0: + return () + else: + return 1j + +def bad_hypot_usage(): + return math.hypot(1) + +def imprecise_list(): + l = [] + return len(l) + +def using_imprecise_list(): + a = np.array([]) + return a.astype(np.int32) + +def unknown_module(): + return numpyz.int32(0) + +def nop(x, y, z): + pass + +def array_setitem_invalid_cast(): + arr = np.empty(1, dtype=np.float64) + arr[0] = 1j # invalid cast from complex to float + return arr + + +class Foo(object): + def __repr__(self): + return "" + + +class TestTypingError(unittest.TestCase): + + def test_unknown_function(self): + try: + njit((),)(foo) + except TypingError as e: + self.assertIn("Untyped global name 'what'", str(e)) + else: + self.fail("Should raise error") + + def test_unknown_attrs(self): + try: + njit((types.int32,),)(bar) + except TypingError as e: + self.assertIn("Unknown attribute 'a' of type int32", str(e)) + else: + self.fail("Should raise error") + + def test_unknown_module(self): + # This used to print "'object' object has no attribute 'int32'" + with self.assertRaises(TypingError) as raises: + njit((),)(unknown_module) + self.assertIn("name 'numpyz' is not defined", str(raises.exception)) + + def test_issue_868(self): + ''' + Summary: multiplying a scalar by a non-scalar would cause a crash in + type inference because TimeDeltaMixOp always assumed at least one of + its operands was an NPTimeDelta in its generic() method. + ''' + with self.assertRaises(TypingError) as raises: + njit((types.Array(types.int32, 1, 'C'),))(issue_868) + + expected = ((_header_lead + " Function() found " + "for signature:\n \n >>> mul(UniTuple({} x 1), {})") + .format(str(types.intp), types.IntegerLiteral(2))) + self.assertIn(expected, str(raises.exception)) + self.assertIn("During: typing of", str(raises.exception)) + + def test_return_type_unification(self): + with self.assertRaises(TypingError) as raises: + njit((types.int32,))(impossible_return_type,) + msg = ("Can't unify return type from the following types: Tuple(), " + "complex128") + self.assertIn(msg, str(raises.exception)) + + def test_bad_hypot_usage(self): + with self.assertRaises(TypingError) as raises: + njit((),)(bad_hypot_usage,) + + errmsg = str(raises.exception) + # Make sure it listed the known signatures. + # This is sensitive to the formatting of the error message. + self.assertIn(" * (float64, float64) -> float64", errmsg) + + # find the context lines + ctx_lines = [x for x in errmsg.splitlines() if "During:" in x ] + + # Check contextual msg + self.assertTrue(re.search(r'.*During: resolving callee type: Function.*hypot', ctx_lines[0])) + self.assertTrue(re.search(r'.*During: typing of call .*test_typingerror.py', ctx_lines[1])) + + + def test_imprecise_list(self): + """ + Type inference should catch that a list type's remain imprecise, + instead of letting lowering fail. + """ + with self.assertRaises(TypingError) as raises: + njit((),)(imprecise_list) + + errmsg = str(raises.exception) + msg = ("Cannot infer the type of variable 'l', have imprecise type: " + "list(undefined)") + self.assertIn(msg, errmsg) + # check help message has gone in + self.assertIn("For Numba to be able to compile a list", errmsg) + + def test_using_imprecise_list(self): + """ + Type inference should report informative error about untyped list. + TODO: #2931 + """ + with self.assertRaises(TypingError) as raises: + njit((),)(using_imprecise_list) + + errmsg = str(raises.exception) + self.assertIn("Undecided type", errmsg) + + def test_array_setitem_invalid_cast(self): + with self.assertRaises(TypingError) as raises: + njit((),)(array_setitem_invalid_cast) + + errmsg = str(raises.exception) + self.assertIn( + _header_lead + " Function({})".format(operator.setitem), + errmsg, + ) + self.assertIn( + "(array(float64, 1d, C), Literal[int](0), complex128)", + errmsg, + ) + + def test_template_rejection_error_message_cascade(self): + from numba import njit + @njit + def foo(): + z = 1 + for a, b in enumerate(z): + pass + return z + + with self.assertRaises(TypingError) as raises: + foo() + errmsg = str(raises.exception) + expected = "No match." + self.assertIn(expected, errmsg) + + ctx_lines = [x for x in errmsg.splitlines() if "During:" in x ] + search = [r'.*During: resolving callee type: Function.*enumerate', + r'.*During: typing of call .*test_typingerror.py'] + for i, x in enumerate(search): + self.assertTrue(re.search(x, ctx_lines[i])) + + +class TestArgumentTypingError(unittest.TestCase): + """ + Test diagnostics of typing errors caused by argument inference failure. + """ + + def test_unsupported_array_dtype(self): + # See issue #1943 + cfunc = jit(nopython=True)(nop) + a = np.ones(3) + a = a.astype(a.dtype.newbyteorder()) + with self.assertRaises(TypingError) as raises: + cfunc(1, a, a) + expected = f"Unsupported array dtype: {a.dtype}" + self.assertIn(expected, str(raises.exception)) + + def test_unsupported_type(self): + cfunc = jit(nopython=True)(nop) + foo = Foo() + with self.assertRaises(TypingError) as raises: + cfunc(1, foo, 1) + + expected=re.compile(("This error may have been caused by the following " + r"argument\(s\):\n- argument 1:.*Cannot determine " + "Numba type of " + "")) + self.assertTrue(expected.search(str(raises.exception)) is not None) + + +class TestCallError(unittest.TestCase): + def test_readonly_array(self): + @jit("(f8[:],)", nopython=True) + def inner(x): + return x + + @jit(nopython=True) + def outer(): + return inner(gvalues) + + gvalues = np.ones(10, dtype=np.float64) + + with self.assertRaises(TypingError) as raises: + outer() + + got = str(raises.exception) + pat = r"Invalid use of.*readonly array\(float64, 1d, C\)" + self.assertIsNotNone(re.search(pat, got)) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_unicode_names.py b/lib/python3.10/site-packages/numba/tests/test_unicode_names.py new file mode 100644 index 0000000000000000000000000000000000000000..0ed8fb756418ee993989ccded14f9b3cedb2521d --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_unicode_names.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- + + +from numba import njit, cfunc +from numba.tests.support import TestCase, unittest +from numba.core import cgutils + +unicode_name1 = u""" +def unicode_name1(ಠ_ರೃ, ಠਊಠ): + return (ಠ_ರೃ) + (ಠਊಠ) +""" + +unicode_name2 = u""" +def Ծ_Ծ(ಠ_ರೃ, ಠਊಠ): + return (ಠ_ರೃ) + (ಠਊಠ) +""" + + +class TestUnicodeNames(TestCase): + def make_testcase(self, src, fname): + glb = {} + exec(src, glb) + fn = glb[fname] + return fn + + def test_unicode_name1(self): + fn = self.make_testcase(unicode_name1, 'unicode_name1') + cfn = njit(fn) + self.assertEqual(cfn(1, 2), 3) + + def test_unicode_name2(self): + fn = self.make_testcase(unicode_name2, 'Ծ_Ծ') + cfn = njit(fn) + self.assertEqual(cfn(1, 2), 3) + + def test_cfunc(self): + fn = self.make_testcase(unicode_name2, 'Ծ_Ծ') + cfn = cfunc("int32(int32, int32)")(fn) + self.assertEqual(cfn.ctypes(1, 2), 3) + + +class TestUnicodeUtils(TestCase): + def test_normalize_ir_text(self): + # non-unicode input + out = cgutils.normalize_ir_text('abc') + # str returned + self.assertIsInstance(out, str) + # try encoding to latin + out.encode('latin1') + + def test_normalize_ir_text_unicode(self): + # unicode input + out = cgutils.normalize_ir_text(unicode_name2) + # str returned + self.assertIsInstance(out, str) + # try encoding to latin + out.encode('latin1') + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/test_usecases.py b/lib/python3.10/site-packages/numba/tests/test_usecases.py new file mode 100644 index 0000000000000000000000000000000000000000..bf58dabe9835c9ee579f751cf8a9478418daf7c7 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/test_usecases.py @@ -0,0 +1,192 @@ +import itertools +import unittest +import numpy as np + +from numba import jit, njit +from numba.core import types +from numba.tests import usecases +from numba.tests.support import TestCase + + +class TestUsecases(TestCase): + # NOTE: All these test cases are run in subprocesses to achieve total + # isolation. + + @TestCase.run_test_in_subprocess + def test_andor(self): + pyfunc = usecases.andor + cfunc = njit((types.int32, types.int32))(pyfunc) + + # Argument boundaries + xs = -1, 0, 1, 9, 10, 11 + ys = -1, 0, 1, 9, 10, 11 + + for args in itertools.product(xs, ys): + self.assertEqual(pyfunc(*args), cfunc(*args), "args %s" % (args,)) + + @TestCase.run_test_in_subprocess + def test_sum1d(self): + pyfunc = usecases.sum1d + cfunc = njit((types.int32, types.int32))(pyfunc) + + ss = -1, 0, 1, 100, 200 + es = -1, 0, 1, 100, 200 + + for args in itertools.product(ss, es): + self.assertEqual(pyfunc(*args), cfunc(*args), args) + + @TestCase.run_test_in_subprocess + def test_sum1d_pyobj(self): + pyfunc = usecases.sum1d + cfunc = jit((types.int32, types.int32), forceobj=True)(pyfunc) + + ss = -1, 0, 1, 100, 200 + es = -1, 0, 1, 100, 200 + + for args in itertools.product(ss, es): + self.assertEqual(pyfunc(*args), cfunc(*args), args) + + @TestCase.run_test_in_subprocess + def test_sum2d(self): + pyfunc = usecases.sum2d + cfunc = njit((types.int32, types.int32))(pyfunc) + + ss = -1, 0, 1, 100, 200 + es = -1, 0, 1, 100, 200 + + for args in itertools.product(ss, es): + self.assertEqual(pyfunc(*args), cfunc(*args), args) + + @TestCase.run_test_in_subprocess + def test_while_count(self): + pyfunc = usecases.while_count + cfunc = njit((types.int32, types.int32))(pyfunc) + + ss = -1, 0, 1, 100, 200 + es = -1, 0, 1, 100, 200 + + for args in itertools.product(ss, es): + self.assertEqual(pyfunc(*args), cfunc(*args), args) + + @TestCase.run_test_in_subprocess + def test_copy_arrays(self): + pyfunc = usecases.copy_arrays + arraytype = types.Array(types.int32, 1, 'A') + cfunc = njit((arraytype, arraytype))(pyfunc) + + nda = 0, 1, 10, 100 + + for nd in nda: + a = np.arange(nd, dtype='int32') + b = np.empty_like(a) + args = a, b + + cfunc(*args) + self.assertPreciseEqual(a, b, msg=str(args)) + + @TestCase.run_test_in_subprocess + def test_copy_arrays2d(self): + pyfunc = usecases.copy_arrays2d + arraytype = types.Array(types.int32, 2, 'A') + cfunc = njit((arraytype, arraytype))(pyfunc) + + nda = (0, 0), (1, 1), (2, 5), (4, 25) + + for nd in nda: + d1, d2 = nd + a = np.arange(d1 * d2, dtype='int32').reshape(d1, d2) + b = np.empty_like(a) + args = a, b + + cfunc(*args) + self.assertPreciseEqual(a, b, msg=str(args)) + + @TestCase.run_test_in_subprocess + def test_string_concat(self): + pyfunc = usecases.string_concat + cfunc = jit((types.int32, types.int32), forceobj=True)(pyfunc) + + xs = -1, 0, 1 + ys = -1, 0, 1 + + for x, y in itertools.product(xs, ys): + args = x, y + self.assertEqual(pyfunc(*args), cfunc(*args), args) + + @TestCase.run_test_in_subprocess + def test_string_len(self): + pyfunc = usecases.string_len + cfunc = jit((types.pyobject,), forceobj=True)(pyfunc) + + test_str = '123456' + self.assertEqual(pyfunc(test_str), cfunc(test_str)) + test_str = '1' + self.assertEqual(pyfunc(test_str), cfunc(test_str)) + test_str = '' + self.assertEqual(pyfunc(test_str), cfunc(test_str)) + + @TestCase.run_test_in_subprocess + def test_string_slicing(self): + pyfunc = usecases.string_slicing + cfunc = jit((types.pyobject,) * 3, forceobj=True)(pyfunc) + + test_str = '123456' + self.assertEqual(pyfunc(test_str, 0, 3), cfunc(test_str, 0, 3)) + self.assertEqual(pyfunc(test_str, 1, 5), cfunc(test_str, 1, 5)) + self.assertEqual(pyfunc(test_str, 2, 3), cfunc(test_str, 2, 3)) + + @TestCase.run_test_in_subprocess + def test_string_conversion(self): + pyfunc = usecases.string_conversion + + cfunc = jit((types.int32,), forceobj=True)(pyfunc) + self.assertEqual(pyfunc(1), cfunc(1)) + + cfunc = jit((types.float32,), forceobj=True)(pyfunc) + self.assertEqual(pyfunc(1.1), cfunc(1.1)) + + @TestCase.run_test_in_subprocess + def test_string_comparisons(self): + import operator + pyfunc = usecases.string_comparison + cfunc = jit((types.pyobject, types.pyobject, types.pyobject), + forceobj=True)(pyfunc) + + test_str1 = '123' + test_str2 = '123' + op = operator.eq + self.assertEqual(pyfunc(test_str1, test_str2, op), + cfunc(test_str1, test_str2, op)) + + test_str1 = '123' + test_str2 = '456' + op = operator.eq + self.assertEqual(pyfunc(test_str1, test_str2, op), + cfunc(test_str1, test_str2, op)) + + test_str1 = '123' + test_str2 = '123' + op = operator.ne + self.assertEqual(pyfunc(test_str1, test_str2, op), + cfunc(test_str1, test_str2, op)) + + test_str1 = '123' + test_str2 = '456' + op = operator.ne + self.assertEqual(pyfunc(test_str1, test_str2, op), + cfunc(test_str1, test_str2, op)) + + @TestCase.run_test_in_subprocess + def test_blackscholes_cnd(self): + pyfunc = usecases.blackscholes_cnd + cfunc = njit((types.float32,))(pyfunc) + + ds = -0.5, 0, 0.5 + + for d in ds: + args = (d,) + self.assertEqual(pyfunc(*args), cfunc(*args), args) + + +if __name__ == '__main__': + unittest.main() diff --git a/lib/python3.10/site-packages/numba/tests/typedlist_usecases.py b/lib/python3.10/site-packages/numba/tests/typedlist_usecases.py new file mode 100644 index 0000000000000000000000000000000000000000..249d3c66f3e30057246152c01ba69b70c13ae230 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/typedlist_usecases.py @@ -0,0 +1,14 @@ +from numba import int32 +from numba.typed import List + + +# global typed-list for testing purposes +global_typed_list = List.empty_list(int32) +for i in (1, 2, 3): + global_typed_list.append(int32(i)) + + +def catch_global(): + x = List() + for i in global_typed_list: + x.append(i) diff --git a/lib/python3.10/site-packages/numba/tests/usecases.py b/lib/python3.10/site-packages/numba/tests/usecases.py new file mode 100644 index 0000000000000000000000000000000000000000..7bdc3119b5dc1d875e79435828a8c616c96efab3 --- /dev/null +++ b/lib/python3.10/site-packages/numba/tests/usecases.py @@ -0,0 +1,93 @@ +import math +import numpy as np +from numba import jit + +_GLOBAL_STR = "abc" + +def sum1d(s, e): + c = 0 + for i in range(s, e): + c += i + return c + + +def sum2d(s, e): + c = 0 + for i in range(s, e): + for j in range(s, e): + c += i * j + return c + + +def while_count(s, e): + i = s + c = 0 + while i < e: + c += i + i += 1 + return c + + +def copy_arrays(a, b): + for i in range(a.shape[0]): + b[i] = a[i] + + +def copy_arrays2d(a, b): + for i in range(a.shape[0]): + for j in range(a.shape[1]): + b[i, j] = a[i, j] + + +def redefine1(): + x = 0 + for i in range(5): + x += 1 + x = 0. + x + for i in range(5): + x += 1 + return x + + +def andor(x, y): + return (x > 0 and x < 10) or (y > 0 and y < 10) + +andornopython = jit(nopython=True)(andor) + + +def string_concat(x, y): + a = "whatzup" + return a + str(x + y) + + +def string_len(s): + return len(s) + + +def string_slicing(s, start, stop): + return s[start:stop] + + +def string_conversion(x): + # the test that calls this has always relied on objmode fallback so force it + object() + return str(x) + + +def string_comparison(s1, s2, op): + return op(s1, s2) + + +def blackscholes_cnd(d): + A1 = 0.31938153 + A2 = -0.356563782 + A3 = 1.781477937 + A4 = -1.821255978 + A5 = 1.330274429 + RSQRT2PI = 0.39894228040143267793994605993438 + K = 1.0 / (1.0 + 0.2316419 * math.fabs(d)) + ret_val = (RSQRT2PI * math.exp(-0.5 * d * d) * + (K * (A1 + K * (A2 + K * (A3 + K * (A4 + K * A5)))))) + if d > 0: + ret_val = 1.0 - ret_val + return ret_val