Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/__pycache__/__init__.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/__pycache__/__main__.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/__pycache__/_version.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/__pycache__/extending.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/__pycache__/runtests.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__init__.py +61 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__main__.py +4 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/__init__.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/__main__.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/_runtests.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/loader.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/main.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/notebook.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/_runtests.py +114 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/loader.py +26 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/main.py +871 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/notebook.py +171 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_array_attr.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_cfunc.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_copy_propagate.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_indexing.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_llvm_pass_timings.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_npdatetime.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_numbers.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_numconv.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_python_int.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_storeslice.cpython-311.pyc +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/cfunc_cache_usecases.py +70 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/__init__.py +10 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_array_arg.py +51 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_basic.py +39 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_break_on_symbol.py +34 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_break_on_symbol_version.py +65 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_conditional_breakpoint.py +45 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_pretty_print.py +69 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/inlining_usecases.py +69 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/__init__.py +10 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/cache_usecases.py +76 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_caching.py +228 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_dufunc.py +1139 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_errors.py +174 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_gufunc.py +870 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_parallel_env_variable.py +38 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_parallel_low_work.py +44 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_parallel_ufunc_issues.py +130 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_ufunc.py +173 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_ufuncbuilding.py +471 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_update_inplace.py +122 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_vectorize_decor.py +151 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/ufuncbuilding_usecases.py +69 -0
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (8.63 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/__pycache__/__main__.cpython-311.pyc
ADDED
|
Binary file (479 Bytes). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/__pycache__/_version.cpython-311.pyc
ADDED
|
Binary file (599 Bytes). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/__pycache__/extending.cpython-311.pyc
ADDED
|
Binary file (288 Bytes). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/__pycache__/runtests.cpython-311.pyc
ADDED
|
Binary file (565 Bytes). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__init__.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import functools
|
| 4 |
+
import unittest
|
| 5 |
+
import traceback
|
| 6 |
+
from fnmatch import fnmatch
|
| 7 |
+
from os.path import join, isfile, relpath, normpath, splitext
|
| 8 |
+
|
| 9 |
+
from .main import NumbaTestProgram, SerialSuite, make_tag_decorator
|
| 10 |
+
from numba.core import config
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def load_testsuite(loader, dir):
|
| 14 |
+
"""Find tests in 'dir'."""
|
| 15 |
+
try:
|
| 16 |
+
suite = unittest.TestSuite()
|
| 17 |
+
files = []
|
| 18 |
+
for f in os.listdir(dir):
|
| 19 |
+
path = join(dir, f)
|
| 20 |
+
if isfile(path) and fnmatch(f, 'test_*.py'):
|
| 21 |
+
files.append(f)
|
| 22 |
+
elif isfile(join(path, '__init__.py')):
|
| 23 |
+
suite.addTests(loader.discover(path))
|
| 24 |
+
for f in files:
|
| 25 |
+
# turn 'f' into a filename relative to the toplevel dir...
|
| 26 |
+
f = relpath(join(dir, f), loader._top_level_dir)
|
| 27 |
+
# ...and translate it to a module name.
|
| 28 |
+
f = splitext(normpath(f.replace(os.path.sep, '.')))[0]
|
| 29 |
+
suite.addTests(loader.loadTestsFromName(f))
|
| 30 |
+
return suite
|
| 31 |
+
except Exception:
|
| 32 |
+
traceback.print_exc(file=sys.stderr)
|
| 33 |
+
sys.exit(-1)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def run_tests(argv=None, defaultTest=None, topleveldir=None,
|
| 37 |
+
xmloutput=None, verbosity=1, nomultiproc=False):
|
| 38 |
+
"""
|
| 39 |
+
args
|
| 40 |
+
----
|
| 41 |
+
- xmloutput [str or None]
|
| 42 |
+
Path of XML output directory (optional)
|
| 43 |
+
- verbosity [int]
|
| 44 |
+
Verbosity level of tests output
|
| 45 |
+
|
| 46 |
+
Returns the TestResult object after running the test *suite*.
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
if xmloutput is not None:
|
| 50 |
+
import xmlrunner
|
| 51 |
+
runner = xmlrunner.XMLTestRunner(output=xmloutput)
|
| 52 |
+
else:
|
| 53 |
+
runner = None
|
| 54 |
+
prog = NumbaTestProgram(argv=argv,
|
| 55 |
+
module=None,
|
| 56 |
+
defaultTest=defaultTest,
|
| 57 |
+
topleveldir=topleveldir,
|
| 58 |
+
testRunner=runner, exit=False,
|
| 59 |
+
verbosity=verbosity,
|
| 60 |
+
nomultiproc=nomultiproc)
|
| 61 |
+
return prog.result
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__main__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
from numba.testing import run_tests
|
| 3 |
+
|
| 4 |
+
sys.exit(0 if run_tests(sys.argv).wasSuccessful() else 1)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (3.09 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/__main__.cpython-311.pyc
ADDED
|
Binary file (471 Bytes). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/_runtests.cpython-311.pyc
ADDED
|
Binary file (6.9 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/loader.cpython-311.pyc
ADDED
|
Binary file (2.49 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/main.cpython-311.pyc
ADDED
|
Binary file (46.8 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/notebook.cpython-311.pyc
ADDED
|
Binary file (8.83 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/_runtests.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
import logging
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def _main(argv, **kwds):
|
| 7 |
+
from numba.testing import run_tests
|
| 8 |
+
# This helper function assumes the first element of argv
|
| 9 |
+
# is the name of the calling program.
|
| 10 |
+
# The 'main' API function is invoked in-process, and thus
|
| 11 |
+
# will synthesize that name.
|
| 12 |
+
|
| 13 |
+
if '--log' in argv:
|
| 14 |
+
logging.basicConfig(level=logging.DEBUG)
|
| 15 |
+
argv.remove('--log')
|
| 16 |
+
|
| 17 |
+
if '--failed-first' in argv:
|
| 18 |
+
# Failed first
|
| 19 |
+
argv.remove('--failed-first')
|
| 20 |
+
return _FailedFirstRunner().main(argv, kwds)
|
| 21 |
+
elif '--last-failed' in argv:
|
| 22 |
+
argv.remove('--last-failed')
|
| 23 |
+
return _FailedFirstRunner(last_failed=True).main(argv, kwds)
|
| 24 |
+
else:
|
| 25 |
+
return run_tests(argv, defaultTest='numba.tests',
|
| 26 |
+
**kwds).wasSuccessful()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def main(*argv, **kwds):
|
| 30 |
+
"""keyword arguments are accepted for backward compatibility only.
|
| 31 |
+
See `numba.testing.run_tests()` documentation for details."""
|
| 32 |
+
return _main(['<main>'] + list(argv), **kwds)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class _FailedFirstRunner(object):
|
| 36 |
+
"""
|
| 37 |
+
Test Runner to handle the failed-first (--failed-first) option.
|
| 38 |
+
"""
|
| 39 |
+
cache_filename = '.runtests_lastfailed'
|
| 40 |
+
|
| 41 |
+
def __init__(self, last_failed=False):
|
| 42 |
+
self.last_failed = last_failed
|
| 43 |
+
|
| 44 |
+
def main(self, argv, kwds):
|
| 45 |
+
from numba.testing import run_tests
|
| 46 |
+
prog = argv[0]
|
| 47 |
+
argv = argv[1:]
|
| 48 |
+
flags = [a for a in argv if a.startswith('-')]
|
| 49 |
+
|
| 50 |
+
all_tests, failed_tests = self.find_last_failed(argv)
|
| 51 |
+
# Prepare tests to run
|
| 52 |
+
if failed_tests:
|
| 53 |
+
ft = "There were {} previously failed tests"
|
| 54 |
+
print(ft.format(len(failed_tests)))
|
| 55 |
+
remaing_tests = [t for t in all_tests
|
| 56 |
+
if t not in failed_tests]
|
| 57 |
+
if self.last_failed:
|
| 58 |
+
tests = list(failed_tests)
|
| 59 |
+
else:
|
| 60 |
+
tests = failed_tests + remaing_tests
|
| 61 |
+
else:
|
| 62 |
+
if self.last_failed:
|
| 63 |
+
tests = []
|
| 64 |
+
else:
|
| 65 |
+
tests = list(all_tests)
|
| 66 |
+
|
| 67 |
+
if not tests:
|
| 68 |
+
print("No tests to run")
|
| 69 |
+
return True
|
| 70 |
+
# Run the testsuite
|
| 71 |
+
print("Running {} tests".format(len(tests)))
|
| 72 |
+
print('Flags', flags)
|
| 73 |
+
result = run_tests([prog] + flags + tests, **kwds)
|
| 74 |
+
# Update failed tests records only if we have run the all the tests
|
| 75 |
+
# last failed.
|
| 76 |
+
if len(tests) == result.testsRun:
|
| 77 |
+
self.save_failed_tests(result, all_tests)
|
| 78 |
+
return result.wasSuccessful()
|
| 79 |
+
|
| 80 |
+
def save_failed_tests(self, result, all_tests):
|
| 81 |
+
print("Saving failed tests to {}".format(self.cache_filename))
|
| 82 |
+
cache = []
|
| 83 |
+
# Find failed tests
|
| 84 |
+
failed = set()
|
| 85 |
+
for case in result.errors + result.failures:
|
| 86 |
+
failed.add(case[0].id())
|
| 87 |
+
# Build cache
|
| 88 |
+
for t in all_tests:
|
| 89 |
+
if t in failed:
|
| 90 |
+
cache.append(t)
|
| 91 |
+
# Write cache
|
| 92 |
+
with open(self.cache_filename, 'w') as fout:
|
| 93 |
+
json.dump(cache, fout)
|
| 94 |
+
|
| 95 |
+
def find_last_failed(self, argv):
|
| 96 |
+
from numba.tests.support import captured_output
|
| 97 |
+
|
| 98 |
+
# Find all tests
|
| 99 |
+
listargv = ['-l'] + [a for a in argv if not a.startswith('-')]
|
| 100 |
+
with captured_output("stdout") as stream:
|
| 101 |
+
main(*listargv)
|
| 102 |
+
|
| 103 |
+
pat = re.compile(r"^(\w+\.)+\w+$")
|
| 104 |
+
lines = stream.getvalue().splitlines()
|
| 105 |
+
all_tests = [x for x in lines if pat.match(x) is not None]
|
| 106 |
+
|
| 107 |
+
try:
|
| 108 |
+
fobj = open(self.cache_filename)
|
| 109 |
+
except OSError:
|
| 110 |
+
failed_tests = []
|
| 111 |
+
else:
|
| 112 |
+
with fobj as fin:
|
| 113 |
+
failed_tests = json.load(fin)
|
| 114 |
+
return all_tests, failed_tests
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/loader.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from unittest import loader, case
|
| 2 |
+
from os.path import isdir, isfile, join, dirname, basename
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class TestLoader(loader.TestLoader):
|
| 6 |
+
|
| 7 |
+
def __init__(self, topleveldir=None):
|
| 8 |
+
super(TestLoader, self).__init__()
|
| 9 |
+
self._top_level_dir = topleveldir or dirname(dirname(dirname(__file__)))
|
| 10 |
+
|
| 11 |
+
def _find_tests(self, start_dir, pattern, namespace=False):
|
| 12 |
+
# Upstream doesn't look for 'load_tests' in start_dir.
|
| 13 |
+
|
| 14 |
+
if isdir(start_dir) and not namespace and isfile(join(start_dir, '__init__.py')):
|
| 15 |
+
name = self._get_name_from_path(start_dir)
|
| 16 |
+
package = self._get_module_from_name(name)
|
| 17 |
+
load_tests = getattr(package, 'load_tests', None)
|
| 18 |
+
tests = self.loadTestsFromModule(package)
|
| 19 |
+
if load_tests is not None:
|
| 20 |
+
try:
|
| 21 |
+
yield load_tests(self, tests, pattern)
|
| 22 |
+
except Exception as e:
|
| 23 |
+
yield loader._make_failed_load_tests(package.__name__, e, self.suiteClass)
|
| 24 |
+
else:
|
| 25 |
+
for t in super(TestLoader, self)._find_tests(start_dir, pattern):
|
| 26 |
+
yield t
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/main.py
ADDED
|
@@ -0,0 +1,871 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import collections
|
| 2 |
+
import contextlib
|
| 3 |
+
import cProfile
|
| 4 |
+
import inspect
|
| 5 |
+
import gc
|
| 6 |
+
import multiprocessing
|
| 7 |
+
import os
|
| 8 |
+
import random
|
| 9 |
+
import sys
|
| 10 |
+
import time
|
| 11 |
+
import unittest
|
| 12 |
+
import warnings
|
| 13 |
+
import zlib
|
| 14 |
+
import traceback
|
| 15 |
+
|
| 16 |
+
from functools import lru_cache
|
| 17 |
+
from io import StringIO
|
| 18 |
+
from unittest import result, runner, signals, suite, loader, case
|
| 19 |
+
|
| 20 |
+
from .loader import TestLoader
|
| 21 |
+
from numba.core import config
|
| 22 |
+
from numba.misc import memoryutils
|
| 23 |
+
|
| 24 |
+
try:
|
| 25 |
+
from multiprocessing import TimeoutError
|
| 26 |
+
except ImportError:
|
| 27 |
+
from Queue import Empty as TimeoutError
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def make_tag_decorator(known_tags):
|
| 31 |
+
"""
|
| 32 |
+
Create a decorator allowing tests to be tagged with the *known_tags*.
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
def tag(*tags):
|
| 36 |
+
"""
|
| 37 |
+
Tag a test method with the given tags.
|
| 38 |
+
Can be used in conjunction with the --tags command-line argument
|
| 39 |
+
for runtests.py.
|
| 40 |
+
"""
|
| 41 |
+
for t in tags:
|
| 42 |
+
if t not in known_tags:
|
| 43 |
+
raise ValueError("unknown tag: %r" % (t,))
|
| 44 |
+
|
| 45 |
+
def decorate(func):
|
| 46 |
+
if (not callable(func) or isinstance(func, type)
|
| 47 |
+
or not func.__name__.startswith('test_')):
|
| 48 |
+
raise TypeError("@tag(...) should be used on test methods")
|
| 49 |
+
try:
|
| 50 |
+
s = func.tags
|
| 51 |
+
except AttributeError:
|
| 52 |
+
s = func.tags = set()
|
| 53 |
+
s.update(tags)
|
| 54 |
+
return func
|
| 55 |
+
return decorate
|
| 56 |
+
|
| 57 |
+
return tag
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
# Chances are the next queried class is the same as the previous, locally 128
|
| 61 |
+
# entries seems to be fastest.
|
| 62 |
+
# Current number of test classes can be found with:
|
| 63 |
+
# $ ./runtests.py -l|sed -e 's/\(.*\)\..*/\1/'|grep ^numba|sort|uniq|wc -l
|
| 64 |
+
# as of writing it's 658.
|
| 65 |
+
@lru_cache(maxsize=128)
|
| 66 |
+
def _get_mtime(cls):
|
| 67 |
+
"""
|
| 68 |
+
Gets the mtime of the file in which a test class is defined.
|
| 69 |
+
"""
|
| 70 |
+
return str(os.path.getmtime(inspect.getfile(cls)))
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def cuda_sensitive_mtime(x):
|
| 74 |
+
"""
|
| 75 |
+
Return a key for sorting tests bases on mtime and test name. For CUDA
|
| 76 |
+
tests, interleaving tests from different classes is dangerous as the CUDA
|
| 77 |
+
context might get reset unexpectedly between methods of a class, so for
|
| 78 |
+
CUDA tests the key prioritises the test module and class ahead of the
|
| 79 |
+
mtime.
|
| 80 |
+
"""
|
| 81 |
+
cls = x.__class__
|
| 82 |
+
key = _get_mtime(cls) + str(x)
|
| 83 |
+
|
| 84 |
+
from numba.cuda.testing import CUDATestCase
|
| 85 |
+
if CUDATestCase in cls.mro():
|
| 86 |
+
key = "%s.%s %s" % (str(cls.__module__), str(cls.__name__), key)
|
| 87 |
+
|
| 88 |
+
return key
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def parse_slice(useslice):
|
| 92 |
+
"""Parses the argument string "useslice" as a shard index and number and
|
| 93 |
+
returns a function that filters on those arguments. i.e. input
|
| 94 |
+
useslice="1:3" leads to output something like `lambda x: zlib.crc32(x) % 3
|
| 95 |
+
== 1`.
|
| 96 |
+
"""
|
| 97 |
+
if callable(useslice):
|
| 98 |
+
return useslice
|
| 99 |
+
if not useslice:
|
| 100 |
+
return lambda x: True
|
| 101 |
+
try:
|
| 102 |
+
(index, count) = useslice.split(":")
|
| 103 |
+
index = int(index)
|
| 104 |
+
count = int(count)
|
| 105 |
+
except Exception:
|
| 106 |
+
msg = (
|
| 107 |
+
"Expected arguments shard index and count to follow "
|
| 108 |
+
"option `-j i:t`, where i is the shard number and t "
|
| 109 |
+
"is the total number of shards, found '%s'" % useslice)
|
| 110 |
+
raise ValueError(msg)
|
| 111 |
+
if count == 0:
|
| 112 |
+
return lambda x: True
|
| 113 |
+
elif count < 0 or index < 0 or index >= count:
|
| 114 |
+
raise ValueError("Sharding out of range")
|
| 115 |
+
else:
|
| 116 |
+
def decide(test):
|
| 117 |
+
func = getattr(test, test._testMethodName)
|
| 118 |
+
if "always_test" in getattr(func, 'tags', {}):
|
| 119 |
+
return True
|
| 120 |
+
return abs(zlib.crc32(test.id().encode('utf-8'))) % count == index
|
| 121 |
+
return decide
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class TestLister(object):
|
| 125 |
+
"""Simply list available tests rather than running them."""
|
| 126 |
+
def __init__(self, useslice):
|
| 127 |
+
self.useslice = parse_slice(useslice)
|
| 128 |
+
|
| 129 |
+
def run(self, test):
|
| 130 |
+
result = runner.TextTestResult(sys.stderr, descriptions=True,
|
| 131 |
+
verbosity=1)
|
| 132 |
+
self._test_list = _flatten_suite(test)
|
| 133 |
+
masked_list = list(filter(self.useslice, self._test_list))
|
| 134 |
+
self._test_list.sort(key=cuda_sensitive_mtime)
|
| 135 |
+
for t in masked_list:
|
| 136 |
+
print(t.id())
|
| 137 |
+
print('%d tests found. %s selected' % (len(self._test_list),
|
| 138 |
+
len(masked_list)))
|
| 139 |
+
return result
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class SerialSuite(unittest.TestSuite):
|
| 143 |
+
"""A simple marker to make sure tests in this suite are run serially.
|
| 144 |
+
|
| 145 |
+
Note: As the suite is going through internals of unittest,
|
| 146 |
+
it may get unpacked and stuffed into a plain TestSuite.
|
| 147 |
+
We need to set an attribute on the TestCase objects to
|
| 148 |
+
remember they should not be run in parallel.
|
| 149 |
+
"""
|
| 150 |
+
|
| 151 |
+
def __init__(self, tests=()):
|
| 152 |
+
super(SerialSuite, self).__init__(tests)
|
| 153 |
+
self.resource_infos = []
|
| 154 |
+
|
| 155 |
+
def addTest(self, test):
|
| 156 |
+
if not isinstance(test, unittest.TestCase):
|
| 157 |
+
# It's a sub-suite, recurse
|
| 158 |
+
for t in test:
|
| 159 |
+
self.addTest(t)
|
| 160 |
+
else:
|
| 161 |
+
# It's a test case, mark it serial
|
| 162 |
+
test._numba_parallel_test_ = False
|
| 163 |
+
super(SerialSuite, self).addTest(test)
|
| 164 |
+
|
| 165 |
+
def run(self, result):
|
| 166 |
+
# Run each test with memory tracking
|
| 167 |
+
for test in self:
|
| 168 |
+
if result.shouldStop:
|
| 169 |
+
break
|
| 170 |
+
memtrack = memoryutils.MemoryTracker(test.id())
|
| 171 |
+
with memtrack.monitor():
|
| 172 |
+
test(result)
|
| 173 |
+
self.resource_infos.append(memtrack.get_summary())
|
| 174 |
+
return result
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
class BasicTestRunner(runner.TextTestRunner):
|
| 178 |
+
def __init__(self, useslice, **kwargs):
|
| 179 |
+
runner.TextTestRunner.__init__(self, **kwargs)
|
| 180 |
+
self.useslice = parse_slice(useslice)
|
| 181 |
+
|
| 182 |
+
def run(self, test):
|
| 183 |
+
run = list(filter(self.useslice, _flatten_suite(test)))
|
| 184 |
+
run.sort(key=cuda_sensitive_mtime)
|
| 185 |
+
wrapped = unittest.TestSuite(run)
|
| 186 |
+
return super(BasicTestRunner, self).run(wrapped)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
# "unittest.main" is really the TestProgram class!
|
| 190 |
+
# (defined in a module named itself "unittest.main"...)
|
| 191 |
+
|
| 192 |
+
class NumbaTestProgram(unittest.main):
|
| 193 |
+
"""
|
| 194 |
+
A TestProgram subclass adding the following options:
|
| 195 |
+
* a -R option to enable reference leak detection
|
| 196 |
+
* a --profile option to enable profiling of the test run
|
| 197 |
+
* a -m option for parallel execution
|
| 198 |
+
* a -l option to (only) list tests
|
| 199 |
+
|
| 200 |
+
Currently the options are only added in 3.4+.
|
| 201 |
+
"""
|
| 202 |
+
|
| 203 |
+
refleak = False
|
| 204 |
+
profile = False
|
| 205 |
+
multiprocess = False
|
| 206 |
+
useslice = None
|
| 207 |
+
list = False
|
| 208 |
+
tags = None
|
| 209 |
+
exclude_tags = None
|
| 210 |
+
random_select = None
|
| 211 |
+
random_seed = 42
|
| 212 |
+
|
| 213 |
+
def __init__(self, *args, **kwargs):
|
| 214 |
+
topleveldir = kwargs.pop('topleveldir', None)
|
| 215 |
+
kwargs['testLoader'] = TestLoader(topleveldir)
|
| 216 |
+
|
| 217 |
+
# HACK to force unittest not to change warning display options
|
| 218 |
+
# (so that NumbaWarnings don't appear all over the place)
|
| 219 |
+
sys.warnoptions.append(':x')
|
| 220 |
+
self.nomultiproc = kwargs.pop('nomultiproc', False)
|
| 221 |
+
super(NumbaTestProgram, self).__init__(*args, **kwargs)
|
| 222 |
+
|
| 223 |
+
def _getParentArgParser(self):
|
| 224 |
+
# NOTE: this hook only exists on Python 3.4+. The options won't be
|
| 225 |
+
# added in earlier versions (which use optparse - 3.3 - or getopt()
|
| 226 |
+
# - 2.x).
|
| 227 |
+
parser = super(NumbaTestProgram, self)._getParentArgParser()
|
| 228 |
+
if self.testRunner is None:
|
| 229 |
+
parser.add_argument('-R', '--refleak', dest='refleak',
|
| 230 |
+
action='store_true',
|
| 231 |
+
help='Detect reference / memory leaks')
|
| 232 |
+
parser.add_argument('-m', '--multiprocess', dest='multiprocess',
|
| 233 |
+
nargs='?',
|
| 234 |
+
type=int,
|
| 235 |
+
const=multiprocessing.cpu_count(),
|
| 236 |
+
help='Parallelize tests')
|
| 237 |
+
parser.add_argument('-l', '--list', dest='list',
|
| 238 |
+
action='store_true',
|
| 239 |
+
help='List tests without running them')
|
| 240 |
+
parser.add_argument('--tags', dest='tags', type=str,
|
| 241 |
+
help='Comma-separated list of tags to select '
|
| 242 |
+
'a subset of the test suite')
|
| 243 |
+
parser.add_argument('--exclude-tags', dest='exclude_tags', type=str,
|
| 244 |
+
help='Comma-separated list of tags to de-select '
|
| 245 |
+
'a subset of the test suite')
|
| 246 |
+
parser.add_argument('--random', dest='random_select', type=float,
|
| 247 |
+
help='Random proportion of tests to select')
|
| 248 |
+
parser.add_argument('--profile', dest='profile',
|
| 249 |
+
action='store_true',
|
| 250 |
+
help='Profile the test run')
|
| 251 |
+
parser.add_argument('-j', '--slice', dest='useslice', nargs='?',
|
| 252 |
+
type=str, const="None",
|
| 253 |
+
help='Shard the test sequence')
|
| 254 |
+
|
| 255 |
+
def git_diff_str(x):
|
| 256 |
+
if x != 'ancestor':
|
| 257 |
+
raise ValueError("invalid option for --gitdiff")
|
| 258 |
+
return x
|
| 259 |
+
|
| 260 |
+
parser.add_argument('-g', '--gitdiff', dest='gitdiff', type=git_diff_str,
|
| 261 |
+
default=False, nargs='?',
|
| 262 |
+
help=('Run tests from changes made against '
|
| 263 |
+
'origin/release0.65 as identified by `git diff`. '
|
| 264 |
+
'If set to "ancestor", the diff compares '
|
| 265 |
+
'against the common ancestor.'))
|
| 266 |
+
return parser
|
| 267 |
+
|
| 268 |
+
def _handle_tags(self, argv, tagstr):
|
| 269 |
+
found = None
|
| 270 |
+
for x in argv:
|
| 271 |
+
if tagstr in x:
|
| 272 |
+
if found is None:
|
| 273 |
+
found = x
|
| 274 |
+
else:
|
| 275 |
+
raise ValueError("argument %s supplied repeatedly" % tagstr)
|
| 276 |
+
|
| 277 |
+
if found is not None:
|
| 278 |
+
posn = argv.index(found)
|
| 279 |
+
try:
|
| 280 |
+
if found == tagstr: # --tagstr <arg>
|
| 281 |
+
tag_args = argv[posn + 1].strip()
|
| 282 |
+
argv.remove(tag_args)
|
| 283 |
+
else: # --tagstr=<arg>
|
| 284 |
+
if '=' in found:
|
| 285 |
+
tag_args = found.split('=')[1].strip()
|
| 286 |
+
else:
|
| 287 |
+
raise AssertionError('unreachable')
|
| 288 |
+
except IndexError:
|
| 289 |
+
# at end of arg list, raise
|
| 290 |
+
msg = "%s requires at least one tag to be specified"
|
| 291 |
+
raise ValueError(msg % tagstr)
|
| 292 |
+
# see if next arg is "end options" or some other flag
|
| 293 |
+
if tag_args.startswith('-'):
|
| 294 |
+
raise ValueError("tag starts with '-', probably a syntax error")
|
| 295 |
+
# see if tag is something like "=<tagname>" which is likely a syntax
|
| 296 |
+
# error of form `--tags =<tagname>`, note the space prior to `=`.
|
| 297 |
+
if '=' in tag_args:
|
| 298 |
+
msg = "%s argument contains '=', probably a syntax error"
|
| 299 |
+
raise ValueError(msg % tagstr)
|
| 300 |
+
attr = tagstr[2:].replace('-', '_')
|
| 301 |
+
setattr(self, attr, tag_args)
|
| 302 |
+
argv.remove(found)
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def parseArgs(self, argv):
|
| 306 |
+
if '-l' in argv:
|
| 307 |
+
argv.remove('-l')
|
| 308 |
+
self.list = True
|
| 309 |
+
|
| 310 |
+
super(NumbaTestProgram, self).parseArgs(argv)
|
| 311 |
+
|
| 312 |
+
# If at this point self.test doesn't exist, it is because
|
| 313 |
+
# no test ID was given in argv. Use the default instead.
|
| 314 |
+
if not hasattr(self, 'test') or not self.test.countTestCases():
|
| 315 |
+
self.testNames = (self.defaultTest,)
|
| 316 |
+
self.createTests()
|
| 317 |
+
|
| 318 |
+
if self.tags:
|
| 319 |
+
tags = [s.strip() for s in self.tags.split(',')]
|
| 320 |
+
self.test = _choose_tagged_tests(self.test, tags, mode='include')
|
| 321 |
+
|
| 322 |
+
if self.exclude_tags:
|
| 323 |
+
tags = [s.strip() for s in self.exclude_tags.split(',')]
|
| 324 |
+
self.test = _choose_tagged_tests(self.test, tags, mode='exclude')
|
| 325 |
+
|
| 326 |
+
if self.random_select:
|
| 327 |
+
self.test = _choose_random_tests(self.test, self.random_select,
|
| 328 |
+
self.random_seed)
|
| 329 |
+
|
| 330 |
+
if self.gitdiff is not False:
|
| 331 |
+
self.test = _choose_gitdiff_tests(
|
| 332 |
+
self.test,
|
| 333 |
+
use_common_ancestor=(self.gitdiff == 'ancestor'),
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
if self.verbosity <= 0:
|
| 337 |
+
# We aren't interested in informational messages / warnings when
|
| 338 |
+
# running with '-q'.
|
| 339 |
+
self.buffer = True
|
| 340 |
+
|
| 341 |
+
def _do_discovery(self, argv, Loader=None):
|
| 342 |
+
# Disable unittest's implicit test discovery when parsing
|
| 343 |
+
# CLI arguments, as it can select other tests than Numba's
|
| 344 |
+
# (e.g. some test_xxx module that may happen to be directly
|
| 345 |
+
# reachable from sys.path)
|
| 346 |
+
return
|
| 347 |
+
|
| 348 |
+
def runTests(self):
|
| 349 |
+
if self.refleak:
|
| 350 |
+
self.testRunner = RefleakTestRunner
|
| 351 |
+
|
| 352 |
+
if not hasattr(sys, "gettotalrefcount"):
|
| 353 |
+
warnings.warn("detecting reference leaks requires a debug build "
|
| 354 |
+
"of Python, only memory leaks will be detected")
|
| 355 |
+
|
| 356 |
+
elif self.list:
|
| 357 |
+
self.testRunner = TestLister(self.useslice)
|
| 358 |
+
|
| 359 |
+
elif self.testRunner is None:
|
| 360 |
+
self.testRunner = BasicTestRunner(self.useslice,
|
| 361 |
+
verbosity=self.verbosity,
|
| 362 |
+
failfast=self.failfast,
|
| 363 |
+
buffer=self.buffer)
|
| 364 |
+
|
| 365 |
+
if self.multiprocess and not self.nomultiproc:
|
| 366 |
+
if self.multiprocess < 1:
|
| 367 |
+
msg = ("Value specified for the number of processes to use in "
|
| 368 |
+
"running the suite must be > 0")
|
| 369 |
+
raise ValueError(msg)
|
| 370 |
+
self.testRunner = ParallelTestRunner(runner.TextTestRunner,
|
| 371 |
+
self.multiprocess,
|
| 372 |
+
self.useslice,
|
| 373 |
+
verbosity=self.verbosity,
|
| 374 |
+
failfast=self.failfast,
|
| 375 |
+
buffer=self.buffer)
|
| 376 |
+
|
| 377 |
+
def run_tests_real():
|
| 378 |
+
super(NumbaTestProgram, self).runTests()
|
| 379 |
+
|
| 380 |
+
if self.profile:
|
| 381 |
+
filename = os.path.splitext(
|
| 382 |
+
os.path.basename(sys.modules['__main__'].__file__)
|
| 383 |
+
)[0] + '.prof'
|
| 384 |
+
p = cProfile.Profile(timer=time.perf_counter) # 3.3+
|
| 385 |
+
p.enable()
|
| 386 |
+
try:
|
| 387 |
+
p.runcall(run_tests_real)
|
| 388 |
+
finally:
|
| 389 |
+
p.disable()
|
| 390 |
+
print("Writing test profile data into %r" % (filename,))
|
| 391 |
+
p.dump_stats(filename)
|
| 392 |
+
else:
|
| 393 |
+
run_tests_real()
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
# These are tests which are generated and injected into the test suite, what
|
| 397 |
+
# gets injected depends on features of the test environment, e.g. TBB presence
|
| 398 |
+
# it's important for doing the CI "slice tests" that these are run at the end
|
| 399 |
+
# See notes in `_flatten_suite` for why. Simple substring matching is used to
|
| 400 |
+
# determine a match.
|
| 401 |
+
_GENERATED = (
|
| 402 |
+
"numba.cuda.tests.cudapy.test_libdevice.TestLibdeviceCompilation",
|
| 403 |
+
"numba.tests.test_num_threads",
|
| 404 |
+
"numba.tests.test_parallel_backend",
|
| 405 |
+
"numba.tests.test_svml",
|
| 406 |
+
"numba.tests.test_ufuncs",
|
| 407 |
+
)
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def _flatten_suite_inner(test):
|
| 411 |
+
"""
|
| 412 |
+
Workhorse for _flatten_suite
|
| 413 |
+
"""
|
| 414 |
+
tests = []
|
| 415 |
+
if isinstance(test, (unittest.TestSuite, list, tuple)):
|
| 416 |
+
for x in test:
|
| 417 |
+
tests.extend(_flatten_suite_inner(x))
|
| 418 |
+
else:
|
| 419 |
+
tests.append(test)
|
| 420 |
+
return tests
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
def _flatten_suite(test):
|
| 424 |
+
"""
|
| 425 |
+
Expand nested suite into list of test cases.
|
| 426 |
+
"""
|
| 427 |
+
tests = _flatten_suite_inner(test)
|
| 428 |
+
# Strip out generated tests and stick them at the end, this is to make sure
|
| 429 |
+
# that tests appear in a consistent order regardless of features available.
|
| 430 |
+
# This is so that a slice through the test suite e.g. (1::N) would likely be
|
| 431 |
+
# consistent up to the point of the generated tests, which rely on specific
|
| 432 |
+
# features.
|
| 433 |
+
generated = set()
|
| 434 |
+
for t in tests:
|
| 435 |
+
for g in _GENERATED:
|
| 436 |
+
if g in str(t):
|
| 437 |
+
generated.add(t)
|
| 438 |
+
normal = set(tests) - generated
|
| 439 |
+
def key(x):
|
| 440 |
+
return x.__module__, type(x).__name__, x._testMethodName
|
| 441 |
+
tests = sorted(normal, key=key)
|
| 442 |
+
tests.extend(sorted(list(generated), key=key))
|
| 443 |
+
return tests
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
def _choose_gitdiff_tests(tests, *, use_common_ancestor=False):
|
| 447 |
+
try:
|
| 448 |
+
from git import Repo
|
| 449 |
+
except ImportError:
|
| 450 |
+
raise ValueError("gitpython needed for git functionality")
|
| 451 |
+
repo = Repo('.')
|
| 452 |
+
path = os.path.join('numba', 'tests')
|
| 453 |
+
if use_common_ancestor:
|
| 454 |
+
print(f"Git diff by common ancestor")
|
| 455 |
+
target = 'origin/release0.65...HEAD'
|
| 456 |
+
else:
|
| 457 |
+
target = 'origin/release0.65..HEAD'
|
| 458 |
+
gdiff_paths = repo.git.diff(target, path, name_only=True).split()
|
| 459 |
+
# normalise the paths as they are unix style from repo.git.diff
|
| 460 |
+
gdiff_paths = [os.path.normpath(x) for x in gdiff_paths]
|
| 461 |
+
selected = []
|
| 462 |
+
gdiff_paths = [os.path.join(repo.working_dir, x) for x in gdiff_paths]
|
| 463 |
+
for test in _flatten_suite(tests):
|
| 464 |
+
assert isinstance(test, unittest.TestCase)
|
| 465 |
+
fname = inspect.getsourcefile(test.__class__)
|
| 466 |
+
if fname in gdiff_paths:
|
| 467 |
+
selected.append(test)
|
| 468 |
+
print("Git diff identified %s tests" % len(selected))
|
| 469 |
+
return unittest.TestSuite(selected)
|
| 470 |
+
|
| 471 |
+
def _choose_tagged_tests(tests, tags, mode='include'):
|
| 472 |
+
"""
|
| 473 |
+
Select tests that are tagged/not tagged with at least one of the given tags.
|
| 474 |
+
Set mode to 'include' to include the tests with tags, or 'exclude' to
|
| 475 |
+
exclude the tests with the tags.
|
| 476 |
+
"""
|
| 477 |
+
selected = []
|
| 478 |
+
tags = set(tags)
|
| 479 |
+
for test in _flatten_suite(tests):
|
| 480 |
+
assert isinstance(test, unittest.TestCase)
|
| 481 |
+
func = getattr(test, test._testMethodName)
|
| 482 |
+
try:
|
| 483 |
+
# Look up the method's underlying function (Python 2)
|
| 484 |
+
func = func.im_func
|
| 485 |
+
except AttributeError:
|
| 486 |
+
pass
|
| 487 |
+
|
| 488 |
+
found_tags = getattr(func, 'tags', None)
|
| 489 |
+
# only include the test if the tags *are* present
|
| 490 |
+
if mode == 'include':
|
| 491 |
+
if found_tags is not None and found_tags & tags:
|
| 492 |
+
selected.append(test)
|
| 493 |
+
elif mode == 'exclude':
|
| 494 |
+
# only include the test if the tags *are not* present
|
| 495 |
+
if found_tags is None or not (found_tags & tags):
|
| 496 |
+
selected.append(test)
|
| 497 |
+
else:
|
| 498 |
+
raise ValueError("Invalid 'mode' supplied: %s." % mode)
|
| 499 |
+
return unittest.TestSuite(selected)
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
def _choose_random_tests(tests, ratio, seed):
|
| 503 |
+
"""
|
| 504 |
+
Choose a given proportion of tests at random.
|
| 505 |
+
"""
|
| 506 |
+
rnd = random.Random()
|
| 507 |
+
rnd.seed(seed)
|
| 508 |
+
if isinstance(tests, unittest.TestSuite):
|
| 509 |
+
tests = _flatten_suite(tests)
|
| 510 |
+
tests = rnd.sample(tests, int(len(tests) * ratio))
|
| 511 |
+
tests = sorted(tests, key=lambda case: case.id())
|
| 512 |
+
return unittest.TestSuite(tests)
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
# The reference leak detection code is liberally taken and adapted from
|
| 516 |
+
# Python's own Lib/test/regrtest.py.
|
| 517 |
+
|
| 518 |
+
def _refleak_cleanup():
|
| 519 |
+
# Collect cyclic trash and read memory statistics immediately after.
|
| 520 |
+
func1 = sys.getallocatedblocks
|
| 521 |
+
try:
|
| 522 |
+
func2 = sys.gettotalrefcount
|
| 523 |
+
except AttributeError:
|
| 524 |
+
func2 = lambda: 42
|
| 525 |
+
|
| 526 |
+
# Flush standard output, so that buffered data is sent to the OS and
|
| 527 |
+
# associated Python objects are reclaimed.
|
| 528 |
+
for stream in (sys.stdout, sys.stderr, sys.__stdout__, sys.__stderr__):
|
| 529 |
+
if stream is not None:
|
| 530 |
+
stream.flush()
|
| 531 |
+
|
| 532 |
+
sys._clear_type_cache()
|
| 533 |
+
# This also clears the various internal CPython freelists.
|
| 534 |
+
gc.collect()
|
| 535 |
+
return func1(), func2()
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
class ReferenceLeakError(RuntimeError):
|
| 539 |
+
pass
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
class IntPool(collections.defaultdict):
|
| 543 |
+
|
| 544 |
+
def __missing__(self, key):
|
| 545 |
+
return key
|
| 546 |
+
|
| 547 |
+
|
| 548 |
+
class RefleakTestResult(runner.TextTestResult):
|
| 549 |
+
|
| 550 |
+
warmup = 3
|
| 551 |
+
repetitions = 6
|
| 552 |
+
|
| 553 |
+
def _huntLeaks(self, test):
|
| 554 |
+
self.stream.flush()
|
| 555 |
+
|
| 556 |
+
repcount = self.repetitions
|
| 557 |
+
nwarmup = self.warmup
|
| 558 |
+
rc_deltas = [0] * (repcount - nwarmup)
|
| 559 |
+
alloc_deltas = [0] * (repcount - nwarmup)
|
| 560 |
+
# Preallocate ints likely to be stored in rc_deltas and alloc_deltas,
|
| 561 |
+
# to make sys.getallocatedblocks() less flaky.
|
| 562 |
+
_int_pool = IntPool()
|
| 563 |
+
for i in range(-200, 200):
|
| 564 |
+
_int_pool[i]
|
| 565 |
+
|
| 566 |
+
for i in range(repcount):
|
| 567 |
+
# Use a pristine, silent result object to avoid recursion
|
| 568 |
+
res = result.TestResult()
|
| 569 |
+
test.run(res)
|
| 570 |
+
# Poorly-written tests may fail when run several times.
|
| 571 |
+
# In this case, abort the refleak run and report the failure.
|
| 572 |
+
if not res.wasSuccessful():
|
| 573 |
+
self.failures.extend(res.failures)
|
| 574 |
+
self.errors.extend(res.errors)
|
| 575 |
+
raise AssertionError
|
| 576 |
+
del res
|
| 577 |
+
alloc_after, rc_after = _refleak_cleanup()
|
| 578 |
+
if i >= nwarmup:
|
| 579 |
+
rc_deltas[i - nwarmup] = _int_pool[rc_after - rc_before]
|
| 580 |
+
alloc_deltas[i - nwarmup] = _int_pool[alloc_after - alloc_before]
|
| 581 |
+
alloc_before, rc_before = alloc_after, rc_after
|
| 582 |
+
return rc_deltas, alloc_deltas
|
| 583 |
+
|
| 584 |
+
def addSuccess(self, test):
|
| 585 |
+
try:
|
| 586 |
+
rc_deltas, alloc_deltas = self._huntLeaks(test)
|
| 587 |
+
except AssertionError:
|
| 588 |
+
# Test failed when repeated
|
| 589 |
+
assert not self.wasSuccessful()
|
| 590 |
+
return
|
| 591 |
+
|
| 592 |
+
# These checkers return False on success, True on failure
|
| 593 |
+
def check_rc_deltas(deltas):
|
| 594 |
+
return any(deltas)
|
| 595 |
+
|
| 596 |
+
def check_alloc_deltas(deltas):
|
| 597 |
+
# At least 1/3rd of 0s
|
| 598 |
+
if 3 * deltas.count(0) < len(deltas):
|
| 599 |
+
return True
|
| 600 |
+
# Nothing else than 1s, 0s and -1s
|
| 601 |
+
if not set(deltas) <= set((1, 0, -1)):
|
| 602 |
+
return True
|
| 603 |
+
return False
|
| 604 |
+
|
| 605 |
+
failed = False
|
| 606 |
+
|
| 607 |
+
for deltas, item_name, checker in [
|
| 608 |
+
(rc_deltas, 'references', check_rc_deltas),
|
| 609 |
+
(alloc_deltas, 'memory blocks', check_alloc_deltas)]:
|
| 610 |
+
if checker(deltas):
|
| 611 |
+
msg = '%s leaked %s %s, sum=%s' % (
|
| 612 |
+
test, deltas, item_name, sum(deltas))
|
| 613 |
+
failed = True
|
| 614 |
+
try:
|
| 615 |
+
raise ReferenceLeakError(msg)
|
| 616 |
+
except Exception:
|
| 617 |
+
exc_info = sys.exc_info()
|
| 618 |
+
if self.showAll:
|
| 619 |
+
self.stream.write("%s = %r " % (item_name, deltas))
|
| 620 |
+
self.addFailure(test, exc_info)
|
| 621 |
+
|
| 622 |
+
if not failed:
|
| 623 |
+
super(RefleakTestResult, self).addSuccess(test)
|
| 624 |
+
|
| 625 |
+
|
| 626 |
+
class RefleakTestRunner(runner.TextTestRunner):
|
| 627 |
+
resultclass = RefleakTestResult
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
class ParallelTestResult(runner.TextTestResult):
|
| 631 |
+
"""
|
| 632 |
+
A TestResult able to inject results from other results.
|
| 633 |
+
"""
|
| 634 |
+
|
| 635 |
+
def add_results(self, result):
|
| 636 |
+
"""
|
| 637 |
+
Add the results from the other *result* to this result.
|
| 638 |
+
"""
|
| 639 |
+
self.stream.write(result.stream.getvalue())
|
| 640 |
+
self.stream.flush()
|
| 641 |
+
self.testsRun += result.testsRun
|
| 642 |
+
self.failures.extend(result.failures)
|
| 643 |
+
self.errors.extend(result.errors)
|
| 644 |
+
self.skipped.extend(result.skipped)
|
| 645 |
+
self.expectedFailures.extend(result.expectedFailures)
|
| 646 |
+
self.unexpectedSuccesses.extend(result.unexpectedSuccesses)
|
| 647 |
+
|
| 648 |
+
|
| 649 |
+
class _MinimalResult(object):
|
| 650 |
+
"""
|
| 651 |
+
A minimal, picklable TestResult-alike object.
|
| 652 |
+
"""
|
| 653 |
+
|
| 654 |
+
__slots__ = (
|
| 655 |
+
'failures', 'errors', 'skipped', 'expectedFailures',
|
| 656 |
+
'unexpectedSuccesses', 'stream', 'shouldStop', 'testsRun',
|
| 657 |
+
'test_id', 'resource_info')
|
| 658 |
+
|
| 659 |
+
def fixup_case(self, case):
|
| 660 |
+
"""
|
| 661 |
+
Remove any unpicklable attributes from TestCase instance *case*.
|
| 662 |
+
"""
|
| 663 |
+
# Python 3.3 doesn't reset this one.
|
| 664 |
+
case._outcomeForDoCleanups = None
|
| 665 |
+
|
| 666 |
+
def __init__(self, original_result, test_id=None, resource_info=None):
|
| 667 |
+
for attr in self.__slots__:
|
| 668 |
+
setattr(self, attr, getattr(original_result, attr, None))
|
| 669 |
+
for case, _ in self.expectedFailures:
|
| 670 |
+
self.fixup_case(case)
|
| 671 |
+
for case, _ in self.errors:
|
| 672 |
+
self.fixup_case(case)
|
| 673 |
+
for case, _ in self.failures:
|
| 674 |
+
self.fixup_case(case)
|
| 675 |
+
self.test_id = test_id
|
| 676 |
+
self.resource_info = resource_info
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
class _FakeStringIO(object):
|
| 680 |
+
"""
|
| 681 |
+
A trivial picklable StringIO-alike for Python 2.
|
| 682 |
+
"""
|
| 683 |
+
|
| 684 |
+
def __init__(self, value):
|
| 685 |
+
self._value = value
|
| 686 |
+
|
| 687 |
+
def getvalue(self):
|
| 688 |
+
return self._value
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
class _MinimalRunner(object):
|
| 692 |
+
"""
|
| 693 |
+
A minimal picklable object able to instantiate a runner in a
|
| 694 |
+
child process and run a test case with it.
|
| 695 |
+
"""
|
| 696 |
+
|
| 697 |
+
def __init__(self, runner_cls, runner_args):
|
| 698 |
+
self.runner_cls = runner_cls
|
| 699 |
+
self.runner_args = runner_args
|
| 700 |
+
|
| 701 |
+
# Python 2 doesn't know how to pickle instance methods, so we use __call__
|
| 702 |
+
# instead.
|
| 703 |
+
|
| 704 |
+
def __call__(self, test):
|
| 705 |
+
# Executed in child process
|
| 706 |
+
kwargs = self.runner_args
|
| 707 |
+
# Force recording of output in a buffer (it will be printed out
|
| 708 |
+
# by the parent).
|
| 709 |
+
kwargs['stream'] = StringIO()
|
| 710 |
+
runner = self.runner_cls(**kwargs)
|
| 711 |
+
result = runner._makeResult()
|
| 712 |
+
# Avoid child tracebacks when Ctrl-C is pressed.
|
| 713 |
+
signals.installHandler()
|
| 714 |
+
signals.registerResult(result)
|
| 715 |
+
result.failfast = runner.failfast
|
| 716 |
+
result.buffer = runner.buffer
|
| 717 |
+
# Create a per-process memory tracker to avoid global state issues
|
| 718 |
+
memtrack = memoryutils.MemoryTracker(test.id())
|
| 719 |
+
with memtrack.monitor():
|
| 720 |
+
with self.cleanup_object(test):
|
| 721 |
+
test(result)
|
| 722 |
+
# HACK as cStringIO.StringIO isn't picklable in 2.x
|
| 723 |
+
result.stream = _FakeStringIO(result.stream.getvalue())
|
| 724 |
+
return _MinimalResult(result, test.id(),
|
| 725 |
+
resource_info=memtrack.get_summary())
|
| 726 |
+
|
| 727 |
+
@contextlib.contextmanager
|
| 728 |
+
def cleanup_object(self, test):
|
| 729 |
+
"""
|
| 730 |
+
A context manager which cleans up unwanted attributes on a test case
|
| 731 |
+
(or any other object).
|
| 732 |
+
"""
|
| 733 |
+
vanilla_attrs = set(test.__dict__)
|
| 734 |
+
try:
|
| 735 |
+
yield test
|
| 736 |
+
finally:
|
| 737 |
+
spurious_attrs = set(test.__dict__) - vanilla_attrs
|
| 738 |
+
for name in spurious_attrs:
|
| 739 |
+
del test.__dict__[name]
|
| 740 |
+
|
| 741 |
+
|
| 742 |
+
def _split_nonparallel_tests(test, sliced):
|
| 743 |
+
"""
|
| 744 |
+
Split test suite into parallel and serial tests.
|
| 745 |
+
"""
|
| 746 |
+
ptests = []
|
| 747 |
+
stests = []
|
| 748 |
+
|
| 749 |
+
flat = [*filter(sliced, _flatten_suite(test))]
|
| 750 |
+
|
| 751 |
+
def is_parallelizable_test_case(test):
|
| 752 |
+
# Guard for the fake test case created by unittest when test
|
| 753 |
+
# discovery fails, as it isn't picklable (e.g. "LoadTestsFailure")
|
| 754 |
+
method_name = test._testMethodName
|
| 755 |
+
method = getattr(test, method_name)
|
| 756 |
+
if method.__name__ != method_name and method.__name__ == "testFailure":
|
| 757 |
+
return False
|
| 758 |
+
# Was parallel execution explicitly disabled?
|
| 759 |
+
return getattr(test, "_numba_parallel_test_", True)
|
| 760 |
+
|
| 761 |
+
for t in flat:
|
| 762 |
+
if is_parallelizable_test_case(t):
|
| 763 |
+
ptests.append(t)
|
| 764 |
+
else:
|
| 765 |
+
stests.append(t)
|
| 766 |
+
|
| 767 |
+
return ptests, stests
|
| 768 |
+
|
| 769 |
+
# A test can't run longer than 10 minutes
|
| 770 |
+
_TIMEOUT = 1200
|
| 771 |
+
|
| 772 |
+
class ParallelTestRunner(runner.TextTestRunner):
|
| 773 |
+
"""
|
| 774 |
+
A test runner which delegates the actual running to a pool of child
|
| 775 |
+
processes.
|
| 776 |
+
"""
|
| 777 |
+
|
| 778 |
+
resultclass = ParallelTestResult
|
| 779 |
+
timeout = _TIMEOUT
|
| 780 |
+
|
| 781 |
+
def __init__(self, runner_cls, nprocs, useslice, **kwargs):
|
| 782 |
+
runner.TextTestRunner.__init__(self, **kwargs)
|
| 783 |
+
self.runner_cls = runner_cls
|
| 784 |
+
self.nprocs = nprocs
|
| 785 |
+
self.useslice = parse_slice(useslice)
|
| 786 |
+
self.runner_args = kwargs
|
| 787 |
+
self.resource_infos = []
|
| 788 |
+
|
| 789 |
+
def _run_inner(self, result):
|
| 790 |
+
# We hijack TextTestRunner.run()'s inner logic by passing this
|
| 791 |
+
# method as if it were a test case.
|
| 792 |
+
child_runner = _MinimalRunner(self.runner_cls, self.runner_args)
|
| 793 |
+
|
| 794 |
+
# Split the tests and recycle the worker process to tame memory usage.
|
| 795 |
+
chunk_size = 100
|
| 796 |
+
splitted_tests = [self._ptests[i:i + chunk_size]
|
| 797 |
+
for i in range(0, len(self._ptests), chunk_size)]
|
| 798 |
+
|
| 799 |
+
spawnctx = multiprocessing.get_context("spawn")
|
| 800 |
+
try:
|
| 801 |
+
for tests in splitted_tests:
|
| 802 |
+
pool = spawnctx.Pool(self.nprocs)
|
| 803 |
+
try:
|
| 804 |
+
self._run_parallel_tests(result, pool, child_runner, tests)
|
| 805 |
+
except Exception:
|
| 806 |
+
# On exception, kill still active workers immediately
|
| 807 |
+
pool.terminate()
|
| 808 |
+
# Make sure exception is reported and not ignored
|
| 809 |
+
raise
|
| 810 |
+
else:
|
| 811 |
+
# Close the pool cleanly unless asked to early out
|
| 812 |
+
if result.shouldStop:
|
| 813 |
+
pool.terminate()
|
| 814 |
+
break
|
| 815 |
+
else:
|
| 816 |
+
pool.close()
|
| 817 |
+
finally:
|
| 818 |
+
# Always join the pool (this is necessary for coverage.py)
|
| 819 |
+
pool.join()
|
| 820 |
+
if not result.shouldStop:
|
| 821 |
+
# Run serial tests with memory tracking
|
| 822 |
+
stests = SerialSuite(self._stests)
|
| 823 |
+
stests.run(result)
|
| 824 |
+
# Add serial test resource infos to the main collection
|
| 825 |
+
self.resource_infos.extend(stests.resource_infos)
|
| 826 |
+
return result
|
| 827 |
+
finally:
|
| 828 |
+
# Always display the resource infos
|
| 829 |
+
if memoryutils.IS_SUPPORTED:
|
| 830 |
+
try:
|
| 831 |
+
print("=== Resource Infos ===")
|
| 832 |
+
for ri in self.resource_infos:
|
| 833 |
+
print(ri)
|
| 834 |
+
except Exception:
|
| 835 |
+
print("ERROR: Ignored exception in priting resource infos")
|
| 836 |
+
traceback.print_exc()
|
| 837 |
+
finally:
|
| 838 |
+
print("=== End Resource Infos ===")
|
| 839 |
+
|
| 840 |
+
def _run_parallel_tests(self, result, pool, child_runner, tests):
|
| 841 |
+
remaining_ids = set(t.id() for t in tests)
|
| 842 |
+
tests.sort(key=cuda_sensitive_mtime)
|
| 843 |
+
it = pool.imap_unordered(child_runner, tests)
|
| 844 |
+
while True:
|
| 845 |
+
try:
|
| 846 |
+
child_result = it.__next__(self.timeout)
|
| 847 |
+
except StopIteration:
|
| 848 |
+
return
|
| 849 |
+
except TimeoutError as e:
|
| 850 |
+
# Diagnose the names of unfinished tests
|
| 851 |
+
msg = ("Tests didn't finish before timeout (or crashed):\n%s"
|
| 852 |
+
% "".join("- %r\n" % tid for tid in sorted(remaining_ids))
|
| 853 |
+
)
|
| 854 |
+
e.args = (msg,) + e.args[1:]
|
| 855 |
+
raise e
|
| 856 |
+
else:
|
| 857 |
+
result.add_results(child_result)
|
| 858 |
+
self.resource_infos.append(child_result.resource_info)
|
| 859 |
+
remaining_ids.discard(child_result.test_id)
|
| 860 |
+
if child_result.shouldStop:
|
| 861 |
+
result.shouldStop = True
|
| 862 |
+
return
|
| 863 |
+
|
| 864 |
+
def run(self, test):
|
| 865 |
+
self._ptests, self._stests = _split_nonparallel_tests(test,
|
| 866 |
+
self.useslice)
|
| 867 |
+
print("Parallel: %s. Serial: %s" % (len(self._ptests),
|
| 868 |
+
len(self._stests)))
|
| 869 |
+
# This will call self._run_inner() on the created result object,
|
| 870 |
+
# and print out the detailed test results at the end.
|
| 871 |
+
return super(ParallelTestRunner, self).run(self._run_inner)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/notebook.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|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TestCase
|
| 2 |
+
|
| 3 |
+
from ipykernel.tests import utils
|
| 4 |
+
from nbformat.converter import convert
|
| 5 |
+
from nbformat.reader import reads
|
| 6 |
+
|
| 7 |
+
import re
|
| 8 |
+
import json
|
| 9 |
+
from copy import copy
|
| 10 |
+
import unittest
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
# py3
|
| 14 |
+
from queue import Empty
|
| 15 |
+
|
| 16 |
+
def isstr(s):
|
| 17 |
+
return isinstance(s, str)
|
| 18 |
+
except ImportError:
|
| 19 |
+
# py2
|
| 20 |
+
from Queue import Empty
|
| 21 |
+
|
| 22 |
+
def isstr(s):
|
| 23 |
+
return isinstance(s, basestring) # noqa
|
| 24 |
+
|
| 25 |
+
class NotebookTest(TestCase):
|
| 26 |
+
"""Validate a notebook. All code cells are executed in order. The output is either checked
|
| 27 |
+
for errors (if no reference output is present), or is compared against expected output.
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
Useful references:
|
| 31 |
+
http://nbformat.readthedocs.org/en/latest/format_description.html
|
| 32 |
+
http://jupyter-client.readthedocs.org/en/latest/messaging.html
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
IGNORE_TYPES = ["execute_request", "execute_input", "status", "pyin"]
|
| 37 |
+
STRIP_KEYS = ["execution_count", "traceback", "prompt_number", "source"]
|
| 38 |
+
NBFORMAT_VERSION = 4
|
| 39 |
+
|
| 40 |
+
def _test_notebook(self, notebook, test):
|
| 41 |
+
|
| 42 |
+
with open(notebook) as f:
|
| 43 |
+
nb = convert(reads(f.read()), self.NBFORMAT_VERSION)
|
| 44 |
+
_, kernel = utils.start_new_kernel()
|
| 45 |
+
for i, c in enumerate([c for c in nb.cells if c.cell_type == 'code']):
|
| 46 |
+
self._test_notebook_cell(self.sanitize_cell(c), i, kernel, test)
|
| 47 |
+
|
| 48 |
+
def _test_notebook_cell(self, cell, i, kernel, test):
|
| 49 |
+
|
| 50 |
+
if hasattr(cell, 'source'): # nbformat 4.0 and later
|
| 51 |
+
code = cell.source
|
| 52 |
+
else:
|
| 53 |
+
code = cell.input
|
| 54 |
+
iopub = kernel.iopub_channel
|
| 55 |
+
kernel.execute(code)
|
| 56 |
+
outputs = []
|
| 57 |
+
msg = None
|
| 58 |
+
no_error = True
|
| 59 |
+
first_error = -1
|
| 60 |
+
error_msg = ''
|
| 61 |
+
while self.should_continue(msg):
|
| 62 |
+
try:
|
| 63 |
+
msg = iopub.get_msg(block=True, timeout=1)
|
| 64 |
+
except Empty:
|
| 65 |
+
continue
|
| 66 |
+
if msg['msg_type'] not in self.IGNORE_TYPES:
|
| 67 |
+
if msg['msg_type'] == 'error':
|
| 68 |
+
error_msg = ' ' + msg['content']['ename'] + '\n ' + msg['content']['evalue']
|
| 69 |
+
no_error = False
|
| 70 |
+
if first_error == -1:
|
| 71 |
+
first_error = i
|
| 72 |
+
i = len(outputs)
|
| 73 |
+
expected = i < len(cell.outputs) and cell.outputs[i] or []
|
| 74 |
+
o = self.transform_message(msg, expected)
|
| 75 |
+
outputs.append(o)
|
| 76 |
+
|
| 77 |
+
if (test == 'check_error'):
|
| 78 |
+
self.assertTrue(no_error, 'Executing cell %d resulted in an error:\n%s'%(first_error, error_msg))
|
| 79 |
+
else:
|
| 80 |
+
# Compare computed output against stored output.
|
| 81 |
+
# TODO: This doesn't work right now as the generated output is too diverse to
|
| 82 |
+
# be verifiable.
|
| 83 |
+
scrub = lambda x: self.dump_canonical(list(self.scrub_outputs(x)))
|
| 84 |
+
scrubbed = scrub(outputs)
|
| 85 |
+
expected = scrub(cell.outputs)
|
| 86 |
+
#print('output=%s'%outputs)
|
| 87 |
+
#print('expected=%s'%expected)
|
| 88 |
+
#self.assertEqual(scrubbed, expected, "\n{}\n\n{}".format(scrubbed, expected))
|
| 89 |
+
|
| 90 |
+
def dump_canonical(self, obj):
|
| 91 |
+
return json.dumps(obj, indent=2, sort_keys=True)
|
| 92 |
+
|
| 93 |
+
def scrub_outputs(self, outputs):
|
| 94 |
+
"""
|
| 95 |
+
remove all scrubs from output data and text
|
| 96 |
+
"""
|
| 97 |
+
for output in outputs:
|
| 98 |
+
out = copy(output)
|
| 99 |
+
|
| 100 |
+
for scrub, sub in []:#self.scrubs.items():
|
| 101 |
+
def _scrubLines(lines):
|
| 102 |
+
if isstr(lines):
|
| 103 |
+
return re.sub(scrub, sub, lines)
|
| 104 |
+
else:
|
| 105 |
+
return [re.sub(scrub, sub, line) for line in lines]
|
| 106 |
+
|
| 107 |
+
if "text" in out:
|
| 108 |
+
out["text"] = _scrubLines(out["text"])
|
| 109 |
+
|
| 110 |
+
if "data" in out:
|
| 111 |
+
if isinstance(out["data"], dict):
|
| 112 |
+
for mime, data in out["data"].items():
|
| 113 |
+
out["data"][mime] = _scrubLines(data)
|
| 114 |
+
else:
|
| 115 |
+
out["data"] = _scrubLines(out["data"])
|
| 116 |
+
yield out
|
| 117 |
+
|
| 118 |
+
def strip_keys(self, d):
|
| 119 |
+
"""
|
| 120 |
+
remove keys from STRIP_KEYS to ensure comparability
|
| 121 |
+
"""
|
| 122 |
+
for key in self.STRIP_KEYS:
|
| 123 |
+
d.pop(key, None)
|
| 124 |
+
return d
|
| 125 |
+
|
| 126 |
+
def sanitize_cell(self, cell):
|
| 127 |
+
"""
|
| 128 |
+
remove non-reproducible things
|
| 129 |
+
"""
|
| 130 |
+
for output in cell.outputs:
|
| 131 |
+
self.strip_keys(output)
|
| 132 |
+
return cell
|
| 133 |
+
|
| 134 |
+
def transform_message(self, msg, expected):
|
| 135 |
+
"""
|
| 136 |
+
transform a message into something like the notebook
|
| 137 |
+
"""
|
| 138 |
+
SWAP_KEYS = {
|
| 139 |
+
"output_type": {
|
| 140 |
+
"pyout": "execute_result",
|
| 141 |
+
"pyerr": "error"
|
| 142 |
+
}
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
output = {
|
| 146 |
+
u"output_type": msg["msg_type"]
|
| 147 |
+
}
|
| 148 |
+
output.update(msg["content"])
|
| 149 |
+
|
| 150 |
+
output = self.strip_keys(output)
|
| 151 |
+
for key, swaps in SWAP_KEYS.items():
|
| 152 |
+
if key in output and output[key] in swaps:
|
| 153 |
+
output[key] = swaps[output[key]]
|
| 154 |
+
|
| 155 |
+
if "data" in output and "data" not in expected:
|
| 156 |
+
output["text"] = output["data"]
|
| 157 |
+
del output["data"]
|
| 158 |
+
|
| 159 |
+
return output
|
| 160 |
+
|
| 161 |
+
def should_continue(self, msg):
|
| 162 |
+
"""
|
| 163 |
+
determine whether the current message is the last for this cell
|
| 164 |
+
"""
|
| 165 |
+
if msg is None:
|
| 166 |
+
return True
|
| 167 |
+
|
| 168 |
+
return not (msg["msg_type"] == "status" and
|
| 169 |
+
msg["content"]["execution_state"] == "idle")
|
| 170 |
+
|
| 171 |
+
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_array_attr.cpython-311.pyc
ADDED
|
Binary file (27.4 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_cfunc.cpython-311.pyc
ADDED
|
Binary file (25.5 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_copy_propagate.cpython-311.pyc
ADDED
|
Binary file (9.27 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_indexing.cpython-311.pyc
ADDED
|
Binary file (70.8 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_llvm_pass_timings.cpython-311.pyc
ADDED
|
Binary file (7.83 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_npdatetime.cpython-311.pyc
ADDED
|
Binary file (92.6 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_numbers.cpython-311.pyc
ADDED
|
Binary file (6.71 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_numconv.cpython-311.pyc
ADDED
|
Binary file (2.34 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_python_int.cpython-311.pyc
ADDED
|
Binary file (3.36 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_storeslice.cpython-311.pyc
ADDED
|
Binary file (4.04 kB). View file
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/cfunc_cache_usecases.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This file will be copied to a temporary directory in order to
|
| 3 |
+
exercise caching compiled C callbacks.
|
| 4 |
+
|
| 5 |
+
See test_cfunc.py.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import sys
|
| 9 |
+
|
| 10 |
+
from numba import cfunc, jit
|
| 11 |
+
from numba.tests.support import TestCase, captured_stderr
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
Z = 1
|
| 15 |
+
|
| 16 |
+
add_sig = "float64(float64, float64)"
|
| 17 |
+
|
| 18 |
+
div_sig = "float64(int64, int64)"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@cfunc(add_sig, cache=True, nopython=True)
|
| 22 |
+
def add_usecase(x, y):
|
| 23 |
+
return x + y + Z
|
| 24 |
+
|
| 25 |
+
@cfunc(add_sig, nopython=True)
|
| 26 |
+
def add_nocache_usecase(x, y):
|
| 27 |
+
return x + y + Z
|
| 28 |
+
|
| 29 |
+
@cfunc(div_sig, cache=True, nopython=True)
|
| 30 |
+
def div_usecase(a, b):
|
| 31 |
+
return a / b
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@jit(nopython=True)
|
| 35 |
+
def inner(x, y):
|
| 36 |
+
return x + y + Z
|
| 37 |
+
|
| 38 |
+
@cfunc(add_sig, cache=True, nopython=True)
|
| 39 |
+
def outer(x, y):
|
| 40 |
+
return inner(-y, x)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class _TestModule(TestCase):
|
| 44 |
+
"""
|
| 45 |
+
Tests for functionality of this module's cfuncs.
|
| 46 |
+
Note this does not define any "test_*" method, instead check_module()
|
| 47 |
+
should be called by hand.
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
def check_module(self, mod):
|
| 51 |
+
f = mod.add_usecase
|
| 52 |
+
self.assertPreciseEqual(f.ctypes(2.0, 3.0), 6.0)
|
| 53 |
+
f = mod.add_nocache_usecase
|
| 54 |
+
self.assertPreciseEqual(f.ctypes(2.0, 3.0), 6.0)
|
| 55 |
+
f = mod.outer
|
| 56 |
+
self.assertPreciseEqual(f.ctypes(5.0, 2.0), 4.0)
|
| 57 |
+
|
| 58 |
+
f = mod.div_usecase
|
| 59 |
+
with captured_stderr() as err:
|
| 60 |
+
self.assertPreciseEqual(f.ctypes(7, 2), 3.5)
|
| 61 |
+
self.assertEqual(err.getvalue(), "")
|
| 62 |
+
with captured_stderr() as err:
|
| 63 |
+
f.ctypes(7, 0)
|
| 64 |
+
err = err.getvalue()
|
| 65 |
+
self.assertIn("ZeroDivisionError", err)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def self_test():
|
| 69 |
+
mod = sys.modules[__name__]
|
| 70 |
+
_TestModule().check_module(mod)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from os.path import dirname
|
| 2 |
+
import unittest
|
| 3 |
+
from unittest.suite import TestSuite
|
| 4 |
+
|
| 5 |
+
from numba.testing import load_testsuite
|
| 6 |
+
|
| 7 |
+
def load_tests(loader, tests, pattern):
|
| 8 |
+
suite = TestSuite()
|
| 9 |
+
suite.addTests(load_testsuite(loader, dirname(__file__)))
|
| 10 |
+
return suite
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_array_arg.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# NOTE: This test is sensitive to line numbers as it checks breakpoints
|
| 2 |
+
from numba import njit, types
|
| 3 |
+
import numpy as np
|
| 4 |
+
from numba.tests.gdb_support import GdbMIDriver
|
| 5 |
+
from numba.tests.support import TestCase, needs_subprocess
|
| 6 |
+
import unittest
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@needs_subprocess
|
| 10 |
+
class Test(TestCase):
|
| 11 |
+
|
| 12 |
+
def test(self):
|
| 13 |
+
@njit(debug=True)
|
| 14 |
+
def foo(x):
|
| 15 |
+
z = np.ones_like(x) # break here
|
| 16 |
+
return x, z
|
| 17 |
+
|
| 18 |
+
tmp = np.ones(5)
|
| 19 |
+
foo(tmp)
|
| 20 |
+
|
| 21 |
+
driver = GdbMIDriver(__file__)
|
| 22 |
+
driver.set_breakpoint(line=15)
|
| 23 |
+
driver.run()
|
| 24 |
+
driver.check_hit_breakpoint(1)
|
| 25 |
+
driver.stack_list_arguments(2)
|
| 26 |
+
llvm_intp = f"i{types.intp.bitwidth}"
|
| 27 |
+
expect = (
|
| 28 |
+
'[frame={level="0",args=[{name="x",type="array(float64, 1d, C) '
|
| 29 |
+
f'({{i8*, i8*, {llvm_intp}, {llvm_intp}, double*, '
|
| 30 |
+
f'[1 x {llvm_intp}], [1 x {llvm_intp}]}})"}}]}}]'
|
| 31 |
+
)
|
| 32 |
+
driver.assert_output(expect)
|
| 33 |
+
driver.stack_list_variables(1)
|
| 34 |
+
# 'z' should be zero-init
|
| 35 |
+
expect = ('{name="z",value="{meminfo = 0x0, parent = 0x0, nitems = 0, '
|
| 36 |
+
'itemsize = 0, data = 0x0, shape = {0}, strides = {0}}"}')
|
| 37 |
+
driver.assert_output(expect)
|
| 38 |
+
driver.set_breakpoint(line=16)
|
| 39 |
+
driver.cont()
|
| 40 |
+
driver.check_hit_breakpoint(2)
|
| 41 |
+
driver.stack_list_variables(1)
|
| 42 |
+
# 'z' should be populated
|
| 43 |
+
expect = (r'^.*\{name="z",value="\{meminfo = 0x[0-9a-f]+ .*, '
|
| 44 |
+
r'parent = 0x0, nitems = 5, itemsize = 8, '
|
| 45 |
+
r'data = 0x[0-9a-f]+, shape = \{5\}, strides = \{8\}\}.*$')
|
| 46 |
+
driver.assert_regex_output(expect)
|
| 47 |
+
driver.quit()
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
if __name__ == '__main__':
|
| 51 |
+
unittest.main()
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_basic.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# NOTE: This test is sensitive to line numbers as it checks breakpoints
|
| 2 |
+
from numba import njit, types
|
| 3 |
+
from numba.tests.gdb_support import GdbMIDriver
|
| 4 |
+
from numba.tests.support import TestCase, needs_subprocess
|
| 5 |
+
import unittest
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@needs_subprocess
|
| 9 |
+
class Test(TestCase):
|
| 10 |
+
|
| 11 |
+
def test(self):
|
| 12 |
+
@njit(debug=True)
|
| 13 |
+
def foo(x):
|
| 14 |
+
z = 7 + x # break here
|
| 15 |
+
return x, z
|
| 16 |
+
|
| 17 |
+
foo(120)
|
| 18 |
+
|
| 19 |
+
sz = types.intp.bitwidth
|
| 20 |
+
driver = GdbMIDriver(__file__)
|
| 21 |
+
driver.set_breakpoint(line=14)
|
| 22 |
+
driver.run()
|
| 23 |
+
driver.check_hit_breakpoint(1)
|
| 24 |
+
driver.stack_list_arguments(2)
|
| 25 |
+
expect = ('[frame={level="0",args=[{name="x",type="int%s",'
|
| 26 |
+
'value="120"}]}]' % sz)
|
| 27 |
+
driver.assert_output(expect)
|
| 28 |
+
driver.stack_list_variables(1)
|
| 29 |
+
expect = '[{name="x",arg="1",value="120"},{name="z",value="0"}]'
|
| 30 |
+
driver.assert_output(expect)
|
| 31 |
+
driver.next()
|
| 32 |
+
driver.stack_list_variables(1)
|
| 33 |
+
expect = '[{name="x",arg="1",value="120"},{name="z",value="127"}]'
|
| 34 |
+
driver.assert_output(expect)
|
| 35 |
+
driver.quit()
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
if __name__ == '__main__':
|
| 39 |
+
unittest.main()
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_break_on_symbol.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# NOTE: This test is sensitive to line numbers as it checks breakpoints
|
| 2 |
+
from numba import njit, types
|
| 3 |
+
from numba.tests.gdb_support import GdbMIDriver
|
| 4 |
+
from numba.tests.support import TestCase, needs_subprocess
|
| 5 |
+
import unittest
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@njit(debug=True)
|
| 9 |
+
def foo(x):
|
| 10 |
+
z = 7 + x
|
| 11 |
+
return x, z
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@needs_subprocess
|
| 15 |
+
class Test(TestCase):
|
| 16 |
+
|
| 17 |
+
def test(self):
|
| 18 |
+
foo(120)
|
| 19 |
+
sz = types.intp.bitwidth
|
| 20 |
+
driver = GdbMIDriver(__file__)
|
| 21 |
+
driver.set_breakpoint(symbol="__main__::foo")
|
| 22 |
+
driver.run() # will hit cpython symbol match
|
| 23 |
+
driver.check_hit_breakpoint(number=1)
|
| 24 |
+
driver.cont() # will hit njit symbol match
|
| 25 |
+
driver.check_hit_breakpoint(number=1, line=10) # Ensure line number
|
| 26 |
+
driver.stack_list_arguments(2)
|
| 27 |
+
expect = ('[frame={level="0",args=[{name="x",type="int%s",'
|
| 28 |
+
'value="120"}]}]' % sz)
|
| 29 |
+
driver.assert_output(expect)
|
| 30 |
+
driver.quit()
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
if __name__ == '__main__':
|
| 34 |
+
unittest.main()
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_break_on_symbol_version.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# NOTE: This test is sensitive to line numbers as it checks breakpoints
|
| 2 |
+
from numba import njit
|
| 3 |
+
from numba.tests.gdb_support import GdbMIDriver
|
| 4 |
+
from numba.tests.support import TestCase, needs_subprocess
|
| 5 |
+
import unittest
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def foo_factory(n):
|
| 9 |
+
@njit(debug=True)
|
| 10 |
+
def foo(x):
|
| 11 |
+
z = 7 + n
|
| 12 |
+
return x, z
|
| 13 |
+
|
| 14 |
+
return foo
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
foo1, foo2, foo3 = [foo_factory(x) for x in range(3)]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@njit(debug=True)
|
| 21 |
+
def call_foo():
|
| 22 |
+
a = foo1(10)
|
| 23 |
+
b = foo2(20)
|
| 24 |
+
c = foo3(30)
|
| 25 |
+
return a, b, c
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@needs_subprocess
|
| 29 |
+
class Test(TestCase):
|
| 30 |
+
|
| 31 |
+
def test(self):
|
| 32 |
+
call_foo()
|
| 33 |
+
driver = GdbMIDriver(__file__)
|
| 34 |
+
# A specific foo, the first one, it has uid=2
|
| 35 |
+
vsym = "__main__::foo_factory::_3clocals_3e::foo[abi:v2]"
|
| 36 |
+
driver.set_breakpoint(symbol=vsym)
|
| 37 |
+
driver.run()
|
| 38 |
+
driver.check_hit_breakpoint(number=1)
|
| 39 |
+
driver.assert_regex_output(r'^.*foo\[abi:v2\].*line="11"')
|
| 40 |
+
driver.stack_list_arguments(2)
|
| 41 |
+
expect = ('[frame={level="0",args=[{name="x",type="Literal[int](10)",'
|
| 42 |
+
'value="10"}]}]')
|
| 43 |
+
driver.assert_output(expect)
|
| 44 |
+
# Now break on any foo
|
| 45 |
+
driver.set_breakpoint(symbol="foo")
|
| 46 |
+
driver.cont()
|
| 47 |
+
driver.check_hit_breakpoint(number=2)
|
| 48 |
+
driver.assert_regex_output(r'^.*foo\[abi:v3\].*line="11"')
|
| 49 |
+
driver.stack_list_arguments(2)
|
| 50 |
+
expect = ('[frame={level="0",args=[{name="x",type="Literal[int](20)",'
|
| 51 |
+
'value="20"}]}]')
|
| 52 |
+
driver.assert_output(expect)
|
| 53 |
+
# and again, hit the third foo
|
| 54 |
+
driver.cont()
|
| 55 |
+
driver.check_hit_breakpoint(number=2)
|
| 56 |
+
driver.assert_regex_output(r'^.*foo\[abi:v4\].*line="11"')
|
| 57 |
+
driver.stack_list_arguments(2)
|
| 58 |
+
expect = ('[frame={level="0",args=[{name="x",type="Literal[int](30)",'
|
| 59 |
+
'value="30"}]}]')
|
| 60 |
+
driver.assert_output(expect)
|
| 61 |
+
driver.quit()
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
if __name__ == '__main__':
|
| 65 |
+
unittest.main()
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_conditional_breakpoint.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# NOTE: This test is sensitive to line numbers as it checks breakpoints
|
| 2 |
+
from numba import njit
|
| 3 |
+
from numba.tests.gdb_support import GdbMIDriver
|
| 4 |
+
from numba.tests.support import TestCase, needs_subprocess
|
| 5 |
+
import unittest
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@needs_subprocess
|
| 9 |
+
class Test(TestCase):
|
| 10 |
+
|
| 11 |
+
def test(self):
|
| 12 |
+
|
| 13 |
+
@njit(debug=True)
|
| 14 |
+
def foo(x, y):
|
| 15 |
+
c = x + y # break-here
|
| 16 |
+
return c
|
| 17 |
+
|
| 18 |
+
@njit(debug=True)
|
| 19 |
+
def call_foo(a):
|
| 20 |
+
acc = 0
|
| 21 |
+
for i in range(10):
|
| 22 |
+
acc += foo(i, a)
|
| 23 |
+
return acc
|
| 24 |
+
|
| 25 |
+
call_foo(10)
|
| 26 |
+
|
| 27 |
+
driver = GdbMIDriver(__file__)
|
| 28 |
+
driver.set_breakpoint(line=15, condition='x == 4')
|
| 29 |
+
driver.run()
|
| 30 |
+
driver.check_hit_breakpoint(1)
|
| 31 |
+
driver.stack_list_arguments(1)
|
| 32 |
+
expect = ('[frame={level="0",args=[{name="x",value="4"},'
|
| 33 |
+
'{name="y",value="10"}]}]')
|
| 34 |
+
driver.assert_output(expect)
|
| 35 |
+
driver.set_breakpoint(line=22, condition='i == 8')
|
| 36 |
+
driver.cont()
|
| 37 |
+
driver.check_hit_breakpoint(2)
|
| 38 |
+
driver.stack_list_variables(1)
|
| 39 |
+
# i should be 8
|
| 40 |
+
driver.assert_output('{name="i",value="8"}')
|
| 41 |
+
driver.quit()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
if __name__ == '__main__':
|
| 45 |
+
unittest.main()
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_pretty_print.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# NOTE: This test is sensitive to line numbers as it checks breakpoints
|
| 2 |
+
from numba import njit
|
| 3 |
+
import numpy as np
|
| 4 |
+
from numba.tests.gdb_support import GdbMIDriver, needs_gdb_py3
|
| 5 |
+
from numba.tests.support import TestCase, needs_subprocess
|
| 6 |
+
from numba.misc.numba_gdbinfo import collect_gdbinfo
|
| 7 |
+
import unittest
|
| 8 |
+
import re
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@needs_gdb_py3
|
| 12 |
+
@needs_subprocess
|
| 13 |
+
class Test(TestCase):
|
| 14 |
+
|
| 15 |
+
def test(self):
|
| 16 |
+
rdt_a = np.dtype([("x", np.int16), ("y", np.float64)], align=True)
|
| 17 |
+
|
| 18 |
+
@njit(debug=True)
|
| 19 |
+
def foo():
|
| 20 |
+
a = 1.234
|
| 21 |
+
b = (1, 2, 3)
|
| 22 |
+
c = ('a', b, 4)
|
| 23 |
+
d = np.arange(5.)
|
| 24 |
+
e = np.array([[1, 3j], [2, 4j]])
|
| 25 |
+
f = "Some string" + " L-Padded string".lstrip()
|
| 26 |
+
g = 11 + 22j
|
| 27 |
+
h = np.arange(24).reshape((4, 6))[::2, ::3]
|
| 28 |
+
i = np.zeros(2, dtype=rdt_a)
|
| 29 |
+
return a, b, c, d, e, f, g, h, i
|
| 30 |
+
|
| 31 |
+
foo()
|
| 32 |
+
|
| 33 |
+
extension = collect_gdbinfo().extension_loc
|
| 34 |
+
driver = GdbMIDriver(__file__, init_cmds=['-x', extension], debug=False)
|
| 35 |
+
driver.set_breakpoint(line=29)
|
| 36 |
+
driver.run()
|
| 37 |
+
driver.check_hit_breakpoint(1)
|
| 38 |
+
|
| 39 |
+
# Ideally the function would be run to get the string repr of locals
|
| 40 |
+
# but not everything appears in DWARF e.g. string literals. Further,
|
| 41 |
+
# str on NumPy arrays seems to vary a bit in output. Therefore a custom
|
| 42 |
+
# match is used.
|
| 43 |
+
|
| 44 |
+
driver.stack_list_variables(1)
|
| 45 |
+
output = driver._captured.after.decode('UTF-8')
|
| 46 |
+
done_str = output.splitlines()[0]
|
| 47 |
+
pat = r'^\^done,variables=\[\{(.*)\}\]$'
|
| 48 |
+
lcls_strs = re.match(pat, done_str).groups()[0].split('},{')
|
| 49 |
+
lcls = {k: v for k, v in [re.match(r'name="(.*)",value="(.*)"',
|
| 50 |
+
x).groups() for x in lcls_strs]}
|
| 51 |
+
expected = dict()
|
| 52 |
+
expected['a'] = r'1\.234'
|
| 53 |
+
expected['b'] = r'\(1, 2, 3\)'
|
| 54 |
+
expected['c'] = r'\(0x0, \(1, 2, 3\), 4\)'
|
| 55 |
+
expected['d'] = r'\\n\[0. 1. 2. 3. 4.\]'
|
| 56 |
+
expected['e'] = r'\\n\[\[1.\+0.j 0.\+3.j\]\\n \[2.\+0.j 0.\+4.j\]\]'
|
| 57 |
+
expected['f'] = "'Some stringL-Padded string'"
|
| 58 |
+
expected['g'] = r"11\+22j"
|
| 59 |
+
expected['h'] = r'\\n\[\[ 0 3\]\\n \[12 15\]\]'
|
| 60 |
+
expected['i'] = r'\\n\[\(0, 0.\) \(0, 0.\)\]'
|
| 61 |
+
|
| 62 |
+
for k, v in expected.items():
|
| 63 |
+
self.assertRegex(lcls[k], v)
|
| 64 |
+
|
| 65 |
+
driver.quit()
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
if __name__ == '__main__':
|
| 69 |
+
unittest.main()
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/inlining_usecases.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" Test cases for inlining IR from another module """
|
| 2 |
+
from numba import jit, njit
|
| 3 |
+
from numba.core import types
|
| 4 |
+
from numba.core.extending import overload
|
| 5 |
+
|
| 6 |
+
_GLOBAL1 = 100
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@njit(inline='always')
|
| 10 |
+
def bar():
|
| 11 |
+
return _GLOBAL1 + 10
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def baz_factory(a):
|
| 15 |
+
b = 17 + a
|
| 16 |
+
|
| 17 |
+
@njit(inline='always')
|
| 18 |
+
def baz():
|
| 19 |
+
return _GLOBAL1 + a - b
|
| 20 |
+
return baz
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def baz():
|
| 24 |
+
return _GLOBAL1 + 10
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@overload(baz, inline='always')
|
| 28 |
+
def baz_ol():
|
| 29 |
+
def impl():
|
| 30 |
+
return _GLOBAL1 + 10
|
| 31 |
+
return impl
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def bop_factory(a):
|
| 35 |
+
b = 17 + a
|
| 36 |
+
|
| 37 |
+
def bop():
|
| 38 |
+
return _GLOBAL1 + a - b
|
| 39 |
+
|
| 40 |
+
@overload(bop, inline='always')
|
| 41 |
+
def baz():
|
| 42 |
+
def impl():
|
| 43 |
+
return _GLOBAL1 + a - b
|
| 44 |
+
return impl
|
| 45 |
+
|
| 46 |
+
return bop
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@jit((types.int32,), nopython=True)
|
| 50 |
+
def inner(a):
|
| 51 |
+
return a + 1
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@jit((types.int32,), nopython=True)
|
| 55 |
+
def more(a):
|
| 56 |
+
return inner(inner(a))
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def outer_simple(a):
|
| 60 |
+
return inner(a) * 2
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def outer_multiple(a):
|
| 64 |
+
return inner(a) * more(a)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@njit
|
| 68 |
+
def __dummy__():
|
| 69 |
+
return
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from os.path import dirname
|
| 2 |
+
import unittest
|
| 3 |
+
from unittest.suite import TestSuite
|
| 4 |
+
|
| 5 |
+
from numba.testing import load_testsuite
|
| 6 |
+
|
| 7 |
+
def load_tests(loader, tests, pattern):
|
| 8 |
+
suite = TestSuite()
|
| 9 |
+
suite.addTests(load_testsuite(loader, dirname(__file__)))
|
| 10 |
+
return suite
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/cache_usecases.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numba as nb
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
#
|
| 5 |
+
# UFunc
|
| 6 |
+
#
|
| 7 |
+
|
| 8 |
+
def direct_ufunc_cache_usecase(**kwargs):
|
| 9 |
+
@nb.vectorize(["intp(intp)", "float64(float64)"], cache=True, **kwargs)
|
| 10 |
+
def ufunc(inp):
|
| 11 |
+
return inp * 2
|
| 12 |
+
|
| 13 |
+
return ufunc
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def indirect_ufunc_cache_usecase(**kwargs):
|
| 17 |
+
@nb.njit(cache=True)
|
| 18 |
+
def indirect_ufunc_core(inp):
|
| 19 |
+
return inp * 3
|
| 20 |
+
|
| 21 |
+
@nb.vectorize(["intp(intp)", "float64(float64)", "complex64(complex64)"],
|
| 22 |
+
**kwargs)
|
| 23 |
+
def ufunc(inp):
|
| 24 |
+
return indirect_ufunc_core(inp)
|
| 25 |
+
|
| 26 |
+
return ufunc
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
#
|
| 30 |
+
# DUFunc
|
| 31 |
+
#
|
| 32 |
+
|
| 33 |
+
def direct_dufunc_cache_usecase(**kwargs):
|
| 34 |
+
@nb.vectorize(cache=True, **kwargs)
|
| 35 |
+
def ufunc(inp):
|
| 36 |
+
return inp * 2
|
| 37 |
+
|
| 38 |
+
return ufunc
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def indirect_dufunc_cache_usecase(**kwargs):
|
| 42 |
+
@nb.njit(cache=True)
|
| 43 |
+
def indirect_ufunc_core(inp):
|
| 44 |
+
return inp * 3
|
| 45 |
+
|
| 46 |
+
@nb.vectorize(**kwargs)
|
| 47 |
+
def ufunc(inp):
|
| 48 |
+
return indirect_ufunc_core(inp)
|
| 49 |
+
|
| 50 |
+
return ufunc
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
#
|
| 54 |
+
# GUFunc
|
| 55 |
+
#
|
| 56 |
+
|
| 57 |
+
def direct_gufunc_cache_usecase(**kwargs):
|
| 58 |
+
@nb.guvectorize(["(intp, intp[:])", "(float64, float64[:])"],
|
| 59 |
+
"()->()", cache=True, **kwargs)
|
| 60 |
+
def gufunc(inp, out):
|
| 61 |
+
out[0] = inp * 2
|
| 62 |
+
|
| 63 |
+
return gufunc
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def indirect_gufunc_cache_usecase(**kwargs):
|
| 67 |
+
@nb.njit(cache=True)
|
| 68 |
+
def core(x):
|
| 69 |
+
return x * 3
|
| 70 |
+
|
| 71 |
+
@nb.guvectorize(["(intp, intp[:])", "(float64, float64[:])",
|
| 72 |
+
"(complex64, complex64[:])"], "()->()", **kwargs)
|
| 73 |
+
def gufunc(inp, out):
|
| 74 |
+
out[0] = core(inp)
|
| 75 |
+
|
| 76 |
+
return gufunc
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_caching.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
import os.path
|
| 3 |
+
import re
|
| 4 |
+
import subprocess
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
from numba.tests.support import capture_cache_log
|
| 9 |
+
from numba.tests.test_caching import BaseCacheTest
|
| 10 |
+
from numba.core import config
|
| 11 |
+
import unittest
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class UfuncCacheTest(BaseCacheTest):
|
| 15 |
+
"""
|
| 16 |
+
Since the cache stats is not exposed by ufunc, we test by looking at the
|
| 17 |
+
cache debug log.
|
| 18 |
+
"""
|
| 19 |
+
_numba_parallel_test_ = False
|
| 20 |
+
|
| 21 |
+
here = os.path.dirname(__file__)
|
| 22 |
+
usecases_file = os.path.join(here, "cache_usecases.py")
|
| 23 |
+
modname = "ufunc_caching_test_fodder"
|
| 24 |
+
|
| 25 |
+
regex_data_saved = re.compile(r'\[cache\] data saved to')
|
| 26 |
+
regex_index_saved = re.compile(r'\[cache\] index saved to')
|
| 27 |
+
|
| 28 |
+
regex_data_loaded = re.compile(r'\[cache\] data loaded from')
|
| 29 |
+
regex_index_loaded = re.compile(r'\[cache\] index loaded from')
|
| 30 |
+
|
| 31 |
+
def check_cache_saved(self, cachelog, count):
|
| 32 |
+
"""
|
| 33 |
+
Check number of cache-save were issued
|
| 34 |
+
"""
|
| 35 |
+
data_saved = self.regex_data_saved.findall(cachelog)
|
| 36 |
+
index_saved = self.regex_index_saved.findall(cachelog)
|
| 37 |
+
self.assertEqual(len(data_saved), count)
|
| 38 |
+
self.assertEqual(len(index_saved), count)
|
| 39 |
+
|
| 40 |
+
def check_cache_loaded(self, cachelog, count):
|
| 41 |
+
"""
|
| 42 |
+
Check number of cache-load were issued
|
| 43 |
+
"""
|
| 44 |
+
data_loaded = self.regex_data_loaded.findall(cachelog)
|
| 45 |
+
index_loaded = self.regex_index_loaded.findall(cachelog)
|
| 46 |
+
self.assertEqual(len(data_loaded), count)
|
| 47 |
+
self.assertEqual(len(index_loaded), count)
|
| 48 |
+
|
| 49 |
+
def check_ufunc_cache(self, usecase_name, n_overloads, **kwargs):
|
| 50 |
+
"""
|
| 51 |
+
Check number of cache load/save.
|
| 52 |
+
There should be one per overloaded version.
|
| 53 |
+
"""
|
| 54 |
+
mod = self.import_module()
|
| 55 |
+
usecase = getattr(mod, usecase_name)
|
| 56 |
+
# New cache entry saved
|
| 57 |
+
with capture_cache_log() as out:
|
| 58 |
+
new_ufunc = usecase(**kwargs)
|
| 59 |
+
cachelog = out.getvalue()
|
| 60 |
+
self.check_cache_saved(cachelog, count=n_overloads)
|
| 61 |
+
|
| 62 |
+
# Use cached version
|
| 63 |
+
with capture_cache_log() as out:
|
| 64 |
+
cached_ufunc = usecase(**kwargs)
|
| 65 |
+
cachelog = out.getvalue()
|
| 66 |
+
self.check_cache_loaded(cachelog, count=n_overloads)
|
| 67 |
+
|
| 68 |
+
return new_ufunc, cached_ufunc
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class TestUfuncCacheTest(UfuncCacheTest):
|
| 72 |
+
|
| 73 |
+
def test_direct_ufunc_cache(self, **kwargs):
|
| 74 |
+
new_ufunc, cached_ufunc = self.check_ufunc_cache(
|
| 75 |
+
"direct_ufunc_cache_usecase", n_overloads=2, **kwargs)
|
| 76 |
+
# Test the cached and original versions
|
| 77 |
+
inp = np.random.random(10).astype(np.float64)
|
| 78 |
+
np.testing.assert_equal(new_ufunc(inp), cached_ufunc(inp))
|
| 79 |
+
inp = np.arange(10, dtype=np.intp)
|
| 80 |
+
np.testing.assert_equal(new_ufunc(inp), cached_ufunc(inp))
|
| 81 |
+
|
| 82 |
+
def test_direct_ufunc_cache_objmode(self):
|
| 83 |
+
self.test_direct_ufunc_cache(forceobj=True)
|
| 84 |
+
|
| 85 |
+
def test_direct_ufunc_cache_parallel(self):
|
| 86 |
+
self.test_direct_ufunc_cache(target='parallel')
|
| 87 |
+
|
| 88 |
+
def test_indirect_ufunc_cache(self, **kwargs):
|
| 89 |
+
new_ufunc, cached_ufunc = self.check_ufunc_cache(
|
| 90 |
+
"indirect_ufunc_cache_usecase", n_overloads=3, **kwargs)
|
| 91 |
+
# Test the cached and original versions
|
| 92 |
+
inp = np.random.random(10).astype(np.float64)
|
| 93 |
+
np.testing.assert_equal(new_ufunc(inp), cached_ufunc(inp))
|
| 94 |
+
inp = np.arange(10, dtype=np.intp)
|
| 95 |
+
np.testing.assert_equal(new_ufunc(inp), cached_ufunc(inp))
|
| 96 |
+
|
| 97 |
+
def test_indirect_ufunc_cache_parallel(self):
|
| 98 |
+
self.test_indirect_ufunc_cache(target='parallel')
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class TestDUfuncCacheTest(UfuncCacheTest):
|
| 102 |
+
# Note: DUFunc doesn't support parallel target yet
|
| 103 |
+
|
| 104 |
+
def check_dufunc_usecase(self, usecase_name):
|
| 105 |
+
mod = self.import_module()
|
| 106 |
+
usecase = getattr(mod, usecase_name)
|
| 107 |
+
# Create dufunc
|
| 108 |
+
with capture_cache_log() as out:
|
| 109 |
+
ufunc = usecase()
|
| 110 |
+
self.check_cache_saved(out.getvalue(), count=0)
|
| 111 |
+
# Compile & cache
|
| 112 |
+
with capture_cache_log() as out:
|
| 113 |
+
ufunc(np.arange(10))
|
| 114 |
+
self.check_cache_saved(out.getvalue(), count=1)
|
| 115 |
+
self.check_cache_loaded(out.getvalue(), count=0)
|
| 116 |
+
# Use cached
|
| 117 |
+
with capture_cache_log() as out:
|
| 118 |
+
ufunc = usecase()
|
| 119 |
+
ufunc(np.arange(10))
|
| 120 |
+
self.check_cache_loaded(out.getvalue(), count=1)
|
| 121 |
+
|
| 122 |
+
def test_direct_dufunc_cache(self):
|
| 123 |
+
# We don't test for objmode because DUfunc don't support it.
|
| 124 |
+
self.check_dufunc_usecase('direct_dufunc_cache_usecase')
|
| 125 |
+
|
| 126 |
+
def test_indirect_dufunc_cache(self):
|
| 127 |
+
self.check_dufunc_usecase('indirect_dufunc_cache_usecase')
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def _fix_raw_path(rstr):
|
| 131 |
+
if config.IS_WIN32:
|
| 132 |
+
rstr = rstr.replace(r'/', r'\\\\')
|
| 133 |
+
return rstr
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class TestGUfuncCacheTest(UfuncCacheTest):
|
| 137 |
+
|
| 138 |
+
def test_filename_prefix(self):
|
| 139 |
+
mod = self.import_module()
|
| 140 |
+
usecase = getattr(mod, "direct_gufunc_cache_usecase")
|
| 141 |
+
with capture_cache_log() as out:
|
| 142 |
+
usecase()
|
| 143 |
+
cachelog = out.getvalue()
|
| 144 |
+
# find number filename with "guf-" prefix
|
| 145 |
+
fmt1 = _fix_raw_path(r'/__pycache__/guf-{}')
|
| 146 |
+
prefixed = re.findall(fmt1.format(self.modname), cachelog)
|
| 147 |
+
fmt2 = _fix_raw_path(r'/__pycache__/{}')
|
| 148 |
+
normal = re.findall(fmt2.format(self.modname), cachelog)
|
| 149 |
+
# expecting 2 overloads
|
| 150 |
+
self.assertGreater(len(normal), 2)
|
| 151 |
+
# expecting equal number of wrappers and overloads cache entries
|
| 152 |
+
self.assertEqual(len(normal), len(prefixed))
|
| 153 |
+
|
| 154 |
+
def test_direct_gufunc_cache(self, **kwargs):
|
| 155 |
+
# 2 cache entry for the 2 overloads
|
| 156 |
+
# and 2 cache entry for the gufunc wrapper
|
| 157 |
+
new_ufunc, cached_ufunc = self.check_ufunc_cache(
|
| 158 |
+
"direct_gufunc_cache_usecase", n_overloads=2 + 2, **kwargs)
|
| 159 |
+
# Test the cached and original versions
|
| 160 |
+
inp = np.random.random(10).astype(np.float64)
|
| 161 |
+
np.testing.assert_equal(new_ufunc(inp), cached_ufunc(inp))
|
| 162 |
+
inp = np.arange(10, dtype=np.intp)
|
| 163 |
+
np.testing.assert_equal(new_ufunc(inp), cached_ufunc(inp))
|
| 164 |
+
|
| 165 |
+
def test_direct_gufunc_cache_objmode(self):
|
| 166 |
+
self.test_direct_gufunc_cache(forceobj=True)
|
| 167 |
+
|
| 168 |
+
def test_direct_gufunc_cache_parallel(self):
|
| 169 |
+
self.test_direct_gufunc_cache(target='parallel')
|
| 170 |
+
|
| 171 |
+
def test_indirect_gufunc_cache(self, **kwargs):
|
| 172 |
+
# 3 cache entry for the 3 overloads
|
| 173 |
+
# and no cache entry for the gufunc wrapper
|
| 174 |
+
new_ufunc, cached_ufunc = self.check_ufunc_cache(
|
| 175 |
+
"indirect_gufunc_cache_usecase", n_overloads=3, **kwargs)
|
| 176 |
+
# Test the cached and original versions
|
| 177 |
+
inp = np.random.random(10).astype(np.float64)
|
| 178 |
+
np.testing.assert_equal(new_ufunc(inp), cached_ufunc(inp))
|
| 179 |
+
inp = np.arange(10, dtype=np.intp)
|
| 180 |
+
np.testing.assert_equal(new_ufunc(inp), cached_ufunc(inp))
|
| 181 |
+
|
| 182 |
+
def test_indirect_gufunc_cache_parallel(self, **kwargs):
|
| 183 |
+
self.test_indirect_gufunc_cache(target='parallel')
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
class TestCacheSpecificIssue(UfuncCacheTest):
|
| 187 |
+
|
| 188 |
+
def run_in_separate_process(self, runcode):
|
| 189 |
+
# Based on the same name util function in test_dispatcher but modified
|
| 190 |
+
# to allow user to define what to run.
|
| 191 |
+
code = """if 1:
|
| 192 |
+
import sys
|
| 193 |
+
|
| 194 |
+
sys.path.insert(0, %(tempdir)r)
|
| 195 |
+
mod = __import__(%(modname)r)
|
| 196 |
+
mod.%(runcode)s
|
| 197 |
+
""" % dict(tempdir=self.tempdir, modname=self.modname,
|
| 198 |
+
runcode=runcode)
|
| 199 |
+
|
| 200 |
+
popen = subprocess.Popen([sys.executable, "-c", code],
|
| 201 |
+
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
| 202 |
+
out, err = popen.communicate()
|
| 203 |
+
if popen.returncode != 0:
|
| 204 |
+
raise AssertionError("process failed with code %s: stderr follows"
|
| 205 |
+
"\n%s\n" % (popen.returncode, err.decode()))
|
| 206 |
+
|
| 207 |
+
#
|
| 208 |
+
# The following test issue #2198 that loading cached (g)ufunc first
|
| 209 |
+
# bypasses some target context initialization.
|
| 210 |
+
#
|
| 211 |
+
|
| 212 |
+
def test_first_load_cached_ufunc(self):
|
| 213 |
+
# ensure function is cached
|
| 214 |
+
self.run_in_separate_process('direct_ufunc_cache_usecase()')
|
| 215 |
+
# use the cached function
|
| 216 |
+
# this will fail if the target context is not init'ed
|
| 217 |
+
self.run_in_separate_process('direct_ufunc_cache_usecase()')
|
| 218 |
+
|
| 219 |
+
def test_first_load_cached_gufunc(self):
|
| 220 |
+
# ensure function is cached
|
| 221 |
+
self.run_in_separate_process('direct_gufunc_cache_usecase()')
|
| 222 |
+
# use the cached function
|
| 223 |
+
# this will fail out if the target context is not init'ed
|
| 224 |
+
self.run_in_separate_process('direct_gufunc_cache_usecase()')
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
if __name__ == '__main__':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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import functools
|
| 2 |
+
import itertools
|
| 3 |
+
import pickle
|
| 4 |
+
import textwrap
|
| 5 |
+
import warnings
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
from numba import njit, vectorize
|
| 10 |
+
from numba.tests.support import MemoryLeakMixin, TestCase
|
| 11 |
+
from numba.core.errors import (TypingError, NumbaNotImplementedError,
|
| 12 |
+
NumbaExperimentalFeatureWarning)
|
| 13 |
+
import unittest
|
| 14 |
+
from numba.np.ufunc import dufunc
|
| 15 |
+
from numba.np.numpy_support import from_dtype
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def pyuadd(a0, a1):
|
| 19 |
+
return a0 + a1
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def pysub(a0, a1):
|
| 23 |
+
return a0 - a1
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def pymult(a0, a1):
|
| 27 |
+
return a0 * a1
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def pydiv(a0, a1):
|
| 31 |
+
return a0 // a1
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def pymin(a0, a1):
|
| 35 |
+
return a0 if a0 < a1 else a1
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class TestDUFunc(MemoryLeakMixin, unittest.TestCase):
|
| 39 |
+
|
| 40 |
+
def nopython_dufunc(self, pyfunc):
|
| 41 |
+
return dufunc.DUFunc(pyfunc, targetoptions=dict(nopython=True))
|
| 42 |
+
|
| 43 |
+
def test_frozen(self):
|
| 44 |
+
duadd = self.nopython_dufunc(pyuadd)
|
| 45 |
+
self.assertFalse(duadd._frozen)
|
| 46 |
+
duadd._frozen = True
|
| 47 |
+
self.assertTrue(duadd._frozen)
|
| 48 |
+
with self.assertRaises(ValueError):
|
| 49 |
+
duadd._frozen = False
|
| 50 |
+
with self.assertRaises(TypeError):
|
| 51 |
+
duadd(np.linspace(0,1,10), np.linspace(1,2,10))
|
| 52 |
+
|
| 53 |
+
def test_scalar(self):
|
| 54 |
+
duadd = self.nopython_dufunc(pyuadd)
|
| 55 |
+
self.assertEqual(pyuadd(1,2), duadd(1,2))
|
| 56 |
+
|
| 57 |
+
def test_npm_call(self):
|
| 58 |
+
duadd = self.nopython_dufunc(pyuadd)
|
| 59 |
+
|
| 60 |
+
@njit
|
| 61 |
+
def npmadd(a0, a1, o0):
|
| 62 |
+
duadd(a0, a1, o0)
|
| 63 |
+
X = np.linspace(0,1.9,20)
|
| 64 |
+
X0 = X[:10]
|
| 65 |
+
X1 = X[10:]
|
| 66 |
+
out0 = np.zeros(10)
|
| 67 |
+
npmadd(X0, X1, out0)
|
| 68 |
+
np.testing.assert_array_equal(X0 + X1, out0)
|
| 69 |
+
Y0 = X0.reshape((2,5))
|
| 70 |
+
Y1 = X1.reshape((2,5))
|
| 71 |
+
out1 = np.zeros((2,5))
|
| 72 |
+
npmadd(Y0, Y1, out1)
|
| 73 |
+
np.testing.assert_array_equal(Y0 + Y1, out1)
|
| 74 |
+
Y2 = X1[:5]
|
| 75 |
+
out2 = np.zeros((2,5))
|
| 76 |
+
npmadd(Y0, Y2, out2)
|
| 77 |
+
np.testing.assert_array_equal(Y0 + Y2, out2)
|
| 78 |
+
|
| 79 |
+
def test_npm_call_implicit_output(self):
|
| 80 |
+
duadd = self.nopython_dufunc(pyuadd)
|
| 81 |
+
|
| 82 |
+
@njit
|
| 83 |
+
def npmadd(a0, a1):
|
| 84 |
+
return duadd(a0, a1)
|
| 85 |
+
X = np.linspace(0,1.9,20)
|
| 86 |
+
X0 = X[:10]
|
| 87 |
+
X1 = X[10:]
|
| 88 |
+
out0 = npmadd(X0, X1)
|
| 89 |
+
np.testing.assert_array_equal(X0 + X1, out0)
|
| 90 |
+
Y0 = X0.reshape((2,5))
|
| 91 |
+
Y1 = X1.reshape((2,5))
|
| 92 |
+
out1 = npmadd(Y0, Y1)
|
| 93 |
+
np.testing.assert_array_equal(Y0 + Y1, out1)
|
| 94 |
+
Y2 = X1[:5]
|
| 95 |
+
out2 = npmadd(Y0, Y2)
|
| 96 |
+
np.testing.assert_array_equal(Y0 + Y2, out2)
|
| 97 |
+
out3 = npmadd(1.,2.)
|
| 98 |
+
self.assertEqual(out3, 3.)
|
| 99 |
+
|
| 100 |
+
def test_ufunc_props(self):
|
| 101 |
+
duadd = self.nopython_dufunc(pyuadd)
|
| 102 |
+
self.assertEqual(duadd.nin, 2)
|
| 103 |
+
self.assertEqual(duadd.nout, 1)
|
| 104 |
+
self.assertEqual(duadd.nargs, duadd.nin + duadd.nout)
|
| 105 |
+
self.assertEqual(duadd.ntypes, 0)
|
| 106 |
+
self.assertEqual(duadd.types, [])
|
| 107 |
+
self.assertEqual(duadd.identity, None)
|
| 108 |
+
duadd(1, 2)
|
| 109 |
+
self.assertEqual(duadd.ntypes, 1)
|
| 110 |
+
self.assertEqual(duadd.ntypes, len(duadd.types))
|
| 111 |
+
self.assertIsNone(duadd.signature)
|
| 112 |
+
|
| 113 |
+
def test_ufunc_props_jit(self):
|
| 114 |
+
duadd = self.nopython_dufunc(pyuadd)
|
| 115 |
+
duadd(1, 2) # initialize types attribute
|
| 116 |
+
|
| 117 |
+
attributes = {'nin': duadd.nin,
|
| 118 |
+
'nout': duadd.nout,
|
| 119 |
+
'nargs': duadd.nargs,
|
| 120 |
+
#'ntypes': duadd.ntypes,
|
| 121 |
+
#'types': duadd.types,
|
| 122 |
+
'identity': duadd.identity,
|
| 123 |
+
'signature': duadd.signature}
|
| 124 |
+
|
| 125 |
+
def get_attr_fn(attr):
|
| 126 |
+
fn = f'''
|
| 127 |
+
def impl():
|
| 128 |
+
return duadd.{attr}
|
| 129 |
+
'''
|
| 130 |
+
l = {}
|
| 131 |
+
exec(textwrap.dedent(fn), {'duadd': duadd}, l)
|
| 132 |
+
return l['impl']
|
| 133 |
+
|
| 134 |
+
for attr, val in attributes.items():
|
| 135 |
+
cfunc = njit(get_attr_fn(attr))
|
| 136 |
+
self.assertEqual(val, cfunc(),
|
| 137 |
+
f'Attribute differs from original: {attr}')
|
| 138 |
+
|
| 139 |
+
# We don't expose [n]types attributes as they are dynamic attributes
|
| 140 |
+
# and can change as the user calls the ufunc
|
| 141 |
+
# cfunc = njit(get_attr_fn('ntypes'))
|
| 142 |
+
# self.assertEqual(cfunc(), 1)
|
| 143 |
+
# duadd(1.1, 2.2)
|
| 144 |
+
# self.assertEqual(cfunc(), 2)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class TestDUFuncMethodsBase(TestCase):
|
| 148 |
+
|
| 149 |
+
@functools.cache
|
| 150 |
+
def _generate_jit(self, ufunc, kind, identity=None):
|
| 151 |
+
assert kind in ('reduce', 'reduceat', 'at')
|
| 152 |
+
if kind == 'reduce':
|
| 153 |
+
if ufunc.nin == 2:
|
| 154 |
+
vec = vectorize(identity=identity)(lambda a, b: ufunc(a, b))
|
| 155 |
+
else:
|
| 156 |
+
vec = vectorize(identity=identity)(lambda a: ufunc(a))
|
| 157 |
+
|
| 158 |
+
@njit
|
| 159 |
+
def fn(array, axis=0, initial=None):
|
| 160 |
+
return vec.reduce(array, axis=axis, initial=initial)
|
| 161 |
+
return fn
|
| 162 |
+
elif kind == 'reduceat':
|
| 163 |
+
if ufunc.nin != 2:
|
| 164 |
+
raise ValueError('reduceat only supported for binary functions')
|
| 165 |
+
vec = vectorize(identity=identity)(lambda a, b: ufunc(a, b))
|
| 166 |
+
|
| 167 |
+
@njit
|
| 168 |
+
def fn(array, indices, axis=0, dtype=None, out=None):
|
| 169 |
+
return vec.reduceat(array, indices, axis, dtype, out)
|
| 170 |
+
return fn
|
| 171 |
+
else:
|
| 172 |
+
if ufunc.nin == 2:
|
| 173 |
+
vec = vectorize(identity=identity)(lambda a, b: ufunc(a, b))
|
| 174 |
+
else:
|
| 175 |
+
vec = vectorize(identity=identity)(lambda a: ufunc(a))
|
| 176 |
+
|
| 177 |
+
@njit
|
| 178 |
+
def fn(*args):
|
| 179 |
+
return vec.at(*args)
|
| 180 |
+
return fn
|
| 181 |
+
|
| 182 |
+
def _reduce(self, ufunc, identity):
|
| 183 |
+
return self._generate_jit(ufunc, 'reduce', identity=identity)
|
| 184 |
+
|
| 185 |
+
def _reduceat(self, ufunc, identity):
|
| 186 |
+
return self._generate_jit(ufunc, 'reduceat', identity=identity)
|
| 187 |
+
|
| 188 |
+
def _at(self, ufunc):
|
| 189 |
+
return self._generate_jit(ufunc, 'at')
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
class TestDUFuncAt(TestDUFuncMethodsBase):
|
| 193 |
+
def _compare_output(self, fn, ufunc, a, *args):
|
| 194 |
+
expected = a.copy()
|
| 195 |
+
got = a.copy()
|
| 196 |
+
ufunc.at(expected, *args)
|
| 197 |
+
fn(got, *args)
|
| 198 |
+
self.assertPreciseEqual(expected, got)
|
| 199 |
+
|
| 200 |
+
def test_numpy_ufunc_at_basic(self):
|
| 201 |
+
# tests taken from: https://github.com/numpy/numpy/blob/27d8c43eb958b4ecee59b4d66908750759a9afc2/numpy/core/tests/test_ufunc.py#L1974-L2003 # noqa: E501
|
| 202 |
+
# NumPy also test this function with a Rational array dtype. We skip
|
| 203 |
+
# this test as Numba doesn't support Rational
|
| 204 |
+
a = np.arange(10, dtype=int)
|
| 205 |
+
|
| 206 |
+
add_at = self._at(np.add)
|
| 207 |
+
negative_at = self._at(np.negative)
|
| 208 |
+
|
| 209 |
+
negative_vec = vectorize()(lambda a: np.negative(a))
|
| 210 |
+
|
| 211 |
+
@njit
|
| 212 |
+
def negative_jit_2(a, indices, b):
|
| 213 |
+
return negative_vec.at(a, indices, b)
|
| 214 |
+
|
| 215 |
+
# basic testing
|
| 216 |
+
self._compare_output(add_at, np.add, a, [2, 5, 2], 1)
|
| 217 |
+
|
| 218 |
+
# missing second operand
|
| 219 |
+
err_msg = 'second operand needed for ufunc'
|
| 220 |
+
with self.assertRaisesRegex(TypingError, err_msg):
|
| 221 |
+
add_at(a.copy(), [2, 5, 3], None)
|
| 222 |
+
|
| 223 |
+
self._compare_output(negative_at, np.negative, a.copy(), [2, 5, 3])
|
| 224 |
+
|
| 225 |
+
b = np.array([100, 100, 100])
|
| 226 |
+
self._compare_output(add_at, np.add, a.copy(), [2, 5, 2], b)
|
| 227 |
+
|
| 228 |
+
# extraneous second operand
|
| 229 |
+
err_msg = 'second operand provided when ufunc is unary'
|
| 230 |
+
with self.assertRaisesRegex(TypingError, err_msg):
|
| 231 |
+
negative_jit_2(a.copy(), [2, 5, 3], [1, 2, 3])
|
| 232 |
+
|
| 233 |
+
with self.assertRaises(TypingError):
|
| 234 |
+
add_at(a.copy(), [2, 5, 3], [[1, 2], 1])
|
| 235 |
+
|
| 236 |
+
def test_ufunc_at_inner_loop(self):
|
| 237 |
+
typecodes = np.typecodes['Complex']
|
| 238 |
+
ufuncs = (np.add, np.subtract, np.multiply)
|
| 239 |
+
for typecode in typecodes:
|
| 240 |
+
|
| 241 |
+
try:
|
| 242 |
+
from_dtype(np.dtype(typecode))
|
| 243 |
+
except NumbaNotImplementedError:
|
| 244 |
+
continue
|
| 245 |
+
|
| 246 |
+
for ufunc in ufuncs:
|
| 247 |
+
a = np.ones(10, dtype=typecode)
|
| 248 |
+
indx = np.concatenate([np.ones(6, dtype=np.intp),
|
| 249 |
+
np.full(18, 4, dtype=np.intp)])
|
| 250 |
+
value = a.dtype.type(1j)
|
| 251 |
+
ufunc_at = self._at(ufunc)
|
| 252 |
+
ufunc_at(a, indx, value)
|
| 253 |
+
expected = np.ones_like(a)
|
| 254 |
+
if ufunc is np.multiply:
|
| 255 |
+
expected[1] = expected[4] = -1
|
| 256 |
+
else:
|
| 257 |
+
expected[1] += 6 * (value if ufunc is np.add else -value)
|
| 258 |
+
expected[4] += 18 * (value if ufunc is np.add else -value)
|
| 259 |
+
|
| 260 |
+
self.assertPreciseEqual(a, expected)
|
| 261 |
+
|
| 262 |
+
def test_ufunc_at_ellipsis(self):
|
| 263 |
+
# Make sure the indexed loop check does not choke on iters
|
| 264 |
+
# with subspaces
|
| 265 |
+
arr = np.zeros(5, dtype=int)
|
| 266 |
+
add_at = self._at(np.add)
|
| 267 |
+
self._compare_output(add_at, np.add, arr, slice(None),
|
| 268 |
+
np.ones(5, dtype=int))
|
| 269 |
+
|
| 270 |
+
def test_ufunc_at_negative(self):
|
| 271 |
+
arr = np.ones(5, dtype=np.int32)
|
| 272 |
+
indx = np.arange(5)
|
| 273 |
+
at = self._at(np.negative)
|
| 274 |
+
at(arr, indx)
|
| 275 |
+
assert np.all(arr == [-1, -1, -1, -1, -1])
|
| 276 |
+
|
| 277 |
+
def test_ufunc_at_large(self):
|
| 278 |
+
# NumPy issue gh-23457
|
| 279 |
+
indices = np.zeros(8195, dtype=np.int16)
|
| 280 |
+
b = np.zeros(8195, dtype=float)
|
| 281 |
+
b[0] = 10
|
| 282 |
+
b[1] = 5
|
| 283 |
+
b[8192:] = 100
|
| 284 |
+
a = np.zeros(1, dtype=float)
|
| 285 |
+
add_at = self._at(np.add)
|
| 286 |
+
add_at(a, indices, b)
|
| 287 |
+
assert a[0] == b.sum()
|
| 288 |
+
|
| 289 |
+
def test_cast_index_fastpath(self):
|
| 290 |
+
arr = np.zeros(10)
|
| 291 |
+
values = np.ones(100000)
|
| 292 |
+
add_at = self._at(np.add)
|
| 293 |
+
# index must be cast, which may be buffered in chunks:
|
| 294 |
+
index = np.zeros(len(values), dtype=np.uint8)
|
| 295 |
+
add_at(arr, index, values)
|
| 296 |
+
assert arr[0] == len(values)
|
| 297 |
+
|
| 298 |
+
def test_ufunc_at_scalar_value_fastpath(self):
|
| 299 |
+
values = (np.ones(1), np.ones(()), np.float64(1.), 1.)
|
| 300 |
+
for value in values:
|
| 301 |
+
arr = np.zeros(1000)
|
| 302 |
+
# index must be cast, which may be buffered in chunks:
|
| 303 |
+
index = np.repeat(np.arange(1000), 2)
|
| 304 |
+
add_at = self._at(np.add)
|
| 305 |
+
add_at(arr, index, value)
|
| 306 |
+
np.testing.assert_array_equal(arr, np.full_like(arr, 2 * value))
|
| 307 |
+
|
| 308 |
+
def test_ufunc_at_multiD(self):
|
| 309 |
+
a = np.arange(9).reshape(3, 3)
|
| 310 |
+
b = np.array([[100, 100, 100], [200, 200, 200], [300, 300, 300]])
|
| 311 |
+
add_at = self._at(np.add)
|
| 312 |
+
add_at(a, (slice(None), np.asarray([1, 2, 1])), b)
|
| 313 |
+
self.assertPreciseEqual(a, np.array(
|
| 314 |
+
[[0, 201, 102], [3, 404, 205], [6, 607, 308]]))
|
| 315 |
+
|
| 316 |
+
a = np.arange(27).reshape(3, 3, 3)
|
| 317 |
+
b = np.array([100, 200, 300])
|
| 318 |
+
add_at(a, (slice(None), slice(None), np.asarray([1, 2, 1])), b)
|
| 319 |
+
self.assertPreciseEqual(a, np.array(
|
| 320 |
+
[[[0, 401, 202],
|
| 321 |
+
[3, 404, 205],
|
| 322 |
+
[6, 407, 208]],
|
| 323 |
+
|
| 324 |
+
[[9, 410, 211],
|
| 325 |
+
[12, 413, 214],
|
| 326 |
+
[15, 416, 217]],
|
| 327 |
+
|
| 328 |
+
[[18, 419, 220],
|
| 329 |
+
[21, 422, 223],
|
| 330 |
+
[24, 425, 226]]]))
|
| 331 |
+
|
| 332 |
+
a = np.arange(9).reshape(3, 3)
|
| 333 |
+
b = np.array([[100, 100, 100], [200, 200, 200], [300, 300, 300]])
|
| 334 |
+
add_at(a, (np.asarray([1, 2, 1]), slice(None)), b)
|
| 335 |
+
self.assertPreciseEqual(a, np.asarray(
|
| 336 |
+
[[0, 1, 2], [403, 404, 405], [206, 207, 208]]))
|
| 337 |
+
|
| 338 |
+
a = np.arange(27).reshape(3, 3, 3)
|
| 339 |
+
b = np.array([100, 200, 300])
|
| 340 |
+
add_at(a, (slice(None), np.asarray([1, 2, 1]), slice(None)), b)
|
| 341 |
+
self.assertPreciseEqual(a, np.asarray(
|
| 342 |
+
[[[0, 1, 2],
|
| 343 |
+
[203, 404, 605],
|
| 344 |
+
[106, 207, 308]],
|
| 345 |
+
|
| 346 |
+
[[9, 10, 11],
|
| 347 |
+
[212, 413, 614],
|
| 348 |
+
[115, 216, 317]],
|
| 349 |
+
|
| 350 |
+
[[18, 19, 20],
|
| 351 |
+
[221, 422, 623],
|
| 352 |
+
[124, 225, 326]]]))
|
| 353 |
+
|
| 354 |
+
a = np.arange(9).reshape(3, 3)
|
| 355 |
+
b = np.array([100, 200, 300])
|
| 356 |
+
add_at(a, (0, np.asarray([1, 2, 1])), b)
|
| 357 |
+
self.assertPreciseEqual(a, np.asarray(
|
| 358 |
+
[[0, 401, 202], [3, 4, 5], [6, 7, 8]]))
|
| 359 |
+
|
| 360 |
+
a = np.arange(27).reshape(3, 3, 3)
|
| 361 |
+
b = np.array([100, 200, 300])
|
| 362 |
+
add_at(a, (np.asarray([1, 2, 1]), 0, slice(None)), b)
|
| 363 |
+
self.assertPreciseEqual(a, np.asarray(
|
| 364 |
+
[[[0, 1, 2],
|
| 365 |
+
[3, 4, 5],
|
| 366 |
+
[6, 7, 8]],
|
| 367 |
+
|
| 368 |
+
[[209, 410, 611],
|
| 369 |
+
[12, 13, 14],
|
| 370 |
+
[15, 16, 17]],
|
| 371 |
+
|
| 372 |
+
[[118, 219, 320],
|
| 373 |
+
[21, 22, 23],
|
| 374 |
+
[24, 25, 26]]]))
|
| 375 |
+
|
| 376 |
+
a = np.arange(27).reshape(3, 3, 3)
|
| 377 |
+
b = np.array([100, 200, 300])
|
| 378 |
+
add_at = self._at(np.add)
|
| 379 |
+
add_at(a, (slice(None), slice(None), slice(None)), b)
|
| 380 |
+
self.assertPreciseEqual(a, np.asarray(
|
| 381 |
+
[[[100, 201, 302],
|
| 382 |
+
[103, 204, 305],
|
| 383 |
+
[106, 207, 308]],
|
| 384 |
+
|
| 385 |
+
[[109, 210, 311],
|
| 386 |
+
[112, 213, 314],
|
| 387 |
+
[115, 216, 317]],
|
| 388 |
+
|
| 389 |
+
[[118, 219, 320],
|
| 390 |
+
[121, 222, 323],
|
| 391 |
+
[124, 225, 326]]]))
|
| 392 |
+
|
| 393 |
+
def test_ufunc_at_0D(self):
|
| 394 |
+
a = np.array(0)
|
| 395 |
+
add_at = self._at(np.add)
|
| 396 |
+
add_at(a, (), 1)
|
| 397 |
+
self.assertPreciseEqual(a, np.array(1))
|
| 398 |
+
|
| 399 |
+
with self.assertRaises(TypingError):
|
| 400 |
+
add_at(a, 0, 1)
|
| 401 |
+
|
| 402 |
+
b = np.arange(3)
|
| 403 |
+
add_at(b, 0, 1)
|
| 404 |
+
self.assertPreciseEqual(b, np.array([1, 1, 2]))
|
| 405 |
+
|
| 406 |
+
# NumPy checks for IndexError but we can't call a jit function with an
|
| 407 |
+
# empty list as Numba raises "can't compute fingerprint of empty list"
|
| 408 |
+
with self.assertRaises(ValueError):
|
| 409 |
+
add_at(a, [], 1)
|
| 410 |
+
|
| 411 |
+
def test_ufunc_at_dtypes(self):
|
| 412 |
+
# Test mixed dtypes
|
| 413 |
+
a = np.arange(10)
|
| 414 |
+
power_at = self._at(np.power)
|
| 415 |
+
power_at(a, [1, 2, 3, 2], 3.5)
|
| 416 |
+
self.assertPreciseEqual(a, np.array([0, 1, 4414, 46, 4, 5, 6, 7, 8, 9]))
|
| 417 |
+
|
| 418 |
+
def test_ufunc_at_boolean(self):
|
| 419 |
+
# Test boolean indexing and boolean ufuncs
|
| 420 |
+
a = np.arange(10)
|
| 421 |
+
index = a % 2 == 0
|
| 422 |
+
equal_at = self._at(np.equal)
|
| 423 |
+
# boolean indexing not supported
|
| 424 |
+
equal_at(a, index, [0, 2, 4, 6, 8])
|
| 425 |
+
self.assertPreciseEqual(a, np.array([1, 1, 1, 3, 1, 5, 1, 7, 1, 9]))
|
| 426 |
+
|
| 427 |
+
def test_ufunc_at_boolean2(self):
|
| 428 |
+
# Test unary operator
|
| 429 |
+
a = np.arange(10, dtype='u4')
|
| 430 |
+
invert_at = self._at(np.invert)
|
| 431 |
+
invert_at(a, [2, 5, 2])
|
| 432 |
+
self.assertPreciseEqual(a, np.array([0, 1, 2, 3, 4, 5 ^ 0xffffffff, 6,
|
| 433 |
+
7, 8, 9], dtype=np.uint32))
|
| 434 |
+
|
| 435 |
+
def test_ufunc_at_advanced(self):
|
| 436 |
+
# Test empty subspace
|
| 437 |
+
orig = np.arange(4)
|
| 438 |
+
a = orig[:, None][:, 0:0]
|
| 439 |
+
add_at = self._at(np.add)
|
| 440 |
+
add_at(a, [0, 1], 3)
|
| 441 |
+
self.assertPreciseEqual(orig, np.arange(4))
|
| 442 |
+
|
| 443 |
+
@unittest.expectedFailure
|
| 444 |
+
def test_ufunc_at_advanced_2(self):
|
| 445 |
+
# Test with swapped byte order
|
| 446 |
+
index = np.array([1, 2, 1], np.dtype('i').newbyteorder())
|
| 447 |
+
values = np.array([1, 2, 3, 4], np.dtype('f').newbyteorder())
|
| 448 |
+
add_at = self._at(np.add)
|
| 449 |
+
add_at(values, index, 3)
|
| 450 |
+
self.assertPreciseEqual(values, [1, 8, 6, 4])
|
| 451 |
+
|
| 452 |
+
def test_ufunc_at_advanced_3(self):
|
| 453 |
+
# Test exception thrown
|
| 454 |
+
values = np.array(['a', 1], dtype=object)
|
| 455 |
+
add_at = self._at(np.add)
|
| 456 |
+
with self.assertRaises(TypingError):
|
| 457 |
+
add_at(values, [0, 1], 1)
|
| 458 |
+
self.assertPreciseEqual(values, np.array(['a', 1], dtype=object))
|
| 459 |
+
|
| 460 |
+
def test_ufunc_at_advanced_4(self):
|
| 461 |
+
# Test multiple output ufuncs raise error, NumPy gh-5665
|
| 462 |
+
modf_at = self._at(np.modf)
|
| 463 |
+
# NumPy raises ValueError as modf returns multiple outputs
|
| 464 |
+
with self.assertRaises(TypingError):
|
| 465 |
+
modf_at(np.arange(10), [1])
|
| 466 |
+
|
| 467 |
+
def test_ufunc_at_advanced_5(self):
|
| 468 |
+
# Test maximum
|
| 469 |
+
maximum_at = self._at(np.maximum)
|
| 470 |
+
a = np.array([1, 2, 3])
|
| 471 |
+
maximum_at(a, [0], 0)
|
| 472 |
+
self.assertPreciseEqual(a, np.array([1, 2, 3]))
|
| 473 |
+
|
| 474 |
+
def test_ufunc_at_negative_indexes(self):
|
| 475 |
+
dtypes = np.typecodes['AllInteger'] + np.typecodes['Float']
|
| 476 |
+
ufuncs = (np.add, np.subtract, np.divide, np.minimum, np.maximum)
|
| 477 |
+
|
| 478 |
+
for dtype in dtypes:
|
| 479 |
+
|
| 480 |
+
if dtype in ('e',): # skip float16 as we don't have an impl. for it
|
| 481 |
+
continue
|
| 482 |
+
|
| 483 |
+
try:
|
| 484 |
+
from_dtype(np.dtype(dtype))
|
| 485 |
+
except NumbaNotImplementedError:
|
| 486 |
+
continue
|
| 487 |
+
|
| 488 |
+
for ufunc in ufuncs:
|
| 489 |
+
a = np.arange(0, 10).astype(dtype)
|
| 490 |
+
indxs = np.array([-1, 1, -1, 2]).astype(np.intp)
|
| 491 |
+
vals = np.array([1, 5, 2, 10], dtype=a.dtype)
|
| 492 |
+
|
| 493 |
+
expected = a.copy()
|
| 494 |
+
for i, v in zip(indxs, vals):
|
| 495 |
+
expected[i] = ufunc(expected[i], v)
|
| 496 |
+
|
| 497 |
+
ufunc_at = self._at(ufunc)
|
| 498 |
+
ufunc_at(a, indxs, vals)
|
| 499 |
+
np.testing.assert_array_equal(a, expected)
|
| 500 |
+
assert np.all(indxs == [-1, 1, -1, 2])
|
| 501 |
+
|
| 502 |
+
@unittest.expectedFailure
|
| 503 |
+
def test_ufunc_at_not_none_signature(self):
|
| 504 |
+
# Test ufuncs with non-trivial signature raise a TypeError
|
| 505 |
+
a = np.ones((2, 2, 2))
|
| 506 |
+
b = np.ones((1, 2, 2))
|
| 507 |
+
# matmul is a gufunc, thus, this will fail atm
|
| 508 |
+
matmul_at = self._at(np.matmul)
|
| 509 |
+
err_msg = 'does not support ufunc with non-trivial signature'
|
| 510 |
+
with self.assertRaisesRegex(TypingError, err_msg):
|
| 511 |
+
matmul_at(a, [0], b)
|
| 512 |
+
|
| 513 |
+
# a = np.array([[[1, 2], [3, 4]]])
|
| 514 |
+
# assert_raises(TypeError, np.linalg._umath_linalg.det.at, a, [0])
|
| 515 |
+
|
| 516 |
+
def test_ufunc_at_no_loop_for_op(self):
|
| 517 |
+
# str dtype does not have a ufunc loop for np.add
|
| 518 |
+
arr = np.ones(10, dtype=str)
|
| 519 |
+
add_at = self._at(np.add)
|
| 520 |
+
# NumPy raises `np.core._exceptions._UFuncNoLoopError`
|
| 521 |
+
with self.assertRaises(TypingError):
|
| 522 |
+
add_at(arr, [0, 1], [0, 1])
|
| 523 |
+
|
| 524 |
+
def test_ufunc_at_output_casting(self):
|
| 525 |
+
arr = np.array([-1])
|
| 526 |
+
equal_at = self._at(np.equal)
|
| 527 |
+
equal_at(arr, [0], [0])
|
| 528 |
+
assert arr[0] == 0
|
| 529 |
+
|
| 530 |
+
def test_ufunc_at_broadcast_failure(self):
|
| 531 |
+
arr = np.arange(5)
|
| 532 |
+
add_at = self._at(np.add)
|
| 533 |
+
|
| 534 |
+
# NumPy raises ValueError('array is not broadcastable to correct shape')
|
| 535 |
+
msg = 'operands could not be broadcast together with remapped shapes'
|
| 536 |
+
with self.assertRaisesRegex(ValueError, msg):
|
| 537 |
+
add_at(arr, [0, 1], [1, 2, 3])
|
| 538 |
+
|
| 539 |
+
def test_ufunc_at_dynamic(self):
|
| 540 |
+
arr = np.arange(5)
|
| 541 |
+
|
| 542 |
+
@vectorize
|
| 543 |
+
def inc(x):
|
| 544 |
+
return x + 1
|
| 545 |
+
|
| 546 |
+
self.assertEqual(len(inc.types), 0)
|
| 547 |
+
|
| 548 |
+
# trying to call inc.at should trigger compilation
|
| 549 |
+
inc.at(arr, [1, 3])
|
| 550 |
+
|
| 551 |
+
self.assertGreater(len(inc.types), 0)
|
| 552 |
+
|
| 553 |
+
def test_ufunc_at_experimental_warning(self):
|
| 554 |
+
arr = np.arange(5)
|
| 555 |
+
add_at = self._at(np.add)
|
| 556 |
+
|
| 557 |
+
with warnings.catch_warnings(record=True) as w:
|
| 558 |
+
warnings.simplefilter('always', NumbaExperimentalFeatureWarning)
|
| 559 |
+
|
| 560 |
+
add_at(arr, [0, 3], 10)
|
| 561 |
+
|
| 562 |
+
self.assertGreater(len(w), 0)
|
| 563 |
+
self.assertIn('ufunc.at feature is experimental', str(w[0].message))
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
class TestDUFuncReduceNumPyTests(TestCase):
|
| 567 |
+
# Tests taken from
|
| 568 |
+
# https://github.com/numpy/numpy/blob/51ee17b6bd4ccec60a5483ee8bff94ad0c0e8585/numpy/_core/tests/test_ufunc.py # noqa: E501
|
| 569 |
+
|
| 570 |
+
def _generate_jit(self, ufunc, identity=None):
|
| 571 |
+
if ufunc.nin == 2:
|
| 572 |
+
vec = vectorize(identity=identity)(lambda a, b: ufunc(a, b))
|
| 573 |
+
else:
|
| 574 |
+
vec = vectorize(identity=identity)(lambda a: ufunc(a))
|
| 575 |
+
|
| 576 |
+
@njit
|
| 577 |
+
def fn(array, axis=0, initial=None):
|
| 578 |
+
return vec.reduce(array, axis=axis, initial=initial)
|
| 579 |
+
return fn
|
| 580 |
+
|
| 581 |
+
@unittest.expectedFailure
|
| 582 |
+
def test_numpy_scalar_reduction(self):
|
| 583 |
+
# scalar reduction is not supported
|
| 584 |
+
power_reduce = self._generate_jit(np.power)
|
| 585 |
+
expected = np.power.reduce(3)
|
| 586 |
+
got = power_reduce(3)
|
| 587 |
+
self.assertPreciseEqual(expected, got)
|
| 588 |
+
|
| 589 |
+
def check_identityless_reduction(self, a):
|
| 590 |
+
def compare_output(a, b):
|
| 591 |
+
# We don't use self.assertPreciseEqual as the dtype differs
|
| 592 |
+
# between the value from the reduction and the hardcoded output
|
| 593 |
+
np.testing.assert_equal(a, b)
|
| 594 |
+
# test taken from:
|
| 595 |
+
# https://github.com/numpy/numpy/blob/51ee17b6bd4ccec60a5483ee8bff94ad0c0e8585/numpy/_core/tests/test_ufunc.py#L1591 # noqa: E501
|
| 596 |
+
|
| 597 |
+
minimum_reduce = self._generate_jit(np.minimum, identity='reorderable')
|
| 598 |
+
|
| 599 |
+
# np.minimum.reduce is an identityless reduction
|
| 600 |
+
|
| 601 |
+
# Verify that it sees the zero at various positions
|
| 602 |
+
a[...] = 1
|
| 603 |
+
a[1, 0, 0] = 0
|
| 604 |
+
compare_output(minimum_reduce(a, axis=None), 0)
|
| 605 |
+
compare_output(minimum_reduce(a, axis=(0, 1)), [0, 1, 1, 1])
|
| 606 |
+
compare_output(minimum_reduce(a, axis=(0, 2)), [0, 1, 1])
|
| 607 |
+
compare_output(minimum_reduce(a, axis=(1, 2)), [1, 0])
|
| 608 |
+
compare_output(minimum_reduce(a, axis=0),
|
| 609 |
+
[[0, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]])
|
| 610 |
+
compare_output(minimum_reduce(a, axis=1),
|
| 611 |
+
[[1, 1, 1, 1], [0, 1, 1, 1]])
|
| 612 |
+
compare_output(minimum_reduce(a, axis=2),
|
| 613 |
+
[[1, 1, 1], [0, 1, 1]])
|
| 614 |
+
compare_output(minimum_reduce(a, axis=()), a)
|
| 615 |
+
|
| 616 |
+
a[...] = 1
|
| 617 |
+
a[0, 1, 0] = 0
|
| 618 |
+
compare_output(minimum_reduce(a, axis=None), 0)
|
| 619 |
+
compare_output(minimum_reduce(a, axis=(0, 1)), [0, 1, 1, 1])
|
| 620 |
+
compare_output(minimum_reduce(a, axis=(0, 2)), [1, 0, 1])
|
| 621 |
+
compare_output(minimum_reduce(a, axis=(1, 2)), [0, 1])
|
| 622 |
+
compare_output(minimum_reduce(a, axis=0),
|
| 623 |
+
[[1, 1, 1, 1], [0, 1, 1, 1], [1, 1, 1, 1]])
|
| 624 |
+
compare_output(minimum_reduce(a, axis=1),
|
| 625 |
+
[[0, 1, 1, 1], [1, 1, 1, 1]])
|
| 626 |
+
compare_output(minimum_reduce(a, axis=2),
|
| 627 |
+
[[1, 0, 1], [1, 1, 1]])
|
| 628 |
+
compare_output(minimum_reduce(a, axis=()), a)
|
| 629 |
+
|
| 630 |
+
a[...] = 1
|
| 631 |
+
a[0, 0, 1] = 0
|
| 632 |
+
compare_output(minimum_reduce(a, axis=None), 0)
|
| 633 |
+
compare_output(minimum_reduce(a, axis=(0, 1)), [1, 0, 1, 1])
|
| 634 |
+
compare_output(minimum_reduce(a, axis=(0, 2)), [0, 1, 1])
|
| 635 |
+
compare_output(minimum_reduce(a, axis=(1, 2)), [0, 1])
|
| 636 |
+
compare_output(minimum_reduce(a, axis=0),
|
| 637 |
+
[[1, 0, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]])
|
| 638 |
+
compare_output(minimum_reduce(a, axis=1),
|
| 639 |
+
[[1, 0, 1, 1], [1, 1, 1, 1]])
|
| 640 |
+
compare_output(minimum_reduce(a, axis=2),
|
| 641 |
+
[[0, 1, 1], [1, 1, 1]])
|
| 642 |
+
compare_output(minimum_reduce(a, axis=()), a)
|
| 643 |
+
|
| 644 |
+
def test_numpy_identityless_reduction_corder(self):
|
| 645 |
+
a = np.empty((2, 3, 4), order='C')
|
| 646 |
+
self.check_identityless_reduction(a)
|
| 647 |
+
|
| 648 |
+
def test_numpy_identityless_reduction_forder(self):
|
| 649 |
+
a = np.empty((2, 3, 4), order='F')
|
| 650 |
+
self.check_identityless_reduction(a)
|
| 651 |
+
|
| 652 |
+
def test_numpy_identityless_reduction_otherorder(self):
|
| 653 |
+
a = np.empty((2, 4, 3), order='C').swapaxes(1, 2)
|
| 654 |
+
self.check_identityless_reduction(a)
|
| 655 |
+
|
| 656 |
+
def test_numpy_identityless_reduction_noncontig(self):
|
| 657 |
+
a = np.empty((3, 5, 4), order='C').swapaxes(1, 2)
|
| 658 |
+
a = a[1:, 1:, 1:]
|
| 659 |
+
self.check_identityless_reduction(a)
|
| 660 |
+
|
| 661 |
+
def test_numpy_identityless_reduction_noncontig_unaligned(self):
|
| 662 |
+
a = np.empty((3 * 4 * 5 * 8 + 1,), dtype='i1')
|
| 663 |
+
a = a[1:].view(dtype='f8')
|
| 664 |
+
a = a.reshape((3, 4, 5))
|
| 665 |
+
a = a[1:, 1:, 1:]
|
| 666 |
+
self.check_identityless_reduction(a)
|
| 667 |
+
|
| 668 |
+
def test_numpy_initial_reduction(self):
|
| 669 |
+
# np.minimum.reduce is an identityless reduction
|
| 670 |
+
add_reduce = self._generate_jit(np.add)
|
| 671 |
+
min_reduce = self._generate_jit(np.minimum)
|
| 672 |
+
max_reduce = self._generate_jit(np.maximum)
|
| 673 |
+
|
| 674 |
+
# For cases like np.maximum(np.abs(...), initial=0)
|
| 675 |
+
# More generally, a supremum over non-negative numbers.
|
| 676 |
+
self.assertPreciseEqual(max_reduce(np.asarray([]), initial=0), 0.0)
|
| 677 |
+
|
| 678 |
+
# For cases like reduction of an empty array over the reals.
|
| 679 |
+
self.assertPreciseEqual(min_reduce(np.asarray([]), initial=np.inf),
|
| 680 |
+
np.inf)
|
| 681 |
+
self.assertPreciseEqual(max_reduce(np.asarray([]), initial=-np.inf),
|
| 682 |
+
-np.inf)
|
| 683 |
+
|
| 684 |
+
# Random tests
|
| 685 |
+
self.assertPreciseEqual(min_reduce(np.asarray([5]), initial=4), 4)
|
| 686 |
+
self.assertPreciseEqual(max_reduce(np.asarray([4]), initial=5), 5)
|
| 687 |
+
self.assertPreciseEqual(max_reduce(np.asarray([5]), initial=4), 5)
|
| 688 |
+
self.assertPreciseEqual(min_reduce(np.asarray([4]), initial=5), 4)
|
| 689 |
+
|
| 690 |
+
# Check initial=None raises ValueError for both types of ufunc
|
| 691 |
+
# reductions
|
| 692 |
+
msg = 'zero-size array to reduction operation'
|
| 693 |
+
for func in (add_reduce, min_reduce):
|
| 694 |
+
with self.assertRaisesRegex(ValueError, msg):
|
| 695 |
+
func(np.asarray([]), initial=None)
|
| 696 |
+
|
| 697 |
+
def test_numpy_empty_reduction_and_identity(self):
|
| 698 |
+
arr = np.zeros((0, 5))
|
| 699 |
+
true_divide_reduce = self._generate_jit(np.true_divide)
|
| 700 |
+
|
| 701 |
+
# OK, since the reduction itself is *not* empty, the result is
|
| 702 |
+
expected = np.true_divide.reduce(arr, axis=1)
|
| 703 |
+
got = true_divide_reduce(arr, axis=1)
|
| 704 |
+
self.assertPreciseEqual(expected, got)
|
| 705 |
+
self.assertPreciseEqual(got.shape, (0,))
|
| 706 |
+
|
| 707 |
+
# Not OK, the reduction itself is empty and we have no identity
|
| 708 |
+
msg = 'zero-size array to reduction operation'
|
| 709 |
+
with self.assertRaisesRegex(ValueError, msg):
|
| 710 |
+
true_divide_reduce(arr, axis=0)
|
| 711 |
+
|
| 712 |
+
# Test that an empty reduction fails also if the result is empty
|
| 713 |
+
arr = np.zeros((0, 0, 5))
|
| 714 |
+
with self.assertRaisesRegex(ValueError, msg):
|
| 715 |
+
true_divide_reduce(arr, axis=1)
|
| 716 |
+
|
| 717 |
+
# Division reduction makes sense with `initial=1` (empty or not):
|
| 718 |
+
expected = np.true_divide.reduce(arr, axis=1, initial=1)
|
| 719 |
+
got = true_divide_reduce(arr, axis=1, initial=1)
|
| 720 |
+
self.assertPreciseEqual(expected, got)
|
| 721 |
+
|
| 722 |
+
def test_identityless_reduction_nonreorderable(self):
|
| 723 |
+
a = np.array([[8.0, 2.0, 2.0], [1.0, 0.5, 0.25]])
|
| 724 |
+
|
| 725 |
+
divide_reduce = self._generate_jit(np.divide)
|
| 726 |
+
res = divide_reduce(a, axis=0)
|
| 727 |
+
self.assertPreciseEqual(res, np.asarray([8.0, 4.0, 8.0]))
|
| 728 |
+
|
| 729 |
+
res = divide_reduce(a, axis=1)
|
| 730 |
+
self.assertPreciseEqual(res, np.asarray([2.0, 8.0]))
|
| 731 |
+
|
| 732 |
+
res = divide_reduce(a, axis=())
|
| 733 |
+
self.assertPreciseEqual(res, a)
|
| 734 |
+
|
| 735 |
+
# will not raise as per Numba issue #9283
|
| 736 |
+
# assert_raises(ValueError, np.divide.reduce, a, axis=(0, 1))
|
| 737 |
+
|
| 738 |
+
def test_reduce_zero_axis(self):
|
| 739 |
+
# If we have a n x m array and do a reduction with axis=1, then we are
|
| 740 |
+
# doing n reductions, and each reduction takes an m-element array. For
|
| 741 |
+
# a reduction operation without an identity, then:
|
| 742 |
+
# n > 0, m > 0: fine
|
| 743 |
+
# n = 0, m > 0: fine, doing 0 reductions of m-element arrays
|
| 744 |
+
# n > 0, m = 0: can't reduce a 0-element array, ValueError
|
| 745 |
+
# n = 0, m = 0: can't reduce a 0-element array, ValueError (for
|
| 746 |
+
# consistency with the above case)
|
| 747 |
+
# This test doesn't actually look at return values, it just checks to
|
| 748 |
+
# make sure that error we get an error in exactly those cases where we
|
| 749 |
+
# expect one, and assumes the calculations themselves are done
|
| 750 |
+
# correctly.
|
| 751 |
+
|
| 752 |
+
def ok(f, *args, **kwargs):
|
| 753 |
+
f(*args, **kwargs)
|
| 754 |
+
|
| 755 |
+
def err(f, *args, **kwargs):
|
| 756 |
+
with self.assertRaises(ValueError):
|
| 757 |
+
f(*args, **kwargs)
|
| 758 |
+
|
| 759 |
+
def t(expect, func, n, m):
|
| 760 |
+
expect(func, np.zeros((n, m)), axis=1)
|
| 761 |
+
expect(func, np.zeros((m, n)), axis=0)
|
| 762 |
+
expect(func, np.zeros((n // 2, n // 2, m)), axis=2)
|
| 763 |
+
expect(func, np.zeros((n // 2, m, n // 2)), axis=1)
|
| 764 |
+
expect(func, np.zeros((n, m // 2, m // 2)), axis=(1, 2))
|
| 765 |
+
expect(func, np.zeros((m // 2, n, m // 2)), axis=(0, 2))
|
| 766 |
+
expect(func, np.zeros((m // 3, m // 3, m // 3,
|
| 767 |
+
n // 2, n // 2)), axis=(0, 1, 2))
|
| 768 |
+
# Check what happens if the inner (resp. outer) dimensions are a
|
| 769 |
+
# mix of zero and non-zero:
|
| 770 |
+
expect(func, np.zeros((10, m, n)), axis=(0, 1))
|
| 771 |
+
expect(func, np.zeros((10, n, m)), axis=(0, 2))
|
| 772 |
+
expect(func, np.zeros((m, 10, n)), axis=0)
|
| 773 |
+
expect(func, np.zeros((10, m, n)), axis=1)
|
| 774 |
+
expect(func, np.zeros((10, n, m)), axis=2)
|
| 775 |
+
|
| 776 |
+
# np.maximum is just an arbitrary ufunc with no reduction identity
|
| 777 |
+
maximum_reduce = self._generate_jit(np.maximum, identity='reorderable')
|
| 778 |
+
self.assertEqual(np.maximum.identity, None)
|
| 779 |
+
t(ok, maximum_reduce, 30, 30)
|
| 780 |
+
t(ok, maximum_reduce, 0, 30)
|
| 781 |
+
t(err, maximum_reduce, 30, 0)
|
| 782 |
+
t(err, maximum_reduce, 0, 0)
|
| 783 |
+
err(maximum_reduce, [])
|
| 784 |
+
maximum_reduce(np.zeros((0, 0)), axis=())
|
| 785 |
+
|
| 786 |
+
# all of the combinations are fine for a reduction that has an
|
| 787 |
+
# identity
|
| 788 |
+
add_reduce = self._generate_jit(np.add, identity=0)
|
| 789 |
+
t(ok, add_reduce, 30, 30)
|
| 790 |
+
t(ok, add_reduce, 0, 30)
|
| 791 |
+
t(ok, add_reduce, 30, 0)
|
| 792 |
+
t(ok, add_reduce, 0, 0)
|
| 793 |
+
add_reduce(np.array([], dtype=np.int64))
|
| 794 |
+
add_reduce(np.zeros((0, 0)), axis=())
|
| 795 |
+
|
| 796 |
+
|
| 797 |
+
class TestDUFuncReduce(TestDUFuncMethodsBase):
|
| 798 |
+
def _check_reduce(self, ufunc, dtype=None, initial=None):
|
| 799 |
+
|
| 800 |
+
@njit
|
| 801 |
+
def foo(a, axis, dtype, initial):
|
| 802 |
+
return ufunc.reduce(a,
|
| 803 |
+
axis=axis,
|
| 804 |
+
dtype=dtype,
|
| 805 |
+
initial=initial)
|
| 806 |
+
|
| 807 |
+
inputs = [
|
| 808 |
+
np.arange(5),
|
| 809 |
+
np.arange(4).reshape(2, 2),
|
| 810 |
+
np.arange(40).reshape(5, 4, 2),
|
| 811 |
+
]
|
| 812 |
+
for array in inputs:
|
| 813 |
+
for axis in range(array.ndim):
|
| 814 |
+
expected = foo.py_func(array, axis, dtype, initial)
|
| 815 |
+
got = foo(array, axis, dtype, initial)
|
| 816 |
+
self.assertPreciseEqual(expected, got)
|
| 817 |
+
|
| 818 |
+
def _check_reduce_axis(self, ufunc, dtype, initial=None):
|
| 819 |
+
|
| 820 |
+
@njit
|
| 821 |
+
def foo(a, axis):
|
| 822 |
+
return ufunc.reduce(a, axis=axis, initial=initial)
|
| 823 |
+
|
| 824 |
+
def _check(*args):
|
| 825 |
+
try:
|
| 826 |
+
expected = foo.py_func(array, axis)
|
| 827 |
+
except ValueError as e:
|
| 828 |
+
self.assertEqual(e.args[0], exc_msg)
|
| 829 |
+
with self.assertRaisesRegex(TypingError, exc_msg):
|
| 830 |
+
got = foo(array, axis)
|
| 831 |
+
else:
|
| 832 |
+
got = foo(array, axis)
|
| 833 |
+
self.assertPreciseEqual(expected, got)
|
| 834 |
+
|
| 835 |
+
exc_msg = (f"reduction operation '{ufunc.__name__}' is not "
|
| 836 |
+
"reorderable, so at most one axis may be specified")
|
| 837 |
+
inputs = [
|
| 838 |
+
np.arange(40, dtype=dtype).reshape(5, 4, 2),
|
| 839 |
+
np.arange(10, dtype=dtype),
|
| 840 |
+
]
|
| 841 |
+
for array in inputs:
|
| 842 |
+
for i in range(1, array.ndim + 1):
|
| 843 |
+
for axis in itertools.combinations(range(array.ndim), r=i):
|
| 844 |
+
_check(array, axis)
|
| 845 |
+
|
| 846 |
+
# corner cases: Reduce over axis=() and axis=None
|
| 847 |
+
for axis in ((), None):
|
| 848 |
+
_check(array, axis)
|
| 849 |
+
|
| 850 |
+
def test_add_reduce(self):
|
| 851 |
+
duadd = vectorize('int64(int64, int64)', identity=0)(pyuadd)
|
| 852 |
+
self._check_reduce(duadd)
|
| 853 |
+
self._check_reduce_axis(duadd, dtype=np.int64)
|
| 854 |
+
|
| 855 |
+
def test_mul_reduce(self):
|
| 856 |
+
dumul = vectorize('int64(int64, int64)', identity=1)(pymult)
|
| 857 |
+
self._check_reduce(dumul)
|
| 858 |
+
|
| 859 |
+
def test_non_associative_reduce(self):
|
| 860 |
+
dusub = vectorize('int64(int64, int64)', identity=None)(pysub)
|
| 861 |
+
dudiv = vectorize('int64(int64, int64)', identity=None)(pydiv)
|
| 862 |
+
self._check_reduce(dusub)
|
| 863 |
+
self._check_reduce_axis(dusub, dtype=np.int64)
|
| 864 |
+
self._check_reduce(dudiv)
|
| 865 |
+
self._check_reduce_axis(dudiv, dtype=np.int64)
|
| 866 |
+
|
| 867 |
+
def test_reduce_dtype(self):
|
| 868 |
+
duadd = vectorize('float64(float64, int64)', identity=0)(pyuadd)
|
| 869 |
+
self._check_reduce(duadd, dtype=np.float64)
|
| 870 |
+
|
| 871 |
+
def test_min_reduce(self):
|
| 872 |
+
dumin = vectorize('int64(int64, int64)', identity='reorderable')(pymin)
|
| 873 |
+
self._check_reduce(dumin, initial=10)
|
| 874 |
+
self._check_reduce_axis(dumin, dtype=np.int64)
|
| 875 |
+
|
| 876 |
+
def test_add_reduce_initial(self):
|
| 877 |
+
# Initial should be used as a start
|
| 878 |
+
duadd = vectorize('int64(int64, int64)', identity=0)(pyuadd)
|
| 879 |
+
self._check_reduce(duadd, dtype=np.int64, initial=100)
|
| 880 |
+
|
| 881 |
+
def test_add_reduce_no_initial_or_identity(self):
|
| 882 |
+
# don't provide an initial or identity value
|
| 883 |
+
duadd = vectorize('int64(int64, int64)')(pyuadd)
|
| 884 |
+
self._check_reduce(duadd, dtype=np.int64)
|
| 885 |
+
|
| 886 |
+
def test_invalid_input(self):
|
| 887 |
+
duadd = vectorize('float64(float64, int64)', identity=0)(pyuadd)
|
| 888 |
+
|
| 889 |
+
@njit
|
| 890 |
+
def foo(a):
|
| 891 |
+
return duadd.reduce(a)
|
| 892 |
+
|
| 893 |
+
exc_msg = 'The first argument "array" must be array-like'
|
| 894 |
+
with self.assertRaisesRegex(TypingError, exc_msg):
|
| 895 |
+
foo('a')
|
| 896 |
+
|
| 897 |
+
def test_dufunc_negative_axis(self):
|
| 898 |
+
duadd = vectorize('int64(int64, int64)', identity=0)(pyuadd)
|
| 899 |
+
|
| 900 |
+
@njit
|
| 901 |
+
def foo(a, axis):
|
| 902 |
+
return duadd.reduce(a, axis=axis)
|
| 903 |
+
|
| 904 |
+
a = np.arange(40).reshape(5, 4, 2)
|
| 905 |
+
cases = (0, -1, (0, -1), (-1, -2), (1, -1), -3)
|
| 906 |
+
for axis in cases:
|
| 907 |
+
expected = duadd.reduce(a, axis)
|
| 908 |
+
got = foo(a, axis)
|
| 909 |
+
self.assertPreciseEqual(expected, got)
|
| 910 |
+
|
| 911 |
+
def test_dufunc_invalid_axis(self):
|
| 912 |
+
duadd = vectorize('int64(int64, int64)', identity=0)(pyuadd)
|
| 913 |
+
|
| 914 |
+
@njit
|
| 915 |
+
def foo(a, axis):
|
| 916 |
+
return duadd.reduce(a, axis=axis)
|
| 917 |
+
|
| 918 |
+
a = np.arange(40).reshape(5, 4, 2)
|
| 919 |
+
cases = ((0, 0), (0, 1, 0), (0, -3), (-1, -1), (-1, 2))
|
| 920 |
+
for axis in cases:
|
| 921 |
+
msg = "duplicate value in 'axis'"
|
| 922 |
+
with self.assertRaisesRegex(ValueError, msg):
|
| 923 |
+
foo(a, axis)
|
| 924 |
+
|
| 925 |
+
cases = (-4, 3, (0, -4),)
|
| 926 |
+
for axis in cases:
|
| 927 |
+
with self.assertRaisesRegex(ValueError, "Invalid axis"):
|
| 928 |
+
foo(a, axis)
|
| 929 |
+
|
| 930 |
+
|
| 931 |
+
class TestDUFuncReduceAt(TestDUFuncMethodsBase):
|
| 932 |
+
def _compare_output(self, ufunc, a, idx, **kwargs):
|
| 933 |
+
identity = getattr(ufunc, 'identity')
|
| 934 |
+
fn = self._reduceat(ufunc, identity)
|
| 935 |
+
expected = a.copy()
|
| 936 |
+
got = a.copy()
|
| 937 |
+
ufunc.reduceat(expected, idx, **kwargs)
|
| 938 |
+
fn(got, idx, **kwargs)
|
| 939 |
+
self.assertPreciseEqual(expected, got)
|
| 940 |
+
|
| 941 |
+
def test_reduceat_out_kw(self):
|
| 942 |
+
arr = np.arange(4)
|
| 943 |
+
idx = np.asarray([0, 3, 1, 2])
|
| 944 |
+
add_reduce = self._reduceat(np.add, 0)
|
| 945 |
+
add_reduce(arr, idx, out=arr)
|
| 946 |
+
self.assertPreciseEqual(np.asarray([3, 3, 3, 6]), arr)
|
| 947 |
+
add_reduce(arr, idx, out=arr)
|
| 948 |
+
self.assertPreciseEqual(np.asarray([9, 6, 6, 12]), arr)
|
| 949 |
+
|
| 950 |
+
@unittest.expectedFailure
|
| 951 |
+
def test_reduceat_axis_kw(self):
|
| 952 |
+
arrays = (
|
| 953 |
+
np.arange(16).reshape(4, 4),
|
| 954 |
+
np.arange(40).reshape(4, 5, 2),
|
| 955 |
+
np.ones((4, 4))
|
| 956 |
+
)
|
| 957 |
+
indices = (
|
| 958 |
+
np.asarray([0, 3, 1, 2, 0]),
|
| 959 |
+
np.asarray([0, 3, 1, 2]),
|
| 960 |
+
)
|
| 961 |
+
axis = (1, 0, -1) # needs gh-9296
|
| 962 |
+
for array in arrays:
|
| 963 |
+
for idx in indices:
|
| 964 |
+
for ax in axis:
|
| 965 |
+
self._compare_output(np.add, array, idx, axis=ax)
|
| 966 |
+
|
| 967 |
+
def test_reduceat_invalid_axis(self):
|
| 968 |
+
arr = np.ones((4, 4))
|
| 969 |
+
idx = np.asarray([0, 3, 1, 2])
|
| 970 |
+
add_reduceat = self._reduceat(np.add, 0)
|
| 971 |
+
|
| 972 |
+
for ax in (2, -3): # needs gh-9296
|
| 973 |
+
msg = (f'axis {ax} is out of bounds for array of dimension '
|
| 974 |
+
f'{arr.ndim}')
|
| 975 |
+
with self.assertRaisesRegex(ValueError, msg):
|
| 976 |
+
add_reduceat(arr, idx, ax)
|
| 977 |
+
|
| 978 |
+
def test_reduceat_cast_args_to_array(self):
|
| 979 |
+
add_reduceat = self._reduceat(np.add, 0)
|
| 980 |
+
|
| 981 |
+
# cast array and indices
|
| 982 |
+
a = [1, 2, 3, 4]
|
| 983 |
+
idx = [1, 2, 3]
|
| 984 |
+
expected = np.add.reduceat(a, idx)
|
| 985 |
+
got = add_reduceat(a, idx)
|
| 986 |
+
self.assertPreciseEqual(expected, got)
|
| 987 |
+
|
| 988 |
+
# array and indices as tuples
|
| 989 |
+
a = (1, 2, 3, 4)
|
| 990 |
+
idx = (1, 2, 3)
|
| 991 |
+
expected = np.add.reduceat(a, idx)
|
| 992 |
+
got = add_reduceat(a, idx)
|
| 993 |
+
self.assertPreciseEqual(expected, got)
|
| 994 |
+
|
| 995 |
+
# tests below this line were copied from NumPy
|
| 996 |
+
# https://github.com/numpy/numpy/blob/7f8dc13b9bcaa26cb378b9c8246110ca1dc9ce75/numpy/_core/tests/test_ufunc.py#L200C1-L200C1 # noqa: E501
|
| 997 |
+
def test_reduceat_basic(self):
|
| 998 |
+
x = np.arange(8)
|
| 999 |
+
idx = [0,4, 1,5, 2,6, 3,7]
|
| 1000 |
+
self._compare_output(np.add, x, idx)
|
| 1001 |
+
|
| 1002 |
+
def test_reduceat_basic_2d(self):
|
| 1003 |
+
x = np.linspace(0, 15, 16).reshape(4, 4)
|
| 1004 |
+
idx = [0, 3, 1, 2, 0]
|
| 1005 |
+
self._compare_output(np.add, x, idx)
|
| 1006 |
+
|
| 1007 |
+
def test_reduceat_shifting_sum(self):
|
| 1008 |
+
L = 6
|
| 1009 |
+
x = np.arange(L)
|
| 1010 |
+
idx = np.array(list(zip(np.arange(L - 2), np.arange(L - 2) + 2))).ravel() # noqa: E501
|
| 1011 |
+
self._compare_output(np.add, x, idx)
|
| 1012 |
+
|
| 1013 |
+
def test_reduceat_int_array_reduceat_inplace(self):
|
| 1014 |
+
# Checks that in-place reduceats work, see also gh-7465
|
| 1015 |
+
arr = np.ones(4, dtype=np.int64)
|
| 1016 |
+
out = np.ones(4, dtype=np.int64)
|
| 1017 |
+
self._compare_output(np.add, arr, np.arange(4), out=arr)
|
| 1018 |
+
self._compare_output(np.add, arr, np.arange(4), out=arr)
|
| 1019 |
+
self.assertPreciseEqual(arr, out)
|
| 1020 |
+
|
| 1021 |
+
# needs gh-9296
|
| 1022 |
+
# And the same if the axis argument is used
|
| 1023 |
+
arr = np.ones((2, 4), dtype=np.int64)
|
| 1024 |
+
arr[0, :] = [2 for i in range(4)]
|
| 1025 |
+
out = np.ones((2, 4), dtype=np.int64)
|
| 1026 |
+
out[0, :] = [2 for i in range(4)]
|
| 1027 |
+
self._compare_output(np.add, arr, np.arange(4), out=arr, axis=-1)
|
| 1028 |
+
self._compare_output(np.add, arr, np.arange(4), out=arr, axis=-1)
|
| 1029 |
+
self.assertPreciseEqual(arr, out)
|
| 1030 |
+
|
| 1031 |
+
def test_reduceat_out_shape_mismatch(self):
|
| 1032 |
+
# Should raise an error mentioning "shape" or "size"
|
| 1033 |
+
# original test has an extra step for accumulate but we don't support
|
| 1034 |
+
# it yet
|
| 1035 |
+
add_reduceat = self._reduceat(np.add, 0)
|
| 1036 |
+
|
| 1037 |
+
for with_cast in (True, False):
|
| 1038 |
+
arr = np.arange(5)
|
| 1039 |
+
out = np.arange(3) # definitely wrong shape
|
| 1040 |
+
if with_cast:
|
| 1041 |
+
# If a cast is necessary on the output, we can be sure to use
|
| 1042 |
+
# the generic NpyIter (non-fast) path.
|
| 1043 |
+
out = out.astype(np.float64)
|
| 1044 |
+
|
| 1045 |
+
with self.assertRaises(ValueError):
|
| 1046 |
+
add_reduceat(arr, [0, 3], out=out)
|
| 1047 |
+
|
| 1048 |
+
def test_reduceat_empty(self):
|
| 1049 |
+
"""Reduceat should work with empty arrays"""
|
| 1050 |
+
indices = np.array([], 'i4')
|
| 1051 |
+
x = np.array([], 'f8')
|
| 1052 |
+
add_reduceat = self._reduceat(np.add, 0)
|
| 1053 |
+
expected = np.add.reduceat(x, indices)
|
| 1054 |
+
got = add_reduceat(x, indices)
|
| 1055 |
+
self.assertPreciseEqual(expected, got)
|
| 1056 |
+
self.assertEqual(expected.dtype, got.dtype)
|
| 1057 |
+
|
| 1058 |
+
# Another case with a slightly different zero-sized shape
|
| 1059 |
+
x = np.ones((5, 2))
|
| 1060 |
+
idx = np.asarray([], dtype=np.intp)
|
| 1061 |
+
self._compare_output(np.add, x, idx, axis=0)
|
| 1062 |
+
self._compare_output(np.add, x, idx, axis=1)
|
| 1063 |
+
|
| 1064 |
+
def test_reduceat_error_ndim_2(self):
|
| 1065 |
+
add_reduceat = self._reduceat(np.add, 0)
|
| 1066 |
+
|
| 1067 |
+
# indices ndim > 1
|
| 1068 |
+
a = np.arange(5)
|
| 1069 |
+
idx = np.arange(10).reshape(5, 2)
|
| 1070 |
+
with self.assertRaisesRegex(TypingError, 'have at most 1 dimension'):
|
| 1071 |
+
add_reduceat(a, idx)
|
| 1072 |
+
|
| 1073 |
+
def test_reduceat_error_non_binary_function(self):
|
| 1074 |
+
# non binary functions
|
| 1075 |
+
@vectorize
|
| 1076 |
+
def neg(a):
|
| 1077 |
+
return np.negative(a)
|
| 1078 |
+
|
| 1079 |
+
@njit
|
| 1080 |
+
def neg_reduceat(a, idx):
|
| 1081 |
+
return neg.reduceat(a, idx)
|
| 1082 |
+
|
| 1083 |
+
a = np.arange(5)
|
| 1084 |
+
msg = 'reduceat only supported for binary functions'
|
| 1085 |
+
with self.assertRaisesRegex(TypingError, msg):
|
| 1086 |
+
neg_reduceat(a, [0, 1, 2])
|
| 1087 |
+
|
| 1088 |
+
def test_reduceat_error_argument_types(self):
|
| 1089 |
+
# first argument must be array-like
|
| 1090 |
+
add_reduceat = self._reduceat(np.add, 0)
|
| 1091 |
+
with self.assertRaisesRegex(TypingError, '"array" must be array-like'):
|
| 1092 |
+
add_reduceat('abc', [1, 2, 3])
|
| 1093 |
+
|
| 1094 |
+
with self.assertRaisesRegex(TypingError, '"indices" must be array-like'): # noqa: E501
|
| 1095 |
+
add_reduceat(np.arange(5), 'abcd')
|
| 1096 |
+
|
| 1097 |
+
with self.assertRaisesRegex(TypingError, 'output must be an array'):
|
| 1098 |
+
add_reduceat(np.arange(5), [1, 2, 3], out=())
|
| 1099 |
+
|
| 1100 |
+
with self.assertRaisesRegex(TypingError, '"axis" must be an integer'):
|
| 1101 |
+
add_reduceat(np.arange(5), [1, 2, 3], axis=(1,))
|
| 1102 |
+
|
| 1103 |
+
|
| 1104 |
+
class TestDUFuncPickling(MemoryLeakMixin, unittest.TestCase):
|
| 1105 |
+
def check(self, ident, result_type):
|
| 1106 |
+
buf = pickle.dumps(ident)
|
| 1107 |
+
rebuilt = pickle.loads(buf)
|
| 1108 |
+
|
| 1109 |
+
# Check reconstructed dufunc
|
| 1110 |
+
r = rebuilt(123)
|
| 1111 |
+
self.assertEqual(123, r)
|
| 1112 |
+
self.assertIsInstance(r, result_type)
|
| 1113 |
+
|
| 1114 |
+
# Try to use reconstructed dufunc in @jit
|
| 1115 |
+
@njit
|
| 1116 |
+
def foo(x):
|
| 1117 |
+
return rebuilt(x)
|
| 1118 |
+
|
| 1119 |
+
r = foo(321)
|
| 1120 |
+
self.assertEqual(321, r)
|
| 1121 |
+
self.assertIsInstance(r, result_type)
|
| 1122 |
+
|
| 1123 |
+
def test_unrestricted(self):
|
| 1124 |
+
@vectorize
|
| 1125 |
+
def ident(x1):
|
| 1126 |
+
return x1
|
| 1127 |
+
|
| 1128 |
+
self.check(ident, result_type=(int, np.integer))
|
| 1129 |
+
|
| 1130 |
+
def test_restricted(self):
|
| 1131 |
+
@vectorize(["float64(float64)"])
|
| 1132 |
+
def ident(x1):
|
| 1133 |
+
return x1
|
| 1134 |
+
|
| 1135 |
+
self.check(ident, result_type=float)
|
| 1136 |
+
|
| 1137 |
+
|
| 1138 |
+
if __name__ == "__main__":
|
| 1139 |
+
unittest.main()
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_errors.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import contextlib
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
from numba import vectorize, guvectorize
|
| 7 |
+
|
| 8 |
+
from numba.tests.support import (TestCase, CheckWarningsMixin,
|
| 9 |
+
skip_macos_fenv_errors)
|
| 10 |
+
import unittest
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def sqrt(val):
|
| 14 |
+
if val < 0.0:
|
| 15 |
+
raise ValueError('Value must be positive')
|
| 16 |
+
return val ** 0.5
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def gufunc_foo(inp, n, out):
|
| 20 |
+
for i in range(inp.shape[0]):
|
| 21 |
+
if inp[i] < 0:
|
| 22 |
+
raise ValueError('Value must be positive')
|
| 23 |
+
out[i] = inp[i] * n[0]
|
| 24 |
+
|
| 25 |
+
def truediv(a, b):
|
| 26 |
+
return a / b
|
| 27 |
+
|
| 28 |
+
def floordiv(a, b):
|
| 29 |
+
return a // b
|
| 30 |
+
|
| 31 |
+
def remainder(a, b):
|
| 32 |
+
return a % b
|
| 33 |
+
|
| 34 |
+
def power(a, b):
|
| 35 |
+
return a ** b
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class TestExceptions(TestCase):
|
| 39 |
+
"""
|
| 40 |
+
Test raising exceptions inside ufuncs.
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
def check_ufunc_raise(self, **vectorize_args):
|
| 44 |
+
f = vectorize(['float64(float64)'], **vectorize_args)(sqrt)
|
| 45 |
+
arr = np.array([1, 4, -2, 9, -1, 16], dtype=np.float64)
|
| 46 |
+
out = np.zeros_like(arr)
|
| 47 |
+
with self.assertRaises(ValueError) as cm:
|
| 48 |
+
f(arr, out)
|
| 49 |
+
self.assertIn('Value must be positive', str(cm.exception))
|
| 50 |
+
# All values were computed except for the ones giving an error
|
| 51 |
+
self.assertEqual(list(out), [1, 2, 0, 3, 0, 4])
|
| 52 |
+
|
| 53 |
+
def test_ufunc_raise(self):
|
| 54 |
+
self.check_ufunc_raise(nopython=True)
|
| 55 |
+
|
| 56 |
+
def test_ufunc_raise_objmode(self):
|
| 57 |
+
self.check_ufunc_raise(forceobj=True)
|
| 58 |
+
|
| 59 |
+
def check_gufunc_raise(self, **vectorize_args):
|
| 60 |
+
f = guvectorize(['int32[:], int32[:], int32[:]'], '(n),()->(n)',
|
| 61 |
+
**vectorize_args)(gufunc_foo)
|
| 62 |
+
arr = np.array([1, 2, -3, 4], dtype=np.int32)
|
| 63 |
+
out = np.zeros_like(arr)
|
| 64 |
+
with self.assertRaises(ValueError) as cm:
|
| 65 |
+
f(arr, 2, out)
|
| 66 |
+
# The gufunc bailed out after the error
|
| 67 |
+
self.assertEqual(list(out), [2, 4, 0, 0])
|
| 68 |
+
|
| 69 |
+
def test_gufunc_raise(self):
|
| 70 |
+
self.check_gufunc_raise(nopython=True)
|
| 71 |
+
|
| 72 |
+
def test_gufunc_raise_objmode(self):
|
| 73 |
+
self.check_gufunc_raise(forceobj=True)
|
| 74 |
+
|
| 75 |
+
class TestFloatingPointExceptions(TestCase, CheckWarningsMixin):
|
| 76 |
+
"""
|
| 77 |
+
Test floating-point exceptions inside ufuncs.
|
| 78 |
+
|
| 79 |
+
Note the warnings emitted by Numpy reflect IEEE-754 semantics.
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
def check_truediv_real(self, dtype):
|
| 83 |
+
"""
|
| 84 |
+
Test 1 / 0 and 0 / 0.
|
| 85 |
+
"""
|
| 86 |
+
f = vectorize(nopython=True)(truediv)
|
| 87 |
+
a = np.array([5., 6., 0., 8.], dtype=dtype)
|
| 88 |
+
b = np.array([1., 0., 0., 4.], dtype=dtype)
|
| 89 |
+
expected = np.array([5., float('inf'), float('nan'), 2.])
|
| 90 |
+
with self.check_warnings(["divide by zero encountered",
|
| 91 |
+
"invalid value encountered"]):
|
| 92 |
+
res = f(a, b)
|
| 93 |
+
self.assertPreciseEqual(res, expected)
|
| 94 |
+
|
| 95 |
+
def test_truediv_float(self):
|
| 96 |
+
self.check_truediv_real(np.float64)
|
| 97 |
+
|
| 98 |
+
def test_truediv_integer(self):
|
| 99 |
+
self.check_truediv_real(np.int32)
|
| 100 |
+
|
| 101 |
+
def check_divmod_float(self, pyfunc, values, messages):
|
| 102 |
+
"""
|
| 103 |
+
Test 1 // 0 and 0 // 0.
|
| 104 |
+
"""
|
| 105 |
+
f = vectorize(nopython=True)(pyfunc)
|
| 106 |
+
a = np.array([5., 6., 0., 9.])
|
| 107 |
+
b = np.array([1., 0., 0., 4.])
|
| 108 |
+
expected = np.array(values)
|
| 109 |
+
with self.check_warnings(messages):
|
| 110 |
+
res = f(a, b)
|
| 111 |
+
self.assertPreciseEqual(res, expected)
|
| 112 |
+
|
| 113 |
+
def test_floordiv_float(self):
|
| 114 |
+
self.check_divmod_float(floordiv,
|
| 115 |
+
[5.0, float('inf'), float('nan'), 2.0],
|
| 116 |
+
["divide by zero encountered",
|
| 117 |
+
"invalid value encountered"])
|
| 118 |
+
|
| 119 |
+
@skip_macos_fenv_errors
|
| 120 |
+
def test_remainder_float(self):
|
| 121 |
+
self.check_divmod_float(remainder,
|
| 122 |
+
[0.0, float('nan'), float('nan'), 1.0],
|
| 123 |
+
["invalid value encountered"])
|
| 124 |
+
|
| 125 |
+
def check_divmod_int(self, pyfunc, values):
|
| 126 |
+
"""
|
| 127 |
+
Test 1 % 0 and 0 % 0.
|
| 128 |
+
"""
|
| 129 |
+
f = vectorize(nopython=True)(pyfunc)
|
| 130 |
+
a = np.array([5, 6, 0, 9])
|
| 131 |
+
b = np.array([1, 0, 0, 4])
|
| 132 |
+
expected = np.array(values)
|
| 133 |
+
# No warnings raised because LLVM makes it difficult
|
| 134 |
+
with self.check_warnings([]):
|
| 135 |
+
res = f(a, b)
|
| 136 |
+
self.assertPreciseEqual(res, expected)
|
| 137 |
+
|
| 138 |
+
def test_floordiv_int(self):
|
| 139 |
+
self.check_divmod_int(floordiv, [5, 0, 0, 2])
|
| 140 |
+
|
| 141 |
+
def test_remainder_int(self):
|
| 142 |
+
self.check_divmod_int(remainder, [0, 0, 0, 1])
|
| 143 |
+
|
| 144 |
+
def test_power_float(self):
|
| 145 |
+
"""
|
| 146 |
+
Test 0 ** -1 and 2 ** <big number>.
|
| 147 |
+
"""
|
| 148 |
+
f = vectorize(nopython=True)(power)
|
| 149 |
+
a = np.array([5., 0., 2., 8.])
|
| 150 |
+
b = np.array([1., -1., 1e20, 4.])
|
| 151 |
+
expected = np.array([5., float('inf'), float('inf'), 4096.])
|
| 152 |
+
with self.check_warnings(["divide by zero encountered",
|
| 153 |
+
"overflow encountered"]):
|
| 154 |
+
res = f(a, b)
|
| 155 |
+
self.assertPreciseEqual(res, expected)
|
| 156 |
+
|
| 157 |
+
def test_power_integer(self):
|
| 158 |
+
"""
|
| 159 |
+
Test 0 ** -1.
|
| 160 |
+
Note 2 ** <big number> returns an undefined value (depending
|
| 161 |
+
on the algorithm).
|
| 162 |
+
"""
|
| 163 |
+
dtype = np.int64
|
| 164 |
+
f = vectorize(["int64(int64, int64)"], nopython=True)(power)
|
| 165 |
+
a = np.array([5, 0, 6], dtype=dtype)
|
| 166 |
+
b = np.array([1, -1, 2], dtype=dtype)
|
| 167 |
+
expected = np.array([5, -2**63, 36], dtype=dtype)
|
| 168 |
+
with self.check_warnings([]):
|
| 169 |
+
res = f(a, b)
|
| 170 |
+
self.assertPreciseEqual(res, expected)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
if __name__ == "__main__":
|
| 174 |
+
unittest.main()
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_gufunc.py
ADDED
|
@@ -0,0 +1,870 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
import pickle
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
from numba import void, float32, float64, int32, int64, jit, guvectorize
|
| 7 |
+
from numba.core.errors import TypingError
|
| 8 |
+
from numba.np.ufunc import GUVectorize
|
| 9 |
+
from numba.tests.support import TestCase, MemoryLeakMixin
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def matmulcore(A, B, C):
|
| 13 |
+
"""docstring for matmulcore"""
|
| 14 |
+
m, n = A.shape
|
| 15 |
+
n, p = B.shape
|
| 16 |
+
for i in range(m):
|
| 17 |
+
for j in range(p):
|
| 18 |
+
C[i, j] = 0
|
| 19 |
+
for k in range(n):
|
| 20 |
+
C[i, j] += A[i, k] * B[k, j]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def axpy(a, x, y, out):
|
| 24 |
+
out[0] = a * x + y
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class TestGUFunc(MemoryLeakMixin, TestCase):
|
| 28 |
+
target = 'cpu'
|
| 29 |
+
|
| 30 |
+
def check_matmul_gufunc(self, gufunc):
|
| 31 |
+
matrix_ct = 1001
|
| 32 |
+
A = np.arange(matrix_ct * 2 * 4, dtype=np.float32).reshape(matrix_ct, 2, 4)
|
| 33 |
+
B = np.arange(matrix_ct * 4 * 5, dtype=np.float32).reshape(matrix_ct, 4, 5)
|
| 34 |
+
|
| 35 |
+
C = gufunc(A, B)
|
| 36 |
+
Gold = np.matmul(A, B)
|
| 37 |
+
|
| 38 |
+
np.testing.assert_allclose(C, Gold, rtol=1e-5, atol=1e-8)
|
| 39 |
+
|
| 40 |
+
def test_gufunc(self):
|
| 41 |
+
gufunc = GUVectorize(matmulcore, '(m,n),(n,p)->(m,p)',
|
| 42 |
+
target=self.target)
|
| 43 |
+
gufunc.add((float32[:, :], float32[:, :], float32[:, :]))
|
| 44 |
+
gufunc = gufunc.build_ufunc()
|
| 45 |
+
|
| 46 |
+
self.check_matmul_gufunc(gufunc)
|
| 47 |
+
|
| 48 |
+
def test_guvectorize_decor(self):
|
| 49 |
+
gufunc = guvectorize([void(float32[:,:], float32[:,:], float32[:,:])],
|
| 50 |
+
'(m,n),(n,p)->(m,p)',
|
| 51 |
+
target=self.target)(matmulcore)
|
| 52 |
+
|
| 53 |
+
self.check_matmul_gufunc(gufunc)
|
| 54 |
+
|
| 55 |
+
def test_ufunc_like(self):
|
| 56 |
+
# Test problem that the stride of "scalar" gufunc argument not properly
|
| 57 |
+
# handled when the actual argument is an array,
|
| 58 |
+
# causing the same value (first value) being repeated.
|
| 59 |
+
gufunc = GUVectorize(axpy, '(), (), () -> ()', target=self.target)
|
| 60 |
+
gufunc.add('(intp, intp, intp, intp[:])')
|
| 61 |
+
gufunc = gufunc.build_ufunc()
|
| 62 |
+
|
| 63 |
+
x = np.arange(10, dtype=np.intp)
|
| 64 |
+
out = gufunc(x, x, x)
|
| 65 |
+
|
| 66 |
+
np.testing.assert_equal(out, x * x + x)
|
| 67 |
+
|
| 68 |
+
def test_axis(self):
|
| 69 |
+
# issue https://github.com/numba/numba/issues/6773
|
| 70 |
+
@guvectorize(["f8[:],f8[:]"], "(n)->(n)")
|
| 71 |
+
def my_cumsum(x, res):
|
| 72 |
+
acc = 0
|
| 73 |
+
for i in range(x.shape[0]):
|
| 74 |
+
acc += x[i]
|
| 75 |
+
res[i] = acc
|
| 76 |
+
|
| 77 |
+
x = np.ones((20, 30))
|
| 78 |
+
# Check regular call
|
| 79 |
+
y = my_cumsum(x, axis=0)
|
| 80 |
+
expected = np.cumsum(x, axis=0)
|
| 81 |
+
np.testing.assert_equal(y, expected)
|
| 82 |
+
# Check "out" kw
|
| 83 |
+
out_kw = np.zeros_like(y)
|
| 84 |
+
my_cumsum(x, out=out_kw, axis=0)
|
| 85 |
+
np.testing.assert_equal(out_kw, expected)
|
| 86 |
+
|
| 87 |
+
def test_docstring(self):
|
| 88 |
+
@guvectorize([(int64[:], int64, int64[:])], '(n),()->(n)')
|
| 89 |
+
def gufunc(x, y, res):
|
| 90 |
+
"docstring for gufunc"
|
| 91 |
+
for i in range(x.shape[0]):
|
| 92 |
+
res[i] = x[i] + y
|
| 93 |
+
|
| 94 |
+
self.assertEqual("numba.tests.npyufunc.test_gufunc", gufunc.__module__)
|
| 95 |
+
self.assertEqual("gufunc", gufunc.__name__)
|
| 96 |
+
self.assertEqual("TestGUFunc.test_docstring.<locals>.gufunc", gufunc.__qualname__)
|
| 97 |
+
self.assertEqual("docstring for gufunc", gufunc.__doc__)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class TestMultipleOutputs(MemoryLeakMixin, TestCase):
|
| 101 |
+
target = 'cpu'
|
| 102 |
+
|
| 103 |
+
def test_multiple_outputs_same_type_passed_in(self):
|
| 104 |
+
@guvectorize('(x)->(x),(x)',
|
| 105 |
+
target=self.target)
|
| 106 |
+
def copy(A, B, C):
|
| 107 |
+
for i in range(B.size):
|
| 108 |
+
B[i] = A[i]
|
| 109 |
+
C[i] = A[i]
|
| 110 |
+
|
| 111 |
+
A = np.arange(10, dtype=np.float32) + 1
|
| 112 |
+
B = np.zeros_like(A)
|
| 113 |
+
C = np.zeros_like(A)
|
| 114 |
+
copy(A, B, C)
|
| 115 |
+
np.testing.assert_allclose(A, B)
|
| 116 |
+
np.testing.assert_allclose(A, C)
|
| 117 |
+
|
| 118 |
+
def test_multiple_outputs_distinct_values(self):
|
| 119 |
+
|
| 120 |
+
@guvectorize('(x)->(x),(x)',
|
| 121 |
+
target=self.target)
|
| 122 |
+
def copy_and_double(A, B, C):
|
| 123 |
+
for i in range(B.size):
|
| 124 |
+
B[i] = A[i]
|
| 125 |
+
C[i] = A[i] * 2
|
| 126 |
+
|
| 127 |
+
A = np.arange(10, dtype=np.float32) + 1
|
| 128 |
+
B = np.zeros_like(A)
|
| 129 |
+
C = np.zeros_like(A)
|
| 130 |
+
copy_and_double(A, B, C)
|
| 131 |
+
np.testing.assert_allclose(A, B)
|
| 132 |
+
np.testing.assert_allclose(A * 2, C)
|
| 133 |
+
|
| 134 |
+
def test_multiple_output_dtypes(self):
|
| 135 |
+
|
| 136 |
+
@guvectorize('(x)->(x),(x)',
|
| 137 |
+
target=self.target)
|
| 138 |
+
def copy_and_multiply(A, B, C):
|
| 139 |
+
for i in range(B.size):
|
| 140 |
+
B[i] = A[i]
|
| 141 |
+
C[i] = A[i] * 1.5
|
| 142 |
+
|
| 143 |
+
A = np.arange(10, dtype=np.int32) + 1
|
| 144 |
+
B = np.zeros_like(A)
|
| 145 |
+
C = np.zeros_like(A, dtype=np.float64)
|
| 146 |
+
copy_and_multiply(A, B, C)
|
| 147 |
+
np.testing.assert_allclose(A, B)
|
| 148 |
+
np.testing.assert_allclose(A * np.float64(1.5), C)
|
| 149 |
+
|
| 150 |
+
def test_incorrect_number_of_pos_args(self):
|
| 151 |
+
@guvectorize('(m),(m)->(m),(m)', target=self.target)
|
| 152 |
+
def f(x, y, z, w):
|
| 153 |
+
pass
|
| 154 |
+
|
| 155 |
+
arr = np.arange(5, dtype=np.int32)
|
| 156 |
+
|
| 157 |
+
# Inputs only, too few
|
| 158 |
+
msg = "Too few arguments for function 'f'"
|
| 159 |
+
with self.assertRaises(TypeError) as te:
|
| 160 |
+
f(arr)
|
| 161 |
+
self.assertIn(msg, str(te.exception))
|
| 162 |
+
|
| 163 |
+
# Inputs and outputs, too many
|
| 164 |
+
with self.assertRaises(TypeError) as te:
|
| 165 |
+
f(arr, arr, arr, arr, arr)
|
| 166 |
+
self.assertIn(msg, str(te.exception))
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class TestGUFuncParallel(TestGUFunc):
|
| 170 |
+
_numba_parallel_test_ = False
|
| 171 |
+
target = 'parallel'
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
class TestDynamicGUFunc(MemoryLeakMixin, TestCase):
|
| 175 |
+
target = 'cpu'
|
| 176 |
+
|
| 177 |
+
def test_dynamic_matmul(self):
|
| 178 |
+
|
| 179 |
+
def check_matmul_gufunc(gufunc, A, B, C):
|
| 180 |
+
Gold = np.matmul(A, B)
|
| 181 |
+
gufunc(A, B, C)
|
| 182 |
+
np.testing.assert_allclose(C, Gold, rtol=1e-5, atol=1e-8)
|
| 183 |
+
|
| 184 |
+
gufunc = GUVectorize(matmulcore, '(m,n),(n,p)->(m,p)',
|
| 185 |
+
target=self.target, is_dynamic=True)
|
| 186 |
+
matrix_ct = 10
|
| 187 |
+
Ai64 = np.arange(matrix_ct * 2 * 4, dtype=np.int64).reshape(matrix_ct, 2, 4)
|
| 188 |
+
Bi64 = np.arange(matrix_ct * 4 * 5, dtype=np.int64).reshape(matrix_ct, 4, 5)
|
| 189 |
+
Ci64 = np.arange(matrix_ct * 2 * 5, dtype=np.int64).reshape(matrix_ct, 2, 5)
|
| 190 |
+
check_matmul_gufunc(gufunc, Ai64, Bi64, Ci64)
|
| 191 |
+
|
| 192 |
+
A = np.arange(matrix_ct * 2 * 4, dtype=np.float32).reshape(matrix_ct, 2, 4)
|
| 193 |
+
B = np.arange(matrix_ct * 4 * 5, dtype=np.float32).reshape(matrix_ct, 4, 5)
|
| 194 |
+
C = np.arange(matrix_ct * 2 * 5, dtype=np.float32).reshape(matrix_ct, 2, 5)
|
| 195 |
+
check_matmul_gufunc(gufunc, A, B, C) # trigger compilation
|
| 196 |
+
|
| 197 |
+
self.assertEqual(len(gufunc.types), 2) # ensure two versions of gufunc
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def test_dynamic_ufunc_like(self):
|
| 201 |
+
|
| 202 |
+
def check_ufunc_output(gufunc, x):
|
| 203 |
+
out = np.zeros(10, dtype=x.dtype)
|
| 204 |
+
out_kw = np.zeros(10, dtype=x.dtype)
|
| 205 |
+
gufunc(x, x, x, out)
|
| 206 |
+
gufunc(x, x, x, out=out_kw)
|
| 207 |
+
golden = x * x + x
|
| 208 |
+
np.testing.assert_equal(out, golden)
|
| 209 |
+
np.testing.assert_equal(out_kw, golden)
|
| 210 |
+
|
| 211 |
+
# Test problem that the stride of "scalar" gufunc argument not properly
|
| 212 |
+
# handled when the actual argument is an array,
|
| 213 |
+
# causing the same value (first value) being repeated.
|
| 214 |
+
gufunc = GUVectorize(axpy, '(), (), () -> ()', target=self.target,
|
| 215 |
+
is_dynamic=True)
|
| 216 |
+
x = np.arange(10, dtype=np.intp)
|
| 217 |
+
check_ufunc_output(gufunc, x)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def test_dynamic_scalar_output(self):
|
| 221 |
+
"""
|
| 222 |
+
Note that scalar output is a 0-dimension array that acts as
|
| 223 |
+
a pointer to the output location.
|
| 224 |
+
"""
|
| 225 |
+
|
| 226 |
+
@guvectorize('(n)->()', target=self.target, nopython=True)
|
| 227 |
+
def sum_row(inp, out):
|
| 228 |
+
tmp = 0.
|
| 229 |
+
for i in range(inp.shape[0]):
|
| 230 |
+
tmp += inp[i]
|
| 231 |
+
out[()] = tmp
|
| 232 |
+
|
| 233 |
+
# inp is (10000, 3)
|
| 234 |
+
# out is (10000)
|
| 235 |
+
# The outer (leftmost) dimension must match or numpy broadcasting is performed.
|
| 236 |
+
|
| 237 |
+
self.assertTrue(sum_row.is_dynamic)
|
| 238 |
+
inp = np.arange(30000, dtype=np.int32).reshape(10000, 3)
|
| 239 |
+
out = np.zeros(10000, dtype=np.int32)
|
| 240 |
+
sum_row(inp, out)
|
| 241 |
+
|
| 242 |
+
# verify result
|
| 243 |
+
for i in range(inp.shape[0]):
|
| 244 |
+
self.assertEqual(out[i], inp[i].sum())
|
| 245 |
+
|
| 246 |
+
msg = "Too few arguments for function 'sum_row'."
|
| 247 |
+
with self.assertRaisesRegex(TypeError, msg):
|
| 248 |
+
sum_row(inp)
|
| 249 |
+
|
| 250 |
+
def test_axis(self):
|
| 251 |
+
# issue https://github.com/numba/numba/issues/6773
|
| 252 |
+
@guvectorize("(n)->(n)")
|
| 253 |
+
def my_cumsum(x, res):
|
| 254 |
+
acc = 0
|
| 255 |
+
for i in range(x.shape[0]):
|
| 256 |
+
acc += x[i]
|
| 257 |
+
res[i] = acc
|
| 258 |
+
|
| 259 |
+
x = np.ones((20, 30))
|
| 260 |
+
expected = np.cumsum(x, axis=0)
|
| 261 |
+
# Check regular call
|
| 262 |
+
y = np.zeros_like(expected)
|
| 263 |
+
my_cumsum(x, y, axis=0)
|
| 264 |
+
np.testing.assert_equal(y, expected)
|
| 265 |
+
# Check "out" kw
|
| 266 |
+
out_kw = np.zeros_like(y)
|
| 267 |
+
my_cumsum(x, out=out_kw, axis=0)
|
| 268 |
+
np.testing.assert_equal(out_kw, expected)
|
| 269 |
+
|
| 270 |
+
def test_gufunc_attributes(self):
|
| 271 |
+
@guvectorize("(n)->(n)")
|
| 272 |
+
def gufunc(x, res):
|
| 273 |
+
acc = 0
|
| 274 |
+
for i in range(x.shape[0]):
|
| 275 |
+
acc += x[i]
|
| 276 |
+
res[i] = acc
|
| 277 |
+
|
| 278 |
+
# ensure gufunc exports attributes
|
| 279 |
+
attrs = ['signature', 'accumulate', 'at', 'outer', 'reduce', 'reduceat']
|
| 280 |
+
for attr in attrs:
|
| 281 |
+
contains = hasattr(gufunc, attr)
|
| 282 |
+
self.assertTrue(contains, 'dynamic gufunc not exporting "%s"' % (attr,))
|
| 283 |
+
|
| 284 |
+
a = np.array([1, 2, 3, 4])
|
| 285 |
+
res = np.array([0, 0, 0, 0])
|
| 286 |
+
gufunc(a, res) # trigger compilation
|
| 287 |
+
self.assertPreciseEqual(res, np.array([1, 3, 6, 10]))
|
| 288 |
+
|
| 289 |
+
# other attributes are not callable from a gufunc with signature
|
| 290 |
+
# see: https://github.com/numba/numba/issues/2794
|
| 291 |
+
# note: this is a limitation in NumPy source code!
|
| 292 |
+
self.assertEqual(gufunc.signature, "(n)->(n)")
|
| 293 |
+
|
| 294 |
+
with self.assertRaises(RuntimeError) as raises:
|
| 295 |
+
gufunc.accumulate(a)
|
| 296 |
+
self.assertEqual(str(raises.exception), "Reduction not defined on ufunc with signature")
|
| 297 |
+
|
| 298 |
+
with self.assertRaises(RuntimeError) as raises:
|
| 299 |
+
gufunc.reduce(a)
|
| 300 |
+
self.assertEqual(str(raises.exception), "Reduction not defined on ufunc with signature")
|
| 301 |
+
|
| 302 |
+
with self.assertRaises(RuntimeError) as raises:
|
| 303 |
+
gufunc.reduceat(a, [0, 2])
|
| 304 |
+
self.assertEqual(str(raises.exception), "Reduction not defined on ufunc with signature")
|
| 305 |
+
|
| 306 |
+
with self.assertRaises(TypeError) as raises:
|
| 307 |
+
gufunc.outer(a, a)
|
| 308 |
+
self.assertEqual(str(raises.exception), "method outer is not allowed in ufunc with non-trivial signature")
|
| 309 |
+
|
| 310 |
+
def test_gufunc_attributes2(self):
|
| 311 |
+
@guvectorize('(),()->()')
|
| 312 |
+
def add(x, y, res):
|
| 313 |
+
res[0] = x + y
|
| 314 |
+
|
| 315 |
+
# add signature "(),() -> ()" is evaluated to None
|
| 316 |
+
self.assertIsNone(add.signature)
|
| 317 |
+
|
| 318 |
+
a = np.array([1, 2, 3, 4])
|
| 319 |
+
b = np.array([4, 3, 2, 1])
|
| 320 |
+
res = np.array([0, 0, 0, 0])
|
| 321 |
+
add(a, b, res) # trigger compilation
|
| 322 |
+
self.assertPreciseEqual(res, np.array([5, 5, 5, 5]))
|
| 323 |
+
|
| 324 |
+
# now test other attributes
|
| 325 |
+
self.assertIsNone(add.signature)
|
| 326 |
+
self.assertEqual(add.reduce(a), 10)
|
| 327 |
+
self.assertPreciseEqual(add.accumulate(a), np.array([1, 3, 6, 10]))
|
| 328 |
+
self.assertPreciseEqual(add.outer([0, 1], [1, 2]), np.array([[1, 2], [2, 3]]))
|
| 329 |
+
self.assertPreciseEqual(add.reduceat(a, [0, 2]), np.array([3, 7]))
|
| 330 |
+
|
| 331 |
+
x = np.array([1, 2, 3, 4])
|
| 332 |
+
y = np.array([1, 2])
|
| 333 |
+
add.at(x, [0, 1], y)
|
| 334 |
+
self.assertPreciseEqual(x, np.array([2, 4, 3, 4]))
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
class TestGUVectorizeScalar(MemoryLeakMixin, TestCase):
|
| 338 |
+
"""
|
| 339 |
+
Nothing keeps user from out-of-bound memory access
|
| 340 |
+
"""
|
| 341 |
+
target = 'cpu'
|
| 342 |
+
|
| 343 |
+
def test_scalar_output(self):
|
| 344 |
+
"""
|
| 345 |
+
Note that scalar output is a 0-dimension array that acts as
|
| 346 |
+
a pointer to the output location.
|
| 347 |
+
"""
|
| 348 |
+
|
| 349 |
+
@guvectorize(['void(int32[:], int32[:])'], '(n)->()',
|
| 350 |
+
target=self.target, nopython=True)
|
| 351 |
+
def sum_row(inp, out):
|
| 352 |
+
tmp = 0.
|
| 353 |
+
for i in range(inp.shape[0]):
|
| 354 |
+
tmp += inp[i]
|
| 355 |
+
out[()] = tmp
|
| 356 |
+
|
| 357 |
+
# inp is (10000, 3)
|
| 358 |
+
# out is (10000)
|
| 359 |
+
# The outer (leftmost) dimension must match or numpy broadcasting is performed.
|
| 360 |
+
|
| 361 |
+
inp = np.arange(30000, dtype=np.int32).reshape(10000, 3)
|
| 362 |
+
out = sum_row(inp)
|
| 363 |
+
|
| 364 |
+
# verify result
|
| 365 |
+
for i in range(inp.shape[0]):
|
| 366 |
+
self.assertEqual(out[i], inp[i].sum())
|
| 367 |
+
|
| 368 |
+
def test_scalar_input(self):
|
| 369 |
+
|
| 370 |
+
@guvectorize(['int32[:], int32[:], int32[:]'], '(n),()->(n)',
|
| 371 |
+
target=self.target, nopython=True)
|
| 372 |
+
def foo(inp, n, out):
|
| 373 |
+
for i in range(inp.shape[0]):
|
| 374 |
+
out[i] = inp[i] * n[0]
|
| 375 |
+
|
| 376 |
+
inp = np.arange(3 * 10, dtype=np.int32).reshape(10, 3)
|
| 377 |
+
# out = np.empty_like(inp)
|
| 378 |
+
out = foo(inp, 2)
|
| 379 |
+
|
| 380 |
+
# verify result
|
| 381 |
+
self.assertPreciseEqual(inp * 2, out)
|
| 382 |
+
|
| 383 |
+
def test_scalar_input_core_type(self):
|
| 384 |
+
def pyfunc(inp, n, out):
|
| 385 |
+
for i in range(inp.size):
|
| 386 |
+
out[i] = n * (inp[i] + 1)
|
| 387 |
+
|
| 388 |
+
my_gufunc = guvectorize(['int32[:], int32, int32[:]'],
|
| 389 |
+
'(n),()->(n)',
|
| 390 |
+
target=self.target)(pyfunc)
|
| 391 |
+
|
| 392 |
+
# test single core loop execution
|
| 393 |
+
arr = np.arange(10).astype(np.int32)
|
| 394 |
+
got = my_gufunc(arr, 2)
|
| 395 |
+
|
| 396 |
+
expected = np.zeros_like(got)
|
| 397 |
+
pyfunc(arr, 2, expected)
|
| 398 |
+
|
| 399 |
+
np.testing.assert_equal(got, expected)
|
| 400 |
+
|
| 401 |
+
# test multiple core loop execution
|
| 402 |
+
arr = np.arange(20).astype(np.int32).reshape(10, 2)
|
| 403 |
+
got = my_gufunc(arr, 2)
|
| 404 |
+
|
| 405 |
+
expected = np.zeros_like(got)
|
| 406 |
+
for ax in range(expected.shape[0]):
|
| 407 |
+
pyfunc(arr[ax], 2, expected[ax])
|
| 408 |
+
|
| 409 |
+
np.testing.assert_equal(got, expected)
|
| 410 |
+
|
| 411 |
+
def test_scalar_input_core_type_error(self):
|
| 412 |
+
with self.assertRaises(TypeError) as raises:
|
| 413 |
+
@guvectorize(['int32[:], int32, int32[:]'], '(n),(n)->(n)',
|
| 414 |
+
target=self.target)
|
| 415 |
+
def pyfunc(a, b, c):
|
| 416 |
+
pass
|
| 417 |
+
self.assertEqual("scalar type int32 given for non scalar argument #2",
|
| 418 |
+
str(raises.exception))
|
| 419 |
+
|
| 420 |
+
def test_ndim_mismatch(self):
|
| 421 |
+
with self.assertRaises(TypeError) as raises:
|
| 422 |
+
@guvectorize(['int32[:], int32[:]'], '(m,n)->(n)',
|
| 423 |
+
target=self.target)
|
| 424 |
+
def pyfunc(a, b):
|
| 425 |
+
pass
|
| 426 |
+
self.assertEqual("type and shape signature mismatch for arg #1",
|
| 427 |
+
str(raises.exception))
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
class TestGUVectorizeScalarParallel(TestGUVectorizeScalar):
|
| 431 |
+
_numba_parallel_test_ = False
|
| 432 |
+
target = 'parallel'
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
class TestGUVectorizePickling(MemoryLeakMixin, TestCase):
|
| 436 |
+
def test_pickle_gufunc_non_dyanmic(self):
|
| 437 |
+
"""Non-dynamic gufunc.
|
| 438 |
+
"""
|
| 439 |
+
@guvectorize(["f8,f8[:]"], "()->()")
|
| 440 |
+
def double(x, out):
|
| 441 |
+
out[:] = x * 2
|
| 442 |
+
|
| 443 |
+
# pickle
|
| 444 |
+
ser = pickle.dumps(double)
|
| 445 |
+
cloned = pickle.loads(ser)
|
| 446 |
+
|
| 447 |
+
# attributes carried over
|
| 448 |
+
self.assertEqual(cloned._frozen, double._frozen)
|
| 449 |
+
self.assertEqual(cloned.identity, double.identity)
|
| 450 |
+
self.assertEqual(cloned.is_dynamic, double.is_dynamic)
|
| 451 |
+
self.assertEqual(cloned.gufunc_builder._sigs,
|
| 452 |
+
double.gufunc_builder._sigs)
|
| 453 |
+
# expected value of attributes
|
| 454 |
+
self.assertTrue(cloned._frozen)
|
| 455 |
+
|
| 456 |
+
cloned.disable_compile()
|
| 457 |
+
self.assertTrue(cloned._frozen)
|
| 458 |
+
|
| 459 |
+
# scalar version
|
| 460 |
+
self.assertPreciseEqual(double(0.5), cloned(0.5))
|
| 461 |
+
# array version
|
| 462 |
+
arr = np.arange(10)
|
| 463 |
+
self.assertPreciseEqual(double(arr), cloned(arr))
|
| 464 |
+
|
| 465 |
+
def test_pickle_gufunc_dyanmic_null_init(self):
|
| 466 |
+
"""Dynamic gufunc w/o prepopulating before pickling.
|
| 467 |
+
"""
|
| 468 |
+
@guvectorize("()->()", identity=1)
|
| 469 |
+
def double(x, out):
|
| 470 |
+
out[:] = x * 2
|
| 471 |
+
|
| 472 |
+
# pickle
|
| 473 |
+
ser = pickle.dumps(double)
|
| 474 |
+
cloned = pickle.loads(ser)
|
| 475 |
+
|
| 476 |
+
# attributes carried over
|
| 477 |
+
self.assertEqual(cloned._frozen, double._frozen)
|
| 478 |
+
self.assertEqual(cloned.identity, double.identity)
|
| 479 |
+
self.assertEqual(cloned.is_dynamic, double.is_dynamic)
|
| 480 |
+
self.assertEqual(cloned.gufunc_builder._sigs,
|
| 481 |
+
double.gufunc_builder._sigs)
|
| 482 |
+
# expected value of attributes
|
| 483 |
+
self.assertFalse(cloned._frozen)
|
| 484 |
+
|
| 485 |
+
# scalar version
|
| 486 |
+
expect = np.zeros(1)
|
| 487 |
+
got = np.zeros(1)
|
| 488 |
+
double(0.5, out=expect)
|
| 489 |
+
cloned(0.5, out=got)
|
| 490 |
+
self.assertPreciseEqual(expect, got)
|
| 491 |
+
# array version
|
| 492 |
+
arr = np.arange(10)
|
| 493 |
+
expect = np.zeros_like(arr)
|
| 494 |
+
got = np.zeros_like(arr)
|
| 495 |
+
double(arr, out=expect)
|
| 496 |
+
cloned(arr, out=got)
|
| 497 |
+
self.assertPreciseEqual(expect, got)
|
| 498 |
+
|
| 499 |
+
def test_pickle_gufunc_dynamic_initialized(self):
|
| 500 |
+
"""Dynamic gufunc prepopulated before pickling.
|
| 501 |
+
|
| 502 |
+
Once unpickled, we disable compilation to verify that the gufunc
|
| 503 |
+
compilation state is carried over.
|
| 504 |
+
"""
|
| 505 |
+
@guvectorize("()->()", identity=1)
|
| 506 |
+
def double(x, out):
|
| 507 |
+
out[:] = x * 2
|
| 508 |
+
|
| 509 |
+
# prepopulate scalar
|
| 510 |
+
expect = np.zeros(1)
|
| 511 |
+
got = np.zeros(1)
|
| 512 |
+
double(0.5, out=expect)
|
| 513 |
+
# prepopulate array
|
| 514 |
+
arr = np.arange(10)
|
| 515 |
+
expect = np.zeros_like(arr)
|
| 516 |
+
got = np.zeros_like(arr)
|
| 517 |
+
double(arr, out=expect)
|
| 518 |
+
|
| 519 |
+
# pickle
|
| 520 |
+
ser = pickle.dumps(double)
|
| 521 |
+
cloned = pickle.loads(ser)
|
| 522 |
+
|
| 523 |
+
# attributes carried over
|
| 524 |
+
self.assertEqual(cloned._frozen, double._frozen)
|
| 525 |
+
self.assertEqual(cloned.identity, double.identity)
|
| 526 |
+
self.assertEqual(cloned.is_dynamic, double.is_dynamic)
|
| 527 |
+
self.assertEqual(cloned.gufunc_builder._sigs,
|
| 528 |
+
double.gufunc_builder._sigs)
|
| 529 |
+
# expected value of attributes
|
| 530 |
+
self.assertFalse(cloned._frozen)
|
| 531 |
+
|
| 532 |
+
# disable compilation
|
| 533 |
+
cloned.disable_compile()
|
| 534 |
+
self.assertTrue(cloned._frozen)
|
| 535 |
+
# scalar version
|
| 536 |
+
expect = np.zeros(1)
|
| 537 |
+
got = np.zeros(1)
|
| 538 |
+
double(0.5, out=expect)
|
| 539 |
+
cloned(0.5, out=got)
|
| 540 |
+
self.assertPreciseEqual(expect, got)
|
| 541 |
+
# array version
|
| 542 |
+
expect = np.zeros_like(arr)
|
| 543 |
+
got = np.zeros_like(arr)
|
| 544 |
+
double(arr, out=expect)
|
| 545 |
+
cloned(arr, out=got)
|
| 546 |
+
self.assertPreciseEqual(expect, got)
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
class TestGUVectorizeJit(MemoryLeakMixin, TestCase):
|
| 550 |
+
target = 'cpu'
|
| 551 |
+
|
| 552 |
+
def check_add_gufunc(self, gufunc):
|
| 553 |
+
@jit(nopython=True)
|
| 554 |
+
def jit_add(x, y, res):
|
| 555 |
+
gufunc(x, y, res)
|
| 556 |
+
|
| 557 |
+
x = np.arange(40, dtype='i8').reshape(4, 2, 5)
|
| 558 |
+
y = np.int32(100)
|
| 559 |
+
res = np.zeros_like(x)
|
| 560 |
+
jit_add(x, y, res)
|
| 561 |
+
self.assertPreciseEqual(res, x + y)
|
| 562 |
+
|
| 563 |
+
def test_add_static(self):
|
| 564 |
+
@guvectorize('int64[:], int64, int64[:]', '(n),()->(n)',
|
| 565 |
+
target=self.target)
|
| 566 |
+
def add(x, y, res):
|
| 567 |
+
for i in range(x.shape[0]):
|
| 568 |
+
res[i] = x[i] + y
|
| 569 |
+
|
| 570 |
+
self.check_add_gufunc(add)
|
| 571 |
+
|
| 572 |
+
def test_add_static_cast_args(self):
|
| 573 |
+
# cast the second argument from i32 -> i64
|
| 574 |
+
@guvectorize('int64[:], int64, int64[:]', '(n),()->(n)',
|
| 575 |
+
target=self.target)
|
| 576 |
+
def add(x, y, res):
|
| 577 |
+
for i in range(x.shape[0]):
|
| 578 |
+
res[i] = x[i] + y
|
| 579 |
+
|
| 580 |
+
self.check_add_gufunc(add)
|
| 581 |
+
|
| 582 |
+
def test_add_dynamic(self):
|
| 583 |
+
@guvectorize('(n),()->(n)', target=self.target)
|
| 584 |
+
def add(x, y, res):
|
| 585 |
+
for i in range(x.shape[0]):
|
| 586 |
+
res[i] = x[i] + y
|
| 587 |
+
|
| 588 |
+
self.check_add_gufunc(add)
|
| 589 |
+
|
| 590 |
+
@unittest.expectedFailure
|
| 591 |
+
def test_object_mode(self):
|
| 592 |
+
@guvectorize('(n),()->(n)', target=self.target, forceobj=True)
|
| 593 |
+
def add(x, y, res):
|
| 594 |
+
for i in range(x.shape[0]):
|
| 595 |
+
res[i] = x[i] + y
|
| 596 |
+
|
| 597 |
+
self.check_add_gufunc(add)
|
| 598 |
+
|
| 599 |
+
def check_matmul(self, jit_func):
|
| 600 |
+
matrix_ct = 1001
|
| 601 |
+
A = np.arange(matrix_ct * 2 * 4, dtype=np.float32).reshape(matrix_ct, 2, 4)
|
| 602 |
+
B = np.arange(matrix_ct * 4 * 5, dtype=np.float32).reshape(matrix_ct, 4, 5)
|
| 603 |
+
C = np.arange(matrix_ct * 2 * 5, dtype=np.float32).reshape(matrix_ct, 2, 5)
|
| 604 |
+
|
| 605 |
+
jit_func(A, B, C)
|
| 606 |
+
Gold = np.matmul(A, B)
|
| 607 |
+
|
| 608 |
+
np.testing.assert_allclose(C, Gold, rtol=1e-5, atol=1e-8)
|
| 609 |
+
|
| 610 |
+
def test_njit_matmul_call(self):
|
| 611 |
+
|
| 612 |
+
gufunc = guvectorize('(m,n),(n,p)->(m,p)',
|
| 613 |
+
target=self.target)(matmulcore)
|
| 614 |
+
|
| 615 |
+
@jit(nopython=True)
|
| 616 |
+
def matmul_jit(A, B, C):
|
| 617 |
+
return gufunc(A, B, C)
|
| 618 |
+
|
| 619 |
+
self.check_matmul(matmul_jit)
|
| 620 |
+
|
| 621 |
+
def test_axpy(self):
|
| 622 |
+
gufunc = GUVectorize(axpy, '(),(),() -> ()', target=self.target,
|
| 623 |
+
is_dynamic=True)
|
| 624 |
+
|
| 625 |
+
@jit(nopython=True)
|
| 626 |
+
def axpy_jit(a, x, y, out):
|
| 627 |
+
gufunc(a, x, y, out)
|
| 628 |
+
|
| 629 |
+
x = np.arange(10, dtype=np.intp)
|
| 630 |
+
out = np.zeros_like(x)
|
| 631 |
+
axpy_jit(x, x, x, out)
|
| 632 |
+
self.assertPreciseEqual(out, x * x + x)
|
| 633 |
+
|
| 634 |
+
def test_output_scalar(self):
|
| 635 |
+
|
| 636 |
+
@guvectorize('(n),(m) -> ()')
|
| 637 |
+
def gufunc(x, y, res):
|
| 638 |
+
res[0] = x.sum() + y.sum()
|
| 639 |
+
|
| 640 |
+
@jit(nopython=True)
|
| 641 |
+
def jit_func(x, y, res):
|
| 642 |
+
gufunc(x, y, res)
|
| 643 |
+
|
| 644 |
+
x = np.arange(40, dtype='i8').reshape(4, 10)
|
| 645 |
+
y = np.arange(20, dtype='i8')
|
| 646 |
+
res = np.zeros(4, dtype='i8')
|
| 647 |
+
jit_func(x, y, res)
|
| 648 |
+
expected = np.zeros_like(res)
|
| 649 |
+
gufunc(x, y, expected)
|
| 650 |
+
self.assertPreciseEqual(res, expected)
|
| 651 |
+
|
| 652 |
+
def test_input_scalar(self):
|
| 653 |
+
|
| 654 |
+
@guvectorize('() -> ()')
|
| 655 |
+
def gufunc(x, res):
|
| 656 |
+
res[0] = x + 100
|
| 657 |
+
|
| 658 |
+
@jit(nopython=True)
|
| 659 |
+
def jit_func(x, res):
|
| 660 |
+
gufunc(x, res)
|
| 661 |
+
|
| 662 |
+
x = np.arange(40, dtype='i8').reshape(5, 2, 4)
|
| 663 |
+
res = np.zeros_like(x)
|
| 664 |
+
jit_func(x, res)
|
| 665 |
+
expected = np.zeros_like(res)
|
| 666 |
+
gufunc(x, expected)
|
| 667 |
+
self.assertPreciseEqual(res, expected)
|
| 668 |
+
|
| 669 |
+
def test_gufunc_ndim_mismatch(self):
|
| 670 |
+
signature = "(n, m), (n, n, n) -> (m), (n, n)"
|
| 671 |
+
@guvectorize(signature)
|
| 672 |
+
def bar(x, y, res, out):
|
| 673 |
+
res[0] = 123
|
| 674 |
+
out[0] = 456
|
| 675 |
+
|
| 676 |
+
@jit(nopython=True)
|
| 677 |
+
def foo(x, y, res, out):
|
| 678 |
+
bar(x, y, res, out)
|
| 679 |
+
|
| 680 |
+
N, M = 2, 3
|
| 681 |
+
x = np.arange(N**2).reshape(N, N)
|
| 682 |
+
y = np.arange(N**3).reshape(N, N, N)
|
| 683 |
+
res = np.arange(M)
|
| 684 |
+
out = np.arange(N**2).reshape(N, N)
|
| 685 |
+
|
| 686 |
+
# calling with a 1d array should result in an error
|
| 687 |
+
with self.assertRaises(TypingError) as raises:
|
| 688 |
+
x_ = np.arange(N * N)
|
| 689 |
+
foo(x_, y, res, out)
|
| 690 |
+
msg = ('bar: Input operand 0 does not have enough dimensions (has '
|
| 691 |
+
f'1, gufunc core with signature {signature} requires 2)')
|
| 692 |
+
self.assertIn(msg, str(raises.exception))
|
| 693 |
+
|
| 694 |
+
with self.assertRaises(TypingError) as raises:
|
| 695 |
+
y_ = np.arange(N * N).reshape(N, N)
|
| 696 |
+
foo(x, y_, res, out)
|
| 697 |
+
msg = ('bar: Input operand 1 does not have enough dimensions (has '
|
| 698 |
+
f'2, gufunc core with signature {signature} requires 3)')
|
| 699 |
+
self.assertIn(msg, str(raises.exception))
|
| 700 |
+
|
| 701 |
+
with self.assertRaises(TypingError) as raises:
|
| 702 |
+
res_ = np.array(3)
|
| 703 |
+
foo(x, y, res_, out)
|
| 704 |
+
msg = ('bar: Output operand 0 does not have enough dimensions (has '
|
| 705 |
+
f'0, gufunc core with signature {signature} requires 1)')
|
| 706 |
+
self.assertIn(msg, str(raises.exception))
|
| 707 |
+
|
| 708 |
+
with self.assertRaises(TypingError) as raises:
|
| 709 |
+
out_ = np.arange(N)
|
| 710 |
+
foo(x, y, res, out_)
|
| 711 |
+
msg = ('bar: Output operand 1 does not have enough dimensions (has '
|
| 712 |
+
f'1, gufunc core with signature {signature} requires 2)')
|
| 713 |
+
self.assertIn(msg, str(raises.exception))
|
| 714 |
+
|
| 715 |
+
def test_mismatch_inner_dimensions(self):
|
| 716 |
+
@guvectorize('(n),(n) -> ()')
|
| 717 |
+
def bar(x, y, res):
|
| 718 |
+
res[0] = 123
|
| 719 |
+
|
| 720 |
+
@jit(nopython=True)
|
| 721 |
+
def foo(x, y, res):
|
| 722 |
+
bar(x, y, res)
|
| 723 |
+
|
| 724 |
+
N = 2
|
| 725 |
+
M = 3
|
| 726 |
+
x = np.empty((5, 3, N))
|
| 727 |
+
y = np.empty((M,))
|
| 728 |
+
res = np.zeros((5, 3))
|
| 729 |
+
|
| 730 |
+
# ensure that NumPy raises an exception
|
| 731 |
+
with self.assertRaises(ValueError) as np_raises:
|
| 732 |
+
bar(x, y, res)
|
| 733 |
+
msg = ('Input operand 1 has a mismatch in its core dimension 0, with '
|
| 734 |
+
'gufunc signature (n),(n) -> () (size 3 is different from 2)')
|
| 735 |
+
self.assertIn(msg, str(np_raises.exception))
|
| 736 |
+
|
| 737 |
+
with self.assertRaises(ValueError) as raises:
|
| 738 |
+
foo(x, y, res)
|
| 739 |
+
msg = ('Operand has a mismatch in one of its core dimensions')
|
| 740 |
+
self.assertIn(msg, str(raises.exception))
|
| 741 |
+
|
| 742 |
+
def test_mismatch_inner_dimensions_input_output(self):
|
| 743 |
+
@guvectorize('(n),(m) -> (n)')
|
| 744 |
+
def bar(x, y, res):
|
| 745 |
+
res[0] = 123
|
| 746 |
+
|
| 747 |
+
@jit(nopython=True)
|
| 748 |
+
def foo(x, y, res):
|
| 749 |
+
bar(x, y, res)
|
| 750 |
+
|
| 751 |
+
N = 2
|
| 752 |
+
M = 3
|
| 753 |
+
x = np.empty((5, 3, N))
|
| 754 |
+
y = np.empty((M,))
|
| 755 |
+
res = np.zeros((5, 3))
|
| 756 |
+
|
| 757 |
+
# ensure that NumPy raises an exception
|
| 758 |
+
with self.assertRaises(ValueError) as np_raises:
|
| 759 |
+
bar(x, y, res)
|
| 760 |
+
msg = ('Output operand 0 has a mismatch in its core dimension 0, with '
|
| 761 |
+
'gufunc signature (n),(m) -> (n) (size 3 is different from 2)')
|
| 762 |
+
self.assertIn(msg, str(np_raises.exception))
|
| 763 |
+
|
| 764 |
+
with self.assertRaises(ValueError) as raises:
|
| 765 |
+
foo(x, y, res)
|
| 766 |
+
msg = ('Operand has a mismatch in one of its core dimensions')
|
| 767 |
+
self.assertIn(msg, str(raises.exception))
|
| 768 |
+
|
| 769 |
+
def test_mismatch_inner_dimensions_output(self):
|
| 770 |
+
@guvectorize('(n),(m) -> (m),(m)')
|
| 771 |
+
def bar(x, y, res, out):
|
| 772 |
+
res[0] = 123
|
| 773 |
+
out[0] = 456
|
| 774 |
+
|
| 775 |
+
@jit(nopython=True)
|
| 776 |
+
def foo(x, y, res, out):
|
| 777 |
+
bar(x, y, res, out)
|
| 778 |
+
|
| 779 |
+
N = 2
|
| 780 |
+
M = 3
|
| 781 |
+
x = np.empty((N,))
|
| 782 |
+
y = np.empty((M,))
|
| 783 |
+
res = np.zeros((N,))
|
| 784 |
+
out = np.zeros((M,))
|
| 785 |
+
|
| 786 |
+
# ensure that NumPy raises an exception
|
| 787 |
+
with self.assertRaises(ValueError) as np_raises:
|
| 788 |
+
bar(x, y, res, out)
|
| 789 |
+
msg = ('Output operand 0 has a mismatch in its core dimension 0, with '
|
| 790 |
+
'gufunc signature (n),(m) -> (m),(m) (size 2 is different from 3)')
|
| 791 |
+
self.assertIn(msg, str(np_raises.exception))
|
| 792 |
+
|
| 793 |
+
with self.assertRaises(ValueError) as raises:
|
| 794 |
+
foo(x, y, res, out)
|
| 795 |
+
msg = ('Operand has a mismatch in one of its core dimensions')
|
| 796 |
+
self.assertIn(msg, str(raises.exception))
|
| 797 |
+
|
| 798 |
+
def test_mismatch_loop_shape(self):
|
| 799 |
+
@guvectorize('(n),(n) -> ()')
|
| 800 |
+
def bar(x, y, res):
|
| 801 |
+
res[0] = 123
|
| 802 |
+
|
| 803 |
+
@jit(nopython=True)
|
| 804 |
+
def foo(x, y, res):
|
| 805 |
+
bar(x, y, res)
|
| 806 |
+
|
| 807 |
+
N = 2
|
| 808 |
+
x = np.empty((1, 5, 3, N,))
|
| 809 |
+
y = np.empty((5, 3, N,))
|
| 810 |
+
res = np.zeros((5, 3))
|
| 811 |
+
|
| 812 |
+
with self.assertRaises(ValueError) as raises:
|
| 813 |
+
foo(x, y, res)
|
| 814 |
+
msg = ('Loop and array shapes are incompatible')
|
| 815 |
+
self.assertIn(msg, str(raises.exception))
|
| 816 |
+
|
| 817 |
+
def test_mismatch_loop_shape_2(self):
|
| 818 |
+
@guvectorize('(n),(n) -> (), (n)')
|
| 819 |
+
def gufunc(x, y, res, out):
|
| 820 |
+
res[0] = x.sum()
|
| 821 |
+
for i in range(x.shape[0]):
|
| 822 |
+
out[i] += x[i] + y.sum()
|
| 823 |
+
|
| 824 |
+
@jit
|
| 825 |
+
def jit_func(x, y, res, out):
|
| 826 |
+
gufunc(x, y, res, out)
|
| 827 |
+
|
| 828 |
+
N = 2
|
| 829 |
+
|
| 830 |
+
x = np.arange(4*N).reshape((4, N))
|
| 831 |
+
y = np.arange(N)
|
| 832 |
+
res = np.empty((3,))
|
| 833 |
+
out = np.zeros((3, N))
|
| 834 |
+
|
| 835 |
+
# ensure that NumPy raises an exception
|
| 836 |
+
with self.assertRaises(ValueError) as np_raises:
|
| 837 |
+
gufunc(x, y, res, out)
|
| 838 |
+
msg = ('operands could not be broadcast together with remapped shapes '
|
| 839 |
+
'[original->remapped]: (4,2)->(4,newaxis) (2,)->() '
|
| 840 |
+
'(3,)->(3,newaxis) (3,2)->(3,2) and requested shape (2)')
|
| 841 |
+
self.assertIn(msg, str(np_raises.exception))
|
| 842 |
+
|
| 843 |
+
with self.assertRaises(ValueError) as raises:
|
| 844 |
+
jit_func(x, y, res, out)
|
| 845 |
+
msg = ('Loop and array shapes are incompatible')
|
| 846 |
+
self.assertIn(msg, str(raises.exception))
|
| 847 |
+
|
| 848 |
+
def test_issue_10287(self):
|
| 849 |
+
@guvectorize([(float64[:], int64, float64[:])], "(n),()->(n)")
|
| 850 |
+
def guve(x, n, res):
|
| 851 |
+
pass
|
| 852 |
+
|
| 853 |
+
|
| 854 |
+
@jit
|
| 855 |
+
def njit_guve(x, n):
|
| 856 |
+
res = np.zeros_like(x)
|
| 857 |
+
guve(x, n, res)
|
| 858 |
+
return res
|
| 859 |
+
|
| 860 |
+
|
| 861 |
+
rng = np.random.default_rng(69)
|
| 862 |
+
|
| 863 |
+
for _ in range(20000):
|
| 864 |
+
x = rng.random(65)
|
| 865 |
+
y = np.repeat(x[None], 130, axis=0)
|
| 866 |
+
njit_guve(y, 5)
|
| 867 |
+
|
| 868 |
+
|
| 869 |
+
if __name__ == '__main__':
|
| 870 |
+
unittest.main()
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_parallel_env_variable.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from numba.np.ufunc.parallel import get_thread_count
|
| 2 |
+
from os import environ as env
|
| 3 |
+
from numba.core import config
|
| 4 |
+
import unittest
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class TestParallelEnvVariable(unittest.TestCase):
|
| 8 |
+
"""
|
| 9 |
+
Tests environment variables related to the underlying "parallel"
|
| 10 |
+
functions for npyufuncs.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
_numba_parallel_test_ = False
|
| 14 |
+
|
| 15 |
+
def test_num_threads_variable(self):
|
| 16 |
+
"""
|
| 17 |
+
Tests the NUMBA_NUM_THREADS env variable behaves as expected.
|
| 18 |
+
"""
|
| 19 |
+
key = 'NUMBA_NUM_THREADS'
|
| 20 |
+
current = str(getattr(env, key, config.NUMBA_NUM_THREADS))
|
| 21 |
+
threads = "3154"
|
| 22 |
+
env[key] = threads
|
| 23 |
+
try:
|
| 24 |
+
config.reload_config()
|
| 25 |
+
except RuntimeError as e:
|
| 26 |
+
# This test should fail if threads have already been launched
|
| 27 |
+
self.assertIn("Cannot set NUMBA_NUM_THREADS", e.args[0])
|
| 28 |
+
else:
|
| 29 |
+
self.assertEqual(threads, str(get_thread_count()))
|
| 30 |
+
self.assertEqual(threads, str(config.NUMBA_NUM_THREADS))
|
| 31 |
+
finally:
|
| 32 |
+
# reset the env variable/set to default. Should not fail even if
|
| 33 |
+
# threads are launched because the value is the same.
|
| 34 |
+
env[key] = current
|
| 35 |
+
config.reload_config()
|
| 36 |
+
|
| 37 |
+
if __name__ == '__main__':
|
| 38 |
+
unittest.main()
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_parallel_low_work.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
There was a deadlock problem when work count is smaller than number of threads.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
from numba import float32, float64, int32, uint32
|
| 8 |
+
from numba.np.ufunc import Vectorize
|
| 9 |
+
import unittest
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def vector_add(a, b):
|
| 13 |
+
return a + b
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class TestParallelLowWorkCount(unittest.TestCase):
|
| 17 |
+
|
| 18 |
+
_numba_parallel_test_ = False
|
| 19 |
+
|
| 20 |
+
def test_low_workcount(self):
|
| 21 |
+
# build parallel native code ufunc
|
| 22 |
+
pv = Vectorize(vector_add, target='parallel')
|
| 23 |
+
for ty in (int32, uint32, float32, float64):
|
| 24 |
+
pv.add(ty(ty, ty))
|
| 25 |
+
para_ufunc = pv.build_ufunc()
|
| 26 |
+
|
| 27 |
+
# build python ufunc
|
| 28 |
+
np_ufunc = np.vectorize(vector_add)
|
| 29 |
+
|
| 30 |
+
# test it out
|
| 31 |
+
def test(ty):
|
| 32 |
+
data = np.arange(1).astype(ty) # just one item
|
| 33 |
+
result = para_ufunc(data, data)
|
| 34 |
+
gold = np_ufunc(data, data)
|
| 35 |
+
np.testing.assert_allclose(gold, result)
|
| 36 |
+
|
| 37 |
+
test(np.double)
|
| 38 |
+
test(np.float32)
|
| 39 |
+
test(np.int32)
|
| 40 |
+
test(np.uint32)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
if __name__ == '__main__':
|
| 44 |
+
unittest.main()
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_parallel_ufunc_issues.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
import ctypes
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
from numba.tests.support import captured_stdout, skip_if_freethreading
|
| 7 |
+
from numba import vectorize, guvectorize
|
| 8 |
+
import unittest
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class TestParUfuncIssues(unittest.TestCase):
|
| 12 |
+
|
| 13 |
+
_numba_parallel_test_ = False
|
| 14 |
+
|
| 15 |
+
def test_thread_response(self):
|
| 16 |
+
"""
|
| 17 |
+
Related to #89.
|
| 18 |
+
This does not test #89 but tests the fix for it.
|
| 19 |
+
We want to make sure the worker threads can be used multiple times
|
| 20 |
+
and with different time gap between each execution.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
@vectorize('float64(float64, float64)', target='parallel')
|
| 24 |
+
def fnv(a, b):
|
| 25 |
+
return a + b
|
| 26 |
+
|
| 27 |
+
sleep_time = 1 # 1 second
|
| 28 |
+
while sleep_time > 0.00001: # 10us
|
| 29 |
+
time.sleep(sleep_time)
|
| 30 |
+
a = b = np.arange(10**5)
|
| 31 |
+
np.testing.assert_equal(a + b, fnv(a, b))
|
| 32 |
+
# Reduce sleep time
|
| 33 |
+
sleep_time /= 2
|
| 34 |
+
|
| 35 |
+
@skip_if_freethreading
|
| 36 |
+
def test_gil_reacquire_deadlock(self):
|
| 37 |
+
"""
|
| 38 |
+
Testing issue #1998 due to GIL reacquiring
|
| 39 |
+
"""
|
| 40 |
+
# make a ctypes callback that requires the GIL
|
| 41 |
+
proto = ctypes.CFUNCTYPE(None, ctypes.c_int32)
|
| 42 |
+
characters = 'abcdefghij'
|
| 43 |
+
|
| 44 |
+
def bar(x):
|
| 45 |
+
print(characters[x])
|
| 46 |
+
|
| 47 |
+
cbar = proto(bar)
|
| 48 |
+
|
| 49 |
+
# our unit under test
|
| 50 |
+
@vectorize(['int32(int32)'], target='parallel', nopython=True)
|
| 51 |
+
def foo(x):
|
| 52 |
+
print(x % 10) # this reacquires the GIL
|
| 53 |
+
cbar(x % 10) # this reacquires the GIL
|
| 54 |
+
return x * 2
|
| 55 |
+
|
| 56 |
+
# Numpy ufunc has a heuristic to determine whether to release the GIL
|
| 57 |
+
# during execution. Small input size (10) seems to not release the GIL.
|
| 58 |
+
# Large input size (1000) seems to release the GIL.
|
| 59 |
+
for nelem in [1, 10, 100, 1000]:
|
| 60 |
+
# inputs
|
| 61 |
+
a = np.arange(nelem, dtype=np.int32)
|
| 62 |
+
acopy = a.copy()
|
| 63 |
+
# run and capture stdout
|
| 64 |
+
with captured_stdout() as buf:
|
| 65 |
+
got = foo(a)
|
| 66 |
+
stdout = buf.getvalue()
|
| 67 |
+
buf.close()
|
| 68 |
+
# process outputs from print
|
| 69 |
+
got_output = sorted(map(lambda x: x.strip(), stdout.splitlines()))
|
| 70 |
+
# build expected output
|
| 71 |
+
expected_output = [str(x % 10) for x in range(nelem)]
|
| 72 |
+
expected_output += [characters[x % 10] for x in range(nelem)]
|
| 73 |
+
expected_output = sorted(expected_output)
|
| 74 |
+
# verify
|
| 75 |
+
self.assertEqual(got_output, expected_output)
|
| 76 |
+
np.testing.assert_equal(got, 2 * acopy)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class TestParGUfuncIssues(unittest.TestCase):
|
| 81 |
+
|
| 82 |
+
_numba_parallel_test_ = False
|
| 83 |
+
|
| 84 |
+
@skip_if_freethreading
|
| 85 |
+
def test_gil_reacquire_deadlock(self):
|
| 86 |
+
"""
|
| 87 |
+
Testing similar issue to #1998 due to GIL reacquiring for Gufunc
|
| 88 |
+
"""
|
| 89 |
+
# make a ctypes callback that requires the GIL
|
| 90 |
+
proto = ctypes.CFUNCTYPE(None, ctypes.c_int32)
|
| 91 |
+
characters = 'abcdefghij'
|
| 92 |
+
|
| 93 |
+
def bar(x):
|
| 94 |
+
print(characters[x])
|
| 95 |
+
|
| 96 |
+
cbar = proto(bar)
|
| 97 |
+
|
| 98 |
+
# our unit under test
|
| 99 |
+
@guvectorize(['(int32, int32[:])'], "()->()",
|
| 100 |
+
target='parallel', nopython=True)
|
| 101 |
+
def foo(x, out):
|
| 102 |
+
print(x % 10) # this reacquires the GIL
|
| 103 |
+
cbar(x % 10) # this reacquires the GIL
|
| 104 |
+
out[0] = x * 2
|
| 105 |
+
|
| 106 |
+
# Numpy ufunc has a heuristic to determine whether to release the GIL
|
| 107 |
+
# during execution. Small input size (10) seems to not release the GIL.
|
| 108 |
+
# Large input size (1000) seems to release the GIL.
|
| 109 |
+
for nelem in [1, 10, 100, 1000]:
|
| 110 |
+
# inputs
|
| 111 |
+
a = np.arange(nelem, dtype=np.int32)
|
| 112 |
+
acopy = a.copy()
|
| 113 |
+
# run and capture stdout
|
| 114 |
+
with captured_stdout() as buf:
|
| 115 |
+
got = foo(a)
|
| 116 |
+
stdout = buf.getvalue()
|
| 117 |
+
buf.close()
|
| 118 |
+
# process outputs from print
|
| 119 |
+
got_output = sorted(map(lambda x: x.strip(), stdout.splitlines()))
|
| 120 |
+
# build expected output
|
| 121 |
+
expected_output = [str(x % 10) for x in range(nelem)]
|
| 122 |
+
expected_output += [characters[x % 10] for x in range(nelem)]
|
| 123 |
+
expected_output = sorted(expected_output)
|
| 124 |
+
# verify
|
| 125 |
+
self.assertEqual(got_output, expected_output)
|
| 126 |
+
np.testing.assert_equal(got, 2 * acopy)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
if __name__ == '__main__':
|
| 130 |
+
unittest.main()
|
data/conda_envs/evalclaw/lib/python3.11/site-pack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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
from numba import float32, jit, njit
|
| 4 |
+
from numba.np.ufunc import Vectorize
|
| 5 |
+
from numba.core.errors import TypingError
|
| 6 |
+
from numba.tests.support import TestCase
|
| 7 |
+
import unittest
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
dtype = np.float32
|
| 11 |
+
a = np.arange(80, dtype=dtype).reshape(8, 10)
|
| 12 |
+
b = a.copy()
|
| 13 |
+
c = a.copy(order='F')
|
| 14 |
+
d = np.arange(16 * 20, dtype=dtype).reshape(16, 20)[::2, ::2]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def add(a, b):
|
| 18 |
+
return a + b
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def add_multiple_args(a, b, c, d):
|
| 22 |
+
return a + b + c + d
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def gufunc_add(a, b):
|
| 26 |
+
result = 0.0
|
| 27 |
+
for i in range(a.shape[0]):
|
| 28 |
+
result += a[i] * b[i]
|
| 29 |
+
|
| 30 |
+
return result
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def ufunc_reduce(ufunc, arg):
|
| 34 |
+
for i in range(arg.ndim):
|
| 35 |
+
arg = ufunc.reduce(arg)
|
| 36 |
+
return arg
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
vectorizers = [
|
| 40 |
+
Vectorize,
|
| 41 |
+
# ParallelVectorize,
|
| 42 |
+
# StreamVectorize,
|
| 43 |
+
# CudaVectorize,
|
| 44 |
+
# GUFuncVectorize,
|
| 45 |
+
]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class TestUFuncs(TestCase):
|
| 49 |
+
|
| 50 |
+
def _test_ufunc_attributes(self, cls, a, b, *args):
|
| 51 |
+
"Test ufunc attributes"
|
| 52 |
+
vectorizer = cls(add, *args)
|
| 53 |
+
vectorizer.add(float32(float32, float32))
|
| 54 |
+
ufunc = vectorizer.build_ufunc()
|
| 55 |
+
|
| 56 |
+
info = (cls, a.ndim)
|
| 57 |
+
self.assertPreciseEqual(ufunc(a, b), a + b, msg=info)
|
| 58 |
+
self.assertPreciseEqual(ufunc_reduce(ufunc, a), np.sum(a), msg=info)
|
| 59 |
+
self.assertPreciseEqual(ufunc.accumulate(a), np.add.accumulate(a),
|
| 60 |
+
msg=info)
|
| 61 |
+
self.assertPreciseEqual(ufunc.outer(a, b), np.add.outer(a, b), msg=info)
|
| 62 |
+
|
| 63 |
+
def _test_broadcasting(self, cls, a, b, c, d):
|
| 64 |
+
"Test multiple args"
|
| 65 |
+
vectorizer = cls(add_multiple_args)
|
| 66 |
+
vectorizer.add(float32(float32, float32, float32, float32))
|
| 67 |
+
ufunc = vectorizer.build_ufunc()
|
| 68 |
+
|
| 69 |
+
info = (cls, a.shape)
|
| 70 |
+
self.assertPreciseEqual(ufunc(a, b, c, d), a + b + c + d, msg=info)
|
| 71 |
+
|
| 72 |
+
def test_ufunc_attributes(self):
|
| 73 |
+
for v in vectorizers: # 1D
|
| 74 |
+
self._test_ufunc_attributes(v, a[0], b[0])
|
| 75 |
+
for v in vectorizers: # 2D
|
| 76 |
+
self._test_ufunc_attributes(v, a, b)
|
| 77 |
+
for v in vectorizers: # 3D
|
| 78 |
+
self._test_ufunc_attributes(v, a[:, np.newaxis, :],
|
| 79 |
+
b[np.newaxis, :, :])
|
| 80 |
+
|
| 81 |
+
def test_broadcasting(self):
|
| 82 |
+
for v in vectorizers: # 1D
|
| 83 |
+
self._test_broadcasting(v, a[0], b[0], c[0], d[0])
|
| 84 |
+
for v in vectorizers: # 2D
|
| 85 |
+
self._test_broadcasting(v, a, b, c, d)
|
| 86 |
+
for v in vectorizers: # 3D
|
| 87 |
+
self._test_broadcasting(v, a[:, np.newaxis, :], b[np.newaxis, :, :],
|
| 88 |
+
c[:, np.newaxis, :], d[np.newaxis, :, :])
|
| 89 |
+
|
| 90 |
+
def test_implicit_broadcasting(self):
|
| 91 |
+
for v in vectorizers:
|
| 92 |
+
vectorizer = v(add)
|
| 93 |
+
vectorizer.add(float32(float32, float32))
|
| 94 |
+
ufunc = vectorizer.build_ufunc()
|
| 95 |
+
|
| 96 |
+
broadcasting_b = b[np.newaxis, :, np.newaxis, np.newaxis, :]
|
| 97 |
+
self.assertPreciseEqual(ufunc(a, broadcasting_b),
|
| 98 |
+
a + broadcasting_b)
|
| 99 |
+
|
| 100 |
+
def test_ufunc_exception_on_write_to_readonly(self):
|
| 101 |
+
z = np.ones(10)
|
| 102 |
+
z.flags.writeable = False # flip write bit
|
| 103 |
+
|
| 104 |
+
tests = []
|
| 105 |
+
expect = "ufunc 'sin' called with an explicit output that is read-only"
|
| 106 |
+
tests.append((jit(nopython=True), TypingError, expect))
|
| 107 |
+
tests.append((jit(forceobj=True), ValueError,
|
| 108 |
+
"output array is read-only"))
|
| 109 |
+
|
| 110 |
+
for dec, exc, msg in tests:
|
| 111 |
+
def test(x):
|
| 112 |
+
a = np.ones(x.shape, x.dtype) # do not copy RO attribute from x
|
| 113 |
+
np.sin(a, x)
|
| 114 |
+
|
| 115 |
+
with self.assertRaises(exc) as raises:
|
| 116 |
+
dec(test)(z)
|
| 117 |
+
|
| 118 |
+
self.assertIn(msg, str(raises.exception))
|
| 119 |
+
|
| 120 |
+
def test_optional_type_handling(self):
|
| 121 |
+
# Tests ufunc compilation with Optional type
|
| 122 |
+
|
| 123 |
+
@njit
|
| 124 |
+
def inner(x, y):
|
| 125 |
+
if y > 2:
|
| 126 |
+
z = None
|
| 127 |
+
else:
|
| 128 |
+
z = np.ones(4)
|
| 129 |
+
return np.add(x, z)
|
| 130 |
+
|
| 131 |
+
# This causes `z` to be np.ones(4) at runtime, success
|
| 132 |
+
self.assertPreciseEqual(inner(np.arange(4), 1),
|
| 133 |
+
np.arange(1, 5).astype(np.float64))
|
| 134 |
+
|
| 135 |
+
with self.assertRaises(TypeError) as raises:
|
| 136 |
+
# This causes `z` to be None at runtime, TypeError raised on the
|
| 137 |
+
# type cast of the Optional.
|
| 138 |
+
inner(np.arange(4), 3)
|
| 139 |
+
|
| 140 |
+
msg = "expected array(float64, 1d, C), got None"
|
| 141 |
+
self.assertIn(msg, str(raises.exception))
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
class TestUFuncsMisc(TestCase):
|
| 145 |
+
# Test for miscellaneous ufunc issues
|
| 146 |
+
|
| 147 |
+
def test_exp2(self):
|
| 148 |
+
# See issue #8898, and TargetLibraryInfo based fix in #9336
|
| 149 |
+
@njit
|
| 150 |
+
def foo(x):
|
| 151 |
+
return np.exp2(x)
|
| 152 |
+
|
| 153 |
+
for ty in (np.int8, np.uint16):
|
| 154 |
+
x = ty(2)
|
| 155 |
+
expected = foo.py_func(x)
|
| 156 |
+
got = foo(x)
|
| 157 |
+
self.assertPreciseEqual(expected, got)
|
| 158 |
+
|
| 159 |
+
def test_log2(self):
|
| 160 |
+
# See issue #8898, and TargetLibraryInfo based fix in #9336
|
| 161 |
+
@njit
|
| 162 |
+
def foo(x):
|
| 163 |
+
return np.log2(x)
|
| 164 |
+
|
| 165 |
+
for ty in (np.int8, np.uint16):
|
| 166 |
+
x = ty(2)
|
| 167 |
+
expected = foo.py_func(x)
|
| 168 |
+
got = foo(x)
|
| 169 |
+
self.assertPreciseEqual(expected, got)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
if __name__ == '__main__':
|
| 173 |
+
unittest.main()
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_ufuncbuilding.py
ADDED
|
@@ -0,0 +1,471 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pickle
|
| 2 |
+
import unittest
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
from numpy.testing import assert_array_equal
|
| 6 |
+
|
| 7 |
+
from numba.np.ufunc.ufuncbuilder import GUFuncBuilder
|
| 8 |
+
from numba import vectorize, guvectorize
|
| 9 |
+
from numba.np.ufunc import PyUFunc_One
|
| 10 |
+
from numba.np.ufunc.dufunc import DUFunc as UFuncBuilder
|
| 11 |
+
from numba.tests.support import tag, TestCase
|
| 12 |
+
from numba.core import config
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class TestUfuncBuilding(TestCase):
|
| 16 |
+
|
| 17 |
+
def test_basic_ufunc(self):
|
| 18 |
+
from numba.tests.npyufunc.ufuncbuilding_usecases import add
|
| 19 |
+
ufb = UFuncBuilder(add)
|
| 20 |
+
cres = ufb.add("int32(int32, int32)")
|
| 21 |
+
self.assertFalse(cres.objectmode)
|
| 22 |
+
cres = ufb.add("int64(int64, int64)")
|
| 23 |
+
self.assertFalse(cres.objectmode)
|
| 24 |
+
ufunc = ufb.build_ufunc()
|
| 25 |
+
|
| 26 |
+
def check(a):
|
| 27 |
+
b = ufunc(a, a)
|
| 28 |
+
self.assertPreciseEqual(a + a, b)
|
| 29 |
+
self.assertEqual(b.dtype, a.dtype)
|
| 30 |
+
|
| 31 |
+
a = np.arange(12, dtype='int32')
|
| 32 |
+
check(a)
|
| 33 |
+
# Non-contiguous dimension
|
| 34 |
+
a = a[::2]
|
| 35 |
+
check(a)
|
| 36 |
+
a = a.reshape((2, 3))
|
| 37 |
+
check(a)
|
| 38 |
+
|
| 39 |
+
# Metadata
|
| 40 |
+
self.assertEqual(ufunc.__name__, "add")
|
| 41 |
+
self.assertIn("An addition", ufunc.__doc__)
|
| 42 |
+
|
| 43 |
+
def test_ufunc_struct(self):
|
| 44 |
+
from numba.tests.npyufunc.ufuncbuilding_usecases import add
|
| 45 |
+
ufb = UFuncBuilder(add)
|
| 46 |
+
cres = ufb.add("complex64(complex64, complex64)")
|
| 47 |
+
self.assertFalse(cres.objectmode)
|
| 48 |
+
ufunc = ufb.build_ufunc()
|
| 49 |
+
|
| 50 |
+
def check(a):
|
| 51 |
+
b = ufunc(a, a)
|
| 52 |
+
self.assertPreciseEqual(a + a, b)
|
| 53 |
+
self.assertEqual(b.dtype, a.dtype)
|
| 54 |
+
|
| 55 |
+
a = np.arange(12, dtype='complex64') + 1j
|
| 56 |
+
check(a)
|
| 57 |
+
# Non-contiguous dimension
|
| 58 |
+
a = a[::2]
|
| 59 |
+
check(a)
|
| 60 |
+
a = a.reshape((2, 3))
|
| 61 |
+
check(a)
|
| 62 |
+
|
| 63 |
+
def test_ufunc_forceobj(self):
|
| 64 |
+
from numba.tests.npyufunc.ufuncbuilding_usecases import add
|
| 65 |
+
ufb = UFuncBuilder(add, targetoptions={'forceobj': True})
|
| 66 |
+
cres = ufb.add("int32(int32, int32)")
|
| 67 |
+
self.assertTrue(cres.objectmode)
|
| 68 |
+
ufunc = ufb.build_ufunc()
|
| 69 |
+
|
| 70 |
+
a = np.arange(10, dtype='int32')
|
| 71 |
+
b = ufunc(a, a)
|
| 72 |
+
self.assertPreciseEqual(a + a, b)
|
| 73 |
+
|
| 74 |
+
def test_nested_call(self):
|
| 75 |
+
"""
|
| 76 |
+
Check nested call to an implicitly-typed ufunc.
|
| 77 |
+
"""
|
| 78 |
+
from numba.tests.npyufunc.ufuncbuilding_usecases import outer
|
| 79 |
+
builder = UFuncBuilder(outer,
|
| 80 |
+
targetoptions={'nopython': True})
|
| 81 |
+
builder.add("(int64, int64)")
|
| 82 |
+
ufunc = builder.build_ufunc()
|
| 83 |
+
self.assertEqual(ufunc(-1, 3), 2)
|
| 84 |
+
|
| 85 |
+
def test_nested_call_explicit(self):
|
| 86 |
+
"""
|
| 87 |
+
Check nested call to an explicitly-typed ufunc.
|
| 88 |
+
"""
|
| 89 |
+
from numba.tests.npyufunc.ufuncbuilding_usecases import outer_explicit
|
| 90 |
+
builder = UFuncBuilder(outer_explicit,
|
| 91 |
+
targetoptions={'nopython': True})
|
| 92 |
+
builder.add("(int64, int64)")
|
| 93 |
+
ufunc = builder.build_ufunc()
|
| 94 |
+
self.assertEqual(ufunc(-1, 3), 2)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class TestUfuncBuildingJitDisabled(TestUfuncBuilding):
|
| 98 |
+
|
| 99 |
+
def setUp(self):
|
| 100 |
+
self.old_disable_jit = config.DISABLE_JIT
|
| 101 |
+
config.DISABLE_JIT = False
|
| 102 |
+
|
| 103 |
+
def tearDown(self):
|
| 104 |
+
config.DISABLE_JIT = self.old_disable_jit
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class TestGUfuncBuilding(TestCase):
|
| 108 |
+
|
| 109 |
+
def test_basic_gufunc(self):
|
| 110 |
+
from numba.tests.npyufunc.ufuncbuilding_usecases import guadd
|
| 111 |
+
gufb = GUFuncBuilder(guadd, "(x, y),(x, y)->(x, y)")
|
| 112 |
+
cres = gufb.add("void(int32[:,:], int32[:,:], int32[:,:])")
|
| 113 |
+
self.assertFalse(cres.objectmode)
|
| 114 |
+
ufunc = gufb.build_ufunc()
|
| 115 |
+
|
| 116 |
+
a = np.arange(10, dtype="int32").reshape(2, 5)
|
| 117 |
+
b = ufunc(a, a)
|
| 118 |
+
|
| 119 |
+
self.assertPreciseEqual(a + a, b)
|
| 120 |
+
self.assertEqual(b.dtype, np.dtype('int32'))
|
| 121 |
+
|
| 122 |
+
# Metadata
|
| 123 |
+
self.assertEqual(ufunc.__name__, "guadd")
|
| 124 |
+
self.assertIn("A generalized addition", ufunc.__doc__)
|
| 125 |
+
|
| 126 |
+
def test_gufunc_struct(self):
|
| 127 |
+
from numba.tests.npyufunc.ufuncbuilding_usecases import guadd
|
| 128 |
+
gufb = GUFuncBuilder(guadd, "(x, y),(x, y)->(x, y)")
|
| 129 |
+
cres = gufb.add("void(complex64[:,:], complex64[:,:], complex64[:,:])")
|
| 130 |
+
self.assertFalse(cres.objectmode)
|
| 131 |
+
ufunc = gufb.build_ufunc()
|
| 132 |
+
|
| 133 |
+
a = np.arange(10, dtype="complex64").reshape(2, 5) + 1j
|
| 134 |
+
b = ufunc(a, a)
|
| 135 |
+
|
| 136 |
+
self.assertPreciseEqual(a + a, b)
|
| 137 |
+
|
| 138 |
+
def test_gufunc_struct_forceobj(self):
|
| 139 |
+
from numba.tests.npyufunc.ufuncbuilding_usecases import guadd
|
| 140 |
+
gufb = GUFuncBuilder(guadd, "(x, y),(x, y)->(x, y)",
|
| 141 |
+
targetoptions=dict(forceobj=True))
|
| 142 |
+
cres = gufb.add("void(complex64[:,:], complex64[:,:], complex64[:,"
|
| 143 |
+
":])")
|
| 144 |
+
self.assertTrue(cres.objectmode)
|
| 145 |
+
ufunc = gufb.build_ufunc()
|
| 146 |
+
|
| 147 |
+
a = np.arange(10, dtype="complex64").reshape(2, 5) + 1j
|
| 148 |
+
b = ufunc(a, a)
|
| 149 |
+
|
| 150 |
+
self.assertPreciseEqual(a + a, b)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class TestGUfuncBuildingJitDisabled(TestGUfuncBuilding):
|
| 154 |
+
|
| 155 |
+
def setUp(self):
|
| 156 |
+
self.old_disable_jit = config.DISABLE_JIT
|
| 157 |
+
config.DISABLE_JIT = False
|
| 158 |
+
|
| 159 |
+
def tearDown(self):
|
| 160 |
+
config.DISABLE_JIT = self.old_disable_jit
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class TestVectorizeDecor(TestCase):
|
| 164 |
+
|
| 165 |
+
_supported_identities = [0, 1, None, "reorderable"]
|
| 166 |
+
|
| 167 |
+
def test_vectorize(self):
|
| 168 |
+
from numba.tests.npyufunc.ufuncbuilding_usecases import add
|
| 169 |
+
ufunc = vectorize(['int32(int32, int32)'])(add)
|
| 170 |
+
a = np.arange(10, dtype='int32')
|
| 171 |
+
b = ufunc(a, a)
|
| 172 |
+
self.assertPreciseEqual(a + a, b)
|
| 173 |
+
|
| 174 |
+
def test_vectorize_objmode(self):
|
| 175 |
+
from numba.tests.npyufunc.ufuncbuilding_usecases import add
|
| 176 |
+
ufunc = vectorize(['int32(int32, int32)'], forceobj=True)(add)
|
| 177 |
+
a = np.arange(10, dtype='int32')
|
| 178 |
+
b = ufunc(a, a)
|
| 179 |
+
self.assertPreciseEqual(a + a, b)
|
| 180 |
+
|
| 181 |
+
def test_vectorize_bool_return(self):
|
| 182 |
+
from numba.tests.npyufunc.ufuncbuilding_usecases import equals
|
| 183 |
+
ufunc = vectorize(['bool_(int32, int32)'])(equals)
|
| 184 |
+
a = np.arange(10, dtype='int32')
|
| 185 |
+
r = ufunc(a,a)
|
| 186 |
+
self.assertPreciseEqual(r, np.ones(r.shape, dtype=np.bool_))
|
| 187 |
+
|
| 188 |
+
def test_vectorize_identity(self):
|
| 189 |
+
from numba.tests.npyufunc.ufuncbuilding_usecases import add
|
| 190 |
+
sig = 'int32(int32, int32)'
|
| 191 |
+
for identity in self._supported_identities:
|
| 192 |
+
ufunc = vectorize([sig], identity=identity)(add)
|
| 193 |
+
expected = None if identity == 'reorderable' else identity
|
| 194 |
+
self.assertEqual(ufunc.identity, expected)
|
| 195 |
+
# Default value is None
|
| 196 |
+
ufunc = vectorize([sig])(add)
|
| 197 |
+
self.assertIs(ufunc.identity, None)
|
| 198 |
+
# Invalid values
|
| 199 |
+
with self.assertRaises(ValueError):
|
| 200 |
+
vectorize([sig], identity='none')(add)
|
| 201 |
+
with self.assertRaises(ValueError):
|
| 202 |
+
vectorize([sig], identity=2)(add)
|
| 203 |
+
|
| 204 |
+
def test_vectorize_no_args(self):
|
| 205 |
+
from numba.tests.npyufunc.ufuncbuilding_usecases import add
|
| 206 |
+
a = np.linspace(0,1,10)
|
| 207 |
+
b = np.linspace(1,2,10)
|
| 208 |
+
ufunc = vectorize(add)
|
| 209 |
+
self.assertPreciseEqual(ufunc(a,b), a + b)
|
| 210 |
+
ufunc2 = vectorize(add)
|
| 211 |
+
c = np.empty(10)
|
| 212 |
+
ufunc2(a, b, c)
|
| 213 |
+
self.assertPreciseEqual(c, a + b)
|
| 214 |
+
|
| 215 |
+
def test_vectorize_only_kws(self):
|
| 216 |
+
from numba.tests.npyufunc.ufuncbuilding_usecases import mul
|
| 217 |
+
a = np.linspace(0,1,10)
|
| 218 |
+
b = np.linspace(1,2,10)
|
| 219 |
+
ufunc = vectorize(identity=PyUFunc_One, nopython=True)(mul)
|
| 220 |
+
self.assertPreciseEqual(ufunc(a,b), a * b)
|
| 221 |
+
|
| 222 |
+
def test_vectorize_output_kwarg(self):
|
| 223 |
+
"""
|
| 224 |
+
Passing the output array as a keyword argument (issue #1867).
|
| 225 |
+
"""
|
| 226 |
+
def check(ufunc):
|
| 227 |
+
a = np.arange(10, 16, dtype='int32')
|
| 228 |
+
out = np.zeros_like(a)
|
| 229 |
+
got = ufunc(a, a, out=out)
|
| 230 |
+
self.assertIs(got, out)
|
| 231 |
+
self.assertPreciseEqual(out, a + a)
|
| 232 |
+
with self.assertRaises(TypeError):
|
| 233 |
+
ufunc(a, a, zzz=out)
|
| 234 |
+
|
| 235 |
+
# With explicit sigs
|
| 236 |
+
from numba.tests.npyufunc.ufuncbuilding_usecases import add
|
| 237 |
+
ufunc = vectorize(['int32(int32, int32)'], nopython=True)(add)
|
| 238 |
+
check(ufunc)
|
| 239 |
+
# With implicit sig
|
| 240 |
+
ufunc = vectorize(nopython=True)(add)
|
| 241 |
+
check(ufunc) # compiling
|
| 242 |
+
check(ufunc) # after compiling
|
| 243 |
+
|
| 244 |
+
def test_guvectorize(self):
|
| 245 |
+
from numba.tests.npyufunc.ufuncbuilding_usecases import guadd
|
| 246 |
+
ufunc = guvectorize(['(int32[:,:], int32[:,:], int32[:,:])'],
|
| 247 |
+
"(x,y),(x,y)->(x,y)")(guadd)
|
| 248 |
+
a = np.arange(10, dtype='int32').reshape(2, 5)
|
| 249 |
+
b = ufunc(a, a)
|
| 250 |
+
self.assertPreciseEqual(a + a, b)
|
| 251 |
+
|
| 252 |
+
def test_guvectorize_no_output(self):
|
| 253 |
+
from numba.tests.npyufunc.ufuncbuilding_usecases import guadd
|
| 254 |
+
ufunc = guvectorize(['(int32[:,:], int32[:,:], int32[:,:])'],
|
| 255 |
+
"(x,y),(x,y),(x,y)")(guadd)
|
| 256 |
+
a = np.arange(10, dtype='int32').reshape(2, 5)
|
| 257 |
+
out = np.zeros_like(a)
|
| 258 |
+
ufunc(a, a, out)
|
| 259 |
+
self.assertPreciseEqual(a + a, out)
|
| 260 |
+
|
| 261 |
+
def test_guvectorize_objectmode(self):
|
| 262 |
+
from numba.tests.npyufunc.ufuncbuilding_usecases import guadd_obj
|
| 263 |
+
ufunc = guvectorize(['(int32[:,:], int32[:,:], int32[:,:])'],
|
| 264 |
+
"(x,y),(x,y)->(x,y)", forceobj=True)(guadd_obj)
|
| 265 |
+
a = np.arange(10, dtype='int32').reshape(2, 5)
|
| 266 |
+
b = ufunc(a, a)
|
| 267 |
+
self.assertPreciseEqual(a + a, b)
|
| 268 |
+
|
| 269 |
+
def test_guvectorize_scalar_objectmode(self):
|
| 270 |
+
"""
|
| 271 |
+
Test passing of scalars to object mode gufuncs.
|
| 272 |
+
"""
|
| 273 |
+
from numba.tests.npyufunc.ufuncbuilding_usecases import guadd_scalar_obj
|
| 274 |
+
ufunc = guvectorize(['(int32[:,:], int32, int32[:,:])'],
|
| 275 |
+
"(x,y),()->(x,y)", forceobj=True)(guadd_scalar_obj)
|
| 276 |
+
a = np.arange(10, dtype='int32').reshape(2, 5)
|
| 277 |
+
b = ufunc(a, 3)
|
| 278 |
+
self.assertPreciseEqual(a + 3, b)
|
| 279 |
+
|
| 280 |
+
def test_guvectorize_error_in_objectmode(self):
|
| 281 |
+
from numba.tests.npyufunc.ufuncbuilding_usecases import guerror, \
|
| 282 |
+
MyException
|
| 283 |
+
ufunc = guvectorize(['(int32[:,:], int32[:,:], int32[:,:])'],
|
| 284 |
+
"(x,y),(x,y)->(x,y)", forceobj=True)(guerror)
|
| 285 |
+
a = np.arange(10, dtype='int32').reshape(2, 5)
|
| 286 |
+
with self.assertRaises(MyException):
|
| 287 |
+
ufunc(a, a)
|
| 288 |
+
|
| 289 |
+
def test_guvectorize_identity(self):
|
| 290 |
+
from numba.tests.npyufunc.ufuncbuilding_usecases import add, guadd
|
| 291 |
+
args = (['(int32[:,:], int32[:,:], int32[:,:])'], "(x,y),(x,y)->(x,y)")
|
| 292 |
+
for identity in self._supported_identities:
|
| 293 |
+
ufunc = guvectorize(*args, identity=identity)(guadd)
|
| 294 |
+
expected = None if identity == 'reorderable' else identity
|
| 295 |
+
self.assertEqual(ufunc.identity, expected)
|
| 296 |
+
# Default value is None
|
| 297 |
+
ufunc = guvectorize(*args)(guadd)
|
| 298 |
+
self.assertIs(ufunc.identity, None)
|
| 299 |
+
# Invalid values
|
| 300 |
+
with self.assertRaises(ValueError):
|
| 301 |
+
guvectorize(*args, identity='none')(add)
|
| 302 |
+
with self.assertRaises(ValueError):
|
| 303 |
+
guvectorize(*args, identity=2)(add)
|
| 304 |
+
|
| 305 |
+
def test_guvectorize_invalid_layout(self):
|
| 306 |
+
from numba.tests.npyufunc.ufuncbuilding_usecases import guadd
|
| 307 |
+
sigs = ['(int32[:,:], int32[:,:], int32[:,:])']
|
| 308 |
+
# Syntax error
|
| 309 |
+
with self.assertRaises(ValueError) as raises:
|
| 310 |
+
guvectorize(sigs, ")-:")(guadd)
|
| 311 |
+
self.assertIn("bad token in signature", str(raises.exception))
|
| 312 |
+
# Output shape can't be inferred from inputs
|
| 313 |
+
with self.assertRaises(NameError) as raises:
|
| 314 |
+
guvectorize(sigs, "(x,y),(x,y)->(x,z,v)")(guadd)
|
| 315 |
+
self.assertEqual(str(raises.exception),
|
| 316 |
+
"undefined output symbols: v,z")
|
| 317 |
+
# Arrow but no outputs
|
| 318 |
+
with self.assertRaises(ValueError) as raises:
|
| 319 |
+
guvectorize(sigs, "(x,y),(x,y),(x,y)->")(guadd)
|
| 320 |
+
# (error message depends on Numpy version)
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
class NEP13Array:
|
| 324 |
+
"""https://numpy.org/neps/nep-0013-ufunc-overrides.html"""
|
| 325 |
+
def __init__(self, array):
|
| 326 |
+
self.array = array
|
| 327 |
+
|
| 328 |
+
def __array__(self):
|
| 329 |
+
return self.array
|
| 330 |
+
|
| 331 |
+
def tolist(self):
|
| 332 |
+
return self.array.tolist()
|
| 333 |
+
|
| 334 |
+
def __array_ufunc__(self, ufunc, method, *args, **kwargs):
|
| 335 |
+
if method != "__call__":
|
| 336 |
+
return NotImplemented
|
| 337 |
+
|
| 338 |
+
return NEP13Array(ufunc(*[np.asarray(x) for x in args], **kwargs))
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
class FakeDaskArray:
|
| 342 |
+
"""This class defines both the NEP13 protocol and the dask collection protocol
|
| 343 |
+
(https://docs.dask.org/en/stable/custom-collections.html). This is a stand-in for
|
| 344 |
+
dask array, dask dataframe, and for any wrapper around them (e.g. xarray or pint).
|
| 345 |
+
"""
|
| 346 |
+
|
| 347 |
+
def __init__(self, array):
|
| 348 |
+
self.array = array
|
| 349 |
+
|
| 350 |
+
def __array_ufunc__(self, ufunc, method, *args, **kwargs):
|
| 351 |
+
if method != "__call__":
|
| 352 |
+
return NotImplemented
|
| 353 |
+
|
| 354 |
+
# Simulate sending the ufunc over the network and applying it on a remote worker
|
| 355 |
+
ufunc = pickle.loads(pickle.dumps(ufunc))
|
| 356 |
+
args = [x.array if isinstance(x, FakeDaskArray) else x for x in args]
|
| 357 |
+
return FakeDaskArray(ufunc(*args, **kwargs))
|
| 358 |
+
|
| 359 |
+
def _dask_method(self, *args, **kwargs):
|
| 360 |
+
raise AssertionError("called potentially expensive method")
|
| 361 |
+
|
| 362 |
+
__array__ = _dask_method
|
| 363 |
+
__dask_graph__ = _dask_method
|
| 364 |
+
__dask_keys__ = _dask_method
|
| 365 |
+
__dask_optimize__ = _dask_method
|
| 366 |
+
__dask_postcompute__ = _dask_method
|
| 367 |
+
__dask_postpersist__ = _dask_method
|
| 368 |
+
__dask_scheduler__ = _dask_method
|
| 369 |
+
__dask_tokenize__ = _dask_method
|
| 370 |
+
compute = _dask_method
|
| 371 |
+
persist = _dask_method
|
| 372 |
+
visualize = _dask_method
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
class TestNEP13WithoutSignature(TestCase):
|
| 376 |
+
|
| 377 |
+
def test_all(self):
|
| 378 |
+
|
| 379 |
+
# note: no signatures specified
|
| 380 |
+
@vectorize(nopython=True)
|
| 381 |
+
def new_ufunc(hundreds, tens, ones):
|
| 382 |
+
return 100*hundreds + 10*tens + ones
|
| 383 |
+
|
| 384 |
+
# give it integers
|
| 385 |
+
a = np.array([1, 2, 3], dtype=np.int64)
|
| 386 |
+
b = np.array([4, 5, 6], dtype=np.int64)
|
| 387 |
+
c = np.array([7, 8, 9], dtype=np.int64)
|
| 388 |
+
|
| 389 |
+
all_np = new_ufunc(a, b, c)
|
| 390 |
+
self.assertIsInstance(all_np, np.ndarray)
|
| 391 |
+
self.assertEqual(all_np.tolist(), [147, 258, 369])
|
| 392 |
+
|
| 393 |
+
nep13_1 = new_ufunc(NEP13Array(a), b, c)
|
| 394 |
+
self.assertIsInstance(nep13_1, NEP13Array)
|
| 395 |
+
self.assertEqual(nep13_1.tolist(), [147, 258, 369])
|
| 396 |
+
|
| 397 |
+
nep13_2 = new_ufunc(a, NEP13Array(b), c)
|
| 398 |
+
self.assertIsInstance(nep13_2, NEP13Array)
|
| 399 |
+
self.assertEqual(nep13_2.tolist(), [147, 258, 369])
|
| 400 |
+
|
| 401 |
+
nep13_3 = new_ufunc(a, b, NEP13Array(c))
|
| 402 |
+
self.assertIsInstance(nep13_3, NEP13Array)
|
| 403 |
+
self.assertEqual(nep13_3.tolist(), [147, 258, 369])
|
| 404 |
+
|
| 405 |
+
# give it floats
|
| 406 |
+
a = np.array([1.1, 2.2, 3.3], dtype=np.float64)
|
| 407 |
+
b = np.array([4.4, 5.5, 6.6], dtype=np.float64)
|
| 408 |
+
c = np.array([7.7, 8.8, 9.9], dtype=np.float64)
|
| 409 |
+
|
| 410 |
+
all_np = new_ufunc(a, b, c)
|
| 411 |
+
self.assertIsInstance(all_np, np.ndarray)
|
| 412 |
+
self.assertEqual(all_np.tolist(), [161.7, 283.8, 405.9])
|
| 413 |
+
|
| 414 |
+
nep13_1 = new_ufunc(NEP13Array(a), b, c)
|
| 415 |
+
self.assertIsInstance(nep13_1, NEP13Array)
|
| 416 |
+
self.assertEqual(nep13_1.tolist(), [161.7, 283.8, 405.9])
|
| 417 |
+
|
| 418 |
+
nep13_2 = new_ufunc(a, NEP13Array(b), c)
|
| 419 |
+
self.assertIsInstance(nep13_2, NEP13Array)
|
| 420 |
+
self.assertEqual(nep13_2.tolist(), [161.7, 283.8, 405.9])
|
| 421 |
+
|
| 422 |
+
nep13_3 = new_ufunc(a, b, NEP13Array(c))
|
| 423 |
+
self.assertIsInstance(nep13_3, NEP13Array)
|
| 424 |
+
self.assertEqual(nep13_3.tolist(), [161.7, 283.8, 405.9])
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
class TestDask(unittest.TestCase):
|
| 428 |
+
"""Test that numba ufuncs are compatible with dask collections and wrappers around
|
| 429 |
+
dask (e.g. xarray or pint) and that they can be serialized, sent over the network,
|
| 430 |
+
deserialized on a different host and applied remotely.
|
| 431 |
+
"""
|
| 432 |
+
|
| 433 |
+
def test_dask_array(self):
|
| 434 |
+
a = FakeDaskArray(np.arange(4, dtype=np.float64))
|
| 435 |
+
expect = np.arange(4, dtype=np.float64) * 2
|
| 436 |
+
|
| 437 |
+
@vectorize(["f8(f8)"])
|
| 438 |
+
def double_static_vectorize(x):
|
| 439 |
+
return x * 2
|
| 440 |
+
|
| 441 |
+
@vectorize()
|
| 442 |
+
def double_dynamic_vectorize(x):
|
| 443 |
+
return x * 2
|
| 444 |
+
|
| 445 |
+
@guvectorize(["f8,f8[:]"], "()->()")
|
| 446 |
+
def double_guvectorize(x, out):
|
| 447 |
+
out[:] = x * 2
|
| 448 |
+
|
| 449 |
+
for func in (
|
| 450 |
+
double_static_vectorize,
|
| 451 |
+
double_dynamic_vectorize,
|
| 452 |
+
double_guvectorize,
|
| 453 |
+
):
|
| 454 |
+
with self.subTest(func):
|
| 455 |
+
b = func(a)
|
| 456 |
+
assert isinstance(b, FakeDaskArray)
|
| 457 |
+
assert_array_equal(b.array, expect)
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
class TestVectorizeDecorJitDisabled(TestVectorizeDecor):
|
| 461 |
+
|
| 462 |
+
def setUp(self):
|
| 463 |
+
self.old_disable_jit = config.DISABLE_JIT
|
| 464 |
+
config.DISABLE_JIT = False
|
| 465 |
+
|
| 466 |
+
def tearDown(self):
|
| 467 |
+
config.DISABLE_JIT = self.old_disable_jit
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
if __name__ == '__main__':
|
| 471 |
+
unittest.main()
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_update_inplace.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
from __future__ import print_function, absolute_import, division
|
| 3 |
+
|
| 4 |
+
import unittest
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
from numba import guvectorize
|
| 8 |
+
from numba.tests.support import TestCase
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def py_replace_2nd(x_t, y_1):
|
| 12 |
+
for t in range(0, x_t.shape[0], 2):
|
| 13 |
+
x_t[t] = y_1[0]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def py_update_3(x0_t, x1_t, x2_t, y_1):
|
| 17 |
+
for t in range(0, x0_t.shape[0]):
|
| 18 |
+
x0_t[t] = y_1[0]
|
| 19 |
+
x1_t[t] = 2 * y_1[0]
|
| 20 |
+
x2_t[t] = 3 * y_1[0]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class TestUpdateInplace(TestCase):
|
| 24 |
+
|
| 25 |
+
def _run_test_for_gufunc(self, gufunc, py_func, expect_f4_to_pass=True,
|
| 26 |
+
z=2):
|
| 27 |
+
for dtype, expect_to_pass in [('f8', True), ('f4', expect_f4_to_pass)]:
|
| 28 |
+
inputs = [np.zeros(10, dtype) for _ in range(gufunc.nin - 1)]
|
| 29 |
+
ex_inputs = [x_t.copy() for x_t in inputs]
|
| 30 |
+
|
| 31 |
+
gufunc(*inputs, z)
|
| 32 |
+
py_func(*ex_inputs, np.array([z]))
|
| 33 |
+
|
| 34 |
+
for i, (x_t, ex_x_t) in enumerate(zip(inputs, ex_inputs)):
|
| 35 |
+
if expect_to_pass:
|
| 36 |
+
np.testing.assert_equal(x_t, ex_x_t, err_msg='input %s' % i)
|
| 37 |
+
else:
|
| 38 |
+
self.assertFalse((x_t == ex_x_t).all(), msg='input %s' % i)
|
| 39 |
+
|
| 40 |
+
def test_update_inplace(self):
|
| 41 |
+
# test without writable_args
|
| 42 |
+
gufunc = guvectorize(['void(f8[:], f8[:])'], '(t),()',
|
| 43 |
+
nopython=True)(py_replace_2nd)
|
| 44 |
+
self._run_test_for_gufunc(gufunc, py_replace_2nd,
|
| 45 |
+
expect_f4_to_pass=False)
|
| 46 |
+
|
| 47 |
+
# test with writable_args
|
| 48 |
+
gufunc = guvectorize(['void(f8[:], f8[:])'], '(t),()',
|
| 49 |
+
nopython=True, writable_args=(0,))(py_replace_2nd)
|
| 50 |
+
self._run_test_for_gufunc(gufunc, py_replace_2nd)
|
| 51 |
+
|
| 52 |
+
# test with writable_args as strings
|
| 53 |
+
gufunc = guvectorize(['void(f8[:], f8[:])'], '(t),()', nopython=True,
|
| 54 |
+
writable_args=('x_t',))(py_replace_2nd)
|
| 55 |
+
self._run_test_for_gufunc(gufunc, py_replace_2nd)
|
| 56 |
+
|
| 57 |
+
def test_update_inplace_with_cache(self):
|
| 58 |
+
# test with writable_args
|
| 59 |
+
gufunc = guvectorize(['void(f8[:], f8[:])'], '(t),()',
|
| 60 |
+
nopython=True, writable_args=(0,),
|
| 61 |
+
cache=True)(py_replace_2nd)
|
| 62 |
+
# 2nd time it is loaded from cache
|
| 63 |
+
gufunc = guvectorize(['void(f8[:], f8[:])'], '(t),()',
|
| 64 |
+
nopython=True, writable_args=(0,),
|
| 65 |
+
cache=True)(py_replace_2nd)
|
| 66 |
+
self._run_test_for_gufunc(gufunc, py_replace_2nd)
|
| 67 |
+
|
| 68 |
+
def test_update_inplace_parallel(self):
|
| 69 |
+
# test with writable_args
|
| 70 |
+
gufunc = guvectorize(['void(f8[:], f8[:])'], '(t),()',
|
| 71 |
+
nopython=True, writable_args=(0,),
|
| 72 |
+
target='parallel')(py_replace_2nd)
|
| 73 |
+
self._run_test_for_gufunc(gufunc, py_replace_2nd)
|
| 74 |
+
|
| 75 |
+
def test_update_inplace_3(self):
|
| 76 |
+
# test without writable_args
|
| 77 |
+
gufunc = guvectorize(['void(f8[:], f8[:], f8[:], f8[:])'],
|
| 78 |
+
'(t),(t),(t),()',
|
| 79 |
+
nopython=True)(py_update_3)
|
| 80 |
+
self._run_test_for_gufunc(gufunc, py_update_3, expect_f4_to_pass=False)
|
| 81 |
+
|
| 82 |
+
# test with writable_args
|
| 83 |
+
gufunc = guvectorize(['void(f8[:], f8[:], f8[:], f8[:])'],
|
| 84 |
+
'(t),(t),(t),()', nopython=True,
|
| 85 |
+
writable_args=(0, 1, 2))(py_update_3)
|
| 86 |
+
self._run_test_for_gufunc(gufunc, py_update_3)
|
| 87 |
+
|
| 88 |
+
# test with writable_args as mix of strings and ints
|
| 89 |
+
gufunc = guvectorize(['void(f8[:], f8[:], f8[:], f8[:])'],
|
| 90 |
+
'(t),(t),(t),()', nopython=True,
|
| 91 |
+
writable_args=('x0_t', 'x1_t', 2))(py_update_3)
|
| 92 |
+
self._run_test_for_gufunc(gufunc, py_update_3)
|
| 93 |
+
|
| 94 |
+
def test_exceptions(self):
|
| 95 |
+
# check that len(writable_args) <= nin
|
| 96 |
+
with self.assertRaises(ValueError):
|
| 97 |
+
guvectorize(['void(f8[:], f8[:])'], '(t),()', nopython=True,
|
| 98 |
+
writable_args=(0, 1, 2, 5))(py_replace_2nd)
|
| 99 |
+
|
| 100 |
+
# check that all values in writable_args are between 0 and nin
|
| 101 |
+
with self.assertRaises(ValueError):
|
| 102 |
+
guvectorize(['void(f8[:], f8[:])'], '(t),()',
|
| 103 |
+
nopython=True, writable_args=(5,))(py_replace_2nd)
|
| 104 |
+
|
| 105 |
+
with self.assertRaises(ValueError):
|
| 106 |
+
guvectorize(['void(f8[:], f8[:])'], '(t),()',
|
| 107 |
+
nopython=True, writable_args=(-1,))(py_replace_2nd)
|
| 108 |
+
|
| 109 |
+
# check that exception is raised when passing non-existing argument name
|
| 110 |
+
with self.assertRaises(RuntimeError):
|
| 111 |
+
guvectorize(['void(f8[:], f8[:])'], '(t),()',
|
| 112 |
+
nopython=True, writable_args=('z_t',))(py_replace_2nd)
|
| 113 |
+
|
| 114 |
+
# writable_args are not supported for target='cuda'
|
| 115 |
+
with self.assertRaises(TypeError):
|
| 116 |
+
guvectorize(['void(f8[:], f8[:])'], '(t),()',
|
| 117 |
+
nopython=True, writable_args=(0,),
|
| 118 |
+
target='cuda')(py_replace_2nd)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
if __name__ == '__main__':
|
| 122 |
+
unittest.main()
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_vectorize_decor.py
ADDED
|
@@ -0,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support import tag, CheckWarningsMixin
|
| 7 |
+
import unittest
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
pi = math.pi
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def sinc(x):
|
| 14 |
+
if x == 0.0:
|
| 15 |
+
return 1.0
|
| 16 |
+
else:
|
| 17 |
+
return math.sin(x * pi) / (pi * x)
|
| 18 |
+
|
| 19 |
+
def scaled_sinc(x, scale):
|
| 20 |
+
if x == 0.0:
|
| 21 |
+
return scale
|
| 22 |
+
else:
|
| 23 |
+
return scale * (math.sin(x * pi) / (pi * x))
|
| 24 |
+
|
| 25 |
+
def vector_add(a, b):
|
| 26 |
+
return a + b
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class BaseVectorizeDecor(object):
|
| 30 |
+
target = None
|
| 31 |
+
wrapper = None
|
| 32 |
+
funcs = {
|
| 33 |
+
'func1': sinc,
|
| 34 |
+
'func2': scaled_sinc,
|
| 35 |
+
'func3': vector_add,
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
@classmethod
|
| 39 |
+
def _run_and_compare(cls, func, sig, A, *args, **kwargs):
|
| 40 |
+
if cls.wrapper is not None:
|
| 41 |
+
func = cls.wrapper(func)
|
| 42 |
+
numba_func = vectorize(sig, target=cls.target)(func)
|
| 43 |
+
numpy_func = np.vectorize(func)
|
| 44 |
+
result = numba_func(A, *args)
|
| 45 |
+
gold = numpy_func(A, *args)
|
| 46 |
+
np.testing.assert_allclose(result, gold, **kwargs)
|
| 47 |
+
|
| 48 |
+
def test_1(self):
|
| 49 |
+
sig = ['float64(float64)', 'float32(float32)']
|
| 50 |
+
func = self.funcs['func1']
|
| 51 |
+
A = np.arange(100, dtype=np.float64)
|
| 52 |
+
self._run_and_compare(func, sig, A)
|
| 53 |
+
|
| 54 |
+
def test_2(self):
|
| 55 |
+
sig = [float64(float64), float32(float32)]
|
| 56 |
+
func = self.funcs['func1']
|
| 57 |
+
A = np.arange(100, dtype=np.float64)
|
| 58 |
+
self._run_and_compare(func, sig, A)
|
| 59 |
+
|
| 60 |
+
def test_3(self):
|
| 61 |
+
sig = ['float64(float64, uint32)']
|
| 62 |
+
func = self.funcs['func2']
|
| 63 |
+
A = np.arange(100, dtype=np.float64)
|
| 64 |
+
scale = np.uint32(3)
|
| 65 |
+
self._run_and_compare(func, sig, A, scale, atol=1e-8)
|
| 66 |
+
|
| 67 |
+
def test_4(self):
|
| 68 |
+
sig = [
|
| 69 |
+
int32(int32, int32),
|
| 70 |
+
uint32(uint32, uint32),
|
| 71 |
+
float32(float32, float32),
|
| 72 |
+
float64(float64, float64),
|
| 73 |
+
]
|
| 74 |
+
func = self.funcs['func3']
|
| 75 |
+
A = np.arange(100, dtype=np.float64)
|
| 76 |
+
self._run_and_compare(func, sig, A, A)
|
| 77 |
+
A = A.astype(np.float32)
|
| 78 |
+
self._run_and_compare(func, sig, A, A)
|
| 79 |
+
A = A.astype(np.int32)
|
| 80 |
+
self._run_and_compare(func, sig, A, A)
|
| 81 |
+
A = A.astype(np.uint32)
|
| 82 |
+
self._run_and_compare(func, sig, A, A)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class TestCPUVectorizeDecor(unittest.TestCase, BaseVectorizeDecor):
|
| 86 |
+
target = 'cpu'
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class TestParallelVectorizeDecor(unittest.TestCase, BaseVectorizeDecor):
|
| 90 |
+
_numba_parallel_test_ = False
|
| 91 |
+
target = 'parallel'
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class TestCPUVectorizeJitted(unittest.TestCase, BaseVectorizeDecor):
|
| 95 |
+
target = 'cpu'
|
| 96 |
+
wrapper = jit(nopython=True)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class BaseVectorizeNopythonArg(unittest.TestCase, CheckWarningsMixin):
|
| 100 |
+
"""
|
| 101 |
+
Test passing the nopython argument to the vectorize decorator.
|
| 102 |
+
"""
|
| 103 |
+
def _test_target_nopython(self, target, warnings, with_sig=True):
|
| 104 |
+
a = np.array([2.0], dtype=np.float32)
|
| 105 |
+
b = np.array([3.0], dtype=np.float32)
|
| 106 |
+
sig = [float32(float32, float32)]
|
| 107 |
+
args = with_sig and [sig] or []
|
| 108 |
+
with self.check_warnings(warnings):
|
| 109 |
+
f = vectorize(*args, target=target, nopython=True)(vector_add)
|
| 110 |
+
f(a, b)
|
| 111 |
+
|
| 112 |
+
class TestVectorizeNopythonArg(BaseVectorizeNopythonArg):
|
| 113 |
+
def test_target_cpu_nopython(self):
|
| 114 |
+
self._test_target_nopython('cpu', [])
|
| 115 |
+
|
| 116 |
+
def test_target_cpu_nopython_no_sig(self):
|
| 117 |
+
self._test_target_nopython('cpu', [], False)
|
| 118 |
+
|
| 119 |
+
def test_target_parallel_nopython(self):
|
| 120 |
+
self._test_target_nopython('parallel', [])
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
class BaseVectorizeUnrecognizedArg(unittest.TestCase, CheckWarningsMixin):
|
| 124 |
+
"""
|
| 125 |
+
Test passing an unrecognized argument to the vectorize decorator.
|
| 126 |
+
"""
|
| 127 |
+
def _test_target_unrecognized_arg(self, target, with_sig=True):
|
| 128 |
+
a = np.array([2.0], dtype=np.float32)
|
| 129 |
+
b = np.array([3.0], dtype=np.float32)
|
| 130 |
+
sig = [float32(float32, float32)]
|
| 131 |
+
args = with_sig and [sig] or []
|
| 132 |
+
with self.assertRaises(KeyError) as raises:
|
| 133 |
+
f = vectorize(*args, target=target, nonexistent=2)(vector_add)
|
| 134 |
+
f(a, b)
|
| 135 |
+
self.assertIn("Unrecognized options", str(raises.exception))
|
| 136 |
+
|
| 137 |
+
class TestVectorizeUnrecognizedArg(BaseVectorizeUnrecognizedArg):
|
| 138 |
+
def test_target_cpu_unrecognized_arg(self):
|
| 139 |
+
self._test_target_unrecognized_arg('cpu')
|
| 140 |
+
|
| 141 |
+
def test_target_cpu_unrecognized_arg_no_sig(self):
|
| 142 |
+
self._test_target_unrecognized_arg('cpu', False)
|
| 143 |
+
|
| 144 |
+
def test_target_parallel_unrecognized_arg(self):
|
| 145 |
+
self._test_target_unrecognized_arg('parallel')
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
if __name__ == '__main__':
|
| 151 |
+
unittest.main()
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/ufuncbuilding_usecases.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from numba import vectorize
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def add(a, b):
|
| 5 |
+
"""An addition"""
|
| 6 |
+
return a + b
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def equals(a, b):
|
| 10 |
+
return a == b
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def mul(a, b):
|
| 14 |
+
"""A multiplication"""
|
| 15 |
+
return a * b
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def guadd(a, b, c):
|
| 19 |
+
"""A generalized addition"""
|
| 20 |
+
x, y = c.shape
|
| 21 |
+
for i in range(x):
|
| 22 |
+
for j in range(y):
|
| 23 |
+
c[i, j] = a[i, j] + b[i, j]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@vectorize(nopython=True)
|
| 27 |
+
def inner(a, b):
|
| 28 |
+
return a + b
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@vectorize(["int64(int64, int64)"], nopython=True)
|
| 32 |
+
def inner_explicit(a, b):
|
| 33 |
+
return a + b
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def outer(a, b):
|
| 37 |
+
return inner(a, b)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def outer_explicit(a, b):
|
| 41 |
+
return inner_explicit(a, b)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class Dummy:
|
| 45 |
+
pass
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def guadd_obj(a, b, c):
|
| 49 |
+
Dummy() # to force object mode
|
| 50 |
+
x, y = c.shape
|
| 51 |
+
for i in range(x):
|
| 52 |
+
for j in range(y):
|
| 53 |
+
c[i, j] = a[i, j] + b[i, j]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def guadd_scalar_obj(a, b, c):
|
| 57 |
+
Dummy() # to force object mode
|
| 58 |
+
x, y = c.shape
|
| 59 |
+
for i in range(x):
|
| 60 |
+
for j in range(y):
|
| 61 |
+
c[i, j] = a[i, j] + b
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class MyException(Exception):
|
| 65 |
+
pass
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def guerror(a, b, c):
|
| 69 |
+
raise MyException
|