diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80cc47dc6722886128c273b11bf914e0a60f8a44 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/__pycache__/__main__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/__pycache__/__main__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e488b0c0c0c812a102a46d9fac95e94b1d96990 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/__pycache__/__main__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/__pycache__/_version.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/__pycache__/_version.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38675dea665e23a5f3906170fbd11a16dbbdd36a Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/__pycache__/_version.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/__pycache__/extending.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/__pycache__/extending.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..430eba891755e591d62c7fd6127770d8788aadb3 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/__pycache__/extending.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/__pycache__/runtests.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/__pycache__/runtests.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0ae85e8160fa2f102640ac483c70e3ff0fd9f05 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/__pycache__/runtests.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4eb89a92fcb80765a6f54b11bebde867ced37aa4 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__init__.py @@ -0,0 +1,61 @@ +import os +import sys +import functools +import unittest +import traceback +from fnmatch import fnmatch +from os.path import join, isfile, relpath, normpath, splitext + +from .main import NumbaTestProgram, SerialSuite, make_tag_decorator +from numba.core import config + + +def load_testsuite(loader, dir): + """Find tests in 'dir'.""" + try: + suite = unittest.TestSuite() + files = [] + for f in os.listdir(dir): + path = join(dir, f) + if isfile(path) and fnmatch(f, 'test_*.py'): + files.append(f) + elif isfile(join(path, '__init__.py')): + suite.addTests(loader.discover(path)) + for f in files: + # turn 'f' into a filename relative to the toplevel dir... + f = relpath(join(dir, f), loader._top_level_dir) + # ...and translate it to a module name. + f = splitext(normpath(f.replace(os.path.sep, '.')))[0] + suite.addTests(loader.loadTestsFromName(f)) + return suite + except Exception: + traceback.print_exc(file=sys.stderr) + sys.exit(-1) + + +def run_tests(argv=None, defaultTest=None, topleveldir=None, + xmloutput=None, verbosity=1, nomultiproc=False): + """ + args + ---- + - xmloutput [str or None] + Path of XML output directory (optional) + - verbosity [int] + Verbosity level of tests output + + Returns the TestResult object after running the test *suite*. + """ + + if xmloutput is not None: + import xmlrunner + runner = xmlrunner.XMLTestRunner(output=xmloutput) + else: + runner = None + prog = NumbaTestProgram(argv=argv, + module=None, + defaultTest=defaultTest, + topleveldir=topleveldir, + testRunner=runner, exit=False, + verbosity=verbosity, + nomultiproc=nomultiproc) + return prog.result diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__main__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..964b0ce910f027dfb48790b49e2360dcd806ad7c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__main__.py @@ -0,0 +1,4 @@ +import sys +from numba.testing import run_tests + +sys.exit(0 if run_tests(sys.argv).wasSuccessful() else 1) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/__init__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63c6dd0ba91742a55c1ae45ece4369980126cbc1 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/__init__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/__main__.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/__main__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c585987f976a1abcea6decf19c872669c6af69e5 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/__main__.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/_runtests.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/_runtests.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15e4f63cc2abfff4668e44dcffab77a947d1b2c1 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/_runtests.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/loader.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/loader.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c69114baf26d093883b15963a78221e126bdaae5 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/loader.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/main.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/main.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e44e1d4d090cb580587d6b4f0b141cbf1e660ad2 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/main.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/notebook.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/notebook.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7e3bb062544fb320d161f8c47ffac9adfaf4d78 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/__pycache__/notebook.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/_runtests.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/_runtests.py new file mode 100644 index 0000000000000000000000000000000000000000..7df2bd7435897ec837b188eb857302d47ea6942b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/_runtests.py @@ -0,0 +1,114 @@ +import json +import re +import logging + + +def _main(argv, **kwds): + from numba.testing import run_tests + # This helper function assumes the first element of argv + # is the name of the calling program. + # The 'main' API function is invoked in-process, and thus + # will synthesize that name. + + if '--log' in argv: + logging.basicConfig(level=logging.DEBUG) + argv.remove('--log') + + if '--failed-first' in argv: + # Failed first + argv.remove('--failed-first') + return _FailedFirstRunner().main(argv, kwds) + elif '--last-failed' in argv: + argv.remove('--last-failed') + return _FailedFirstRunner(last_failed=True).main(argv, kwds) + else: + return run_tests(argv, defaultTest='numba.tests', + **kwds).wasSuccessful() + + +def main(*argv, **kwds): + """keyword arguments are accepted for backward compatibility only. + See `numba.testing.run_tests()` documentation for details.""" + return _main(['
'] + list(argv), **kwds) + + +class _FailedFirstRunner(object): + """ + Test Runner to handle the failed-first (--failed-first) option. + """ + cache_filename = '.runtests_lastfailed' + + def __init__(self, last_failed=False): + self.last_failed = last_failed + + def main(self, argv, kwds): + from numba.testing import run_tests + prog = argv[0] + argv = argv[1:] + flags = [a for a in argv if a.startswith('-')] + + all_tests, failed_tests = self.find_last_failed(argv) + # Prepare tests to run + if failed_tests: + ft = "There were {} previously failed tests" + print(ft.format(len(failed_tests))) + remaing_tests = [t for t in all_tests + if t not in failed_tests] + if self.last_failed: + tests = list(failed_tests) + else: + tests = failed_tests + remaing_tests + else: + if self.last_failed: + tests = [] + else: + tests = list(all_tests) + + if not tests: + print("No tests to run") + return True + # Run the testsuite + print("Running {} tests".format(len(tests))) + print('Flags', flags) + result = run_tests([prog] + flags + tests, **kwds) + # Update failed tests records only if we have run the all the tests + # last failed. + if len(tests) == result.testsRun: + self.save_failed_tests(result, all_tests) + return result.wasSuccessful() + + def save_failed_tests(self, result, all_tests): + print("Saving failed tests to {}".format(self.cache_filename)) + cache = [] + # Find failed tests + failed = set() + for case in result.errors + result.failures: + failed.add(case[0].id()) + # Build cache + for t in all_tests: + if t in failed: + cache.append(t) + # Write cache + with open(self.cache_filename, 'w') as fout: + json.dump(cache, fout) + + def find_last_failed(self, argv): + from numba.tests.support import captured_output + + # Find all tests + listargv = ['-l'] + [a for a in argv if not a.startswith('-')] + with captured_output("stdout") as stream: + main(*listargv) + + pat = re.compile(r"^(\w+\.)+\w+$") + lines = stream.getvalue().splitlines() + all_tests = [x for x in lines if pat.match(x) is not None] + + try: + fobj = open(self.cache_filename) + except OSError: + failed_tests = [] + else: + with fobj as fin: + failed_tests = json.load(fin) + return all_tests, failed_tests diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/loader.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/loader.py new file mode 100644 index 0000000000000000000000000000000000000000..66ba417d62b2bf7e7789c8a54eba972c8d7b7624 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/loader.py @@ -0,0 +1,26 @@ +from unittest import loader, case +from os.path import isdir, isfile, join, dirname, basename + + +class TestLoader(loader.TestLoader): + + def __init__(self, topleveldir=None): + super(TestLoader, self).__init__() + self._top_level_dir = topleveldir or dirname(dirname(dirname(__file__))) + + def _find_tests(self, start_dir, pattern, namespace=False): + # Upstream doesn't look for 'load_tests' in start_dir. + + if isdir(start_dir) and not namespace and isfile(join(start_dir, '__init__.py')): + name = self._get_name_from_path(start_dir) + package = self._get_module_from_name(name) + load_tests = getattr(package, 'load_tests', None) + tests = self.loadTestsFromModule(package) + if load_tests is not None: + try: + yield load_tests(self, tests, pattern) + except Exception as e: + yield loader._make_failed_load_tests(package.__name__, e, self.suiteClass) + else: + for t in super(TestLoader, self)._find_tests(start_dir, pattern): + yield t diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/main.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/main.py new file mode 100644 index 0000000000000000000000000000000000000000..17b357bdb24ecb6b5062dea9f3f31378a6afb587 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/main.py @@ -0,0 +1,871 @@ +import collections +import contextlib +import cProfile +import inspect +import gc +import multiprocessing +import os +import random +import sys +import time +import unittest +import warnings +import zlib +import traceback + +from functools import lru_cache +from io import StringIO +from unittest import result, runner, signals, suite, loader, case + +from .loader import TestLoader +from numba.core import config +from numba.misc import memoryutils + +try: + from multiprocessing import TimeoutError +except ImportError: + from Queue import Empty as TimeoutError + + +def make_tag_decorator(known_tags): + """ + Create a decorator allowing tests to be tagged with the *known_tags*. + """ + + def tag(*tags): + """ + Tag a test method with the given tags. + Can be used in conjunction with the --tags command-line argument + for runtests.py. + """ + for t in tags: + if t not in known_tags: + raise ValueError("unknown tag: %r" % (t,)) + + def decorate(func): + if (not callable(func) or isinstance(func, type) + or not func.__name__.startswith('test_')): + raise TypeError("@tag(...) should be used on test methods") + try: + s = func.tags + except AttributeError: + s = func.tags = set() + s.update(tags) + return func + return decorate + + return tag + + +# Chances are the next queried class is the same as the previous, locally 128 +# entries seems to be fastest. +# Current number of test classes can be found with: +# $ ./runtests.py -l|sed -e 's/\(.*\)\..*/\1/'|grep ^numba|sort|uniq|wc -l +# as of writing it's 658. +@lru_cache(maxsize=128) +def _get_mtime(cls): + """ + Gets the mtime of the file in which a test class is defined. + """ + return str(os.path.getmtime(inspect.getfile(cls))) + + +def cuda_sensitive_mtime(x): + """ + Return a key for sorting tests bases on mtime and test name. For CUDA + tests, interleaving tests from different classes is dangerous as the CUDA + context might get reset unexpectedly between methods of a class, so for + CUDA tests the key prioritises the test module and class ahead of the + mtime. + """ + cls = x.__class__ + key = _get_mtime(cls) + str(x) + + from numba.cuda.testing import CUDATestCase + if CUDATestCase in cls.mro(): + key = "%s.%s %s" % (str(cls.__module__), str(cls.__name__), key) + + return key + + +def parse_slice(useslice): + """Parses the argument string "useslice" as a shard index and number and + returns a function that filters on those arguments. i.e. input + useslice="1:3" leads to output something like `lambda x: zlib.crc32(x) % 3 + == 1`. + """ + if callable(useslice): + return useslice + if not useslice: + return lambda x: True + try: + (index, count) = useslice.split(":") + index = int(index) + count = int(count) + except Exception: + msg = ( + "Expected arguments shard index and count to follow " + "option `-j i:t`, where i is the shard number and t " + "is the total number of shards, found '%s'" % useslice) + raise ValueError(msg) + if count == 0: + return lambda x: True + elif count < 0 or index < 0 or index >= count: + raise ValueError("Sharding out of range") + else: + def decide(test): + func = getattr(test, test._testMethodName) + if "always_test" in getattr(func, 'tags', {}): + return True + return abs(zlib.crc32(test.id().encode('utf-8'))) % count == index + return decide + + +class TestLister(object): + """Simply list available tests rather than running them.""" + def __init__(self, useslice): + self.useslice = parse_slice(useslice) + + def run(self, test): + result = runner.TextTestResult(sys.stderr, descriptions=True, + verbosity=1) + self._test_list = _flatten_suite(test) + masked_list = list(filter(self.useslice, self._test_list)) + self._test_list.sort(key=cuda_sensitive_mtime) + for t in masked_list: + print(t.id()) + print('%d tests found. %s selected' % (len(self._test_list), + len(masked_list))) + return result + + +class SerialSuite(unittest.TestSuite): + """A simple marker to make sure tests in this suite are run serially. + + Note: As the suite is going through internals of unittest, + it may get unpacked and stuffed into a plain TestSuite. + We need to set an attribute on the TestCase objects to + remember they should not be run in parallel. + """ + + def __init__(self, tests=()): + super(SerialSuite, self).__init__(tests) + self.resource_infos = [] + + def addTest(self, test): + if not isinstance(test, unittest.TestCase): + # It's a sub-suite, recurse + for t in test: + self.addTest(t) + else: + # It's a test case, mark it serial + test._numba_parallel_test_ = False + super(SerialSuite, self).addTest(test) + + def run(self, result): + # Run each test with memory tracking + for test in self: + if result.shouldStop: + break + memtrack = memoryutils.MemoryTracker(test.id()) + with memtrack.monitor(): + test(result) + self.resource_infos.append(memtrack.get_summary()) + return result + + +class BasicTestRunner(runner.TextTestRunner): + def __init__(self, useslice, **kwargs): + runner.TextTestRunner.__init__(self, **kwargs) + self.useslice = parse_slice(useslice) + + def run(self, test): + run = list(filter(self.useslice, _flatten_suite(test))) + run.sort(key=cuda_sensitive_mtime) + wrapped = unittest.TestSuite(run) + return super(BasicTestRunner, self).run(wrapped) + + +# "unittest.main" is really the TestProgram class! +# (defined in a module named itself "unittest.main"...) + +class NumbaTestProgram(unittest.main): + """ + A TestProgram subclass adding the following options: + * a -R option to enable reference leak detection + * a --profile option to enable profiling of the test run + * a -m option for parallel execution + * a -l option to (only) list tests + + Currently the options are only added in 3.4+. + """ + + refleak = False + profile = False + multiprocess = False + useslice = None + list = False + tags = None + exclude_tags = None + random_select = None + random_seed = 42 + + def __init__(self, *args, **kwargs): + topleveldir = kwargs.pop('topleveldir', None) + kwargs['testLoader'] = TestLoader(topleveldir) + + # HACK to force unittest not to change warning display options + # (so that NumbaWarnings don't appear all over the place) + sys.warnoptions.append(':x') + self.nomultiproc = kwargs.pop('nomultiproc', False) + super(NumbaTestProgram, self).__init__(*args, **kwargs) + + def _getParentArgParser(self): + # NOTE: this hook only exists on Python 3.4+. The options won't be + # added in earlier versions (which use optparse - 3.3 - or getopt() + # - 2.x). + parser = super(NumbaTestProgram, self)._getParentArgParser() + if self.testRunner is None: + parser.add_argument('-R', '--refleak', dest='refleak', + action='store_true', + help='Detect reference / memory leaks') + parser.add_argument('-m', '--multiprocess', dest='multiprocess', + nargs='?', + type=int, + const=multiprocessing.cpu_count(), + help='Parallelize tests') + parser.add_argument('-l', '--list', dest='list', + action='store_true', + help='List tests without running them') + parser.add_argument('--tags', dest='tags', type=str, + help='Comma-separated list of tags to select ' + 'a subset of the test suite') + parser.add_argument('--exclude-tags', dest='exclude_tags', type=str, + help='Comma-separated list of tags to de-select ' + 'a subset of the test suite') + parser.add_argument('--random', dest='random_select', type=float, + help='Random proportion of tests to select') + parser.add_argument('--profile', dest='profile', + action='store_true', + help='Profile the test run') + parser.add_argument('-j', '--slice', dest='useslice', nargs='?', + type=str, const="None", + help='Shard the test sequence') + + def git_diff_str(x): + if x != 'ancestor': + raise ValueError("invalid option for --gitdiff") + return x + + parser.add_argument('-g', '--gitdiff', dest='gitdiff', type=git_diff_str, + default=False, nargs='?', + help=('Run tests from changes made against ' + 'origin/release0.65 as identified by `git diff`. ' + 'If set to "ancestor", the diff compares ' + 'against the common ancestor.')) + return parser + + def _handle_tags(self, argv, tagstr): + found = None + for x in argv: + if tagstr in x: + if found is None: + found = x + else: + raise ValueError("argument %s supplied repeatedly" % tagstr) + + if found is not None: + posn = argv.index(found) + try: + if found == tagstr: # --tagstr + tag_args = argv[posn + 1].strip() + argv.remove(tag_args) + else: # --tagstr= + if '=' in found: + tag_args = found.split('=')[1].strip() + else: + raise AssertionError('unreachable') + except IndexError: + # at end of arg list, raise + msg = "%s requires at least one tag to be specified" + raise ValueError(msg % tagstr) + # see if next arg is "end options" or some other flag + if tag_args.startswith('-'): + raise ValueError("tag starts with '-', probably a syntax error") + # see if tag is something like "=" which is likely a syntax + # error of form `--tags =`, note the space prior to `=`. + if '=' in tag_args: + msg = "%s argument contains '=', probably a syntax error" + raise ValueError(msg % tagstr) + attr = tagstr[2:].replace('-', '_') + setattr(self, attr, tag_args) + argv.remove(found) + + + def parseArgs(self, argv): + if '-l' in argv: + argv.remove('-l') + self.list = True + + super(NumbaTestProgram, self).parseArgs(argv) + + # If at this point self.test doesn't exist, it is because + # no test ID was given in argv. Use the default instead. + if not hasattr(self, 'test') or not self.test.countTestCases(): + self.testNames = (self.defaultTest,) + self.createTests() + + if self.tags: + tags = [s.strip() for s in self.tags.split(',')] + self.test = _choose_tagged_tests(self.test, tags, mode='include') + + if self.exclude_tags: + tags = [s.strip() for s in self.exclude_tags.split(',')] + self.test = _choose_tagged_tests(self.test, tags, mode='exclude') + + if self.random_select: + self.test = _choose_random_tests(self.test, self.random_select, + self.random_seed) + + if self.gitdiff is not False: + self.test = _choose_gitdiff_tests( + self.test, + use_common_ancestor=(self.gitdiff == 'ancestor'), + ) + + if self.verbosity <= 0: + # We aren't interested in informational messages / warnings when + # running with '-q'. + self.buffer = True + + def _do_discovery(self, argv, Loader=None): + # Disable unittest's implicit test discovery when parsing + # CLI arguments, as it can select other tests than Numba's + # (e.g. some test_xxx module that may happen to be directly + # reachable from sys.path) + return + + def runTests(self): + if self.refleak: + self.testRunner = RefleakTestRunner + + if not hasattr(sys, "gettotalrefcount"): + warnings.warn("detecting reference leaks requires a debug build " + "of Python, only memory leaks will be detected") + + elif self.list: + self.testRunner = TestLister(self.useslice) + + elif self.testRunner is None: + self.testRunner = BasicTestRunner(self.useslice, + verbosity=self.verbosity, + failfast=self.failfast, + buffer=self.buffer) + + if self.multiprocess and not self.nomultiproc: + if self.multiprocess < 1: + msg = ("Value specified for the number of processes to use in " + "running the suite must be > 0") + raise ValueError(msg) + self.testRunner = ParallelTestRunner(runner.TextTestRunner, + self.multiprocess, + self.useslice, + verbosity=self.verbosity, + failfast=self.failfast, + buffer=self.buffer) + + def run_tests_real(): + super(NumbaTestProgram, self).runTests() + + if self.profile: + filename = os.path.splitext( + os.path.basename(sys.modules['__main__'].__file__) + )[0] + '.prof' + p = cProfile.Profile(timer=time.perf_counter) # 3.3+ + p.enable() + try: + p.runcall(run_tests_real) + finally: + p.disable() + print("Writing test profile data into %r" % (filename,)) + p.dump_stats(filename) + else: + run_tests_real() + + +# These are tests which are generated and injected into the test suite, what +# gets injected depends on features of the test environment, e.g. TBB presence +# it's important for doing the CI "slice tests" that these are run at the end +# See notes in `_flatten_suite` for why. Simple substring matching is used to +# determine a match. +_GENERATED = ( + "numba.cuda.tests.cudapy.test_libdevice.TestLibdeviceCompilation", + "numba.tests.test_num_threads", + "numba.tests.test_parallel_backend", + "numba.tests.test_svml", + "numba.tests.test_ufuncs", +) + + +def _flatten_suite_inner(test): + """ + Workhorse for _flatten_suite + """ + tests = [] + if isinstance(test, (unittest.TestSuite, list, tuple)): + for x in test: + tests.extend(_flatten_suite_inner(x)) + else: + tests.append(test) + return tests + + +def _flatten_suite(test): + """ + Expand nested suite into list of test cases. + """ + tests = _flatten_suite_inner(test) + # Strip out generated tests and stick them at the end, this is to make sure + # that tests appear in a consistent order regardless of features available. + # This is so that a slice through the test suite e.g. (1::N) would likely be + # consistent up to the point of the generated tests, which rely on specific + # features. + generated = set() + for t in tests: + for g in _GENERATED: + if g in str(t): + generated.add(t) + normal = set(tests) - generated + def key(x): + return x.__module__, type(x).__name__, x._testMethodName + tests = sorted(normal, key=key) + tests.extend(sorted(list(generated), key=key)) + return tests + + +def _choose_gitdiff_tests(tests, *, use_common_ancestor=False): + try: + from git import Repo + except ImportError: + raise ValueError("gitpython needed for git functionality") + repo = Repo('.') + path = os.path.join('numba', 'tests') + if use_common_ancestor: + print(f"Git diff by common ancestor") + target = 'origin/release0.65...HEAD' + else: + target = 'origin/release0.65..HEAD' + gdiff_paths = repo.git.diff(target, path, name_only=True).split() + # normalise the paths as they are unix style from repo.git.diff + gdiff_paths = [os.path.normpath(x) for x in gdiff_paths] + selected = [] + gdiff_paths = [os.path.join(repo.working_dir, x) for x in gdiff_paths] + for test in _flatten_suite(tests): + assert isinstance(test, unittest.TestCase) + fname = inspect.getsourcefile(test.__class__) + if fname in gdiff_paths: + selected.append(test) + print("Git diff identified %s tests" % len(selected)) + return unittest.TestSuite(selected) + +def _choose_tagged_tests(tests, tags, mode='include'): + """ + Select tests that are tagged/not tagged with at least one of the given tags. + Set mode to 'include' to include the tests with tags, or 'exclude' to + exclude the tests with the tags. + """ + selected = [] + tags = set(tags) + for test in _flatten_suite(tests): + assert isinstance(test, unittest.TestCase) + func = getattr(test, test._testMethodName) + try: + # Look up the method's underlying function (Python 2) + func = func.im_func + except AttributeError: + pass + + found_tags = getattr(func, 'tags', None) + # only include the test if the tags *are* present + if mode == 'include': + if found_tags is not None and found_tags & tags: + selected.append(test) + elif mode == 'exclude': + # only include the test if the tags *are not* present + if found_tags is None or not (found_tags & tags): + selected.append(test) + else: + raise ValueError("Invalid 'mode' supplied: %s." % mode) + return unittest.TestSuite(selected) + + +def _choose_random_tests(tests, ratio, seed): + """ + Choose a given proportion of tests at random. + """ + rnd = random.Random() + rnd.seed(seed) + if isinstance(tests, unittest.TestSuite): + tests = _flatten_suite(tests) + tests = rnd.sample(tests, int(len(tests) * ratio)) + tests = sorted(tests, key=lambda case: case.id()) + return unittest.TestSuite(tests) + + +# The reference leak detection code is liberally taken and adapted from +# Python's own Lib/test/regrtest.py. + +def _refleak_cleanup(): + # Collect cyclic trash and read memory statistics immediately after. + func1 = sys.getallocatedblocks + try: + func2 = sys.gettotalrefcount + except AttributeError: + func2 = lambda: 42 + + # Flush standard output, so that buffered data is sent to the OS and + # associated Python objects are reclaimed. + for stream in (sys.stdout, sys.stderr, sys.__stdout__, sys.__stderr__): + if stream is not None: + stream.flush() + + sys._clear_type_cache() + # This also clears the various internal CPython freelists. + gc.collect() + return func1(), func2() + + +class ReferenceLeakError(RuntimeError): + pass + + +class IntPool(collections.defaultdict): + + def __missing__(self, key): + return key + + +class RefleakTestResult(runner.TextTestResult): + + warmup = 3 + repetitions = 6 + + def _huntLeaks(self, test): + self.stream.flush() + + repcount = self.repetitions + nwarmup = self.warmup + rc_deltas = [0] * (repcount - nwarmup) + alloc_deltas = [0] * (repcount - nwarmup) + # Preallocate ints likely to be stored in rc_deltas and alloc_deltas, + # to make sys.getallocatedblocks() less flaky. + _int_pool = IntPool() + for i in range(-200, 200): + _int_pool[i] + + for i in range(repcount): + # Use a pristine, silent result object to avoid recursion + res = result.TestResult() + test.run(res) + # Poorly-written tests may fail when run several times. + # In this case, abort the refleak run and report the failure. + if not res.wasSuccessful(): + self.failures.extend(res.failures) + self.errors.extend(res.errors) + raise AssertionError + del res + alloc_after, rc_after = _refleak_cleanup() + if i >= nwarmup: + rc_deltas[i - nwarmup] = _int_pool[rc_after - rc_before] + alloc_deltas[i - nwarmup] = _int_pool[alloc_after - alloc_before] + alloc_before, rc_before = alloc_after, rc_after + return rc_deltas, alloc_deltas + + def addSuccess(self, test): + try: + rc_deltas, alloc_deltas = self._huntLeaks(test) + except AssertionError: + # Test failed when repeated + assert not self.wasSuccessful() + return + + # These checkers return False on success, True on failure + def check_rc_deltas(deltas): + return any(deltas) + + def check_alloc_deltas(deltas): + # At least 1/3rd of 0s + if 3 * deltas.count(0) < len(deltas): + return True + # Nothing else than 1s, 0s and -1s + if not set(deltas) <= set((1, 0, -1)): + return True + return False + + failed = False + + for deltas, item_name, checker in [ + (rc_deltas, 'references', check_rc_deltas), + (alloc_deltas, 'memory blocks', check_alloc_deltas)]: + if checker(deltas): + msg = '%s leaked %s %s, sum=%s' % ( + test, deltas, item_name, sum(deltas)) + failed = True + try: + raise ReferenceLeakError(msg) + except Exception: + exc_info = sys.exc_info() + if self.showAll: + self.stream.write("%s = %r " % (item_name, deltas)) + self.addFailure(test, exc_info) + + if not failed: + super(RefleakTestResult, self).addSuccess(test) + + +class RefleakTestRunner(runner.TextTestRunner): + resultclass = RefleakTestResult + + +class ParallelTestResult(runner.TextTestResult): + """ + A TestResult able to inject results from other results. + """ + + def add_results(self, result): + """ + Add the results from the other *result* to this result. + """ + self.stream.write(result.stream.getvalue()) + self.stream.flush() + self.testsRun += result.testsRun + self.failures.extend(result.failures) + self.errors.extend(result.errors) + self.skipped.extend(result.skipped) + self.expectedFailures.extend(result.expectedFailures) + self.unexpectedSuccesses.extend(result.unexpectedSuccesses) + + +class _MinimalResult(object): + """ + A minimal, picklable TestResult-alike object. + """ + + __slots__ = ( + 'failures', 'errors', 'skipped', 'expectedFailures', + 'unexpectedSuccesses', 'stream', 'shouldStop', 'testsRun', + 'test_id', 'resource_info') + + def fixup_case(self, case): + """ + Remove any unpicklable attributes from TestCase instance *case*. + """ + # Python 3.3 doesn't reset this one. + case._outcomeForDoCleanups = None + + def __init__(self, original_result, test_id=None, resource_info=None): + for attr in self.__slots__: + setattr(self, attr, getattr(original_result, attr, None)) + for case, _ in self.expectedFailures: + self.fixup_case(case) + for case, _ in self.errors: + self.fixup_case(case) + for case, _ in self.failures: + self.fixup_case(case) + self.test_id = test_id + self.resource_info = resource_info + + +class _FakeStringIO(object): + """ + A trivial picklable StringIO-alike for Python 2. + """ + + def __init__(self, value): + self._value = value + + def getvalue(self): + return self._value + + +class _MinimalRunner(object): + """ + A minimal picklable object able to instantiate a runner in a + child process and run a test case with it. + """ + + def __init__(self, runner_cls, runner_args): + self.runner_cls = runner_cls + self.runner_args = runner_args + + # Python 2 doesn't know how to pickle instance methods, so we use __call__ + # instead. + + def __call__(self, test): + # Executed in child process + kwargs = self.runner_args + # Force recording of output in a buffer (it will be printed out + # by the parent). + kwargs['stream'] = StringIO() + runner = self.runner_cls(**kwargs) + result = runner._makeResult() + # Avoid child tracebacks when Ctrl-C is pressed. + signals.installHandler() + signals.registerResult(result) + result.failfast = runner.failfast + result.buffer = runner.buffer + # Create a per-process memory tracker to avoid global state issues + memtrack = memoryutils.MemoryTracker(test.id()) + with memtrack.monitor(): + with self.cleanup_object(test): + test(result) + # HACK as cStringIO.StringIO isn't picklable in 2.x + result.stream = _FakeStringIO(result.stream.getvalue()) + return _MinimalResult(result, test.id(), + resource_info=memtrack.get_summary()) + + @contextlib.contextmanager + def cleanup_object(self, test): + """ + A context manager which cleans up unwanted attributes on a test case + (or any other object). + """ + vanilla_attrs = set(test.__dict__) + try: + yield test + finally: + spurious_attrs = set(test.__dict__) - vanilla_attrs + for name in spurious_attrs: + del test.__dict__[name] + + +def _split_nonparallel_tests(test, sliced): + """ + Split test suite into parallel and serial tests. + """ + ptests = [] + stests = [] + + flat = [*filter(sliced, _flatten_suite(test))] + + def is_parallelizable_test_case(test): + # Guard for the fake test case created by unittest when test + # discovery fails, as it isn't picklable (e.g. "LoadTestsFailure") + method_name = test._testMethodName + method = getattr(test, method_name) + if method.__name__ != method_name and method.__name__ == "testFailure": + return False + # Was parallel execution explicitly disabled? + return getattr(test, "_numba_parallel_test_", True) + + for t in flat: + if is_parallelizable_test_case(t): + ptests.append(t) + else: + stests.append(t) + + return ptests, stests + +# A test can't run longer than 10 minutes +_TIMEOUT = 1200 + +class ParallelTestRunner(runner.TextTestRunner): + """ + A test runner which delegates the actual running to a pool of child + processes. + """ + + resultclass = ParallelTestResult + timeout = _TIMEOUT + + def __init__(self, runner_cls, nprocs, useslice, **kwargs): + runner.TextTestRunner.__init__(self, **kwargs) + self.runner_cls = runner_cls + self.nprocs = nprocs + self.useslice = parse_slice(useslice) + self.runner_args = kwargs + self.resource_infos = [] + + def _run_inner(self, result): + # We hijack TextTestRunner.run()'s inner logic by passing this + # method as if it were a test case. + child_runner = _MinimalRunner(self.runner_cls, self.runner_args) + + # Split the tests and recycle the worker process to tame memory usage. + chunk_size = 100 + splitted_tests = [self._ptests[i:i + chunk_size] + for i in range(0, len(self._ptests), chunk_size)] + + spawnctx = multiprocessing.get_context("spawn") + try: + for tests in splitted_tests: + pool = spawnctx.Pool(self.nprocs) + try: + self._run_parallel_tests(result, pool, child_runner, tests) + except Exception: + # On exception, kill still active workers immediately + pool.terminate() + # Make sure exception is reported and not ignored + raise + else: + # Close the pool cleanly unless asked to early out + if result.shouldStop: + pool.terminate() + break + else: + pool.close() + finally: + # Always join the pool (this is necessary for coverage.py) + pool.join() + if not result.shouldStop: + # Run serial tests with memory tracking + stests = SerialSuite(self._stests) + stests.run(result) + # Add serial test resource infos to the main collection + self.resource_infos.extend(stests.resource_infos) + return result + finally: + # Always display the resource infos + if memoryutils.IS_SUPPORTED: + try: + print("=== Resource Infos ===") + for ri in self.resource_infos: + print(ri) + except Exception: + print("ERROR: Ignored exception in priting resource infos") + traceback.print_exc() + finally: + print("=== End Resource Infos ===") + + def _run_parallel_tests(self, result, pool, child_runner, tests): + remaining_ids = set(t.id() for t in tests) + tests.sort(key=cuda_sensitive_mtime) + it = pool.imap_unordered(child_runner, tests) + while True: + try: + child_result = it.__next__(self.timeout) + except StopIteration: + return + except TimeoutError as e: + # Diagnose the names of unfinished tests + msg = ("Tests didn't finish before timeout (or crashed):\n%s" + % "".join("- %r\n" % tid for tid in sorted(remaining_ids)) + ) + e.args = (msg,) + e.args[1:] + raise e + else: + result.add_results(child_result) + self.resource_infos.append(child_result.resource_info) + remaining_ids.discard(child_result.test_id) + if child_result.shouldStop: + result.shouldStop = True + return + + def run(self, test): + self._ptests, self._stests = _split_nonparallel_tests(test, + self.useslice) + print("Parallel: %s. Serial: %s" % (len(self._ptests), + len(self._stests))) + # This will call self._run_inner() on the created result object, + # and print out the detailed test results at the end. + return super(ParallelTestRunner, self).run(self._run_inner) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/notebook.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/notebook.py new file mode 100644 index 0000000000000000000000000000000000000000..646a92d739c755f91efc42b6591d3d07ed1e3af8 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/testing/notebook.py @@ -0,0 +1,171 @@ +from unittest import TestCase + +from ipykernel.tests import utils +from nbformat.converter import convert +from nbformat.reader import reads + +import re +import json +from copy import copy +import unittest + +try: + # py3 + from queue import Empty + + def isstr(s): + return isinstance(s, str) +except ImportError: + # py2 + from Queue import Empty + + def isstr(s): + return isinstance(s, basestring) # noqa + +class NotebookTest(TestCase): + """Validate a notebook. All code cells are executed in order. The output is either checked + for errors (if no reference output is present), or is compared against expected output. + + + Useful references: + http://nbformat.readthedocs.org/en/latest/format_description.html + http://jupyter-client.readthedocs.org/en/latest/messaging.html +""" + + + IGNORE_TYPES = ["execute_request", "execute_input", "status", "pyin"] + STRIP_KEYS = ["execution_count", "traceback", "prompt_number", "source"] + NBFORMAT_VERSION = 4 + + def _test_notebook(self, notebook, test): + + with open(notebook) as f: + nb = convert(reads(f.read()), self.NBFORMAT_VERSION) + _, kernel = utils.start_new_kernel() + for i, c in enumerate([c for c in nb.cells if c.cell_type == 'code']): + self._test_notebook_cell(self.sanitize_cell(c), i, kernel, test) + + def _test_notebook_cell(self, cell, i, kernel, test): + + if hasattr(cell, 'source'): # nbformat 4.0 and later + code = cell.source + else: + code = cell.input + iopub = kernel.iopub_channel + kernel.execute(code) + outputs = [] + msg = None + no_error = True + first_error = -1 + error_msg = '' + while self.should_continue(msg): + try: + msg = iopub.get_msg(block=True, timeout=1) + except Empty: + continue + if msg['msg_type'] not in self.IGNORE_TYPES: + if msg['msg_type'] == 'error': + error_msg = ' ' + msg['content']['ename'] + '\n ' + msg['content']['evalue'] + no_error = False + if first_error == -1: + first_error = i + i = len(outputs) + expected = i < len(cell.outputs) and cell.outputs[i] or [] + o = self.transform_message(msg, expected) + outputs.append(o) + + if (test == 'check_error'): + self.assertTrue(no_error, 'Executing cell %d resulted in an error:\n%s'%(first_error, error_msg)) + else: + # Compare computed output against stored output. + # TODO: This doesn't work right now as the generated output is too diverse to + # be verifiable. + scrub = lambda x: self.dump_canonical(list(self.scrub_outputs(x))) + scrubbed = scrub(outputs) + expected = scrub(cell.outputs) + #print('output=%s'%outputs) + #print('expected=%s'%expected) + #self.assertEqual(scrubbed, expected, "\n{}\n\n{}".format(scrubbed, expected)) + + def dump_canonical(self, obj): + return json.dumps(obj, indent=2, sort_keys=True) + + def scrub_outputs(self, outputs): + """ + remove all scrubs from output data and text + """ + for output in outputs: + out = copy(output) + + for scrub, sub in []:#self.scrubs.items(): + def _scrubLines(lines): + if isstr(lines): + return re.sub(scrub, sub, lines) + else: + return [re.sub(scrub, sub, line) for line in lines] + + if "text" in out: + out["text"] = _scrubLines(out["text"]) + + if "data" in out: + if isinstance(out["data"], dict): + for mime, data in out["data"].items(): + out["data"][mime] = _scrubLines(data) + else: + out["data"] = _scrubLines(out["data"]) + yield out + + def strip_keys(self, d): + """ + remove keys from STRIP_KEYS to ensure comparability + """ + for key in self.STRIP_KEYS: + d.pop(key, None) + return d + + def sanitize_cell(self, cell): + """ + remove non-reproducible things + """ + for output in cell.outputs: + self.strip_keys(output) + return cell + + def transform_message(self, msg, expected): + """ + transform a message into something like the notebook + """ + SWAP_KEYS = { + "output_type": { + "pyout": "execute_result", + "pyerr": "error" + } + } + + output = { + u"output_type": msg["msg_type"] + } + output.update(msg["content"]) + + output = self.strip_keys(output) + for key, swaps in SWAP_KEYS.items(): + if key in output and output[key] in swaps: + output[key] = swaps[output[key]] + + if "data" in output and "data" not in expected: + output["text"] = output["data"] + del output["data"] + + return output + + def should_continue(self, msg): + """ + determine whether the current message is the last for this cell + """ + if msg is None: + return True + + return not (msg["msg_type"] == "status" and + msg["content"]["execution_state"] == "idle") + + diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_array_attr.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_array_attr.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da793d89e71f5dea12556becd034d98e79caee5f Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_array_attr.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_cfunc.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_cfunc.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d0a2a4abaf2308b461950b0266d70f6c9cd04d0 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_cfunc.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_copy_propagate.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_copy_propagate.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22eca27fd879bceb07dc470b0ddacad345bda406 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_copy_propagate.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_indexing.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_indexing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..717141b6f5d90e5d47f5dac83edd0e83ecfa4d75 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_indexing.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_llvm_pass_timings.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_llvm_pass_timings.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb0665ec169e575cfde273df1064470f9cd89322 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_llvm_pass_timings.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_npdatetime.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_npdatetime.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..adfb8a08ddfbc87d091fd857975d58ef7c316882 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_npdatetime.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_numbers.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_numbers.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e430c6fdfb81a51e68bed0e73670537f22772a3 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_numbers.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_numconv.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_numconv.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c861a1a6d5a03ccda32e67ff6cfd6fd843a46036 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_numconv.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_python_int.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_python_int.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70030e484d24ac8b94160b78261a706fa027beee Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_python_int.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_storeslice.cpython-311.pyc b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_storeslice.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c93f8f83ee14a92e8318627ecbf2b32fd36128a2 Binary files /dev/null and b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/__pycache__/test_storeslice.cpython-311.pyc differ diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/cfunc_cache_usecases.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/cfunc_cache_usecases.py new file mode 100644 index 0000000000000000000000000000000000000000..24c3079ceaa1ee74463d40ff57ed68cf9a1ae9a8 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/cfunc_cache_usecases.py @@ -0,0 +1,70 @@ +""" +This file will be copied to a temporary directory in order to +exercise caching compiled C callbacks. + +See test_cfunc.py. +""" + +import sys + +from numba import cfunc, jit +from numba.tests.support import TestCase, captured_stderr + + +Z = 1 + +add_sig = "float64(float64, float64)" + +div_sig = "float64(int64, int64)" + + +@cfunc(add_sig, cache=True, nopython=True) +def add_usecase(x, y): + return x + y + Z + +@cfunc(add_sig, nopython=True) +def add_nocache_usecase(x, y): + return x + y + Z + +@cfunc(div_sig, cache=True, nopython=True) +def div_usecase(a, b): + return a / b + + +@jit(nopython=True) +def inner(x, y): + return x + y + Z + +@cfunc(add_sig, cache=True, nopython=True) +def outer(x, y): + return inner(-y, x) + + +class _TestModule(TestCase): + """ + Tests for functionality of this module's cfuncs. + Note this does not define any "test_*" method, instead check_module() + should be called by hand. + """ + + def check_module(self, mod): + f = mod.add_usecase + self.assertPreciseEqual(f.ctypes(2.0, 3.0), 6.0) + f = mod.add_nocache_usecase + self.assertPreciseEqual(f.ctypes(2.0, 3.0), 6.0) + f = mod.outer + self.assertPreciseEqual(f.ctypes(5.0, 2.0), 4.0) + + f = mod.div_usecase + with captured_stderr() as err: + self.assertPreciseEqual(f.ctypes(7, 2), 3.5) + self.assertEqual(err.getvalue(), "") + with captured_stderr() as err: + f.ctypes(7, 0) + err = err.getvalue() + self.assertIn("ZeroDivisionError", err) + + +def self_test(): + mod = sys.modules[__name__] + _TestModule().check_module(mod) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b2958441fe7a098eeb66fe183b62bd4ff0edbbe2 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/__init__.py @@ -0,0 +1,10 @@ +from os.path import dirname +import unittest +from unittest.suite import TestSuite + +from numba.testing import load_testsuite + +def load_tests(loader, tests, pattern): + suite = TestSuite() + suite.addTests(load_testsuite(loader, dirname(__file__))) + return suite diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_array_arg.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_array_arg.py new file mode 100644 index 0000000000000000000000000000000000000000..cb48dae2c536a7b1e2568244bf2058ce934238f0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_array_arg.py @@ -0,0 +1,51 @@ +# NOTE: This test is sensitive to line numbers as it checks breakpoints +from numba import njit, types +import numpy as np +from numba.tests.gdb_support import GdbMIDriver +from numba.tests.support import TestCase, needs_subprocess +import unittest + + +@needs_subprocess +class Test(TestCase): + + def test(self): + @njit(debug=True) + def foo(x): + z = np.ones_like(x) # break here + return x, z + + tmp = np.ones(5) + foo(tmp) + + driver = GdbMIDriver(__file__) + driver.set_breakpoint(line=15) + driver.run() + driver.check_hit_breakpoint(1) + driver.stack_list_arguments(2) + llvm_intp = f"i{types.intp.bitwidth}" + expect = ( + '[frame={level="0",args=[{name="x",type="array(float64, 1d, C) ' + f'({{i8*, i8*, {llvm_intp}, {llvm_intp}, double*, ' + f'[1 x {llvm_intp}], [1 x {llvm_intp}]}})"}}]}}]' + ) + driver.assert_output(expect) + driver.stack_list_variables(1) + # 'z' should be zero-init + expect = ('{name="z",value="{meminfo = 0x0, parent = 0x0, nitems = 0, ' + 'itemsize = 0, data = 0x0, shape = {0}, strides = {0}}"}') + driver.assert_output(expect) + driver.set_breakpoint(line=16) + driver.cont() + driver.check_hit_breakpoint(2) + driver.stack_list_variables(1) + # 'z' should be populated + expect = (r'^.*\{name="z",value="\{meminfo = 0x[0-9a-f]+ .*, ' + r'parent = 0x0, nitems = 5, itemsize = 8, ' + r'data = 0x[0-9a-f]+, shape = \{5\}, strides = \{8\}\}.*$') + driver.assert_regex_output(expect) + driver.quit() + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_basic.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..2a28d6f7468221098ac56e41cb221f704b27a0be --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_basic.py @@ -0,0 +1,39 @@ +# NOTE: This test is sensitive to line numbers as it checks breakpoints +from numba import njit, types +from numba.tests.gdb_support import GdbMIDriver +from numba.tests.support import TestCase, needs_subprocess +import unittest + + +@needs_subprocess +class Test(TestCase): + + def test(self): + @njit(debug=True) + def foo(x): + z = 7 + x # break here + return x, z + + foo(120) + + sz = types.intp.bitwidth + driver = GdbMIDriver(__file__) + driver.set_breakpoint(line=14) + driver.run() + driver.check_hit_breakpoint(1) + driver.stack_list_arguments(2) + expect = ('[frame={level="0",args=[{name="x",type="int%s",' + 'value="120"}]}]' % sz) + driver.assert_output(expect) + driver.stack_list_variables(1) + expect = '[{name="x",arg="1",value="120"},{name="z",value="0"}]' + driver.assert_output(expect) + driver.next() + driver.stack_list_variables(1) + expect = '[{name="x",arg="1",value="120"},{name="z",value="127"}]' + driver.assert_output(expect) + driver.quit() + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_break_on_symbol.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_break_on_symbol.py new file mode 100644 index 0000000000000000000000000000000000000000..7743aafc3bebc87db5257452c34ada5b1cf5b682 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_break_on_symbol.py @@ -0,0 +1,34 @@ +# NOTE: This test is sensitive to line numbers as it checks breakpoints +from numba import njit, types +from numba.tests.gdb_support import GdbMIDriver +from numba.tests.support import TestCase, needs_subprocess +import unittest + + +@njit(debug=True) +def foo(x): + z = 7 + x + return x, z + + +@needs_subprocess +class Test(TestCase): + + def test(self): + foo(120) + sz = types.intp.bitwidth + driver = GdbMIDriver(__file__) + driver.set_breakpoint(symbol="__main__::foo") + driver.run() # will hit cpython symbol match + driver.check_hit_breakpoint(number=1) + driver.cont() # will hit njit symbol match + driver.check_hit_breakpoint(number=1, line=10) # Ensure line number + driver.stack_list_arguments(2) + expect = ('[frame={level="0",args=[{name="x",type="int%s",' + 'value="120"}]}]' % sz) + driver.assert_output(expect) + driver.quit() + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_break_on_symbol_version.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_break_on_symbol_version.py new file mode 100644 index 0000000000000000000000000000000000000000..72f09b19ab11f11b3d6bfb68cefec554a6e9f29e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_break_on_symbol_version.py @@ -0,0 +1,65 @@ +# NOTE: This test is sensitive to line numbers as it checks breakpoints +from numba import njit +from numba.tests.gdb_support import GdbMIDriver +from numba.tests.support import TestCase, needs_subprocess +import unittest + + +def foo_factory(n): + @njit(debug=True) + def foo(x): + z = 7 + n + return x, z + + return foo + + +foo1, foo2, foo3 = [foo_factory(x) for x in range(3)] + + +@njit(debug=True) +def call_foo(): + a = foo1(10) + b = foo2(20) + c = foo3(30) + return a, b, c + + +@needs_subprocess +class Test(TestCase): + + def test(self): + call_foo() + driver = GdbMIDriver(__file__) + # A specific foo, the first one, it has uid=2 + vsym = "__main__::foo_factory::_3clocals_3e::foo[abi:v2]" + driver.set_breakpoint(symbol=vsym) + driver.run() + driver.check_hit_breakpoint(number=1) + driver.assert_regex_output(r'^.*foo\[abi:v2\].*line="11"') + driver.stack_list_arguments(2) + expect = ('[frame={level="0",args=[{name="x",type="Literal[int](10)",' + 'value="10"}]}]') + driver.assert_output(expect) + # Now break on any foo + driver.set_breakpoint(symbol="foo") + driver.cont() + driver.check_hit_breakpoint(number=2) + driver.assert_regex_output(r'^.*foo\[abi:v3\].*line="11"') + driver.stack_list_arguments(2) + expect = ('[frame={level="0",args=[{name="x",type="Literal[int](20)",' + 'value="20"}]}]') + driver.assert_output(expect) + # and again, hit the third foo + driver.cont() + driver.check_hit_breakpoint(number=2) + driver.assert_regex_output(r'^.*foo\[abi:v4\].*line="11"') + driver.stack_list_arguments(2) + expect = ('[frame={level="0",args=[{name="x",type="Literal[int](30)",' + 'value="30"}]}]') + driver.assert_output(expect) + driver.quit() + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_conditional_breakpoint.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_conditional_breakpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..867a53eb16b82cb0fbd5e03a8e833afd3640bfcf --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_conditional_breakpoint.py @@ -0,0 +1,45 @@ +# NOTE: This test is sensitive to line numbers as it checks breakpoints +from numba import njit +from numba.tests.gdb_support import GdbMIDriver +from numba.tests.support import TestCase, needs_subprocess +import unittest + + +@needs_subprocess +class Test(TestCase): + + def test(self): + + @njit(debug=True) + def foo(x, y): + c = x + y # break-here + return c + + @njit(debug=True) + def call_foo(a): + acc = 0 + for i in range(10): + acc += foo(i, a) + return acc + + call_foo(10) + + driver = GdbMIDriver(__file__) + driver.set_breakpoint(line=15, condition='x == 4') + driver.run() + driver.check_hit_breakpoint(1) + driver.stack_list_arguments(1) + expect = ('[frame={level="0",args=[{name="x",value="4"},' + '{name="y",value="10"}]}]') + driver.assert_output(expect) + driver.set_breakpoint(line=22, condition='i == 8') + driver.cont() + driver.check_hit_breakpoint(2) + driver.stack_list_variables(1) + # i should be 8 + driver.assert_output('{name="i",value="8"}') + driver.quit() + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_pretty_print.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_pretty_print.py new file mode 100644 index 0000000000000000000000000000000000000000..b0be5dbe8e4fcb78e2c1edafc679a4ebe3b1bbee --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/gdb/test_pretty_print.py @@ -0,0 +1,69 @@ +# NOTE: This test is sensitive to line numbers as it checks breakpoints +from numba import njit +import numpy as np +from numba.tests.gdb_support import GdbMIDriver, needs_gdb_py3 +from numba.tests.support import TestCase, needs_subprocess +from numba.misc.numba_gdbinfo import collect_gdbinfo +import unittest +import re + + +@needs_gdb_py3 +@needs_subprocess +class Test(TestCase): + + def test(self): + rdt_a = np.dtype([("x", np.int16), ("y", np.float64)], align=True) + + @njit(debug=True) + def foo(): + a = 1.234 + b = (1, 2, 3) + c = ('a', b, 4) + d = np.arange(5.) + e = np.array([[1, 3j], [2, 4j]]) + f = "Some string" + " L-Padded string".lstrip() + g = 11 + 22j + h = np.arange(24).reshape((4, 6))[::2, ::3] + i = np.zeros(2, dtype=rdt_a) + return a, b, c, d, e, f, g, h, i + + foo() + + extension = collect_gdbinfo().extension_loc + driver = GdbMIDriver(__file__, init_cmds=['-x', extension], debug=False) + driver.set_breakpoint(line=29) + driver.run() + driver.check_hit_breakpoint(1) + + # Ideally the function would be run to get the string repr of locals + # but not everything appears in DWARF e.g. string literals. Further, + # str on NumPy arrays seems to vary a bit in output. Therefore a custom + # match is used. + + driver.stack_list_variables(1) + output = driver._captured.after.decode('UTF-8') + done_str = output.splitlines()[0] + pat = r'^\^done,variables=\[\{(.*)\}\]$' + lcls_strs = re.match(pat, done_str).groups()[0].split('},{') + lcls = {k: v for k, v in [re.match(r'name="(.*)",value="(.*)"', + x).groups() for x in lcls_strs]} + expected = dict() + expected['a'] = r'1\.234' + expected['b'] = r'\(1, 2, 3\)' + expected['c'] = r'\(0x0, \(1, 2, 3\), 4\)' + expected['d'] = r'\\n\[0. 1. 2. 3. 4.\]' + expected['e'] = r'\\n\[\[1.\+0.j 0.\+3.j\]\\n \[2.\+0.j 0.\+4.j\]\]' + expected['f'] = "'Some stringL-Padded string'" + expected['g'] = r"11\+22j" + expected['h'] = r'\\n\[\[ 0 3\]\\n \[12 15\]\]' + expected['i'] = r'\\n\[\(0, 0.\) \(0, 0.\)\]' + + for k, v in expected.items(): + self.assertRegex(lcls[k], v) + + driver.quit() + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/inlining_usecases.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/inlining_usecases.py new file mode 100644 index 0000000000000000000000000000000000000000..663b7d3c4798a2add0689a3d52a3c82e034c81e4 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/inlining_usecases.py @@ -0,0 +1,69 @@ +""" Test cases for inlining IR from another module """ +from numba import jit, njit +from numba.core import types +from numba.core.extending import overload + +_GLOBAL1 = 100 + + +@njit(inline='always') +def bar(): + return _GLOBAL1 + 10 + + +def baz_factory(a): + b = 17 + a + + @njit(inline='always') + def baz(): + return _GLOBAL1 + a - b + return baz + + +def baz(): + return _GLOBAL1 + 10 + + +@overload(baz, inline='always') +def baz_ol(): + def impl(): + return _GLOBAL1 + 10 + return impl + + +def bop_factory(a): + b = 17 + a + + def bop(): + return _GLOBAL1 + a - b + + @overload(bop, inline='always') + def baz(): + def impl(): + return _GLOBAL1 + a - b + return impl + + return bop + + +@jit((types.int32,), nopython=True) +def inner(a): + return a + 1 + + +@jit((types.int32,), nopython=True) +def more(a): + return inner(inner(a)) + + +def outer_simple(a): + return inner(a) * 2 + + +def outer_multiple(a): + return inner(a) * more(a) + + +@njit +def __dummy__(): + return diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b2958441fe7a098eeb66fe183b62bd4ff0edbbe2 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/__init__.py @@ -0,0 +1,10 @@ +from os.path import dirname +import unittest +from unittest.suite import TestSuite + +from numba.testing import load_testsuite + +def load_tests(loader, tests, pattern): + suite = TestSuite() + suite.addTests(load_testsuite(loader, dirname(__file__))) + return suite diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/cache_usecases.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/cache_usecases.py new file mode 100644 index 0000000000000000000000000000000000000000..4d250756d404b1e87115e4a191768925e5c2bc21 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/cache_usecases.py @@ -0,0 +1,76 @@ +import numba as nb + + +# +# UFunc +# + +def direct_ufunc_cache_usecase(**kwargs): + @nb.vectorize(["intp(intp)", "float64(float64)"], cache=True, **kwargs) + def ufunc(inp): + return inp * 2 + + return ufunc + + +def indirect_ufunc_cache_usecase(**kwargs): + @nb.njit(cache=True) + def indirect_ufunc_core(inp): + return inp * 3 + + @nb.vectorize(["intp(intp)", "float64(float64)", "complex64(complex64)"], + **kwargs) + def ufunc(inp): + return indirect_ufunc_core(inp) + + return ufunc + + +# +# DUFunc +# + +def direct_dufunc_cache_usecase(**kwargs): + @nb.vectorize(cache=True, **kwargs) + def ufunc(inp): + return inp * 2 + + return ufunc + + +def indirect_dufunc_cache_usecase(**kwargs): + @nb.njit(cache=True) + def indirect_ufunc_core(inp): + return inp * 3 + + @nb.vectorize(**kwargs) + def ufunc(inp): + return indirect_ufunc_core(inp) + + return ufunc + + +# +# GUFunc +# + +def direct_gufunc_cache_usecase(**kwargs): + @nb.guvectorize(["(intp, intp[:])", "(float64, float64[:])"], + "()->()", cache=True, **kwargs) + def gufunc(inp, out): + out[0] = inp * 2 + + return gufunc + + +def indirect_gufunc_cache_usecase(**kwargs): + @nb.njit(cache=True) + def core(x): + return x * 3 + + @nb.guvectorize(["(intp, intp[:])", "(float64, float64[:])", + "(complex64, complex64[:])"], "()->()", **kwargs) + def gufunc(inp, out): + out[0] = core(inp) + + return gufunc diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_caching.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_caching.py new file mode 100644 index 0000000000000000000000000000000000000000..cfb47f113211721bdeea9ea2327f811833706e9b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_caching.py @@ -0,0 +1,228 @@ +import sys +import os.path +import re +import subprocess + +import numpy as np + +from numba.tests.support import capture_cache_log +from numba.tests.test_caching import BaseCacheTest +from numba.core import config +import unittest + + +class UfuncCacheTest(BaseCacheTest): + """ + Since the cache stats is not exposed by ufunc, we test by looking at the + cache debug log. + """ + _numba_parallel_test_ = False + + here = os.path.dirname(__file__) + usecases_file = os.path.join(here, "cache_usecases.py") + modname = "ufunc_caching_test_fodder" + + regex_data_saved = re.compile(r'\[cache\] data saved to') + regex_index_saved = re.compile(r'\[cache\] index saved to') + + regex_data_loaded = re.compile(r'\[cache\] data loaded from') + regex_index_loaded = re.compile(r'\[cache\] index loaded from') + + def check_cache_saved(self, cachelog, count): + """ + Check number of cache-save were issued + """ + data_saved = self.regex_data_saved.findall(cachelog) + index_saved = self.regex_index_saved.findall(cachelog) + self.assertEqual(len(data_saved), count) + self.assertEqual(len(index_saved), count) + + def check_cache_loaded(self, cachelog, count): + """ + Check number of cache-load were issued + """ + data_loaded = self.regex_data_loaded.findall(cachelog) + index_loaded = self.regex_index_loaded.findall(cachelog) + self.assertEqual(len(data_loaded), count) + self.assertEqual(len(index_loaded), count) + + def check_ufunc_cache(self, usecase_name, n_overloads, **kwargs): + """ + Check number of cache load/save. + There should be one per overloaded version. + """ + mod = self.import_module() + usecase = getattr(mod, usecase_name) + # New cache entry saved + with capture_cache_log() as out: + new_ufunc = usecase(**kwargs) + cachelog = out.getvalue() + self.check_cache_saved(cachelog, count=n_overloads) + + # Use cached version + with capture_cache_log() as out: + cached_ufunc = usecase(**kwargs) + cachelog = out.getvalue() + self.check_cache_loaded(cachelog, count=n_overloads) + + return new_ufunc, cached_ufunc + + +class TestUfuncCacheTest(UfuncCacheTest): + + def test_direct_ufunc_cache(self, **kwargs): + new_ufunc, cached_ufunc = self.check_ufunc_cache( + "direct_ufunc_cache_usecase", n_overloads=2, **kwargs) + # Test the cached and original versions + inp = np.random.random(10).astype(np.float64) + np.testing.assert_equal(new_ufunc(inp), cached_ufunc(inp)) + inp = np.arange(10, dtype=np.intp) + np.testing.assert_equal(new_ufunc(inp), cached_ufunc(inp)) + + def test_direct_ufunc_cache_objmode(self): + self.test_direct_ufunc_cache(forceobj=True) + + def test_direct_ufunc_cache_parallel(self): + self.test_direct_ufunc_cache(target='parallel') + + def test_indirect_ufunc_cache(self, **kwargs): + new_ufunc, cached_ufunc = self.check_ufunc_cache( + "indirect_ufunc_cache_usecase", n_overloads=3, **kwargs) + # Test the cached and original versions + inp = np.random.random(10).astype(np.float64) + np.testing.assert_equal(new_ufunc(inp), cached_ufunc(inp)) + inp = np.arange(10, dtype=np.intp) + np.testing.assert_equal(new_ufunc(inp), cached_ufunc(inp)) + + def test_indirect_ufunc_cache_parallel(self): + self.test_indirect_ufunc_cache(target='parallel') + + +class TestDUfuncCacheTest(UfuncCacheTest): + # Note: DUFunc doesn't support parallel target yet + + def check_dufunc_usecase(self, usecase_name): + mod = self.import_module() + usecase = getattr(mod, usecase_name) + # Create dufunc + with capture_cache_log() as out: + ufunc = usecase() + self.check_cache_saved(out.getvalue(), count=0) + # Compile & cache + with capture_cache_log() as out: + ufunc(np.arange(10)) + self.check_cache_saved(out.getvalue(), count=1) + self.check_cache_loaded(out.getvalue(), count=0) + # Use cached + with capture_cache_log() as out: + ufunc = usecase() + ufunc(np.arange(10)) + self.check_cache_loaded(out.getvalue(), count=1) + + def test_direct_dufunc_cache(self): + # We don't test for objmode because DUfunc don't support it. + self.check_dufunc_usecase('direct_dufunc_cache_usecase') + + def test_indirect_dufunc_cache(self): + self.check_dufunc_usecase('indirect_dufunc_cache_usecase') + + +def _fix_raw_path(rstr): + if config.IS_WIN32: + rstr = rstr.replace(r'/', r'\\\\') + return rstr + + +class TestGUfuncCacheTest(UfuncCacheTest): + + def test_filename_prefix(self): + mod = self.import_module() + usecase = getattr(mod, "direct_gufunc_cache_usecase") + with capture_cache_log() as out: + usecase() + cachelog = out.getvalue() + # find number filename with "guf-" prefix + fmt1 = _fix_raw_path(r'/__pycache__/guf-{}') + prefixed = re.findall(fmt1.format(self.modname), cachelog) + fmt2 = _fix_raw_path(r'/__pycache__/{}') + normal = re.findall(fmt2.format(self.modname), cachelog) + # expecting 2 overloads + self.assertGreater(len(normal), 2) + # expecting equal number of wrappers and overloads cache entries + self.assertEqual(len(normal), len(prefixed)) + + def test_direct_gufunc_cache(self, **kwargs): + # 2 cache entry for the 2 overloads + # and 2 cache entry for the gufunc wrapper + new_ufunc, cached_ufunc = self.check_ufunc_cache( + "direct_gufunc_cache_usecase", n_overloads=2 + 2, **kwargs) + # Test the cached and original versions + inp = np.random.random(10).astype(np.float64) + np.testing.assert_equal(new_ufunc(inp), cached_ufunc(inp)) + inp = np.arange(10, dtype=np.intp) + np.testing.assert_equal(new_ufunc(inp), cached_ufunc(inp)) + + def test_direct_gufunc_cache_objmode(self): + self.test_direct_gufunc_cache(forceobj=True) + + def test_direct_gufunc_cache_parallel(self): + self.test_direct_gufunc_cache(target='parallel') + + def test_indirect_gufunc_cache(self, **kwargs): + # 3 cache entry for the 3 overloads + # and no cache entry for the gufunc wrapper + new_ufunc, cached_ufunc = self.check_ufunc_cache( + "indirect_gufunc_cache_usecase", n_overloads=3, **kwargs) + # Test the cached and original versions + inp = np.random.random(10).astype(np.float64) + np.testing.assert_equal(new_ufunc(inp), cached_ufunc(inp)) + inp = np.arange(10, dtype=np.intp) + np.testing.assert_equal(new_ufunc(inp), cached_ufunc(inp)) + + def test_indirect_gufunc_cache_parallel(self, **kwargs): + self.test_indirect_gufunc_cache(target='parallel') + + +class TestCacheSpecificIssue(UfuncCacheTest): + + def run_in_separate_process(self, runcode): + # Based on the same name util function in test_dispatcher but modified + # to allow user to define what to run. + code = """if 1: + import sys + + sys.path.insert(0, %(tempdir)r) + mod = __import__(%(modname)r) + mod.%(runcode)s + """ % dict(tempdir=self.tempdir, modname=self.modname, + runcode=runcode) + + popen = subprocess.Popen([sys.executable, "-c", code], + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + out, err = popen.communicate() + if popen.returncode != 0: + raise AssertionError("process failed with code %s: stderr follows" + "\n%s\n" % (popen.returncode, err.decode())) + + # + # The following test issue #2198 that loading cached (g)ufunc first + # bypasses some target context initialization. + # + + def test_first_load_cached_ufunc(self): + # ensure function is cached + self.run_in_separate_process('direct_ufunc_cache_usecase()') + # use the cached function + # this will fail if the target context is not init'ed + self.run_in_separate_process('direct_ufunc_cache_usecase()') + + def test_first_load_cached_gufunc(self): + # ensure function is cached + self.run_in_separate_process('direct_gufunc_cache_usecase()') + # use the cached function + # this will fail out if the target context is not init'ed + self.run_in_separate_process('direct_gufunc_cache_usecase()') + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_dufunc.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_dufunc.py new file mode 100644 index 0000000000000000000000000000000000000000..da4e9bf9ad49a67ee010acfbe5ac447164163192 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_dufunc.py @@ -0,0 +1,1139 @@ +import functools +import itertools +import pickle +import textwrap +import warnings + +import numpy as np + +from numba import njit, vectorize +from numba.tests.support import MemoryLeakMixin, TestCase +from numba.core.errors import (TypingError, NumbaNotImplementedError, + NumbaExperimentalFeatureWarning) +import unittest +from numba.np.ufunc import dufunc +from numba.np.numpy_support import from_dtype + + +def pyuadd(a0, a1): + return a0 + a1 + + +def pysub(a0, a1): + return a0 - a1 + + +def pymult(a0, a1): + return a0 * a1 + + +def pydiv(a0, a1): + return a0 // a1 + + +def pymin(a0, a1): + return a0 if a0 < a1 else a1 + + +class TestDUFunc(MemoryLeakMixin, unittest.TestCase): + + def nopython_dufunc(self, pyfunc): + return dufunc.DUFunc(pyfunc, targetoptions=dict(nopython=True)) + + def test_frozen(self): + duadd = self.nopython_dufunc(pyuadd) + self.assertFalse(duadd._frozen) + duadd._frozen = True + self.assertTrue(duadd._frozen) + with self.assertRaises(ValueError): + duadd._frozen = False + with self.assertRaises(TypeError): + duadd(np.linspace(0,1,10), np.linspace(1,2,10)) + + def test_scalar(self): + duadd = self.nopython_dufunc(pyuadd) + self.assertEqual(pyuadd(1,2), duadd(1,2)) + + def test_npm_call(self): + duadd = self.nopython_dufunc(pyuadd) + + @njit + def npmadd(a0, a1, o0): + duadd(a0, a1, o0) + X = np.linspace(0,1.9,20) + X0 = X[:10] + X1 = X[10:] + out0 = np.zeros(10) + npmadd(X0, X1, out0) + np.testing.assert_array_equal(X0 + X1, out0) + Y0 = X0.reshape((2,5)) + Y1 = X1.reshape((2,5)) + out1 = np.zeros((2,5)) + npmadd(Y0, Y1, out1) + np.testing.assert_array_equal(Y0 + Y1, out1) + Y2 = X1[:5] + out2 = np.zeros((2,5)) + npmadd(Y0, Y2, out2) + np.testing.assert_array_equal(Y0 + Y2, out2) + + def test_npm_call_implicit_output(self): + duadd = self.nopython_dufunc(pyuadd) + + @njit + def npmadd(a0, a1): + return duadd(a0, a1) + X = np.linspace(0,1.9,20) + X0 = X[:10] + X1 = X[10:] + out0 = npmadd(X0, X1) + np.testing.assert_array_equal(X0 + X1, out0) + Y0 = X0.reshape((2,5)) + Y1 = X1.reshape((2,5)) + out1 = npmadd(Y0, Y1) + np.testing.assert_array_equal(Y0 + Y1, out1) + Y2 = X1[:5] + out2 = npmadd(Y0, Y2) + np.testing.assert_array_equal(Y0 + Y2, out2) + out3 = npmadd(1.,2.) + self.assertEqual(out3, 3.) + + def test_ufunc_props(self): + duadd = self.nopython_dufunc(pyuadd) + self.assertEqual(duadd.nin, 2) + self.assertEqual(duadd.nout, 1) + self.assertEqual(duadd.nargs, duadd.nin + duadd.nout) + self.assertEqual(duadd.ntypes, 0) + self.assertEqual(duadd.types, []) + self.assertEqual(duadd.identity, None) + duadd(1, 2) + self.assertEqual(duadd.ntypes, 1) + self.assertEqual(duadd.ntypes, len(duadd.types)) + self.assertIsNone(duadd.signature) + + def test_ufunc_props_jit(self): + duadd = self.nopython_dufunc(pyuadd) + duadd(1, 2) # initialize types attribute + + attributes = {'nin': duadd.nin, + 'nout': duadd.nout, + 'nargs': duadd.nargs, + #'ntypes': duadd.ntypes, + #'types': duadd.types, + 'identity': duadd.identity, + 'signature': duadd.signature} + + def get_attr_fn(attr): + fn = f''' + def impl(): + return duadd.{attr} + ''' + l = {} + exec(textwrap.dedent(fn), {'duadd': duadd}, l) + return l['impl'] + + for attr, val in attributes.items(): + cfunc = njit(get_attr_fn(attr)) + self.assertEqual(val, cfunc(), + f'Attribute differs from original: {attr}') + + # We don't expose [n]types attributes as they are dynamic attributes + # and can change as the user calls the ufunc + # cfunc = njit(get_attr_fn('ntypes')) + # self.assertEqual(cfunc(), 1) + # duadd(1.1, 2.2) + # self.assertEqual(cfunc(), 2) + + +class TestDUFuncMethodsBase(TestCase): + + @functools.cache + def _generate_jit(self, ufunc, kind, identity=None): + assert kind in ('reduce', 'reduceat', 'at') + if kind == 'reduce': + if ufunc.nin == 2: + vec = vectorize(identity=identity)(lambda a, b: ufunc(a, b)) + else: + vec = vectorize(identity=identity)(lambda a: ufunc(a)) + + @njit + def fn(array, axis=0, initial=None): + return vec.reduce(array, axis=axis, initial=initial) + return fn + elif kind == 'reduceat': + if ufunc.nin != 2: + raise ValueError('reduceat only supported for binary functions') + vec = vectorize(identity=identity)(lambda a, b: ufunc(a, b)) + + @njit + def fn(array, indices, axis=0, dtype=None, out=None): + return vec.reduceat(array, indices, axis, dtype, out) + return fn + else: + if ufunc.nin == 2: + vec = vectorize(identity=identity)(lambda a, b: ufunc(a, b)) + else: + vec = vectorize(identity=identity)(lambda a: ufunc(a)) + + @njit + def fn(*args): + return vec.at(*args) + return fn + + def _reduce(self, ufunc, identity): + return self._generate_jit(ufunc, 'reduce', identity=identity) + + def _reduceat(self, ufunc, identity): + return self._generate_jit(ufunc, 'reduceat', identity=identity) + + def _at(self, ufunc): + return self._generate_jit(ufunc, 'at') + + +class TestDUFuncAt(TestDUFuncMethodsBase): + def _compare_output(self, fn, ufunc, a, *args): + expected = a.copy() + got = a.copy() + ufunc.at(expected, *args) + fn(got, *args) + self.assertPreciseEqual(expected, got) + + def test_numpy_ufunc_at_basic(self): + # tests taken from: https://github.com/numpy/numpy/blob/27d8c43eb958b4ecee59b4d66908750759a9afc2/numpy/core/tests/test_ufunc.py#L1974-L2003 # noqa: E501 + # NumPy also test this function with a Rational array dtype. We skip + # this test as Numba doesn't support Rational + a = np.arange(10, dtype=int) + + add_at = self._at(np.add) + negative_at = self._at(np.negative) + + negative_vec = vectorize()(lambda a: np.negative(a)) + + @njit + def negative_jit_2(a, indices, b): + return negative_vec.at(a, indices, b) + + # basic testing + self._compare_output(add_at, np.add, a, [2, 5, 2], 1) + + # missing second operand + err_msg = 'second operand needed for ufunc' + with self.assertRaisesRegex(TypingError, err_msg): + add_at(a.copy(), [2, 5, 3], None) + + self._compare_output(negative_at, np.negative, a.copy(), [2, 5, 3]) + + b = np.array([100, 100, 100]) + self._compare_output(add_at, np.add, a.copy(), [2, 5, 2], b) + + # extraneous second operand + err_msg = 'second operand provided when ufunc is unary' + with self.assertRaisesRegex(TypingError, err_msg): + negative_jit_2(a.copy(), [2, 5, 3], [1, 2, 3]) + + with self.assertRaises(TypingError): + add_at(a.copy(), [2, 5, 3], [[1, 2], 1]) + + def test_ufunc_at_inner_loop(self): + typecodes = np.typecodes['Complex'] + ufuncs = (np.add, np.subtract, np.multiply) + for typecode in typecodes: + + try: + from_dtype(np.dtype(typecode)) + except NumbaNotImplementedError: + continue + + for ufunc in ufuncs: + a = np.ones(10, dtype=typecode) + indx = np.concatenate([np.ones(6, dtype=np.intp), + np.full(18, 4, dtype=np.intp)]) + value = a.dtype.type(1j) + ufunc_at = self._at(ufunc) + ufunc_at(a, indx, value) + expected = np.ones_like(a) + if ufunc is np.multiply: + expected[1] = expected[4] = -1 + else: + expected[1] += 6 * (value if ufunc is np.add else -value) + expected[4] += 18 * (value if ufunc is np.add else -value) + + self.assertPreciseEqual(a, expected) + + def test_ufunc_at_ellipsis(self): + # Make sure the indexed loop check does not choke on iters + # with subspaces + arr = np.zeros(5, dtype=int) + add_at = self._at(np.add) + self._compare_output(add_at, np.add, arr, slice(None), + np.ones(5, dtype=int)) + + def test_ufunc_at_negative(self): + arr = np.ones(5, dtype=np.int32) + indx = np.arange(5) + at = self._at(np.negative) + at(arr, indx) + assert np.all(arr == [-1, -1, -1, -1, -1]) + + def test_ufunc_at_large(self): + # NumPy issue gh-23457 + indices = np.zeros(8195, dtype=np.int16) + b = np.zeros(8195, dtype=float) + b[0] = 10 + b[1] = 5 + b[8192:] = 100 + a = np.zeros(1, dtype=float) + add_at = self._at(np.add) + add_at(a, indices, b) + assert a[0] == b.sum() + + def test_cast_index_fastpath(self): + arr = np.zeros(10) + values = np.ones(100000) + add_at = self._at(np.add) + # index must be cast, which may be buffered in chunks: + index = np.zeros(len(values), dtype=np.uint8) + add_at(arr, index, values) + assert arr[0] == len(values) + + def test_ufunc_at_scalar_value_fastpath(self): + values = (np.ones(1), np.ones(()), np.float64(1.), 1.) + for value in values: + arr = np.zeros(1000) + # index must be cast, which may be buffered in chunks: + index = np.repeat(np.arange(1000), 2) + add_at = self._at(np.add) + add_at(arr, index, value) + np.testing.assert_array_equal(arr, np.full_like(arr, 2 * value)) + + def test_ufunc_at_multiD(self): + a = np.arange(9).reshape(3, 3) + b = np.array([[100, 100, 100], [200, 200, 200], [300, 300, 300]]) + add_at = self._at(np.add) + add_at(a, (slice(None), np.asarray([1, 2, 1])), b) + self.assertPreciseEqual(a, np.array( + [[0, 201, 102], [3, 404, 205], [6, 607, 308]])) + + a = np.arange(27).reshape(3, 3, 3) + b = np.array([100, 200, 300]) + add_at(a, (slice(None), slice(None), np.asarray([1, 2, 1])), b) + self.assertPreciseEqual(a, np.array( + [[[0, 401, 202], + [3, 404, 205], + [6, 407, 208]], + + [[9, 410, 211], + [12, 413, 214], + [15, 416, 217]], + + [[18, 419, 220], + [21, 422, 223], + [24, 425, 226]]])) + + a = np.arange(9).reshape(3, 3) + b = np.array([[100, 100, 100], [200, 200, 200], [300, 300, 300]]) + add_at(a, (np.asarray([1, 2, 1]), slice(None)), b) + self.assertPreciseEqual(a, np.asarray( + [[0, 1, 2], [403, 404, 405], [206, 207, 208]])) + + a = np.arange(27).reshape(3, 3, 3) + b = np.array([100, 200, 300]) + add_at(a, (slice(None), np.asarray([1, 2, 1]), slice(None)), b) + self.assertPreciseEqual(a, np.asarray( + [[[0, 1, 2], + [203, 404, 605], + [106, 207, 308]], + + [[9, 10, 11], + [212, 413, 614], + [115, 216, 317]], + + [[18, 19, 20], + [221, 422, 623], + [124, 225, 326]]])) + + a = np.arange(9).reshape(3, 3) + b = np.array([100, 200, 300]) + add_at(a, (0, np.asarray([1, 2, 1])), b) + self.assertPreciseEqual(a, np.asarray( + [[0, 401, 202], [3, 4, 5], [6, 7, 8]])) + + a = np.arange(27).reshape(3, 3, 3) + b = np.array([100, 200, 300]) + add_at(a, (np.asarray([1, 2, 1]), 0, slice(None)), b) + self.assertPreciseEqual(a, np.asarray( + [[[0, 1, 2], + [3, 4, 5], + [6, 7, 8]], + + [[209, 410, 611], + [12, 13, 14], + [15, 16, 17]], + + [[118, 219, 320], + [21, 22, 23], + [24, 25, 26]]])) + + a = np.arange(27).reshape(3, 3, 3) + b = np.array([100, 200, 300]) + add_at = self._at(np.add) + add_at(a, (slice(None), slice(None), slice(None)), b) + self.assertPreciseEqual(a, np.asarray( + [[[100, 201, 302], + [103, 204, 305], + [106, 207, 308]], + + [[109, 210, 311], + [112, 213, 314], + [115, 216, 317]], + + [[118, 219, 320], + [121, 222, 323], + [124, 225, 326]]])) + + def test_ufunc_at_0D(self): + a = np.array(0) + add_at = self._at(np.add) + add_at(a, (), 1) + self.assertPreciseEqual(a, np.array(1)) + + with self.assertRaises(TypingError): + add_at(a, 0, 1) + + b = np.arange(3) + add_at(b, 0, 1) + self.assertPreciseEqual(b, np.array([1, 1, 2])) + + # NumPy checks for IndexError but we can't call a jit function with an + # empty list as Numba raises "can't compute fingerprint of empty list" + with self.assertRaises(ValueError): + add_at(a, [], 1) + + def test_ufunc_at_dtypes(self): + # Test mixed dtypes + a = np.arange(10) + power_at = self._at(np.power) + power_at(a, [1, 2, 3, 2], 3.5) + self.assertPreciseEqual(a, np.array([0, 1, 4414, 46, 4, 5, 6, 7, 8, 9])) + + def test_ufunc_at_boolean(self): + # Test boolean indexing and boolean ufuncs + a = np.arange(10) + index = a % 2 == 0 + equal_at = self._at(np.equal) + # boolean indexing not supported + equal_at(a, index, [0, 2, 4, 6, 8]) + self.assertPreciseEqual(a, np.array([1, 1, 1, 3, 1, 5, 1, 7, 1, 9])) + + def test_ufunc_at_boolean2(self): + # Test unary operator + a = np.arange(10, dtype='u4') + invert_at = self._at(np.invert) + invert_at(a, [2, 5, 2]) + self.assertPreciseEqual(a, np.array([0, 1, 2, 3, 4, 5 ^ 0xffffffff, 6, + 7, 8, 9], dtype=np.uint32)) + + def test_ufunc_at_advanced(self): + # Test empty subspace + orig = np.arange(4) + a = orig[:, None][:, 0:0] + add_at = self._at(np.add) + add_at(a, [0, 1], 3) + self.assertPreciseEqual(orig, np.arange(4)) + + @unittest.expectedFailure + def test_ufunc_at_advanced_2(self): + # Test with swapped byte order + index = np.array([1, 2, 1], np.dtype('i').newbyteorder()) + values = np.array([1, 2, 3, 4], np.dtype('f').newbyteorder()) + add_at = self._at(np.add) + add_at(values, index, 3) + self.assertPreciseEqual(values, [1, 8, 6, 4]) + + def test_ufunc_at_advanced_3(self): + # Test exception thrown + values = np.array(['a', 1], dtype=object) + add_at = self._at(np.add) + with self.assertRaises(TypingError): + add_at(values, [0, 1], 1) + self.assertPreciseEqual(values, np.array(['a', 1], dtype=object)) + + def test_ufunc_at_advanced_4(self): + # Test multiple output ufuncs raise error, NumPy gh-5665 + modf_at = self._at(np.modf) + # NumPy raises ValueError as modf returns multiple outputs + with self.assertRaises(TypingError): + modf_at(np.arange(10), [1]) + + def test_ufunc_at_advanced_5(self): + # Test maximum + maximum_at = self._at(np.maximum) + a = np.array([1, 2, 3]) + maximum_at(a, [0], 0) + self.assertPreciseEqual(a, np.array([1, 2, 3])) + + def test_ufunc_at_negative_indexes(self): + dtypes = np.typecodes['AllInteger'] + np.typecodes['Float'] + ufuncs = (np.add, np.subtract, np.divide, np.minimum, np.maximum) + + for dtype in dtypes: + + if dtype in ('e',): # skip float16 as we don't have an impl. for it + continue + + try: + from_dtype(np.dtype(dtype)) + except NumbaNotImplementedError: + continue + + for ufunc in ufuncs: + a = np.arange(0, 10).astype(dtype) + indxs = np.array([-1, 1, -1, 2]).astype(np.intp) + vals = np.array([1, 5, 2, 10], dtype=a.dtype) + + expected = a.copy() + for i, v in zip(indxs, vals): + expected[i] = ufunc(expected[i], v) + + ufunc_at = self._at(ufunc) + ufunc_at(a, indxs, vals) + np.testing.assert_array_equal(a, expected) + assert np.all(indxs == [-1, 1, -1, 2]) + + @unittest.expectedFailure + def test_ufunc_at_not_none_signature(self): + # Test ufuncs with non-trivial signature raise a TypeError + a = np.ones((2, 2, 2)) + b = np.ones((1, 2, 2)) + # matmul is a gufunc, thus, this will fail atm + matmul_at = self._at(np.matmul) + err_msg = 'does not support ufunc with non-trivial signature' + with self.assertRaisesRegex(TypingError, err_msg): + matmul_at(a, [0], b) + + # a = np.array([[[1, 2], [3, 4]]]) + # assert_raises(TypeError, np.linalg._umath_linalg.det.at, a, [0]) + + def test_ufunc_at_no_loop_for_op(self): + # str dtype does not have a ufunc loop for np.add + arr = np.ones(10, dtype=str) + add_at = self._at(np.add) + # NumPy raises `np.core._exceptions._UFuncNoLoopError` + with self.assertRaises(TypingError): + add_at(arr, [0, 1], [0, 1]) + + def test_ufunc_at_output_casting(self): + arr = np.array([-1]) + equal_at = self._at(np.equal) + equal_at(arr, [0], [0]) + assert arr[0] == 0 + + def test_ufunc_at_broadcast_failure(self): + arr = np.arange(5) + add_at = self._at(np.add) + + # NumPy raises ValueError('array is not broadcastable to correct shape') + msg = 'operands could not be broadcast together with remapped shapes' + with self.assertRaisesRegex(ValueError, msg): + add_at(arr, [0, 1], [1, 2, 3]) + + def test_ufunc_at_dynamic(self): + arr = np.arange(5) + + @vectorize + def inc(x): + return x + 1 + + self.assertEqual(len(inc.types), 0) + + # trying to call inc.at should trigger compilation + inc.at(arr, [1, 3]) + + self.assertGreater(len(inc.types), 0) + + def test_ufunc_at_experimental_warning(self): + arr = np.arange(5) + add_at = self._at(np.add) + + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always', NumbaExperimentalFeatureWarning) + + add_at(arr, [0, 3], 10) + + self.assertGreater(len(w), 0) + self.assertIn('ufunc.at feature is experimental', str(w[0].message)) + + +class TestDUFuncReduceNumPyTests(TestCase): + # Tests taken from + # https://github.com/numpy/numpy/blob/51ee17b6bd4ccec60a5483ee8bff94ad0c0e8585/numpy/_core/tests/test_ufunc.py # noqa: E501 + + def _generate_jit(self, ufunc, identity=None): + if ufunc.nin == 2: + vec = vectorize(identity=identity)(lambda a, b: ufunc(a, b)) + else: + vec = vectorize(identity=identity)(lambda a: ufunc(a)) + + @njit + def fn(array, axis=0, initial=None): + return vec.reduce(array, axis=axis, initial=initial) + return fn + + @unittest.expectedFailure + def test_numpy_scalar_reduction(self): + # scalar reduction is not supported + power_reduce = self._generate_jit(np.power) + expected = np.power.reduce(3) + got = power_reduce(3) + self.assertPreciseEqual(expected, got) + + def check_identityless_reduction(self, a): + def compare_output(a, b): + # We don't use self.assertPreciseEqual as the dtype differs + # between the value from the reduction and the hardcoded output + np.testing.assert_equal(a, b) + # test taken from: + # https://github.com/numpy/numpy/blob/51ee17b6bd4ccec60a5483ee8bff94ad0c0e8585/numpy/_core/tests/test_ufunc.py#L1591 # noqa: E501 + + minimum_reduce = self._generate_jit(np.minimum, identity='reorderable') + + # np.minimum.reduce is an identityless reduction + + # Verify that it sees the zero at various positions + a[...] = 1 + a[1, 0, 0] = 0 + compare_output(minimum_reduce(a, axis=None), 0) + compare_output(minimum_reduce(a, axis=(0, 1)), [0, 1, 1, 1]) + compare_output(minimum_reduce(a, axis=(0, 2)), [0, 1, 1]) + compare_output(minimum_reduce(a, axis=(1, 2)), [1, 0]) + compare_output(minimum_reduce(a, axis=0), + [[0, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]) + compare_output(minimum_reduce(a, axis=1), + [[1, 1, 1, 1], [0, 1, 1, 1]]) + compare_output(minimum_reduce(a, axis=2), + [[1, 1, 1], [0, 1, 1]]) + compare_output(minimum_reduce(a, axis=()), a) + + a[...] = 1 + a[0, 1, 0] = 0 + compare_output(minimum_reduce(a, axis=None), 0) + compare_output(minimum_reduce(a, axis=(0, 1)), [0, 1, 1, 1]) + compare_output(minimum_reduce(a, axis=(0, 2)), [1, 0, 1]) + compare_output(minimum_reduce(a, axis=(1, 2)), [0, 1]) + compare_output(minimum_reduce(a, axis=0), + [[1, 1, 1, 1], [0, 1, 1, 1], [1, 1, 1, 1]]) + compare_output(minimum_reduce(a, axis=1), + [[0, 1, 1, 1], [1, 1, 1, 1]]) + compare_output(minimum_reduce(a, axis=2), + [[1, 0, 1], [1, 1, 1]]) + compare_output(minimum_reduce(a, axis=()), a) + + a[...] = 1 + a[0, 0, 1] = 0 + compare_output(minimum_reduce(a, axis=None), 0) + compare_output(minimum_reduce(a, axis=(0, 1)), [1, 0, 1, 1]) + compare_output(minimum_reduce(a, axis=(0, 2)), [0, 1, 1]) + compare_output(minimum_reduce(a, axis=(1, 2)), [0, 1]) + compare_output(minimum_reduce(a, axis=0), + [[1, 0, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]) + compare_output(minimum_reduce(a, axis=1), + [[1, 0, 1, 1], [1, 1, 1, 1]]) + compare_output(minimum_reduce(a, axis=2), + [[0, 1, 1], [1, 1, 1]]) + compare_output(minimum_reduce(a, axis=()), a) + + def test_numpy_identityless_reduction_corder(self): + a = np.empty((2, 3, 4), order='C') + self.check_identityless_reduction(a) + + def test_numpy_identityless_reduction_forder(self): + a = np.empty((2, 3, 4), order='F') + self.check_identityless_reduction(a) + + def test_numpy_identityless_reduction_otherorder(self): + a = np.empty((2, 4, 3), order='C').swapaxes(1, 2) + self.check_identityless_reduction(a) + + def test_numpy_identityless_reduction_noncontig(self): + a = np.empty((3, 5, 4), order='C').swapaxes(1, 2) + a = a[1:, 1:, 1:] + self.check_identityless_reduction(a) + + def test_numpy_identityless_reduction_noncontig_unaligned(self): + a = np.empty((3 * 4 * 5 * 8 + 1,), dtype='i1') + a = a[1:].view(dtype='f8') + a = a.reshape((3, 4, 5)) + a = a[1:, 1:, 1:] + self.check_identityless_reduction(a) + + def test_numpy_initial_reduction(self): + # np.minimum.reduce is an identityless reduction + add_reduce = self._generate_jit(np.add) + min_reduce = self._generate_jit(np.minimum) + max_reduce = self._generate_jit(np.maximum) + + # For cases like np.maximum(np.abs(...), initial=0) + # More generally, a supremum over non-negative numbers. + self.assertPreciseEqual(max_reduce(np.asarray([]), initial=0), 0.0) + + # For cases like reduction of an empty array over the reals. + self.assertPreciseEqual(min_reduce(np.asarray([]), initial=np.inf), + np.inf) + self.assertPreciseEqual(max_reduce(np.asarray([]), initial=-np.inf), + -np.inf) + + # Random tests + self.assertPreciseEqual(min_reduce(np.asarray([5]), initial=4), 4) + self.assertPreciseEqual(max_reduce(np.asarray([4]), initial=5), 5) + self.assertPreciseEqual(max_reduce(np.asarray([5]), initial=4), 5) + self.assertPreciseEqual(min_reduce(np.asarray([4]), initial=5), 4) + + # Check initial=None raises ValueError for both types of ufunc + # reductions + msg = 'zero-size array to reduction operation' + for func in (add_reduce, min_reduce): + with self.assertRaisesRegex(ValueError, msg): + func(np.asarray([]), initial=None) + + def test_numpy_empty_reduction_and_identity(self): + arr = np.zeros((0, 5)) + true_divide_reduce = self._generate_jit(np.true_divide) + + # OK, since the reduction itself is *not* empty, the result is + expected = np.true_divide.reduce(arr, axis=1) + got = true_divide_reduce(arr, axis=1) + self.assertPreciseEqual(expected, got) + self.assertPreciseEqual(got.shape, (0,)) + + # Not OK, the reduction itself is empty and we have no identity + msg = 'zero-size array to reduction operation' + with self.assertRaisesRegex(ValueError, msg): + true_divide_reduce(arr, axis=0) + + # Test that an empty reduction fails also if the result is empty + arr = np.zeros((0, 0, 5)) + with self.assertRaisesRegex(ValueError, msg): + true_divide_reduce(arr, axis=1) + + # Division reduction makes sense with `initial=1` (empty or not): + expected = np.true_divide.reduce(arr, axis=1, initial=1) + got = true_divide_reduce(arr, axis=1, initial=1) + self.assertPreciseEqual(expected, got) + + def test_identityless_reduction_nonreorderable(self): + a = np.array([[8.0, 2.0, 2.0], [1.0, 0.5, 0.25]]) + + divide_reduce = self._generate_jit(np.divide) + res = divide_reduce(a, axis=0) + self.assertPreciseEqual(res, np.asarray([8.0, 4.0, 8.0])) + + res = divide_reduce(a, axis=1) + self.assertPreciseEqual(res, np.asarray([2.0, 8.0])) + + res = divide_reduce(a, axis=()) + self.assertPreciseEqual(res, a) + + # will not raise as per Numba issue #9283 + # assert_raises(ValueError, np.divide.reduce, a, axis=(0, 1)) + + def test_reduce_zero_axis(self): + # If we have a n x m array and do a reduction with axis=1, then we are + # doing n reductions, and each reduction takes an m-element array. For + # a reduction operation without an identity, then: + # n > 0, m > 0: fine + # n = 0, m > 0: fine, doing 0 reductions of m-element arrays + # n > 0, m = 0: can't reduce a 0-element array, ValueError + # n = 0, m = 0: can't reduce a 0-element array, ValueError (for + # consistency with the above case) + # This test doesn't actually look at return values, it just checks to + # make sure that error we get an error in exactly those cases where we + # expect one, and assumes the calculations themselves are done + # correctly. + + def ok(f, *args, **kwargs): + f(*args, **kwargs) + + def err(f, *args, **kwargs): + with self.assertRaises(ValueError): + f(*args, **kwargs) + + def t(expect, func, n, m): + expect(func, np.zeros((n, m)), axis=1) + expect(func, np.zeros((m, n)), axis=0) + expect(func, np.zeros((n // 2, n // 2, m)), axis=2) + expect(func, np.zeros((n // 2, m, n // 2)), axis=1) + expect(func, np.zeros((n, m // 2, m // 2)), axis=(1, 2)) + expect(func, np.zeros((m // 2, n, m // 2)), axis=(0, 2)) + expect(func, np.zeros((m // 3, m // 3, m // 3, + n // 2, n // 2)), axis=(0, 1, 2)) + # Check what happens if the inner (resp. outer) dimensions are a + # mix of zero and non-zero: + expect(func, np.zeros((10, m, n)), axis=(0, 1)) + expect(func, np.zeros((10, n, m)), axis=(0, 2)) + expect(func, np.zeros((m, 10, n)), axis=0) + expect(func, np.zeros((10, m, n)), axis=1) + expect(func, np.zeros((10, n, m)), axis=2) + + # np.maximum is just an arbitrary ufunc with no reduction identity + maximum_reduce = self._generate_jit(np.maximum, identity='reorderable') + self.assertEqual(np.maximum.identity, None) + t(ok, maximum_reduce, 30, 30) + t(ok, maximum_reduce, 0, 30) + t(err, maximum_reduce, 30, 0) + t(err, maximum_reduce, 0, 0) + err(maximum_reduce, []) + maximum_reduce(np.zeros((0, 0)), axis=()) + + # all of the combinations are fine for a reduction that has an + # identity + add_reduce = self._generate_jit(np.add, identity=0) + t(ok, add_reduce, 30, 30) + t(ok, add_reduce, 0, 30) + t(ok, add_reduce, 30, 0) + t(ok, add_reduce, 0, 0) + add_reduce(np.array([], dtype=np.int64)) + add_reduce(np.zeros((0, 0)), axis=()) + + +class TestDUFuncReduce(TestDUFuncMethodsBase): + def _check_reduce(self, ufunc, dtype=None, initial=None): + + @njit + def foo(a, axis, dtype, initial): + return ufunc.reduce(a, + axis=axis, + dtype=dtype, + initial=initial) + + inputs = [ + np.arange(5), + np.arange(4).reshape(2, 2), + np.arange(40).reshape(5, 4, 2), + ] + for array in inputs: + for axis in range(array.ndim): + expected = foo.py_func(array, axis, dtype, initial) + got = foo(array, axis, dtype, initial) + self.assertPreciseEqual(expected, got) + + def _check_reduce_axis(self, ufunc, dtype, initial=None): + + @njit + def foo(a, axis): + return ufunc.reduce(a, axis=axis, initial=initial) + + def _check(*args): + try: + expected = foo.py_func(array, axis) + except ValueError as e: + self.assertEqual(e.args[0], exc_msg) + with self.assertRaisesRegex(TypingError, exc_msg): + got = foo(array, axis) + else: + got = foo(array, axis) + self.assertPreciseEqual(expected, got) + + exc_msg = (f"reduction operation '{ufunc.__name__}' is not " + "reorderable, so at most one axis may be specified") + inputs = [ + np.arange(40, dtype=dtype).reshape(5, 4, 2), + np.arange(10, dtype=dtype), + ] + for array in inputs: + for i in range(1, array.ndim + 1): + for axis in itertools.combinations(range(array.ndim), r=i): + _check(array, axis) + + # corner cases: Reduce over axis=() and axis=None + for axis in ((), None): + _check(array, axis) + + def test_add_reduce(self): + duadd = vectorize('int64(int64, int64)', identity=0)(pyuadd) + self._check_reduce(duadd) + self._check_reduce_axis(duadd, dtype=np.int64) + + def test_mul_reduce(self): + dumul = vectorize('int64(int64, int64)', identity=1)(pymult) + self._check_reduce(dumul) + + def test_non_associative_reduce(self): + dusub = vectorize('int64(int64, int64)', identity=None)(pysub) + dudiv = vectorize('int64(int64, int64)', identity=None)(pydiv) + self._check_reduce(dusub) + self._check_reduce_axis(dusub, dtype=np.int64) + self._check_reduce(dudiv) + self._check_reduce_axis(dudiv, dtype=np.int64) + + def test_reduce_dtype(self): + duadd = vectorize('float64(float64, int64)', identity=0)(pyuadd) + self._check_reduce(duadd, dtype=np.float64) + + def test_min_reduce(self): + dumin = vectorize('int64(int64, int64)', identity='reorderable')(pymin) + self._check_reduce(dumin, initial=10) + self._check_reduce_axis(dumin, dtype=np.int64) + + def test_add_reduce_initial(self): + # Initial should be used as a start + duadd = vectorize('int64(int64, int64)', identity=0)(pyuadd) + self._check_reduce(duadd, dtype=np.int64, initial=100) + + def test_add_reduce_no_initial_or_identity(self): + # don't provide an initial or identity value + duadd = vectorize('int64(int64, int64)')(pyuadd) + self._check_reduce(duadd, dtype=np.int64) + + def test_invalid_input(self): + duadd = vectorize('float64(float64, int64)', identity=0)(pyuadd) + + @njit + def foo(a): + return duadd.reduce(a) + + exc_msg = 'The first argument "array" must be array-like' + with self.assertRaisesRegex(TypingError, exc_msg): + foo('a') + + def test_dufunc_negative_axis(self): + duadd = vectorize('int64(int64, int64)', identity=0)(pyuadd) + + @njit + def foo(a, axis): + return duadd.reduce(a, axis=axis) + + a = np.arange(40).reshape(5, 4, 2) + cases = (0, -1, (0, -1), (-1, -2), (1, -1), -3) + for axis in cases: + expected = duadd.reduce(a, axis) + got = foo(a, axis) + self.assertPreciseEqual(expected, got) + + def test_dufunc_invalid_axis(self): + duadd = vectorize('int64(int64, int64)', identity=0)(pyuadd) + + @njit + def foo(a, axis): + return duadd.reduce(a, axis=axis) + + a = np.arange(40).reshape(5, 4, 2) + cases = ((0, 0), (0, 1, 0), (0, -3), (-1, -1), (-1, 2)) + for axis in cases: + msg = "duplicate value in 'axis'" + with self.assertRaisesRegex(ValueError, msg): + foo(a, axis) + + cases = (-4, 3, (0, -4),) + for axis in cases: + with self.assertRaisesRegex(ValueError, "Invalid axis"): + foo(a, axis) + + +class TestDUFuncReduceAt(TestDUFuncMethodsBase): + def _compare_output(self, ufunc, a, idx, **kwargs): + identity = getattr(ufunc, 'identity') + fn = self._reduceat(ufunc, identity) + expected = a.copy() + got = a.copy() + ufunc.reduceat(expected, idx, **kwargs) + fn(got, idx, **kwargs) + self.assertPreciseEqual(expected, got) + + def test_reduceat_out_kw(self): + arr = np.arange(4) + idx = np.asarray([0, 3, 1, 2]) + add_reduce = self._reduceat(np.add, 0) + add_reduce(arr, idx, out=arr) + self.assertPreciseEqual(np.asarray([3, 3, 3, 6]), arr) + add_reduce(arr, idx, out=arr) + self.assertPreciseEqual(np.asarray([9, 6, 6, 12]), arr) + + @unittest.expectedFailure + def test_reduceat_axis_kw(self): + arrays = ( + np.arange(16).reshape(4, 4), + np.arange(40).reshape(4, 5, 2), + np.ones((4, 4)) + ) + indices = ( + np.asarray([0, 3, 1, 2, 0]), + np.asarray([0, 3, 1, 2]), + ) + axis = (1, 0, -1) # needs gh-9296 + for array in arrays: + for idx in indices: + for ax in axis: + self._compare_output(np.add, array, idx, axis=ax) + + def test_reduceat_invalid_axis(self): + arr = np.ones((4, 4)) + idx = np.asarray([0, 3, 1, 2]) + add_reduceat = self._reduceat(np.add, 0) + + for ax in (2, -3): # needs gh-9296 + msg = (f'axis {ax} is out of bounds for array of dimension ' + f'{arr.ndim}') + with self.assertRaisesRegex(ValueError, msg): + add_reduceat(arr, idx, ax) + + def test_reduceat_cast_args_to_array(self): + add_reduceat = self._reduceat(np.add, 0) + + # cast array and indices + a = [1, 2, 3, 4] + idx = [1, 2, 3] + expected = np.add.reduceat(a, idx) + got = add_reduceat(a, idx) + self.assertPreciseEqual(expected, got) + + # array and indices as tuples + a = (1, 2, 3, 4) + idx = (1, 2, 3) + expected = np.add.reduceat(a, idx) + got = add_reduceat(a, idx) + self.assertPreciseEqual(expected, got) + + # tests below this line were copied from NumPy + # https://github.com/numpy/numpy/blob/7f8dc13b9bcaa26cb378b9c8246110ca1dc9ce75/numpy/_core/tests/test_ufunc.py#L200C1-L200C1 # noqa: E501 + def test_reduceat_basic(self): + x = np.arange(8) + idx = [0,4, 1,5, 2,6, 3,7] + self._compare_output(np.add, x, idx) + + def test_reduceat_basic_2d(self): + x = np.linspace(0, 15, 16).reshape(4, 4) + idx = [0, 3, 1, 2, 0] + self._compare_output(np.add, x, idx) + + def test_reduceat_shifting_sum(self): + L = 6 + x = np.arange(L) + idx = np.array(list(zip(np.arange(L - 2), np.arange(L - 2) + 2))).ravel() # noqa: E501 + self._compare_output(np.add, x, idx) + + def test_reduceat_int_array_reduceat_inplace(self): + # Checks that in-place reduceats work, see also gh-7465 + arr = np.ones(4, dtype=np.int64) + out = np.ones(4, dtype=np.int64) + self._compare_output(np.add, arr, np.arange(4), out=arr) + self._compare_output(np.add, arr, np.arange(4), out=arr) + self.assertPreciseEqual(arr, out) + + # needs gh-9296 + # And the same if the axis argument is used + arr = np.ones((2, 4), dtype=np.int64) + arr[0, :] = [2 for i in range(4)] + out = np.ones((2, 4), dtype=np.int64) + out[0, :] = [2 for i in range(4)] + self._compare_output(np.add, arr, np.arange(4), out=arr, axis=-1) + self._compare_output(np.add, arr, np.arange(4), out=arr, axis=-1) + self.assertPreciseEqual(arr, out) + + def test_reduceat_out_shape_mismatch(self): + # Should raise an error mentioning "shape" or "size" + # original test has an extra step for accumulate but we don't support + # it yet + add_reduceat = self._reduceat(np.add, 0) + + for with_cast in (True, False): + arr = np.arange(5) + out = np.arange(3) # definitely wrong shape + if with_cast: + # If a cast is necessary on the output, we can be sure to use + # the generic NpyIter (non-fast) path. + out = out.astype(np.float64) + + with self.assertRaises(ValueError): + add_reduceat(arr, [0, 3], out=out) + + def test_reduceat_empty(self): + """Reduceat should work with empty arrays""" + indices = np.array([], 'i4') + x = np.array([], 'f8') + add_reduceat = self._reduceat(np.add, 0) + expected = np.add.reduceat(x, indices) + got = add_reduceat(x, indices) + self.assertPreciseEqual(expected, got) + self.assertEqual(expected.dtype, got.dtype) + + # Another case with a slightly different zero-sized shape + x = np.ones((5, 2)) + idx = np.asarray([], dtype=np.intp) + self._compare_output(np.add, x, idx, axis=0) + self._compare_output(np.add, x, idx, axis=1) + + def test_reduceat_error_ndim_2(self): + add_reduceat = self._reduceat(np.add, 0) + + # indices ndim > 1 + a = np.arange(5) + idx = np.arange(10).reshape(5, 2) + with self.assertRaisesRegex(TypingError, 'have at most 1 dimension'): + add_reduceat(a, idx) + + def test_reduceat_error_non_binary_function(self): + # non binary functions + @vectorize + def neg(a): + return np.negative(a) + + @njit + def neg_reduceat(a, idx): + return neg.reduceat(a, idx) + + a = np.arange(5) + msg = 'reduceat only supported for binary functions' + with self.assertRaisesRegex(TypingError, msg): + neg_reduceat(a, [0, 1, 2]) + + def test_reduceat_error_argument_types(self): + # first argument must be array-like + add_reduceat = self._reduceat(np.add, 0) + with self.assertRaisesRegex(TypingError, '"array" must be array-like'): + add_reduceat('abc', [1, 2, 3]) + + with self.assertRaisesRegex(TypingError, '"indices" must be array-like'): # noqa: E501 + add_reduceat(np.arange(5), 'abcd') + + with self.assertRaisesRegex(TypingError, 'output must be an array'): + add_reduceat(np.arange(5), [1, 2, 3], out=()) + + with self.assertRaisesRegex(TypingError, '"axis" must be an integer'): + add_reduceat(np.arange(5), [1, 2, 3], axis=(1,)) + + +class TestDUFuncPickling(MemoryLeakMixin, unittest.TestCase): + def check(self, ident, result_type): + buf = pickle.dumps(ident) + rebuilt = pickle.loads(buf) + + # Check reconstructed dufunc + r = rebuilt(123) + self.assertEqual(123, r) + self.assertIsInstance(r, result_type) + + # Try to use reconstructed dufunc in @jit + @njit + def foo(x): + return rebuilt(x) + + r = foo(321) + self.assertEqual(321, r) + self.assertIsInstance(r, result_type) + + def test_unrestricted(self): + @vectorize + def ident(x1): + return x1 + + self.check(ident, result_type=(int, np.integer)) + + def test_restricted(self): + @vectorize(["float64(float64)"]) + def ident(x1): + return x1 + + self.check(ident, result_type=float) + + +if __name__ == "__main__": + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_errors.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_errors.py new file mode 100644 index 0000000000000000000000000000000000000000..948655d22b44fc76faf4ed31ad57dd5b6b59a574 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_errors.py @@ -0,0 +1,174 @@ +import contextlib +import sys + +import numpy as np + +from numba import vectorize, guvectorize + +from numba.tests.support import (TestCase, CheckWarningsMixin, + skip_macos_fenv_errors) +import unittest + + +def sqrt(val): + if val < 0.0: + raise ValueError('Value must be positive') + return val ** 0.5 + + +def gufunc_foo(inp, n, out): + for i in range(inp.shape[0]): + if inp[i] < 0: + raise ValueError('Value must be positive') + out[i] = inp[i] * n[0] + +def truediv(a, b): + return a / b + +def floordiv(a, b): + return a // b + +def remainder(a, b): + return a % b + +def power(a, b): + return a ** b + + +class TestExceptions(TestCase): + """ + Test raising exceptions inside ufuncs. + """ + + def check_ufunc_raise(self, **vectorize_args): + f = vectorize(['float64(float64)'], **vectorize_args)(sqrt) + arr = np.array([1, 4, -2, 9, -1, 16], dtype=np.float64) + out = np.zeros_like(arr) + with self.assertRaises(ValueError) as cm: + f(arr, out) + self.assertIn('Value must be positive', str(cm.exception)) + # All values were computed except for the ones giving an error + self.assertEqual(list(out), [1, 2, 0, 3, 0, 4]) + + def test_ufunc_raise(self): + self.check_ufunc_raise(nopython=True) + + def test_ufunc_raise_objmode(self): + self.check_ufunc_raise(forceobj=True) + + def check_gufunc_raise(self, **vectorize_args): + f = guvectorize(['int32[:], int32[:], int32[:]'], '(n),()->(n)', + **vectorize_args)(gufunc_foo) + arr = np.array([1, 2, -3, 4], dtype=np.int32) + out = np.zeros_like(arr) + with self.assertRaises(ValueError) as cm: + f(arr, 2, out) + # The gufunc bailed out after the error + self.assertEqual(list(out), [2, 4, 0, 0]) + + def test_gufunc_raise(self): + self.check_gufunc_raise(nopython=True) + + def test_gufunc_raise_objmode(self): + self.check_gufunc_raise(forceobj=True) + +class TestFloatingPointExceptions(TestCase, CheckWarningsMixin): + """ + Test floating-point exceptions inside ufuncs. + + Note the warnings emitted by Numpy reflect IEEE-754 semantics. + """ + + def check_truediv_real(self, dtype): + """ + Test 1 / 0 and 0 / 0. + """ + f = vectorize(nopython=True)(truediv) + a = np.array([5., 6., 0., 8.], dtype=dtype) + b = np.array([1., 0., 0., 4.], dtype=dtype) + expected = np.array([5., float('inf'), float('nan'), 2.]) + with self.check_warnings(["divide by zero encountered", + "invalid value encountered"]): + res = f(a, b) + self.assertPreciseEqual(res, expected) + + def test_truediv_float(self): + self.check_truediv_real(np.float64) + + def test_truediv_integer(self): + self.check_truediv_real(np.int32) + + def check_divmod_float(self, pyfunc, values, messages): + """ + Test 1 // 0 and 0 // 0. + """ + f = vectorize(nopython=True)(pyfunc) + a = np.array([5., 6., 0., 9.]) + b = np.array([1., 0., 0., 4.]) + expected = np.array(values) + with self.check_warnings(messages): + res = f(a, b) + self.assertPreciseEqual(res, expected) + + def test_floordiv_float(self): + self.check_divmod_float(floordiv, + [5.0, float('inf'), float('nan'), 2.0], + ["divide by zero encountered", + "invalid value encountered"]) + + @skip_macos_fenv_errors + def test_remainder_float(self): + self.check_divmod_float(remainder, + [0.0, float('nan'), float('nan'), 1.0], + ["invalid value encountered"]) + + def check_divmod_int(self, pyfunc, values): + """ + Test 1 % 0 and 0 % 0. + """ + f = vectorize(nopython=True)(pyfunc) + a = np.array([5, 6, 0, 9]) + b = np.array([1, 0, 0, 4]) + expected = np.array(values) + # No warnings raised because LLVM makes it difficult + with self.check_warnings([]): + res = f(a, b) + self.assertPreciseEqual(res, expected) + + def test_floordiv_int(self): + self.check_divmod_int(floordiv, [5, 0, 0, 2]) + + def test_remainder_int(self): + self.check_divmod_int(remainder, [0, 0, 0, 1]) + + def test_power_float(self): + """ + Test 0 ** -1 and 2 ** . + """ + f = vectorize(nopython=True)(power) + a = np.array([5., 0., 2., 8.]) + b = np.array([1., -1., 1e20, 4.]) + expected = np.array([5., float('inf'), float('inf'), 4096.]) + with self.check_warnings(["divide by zero encountered", + "overflow encountered"]): + res = f(a, b) + self.assertPreciseEqual(res, expected) + + def test_power_integer(self): + """ + Test 0 ** -1. + Note 2 ** returns an undefined value (depending + on the algorithm). + """ + dtype = np.int64 + f = vectorize(["int64(int64, int64)"], nopython=True)(power) + a = np.array([5, 0, 6], dtype=dtype) + b = np.array([1, -1, 2], dtype=dtype) + expected = np.array([5, -2**63, 36], dtype=dtype) + with self.check_warnings([]): + res = f(a, b) + self.assertPreciseEqual(res, expected) + + +if __name__ == "__main__": + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_gufunc.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_gufunc.py new file mode 100644 index 0000000000000000000000000000000000000000..76b21ca25003905a23cd36654cb795f1b95b218e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_gufunc.py @@ -0,0 +1,870 @@ +import unittest +import pickle + +import numpy as np + +from numba import void, float32, float64, int32, int64, jit, guvectorize +from numba.core.errors import TypingError +from numba.np.ufunc import GUVectorize +from numba.tests.support import TestCase, MemoryLeakMixin + + +def matmulcore(A, B, C): + """docstring for matmulcore""" + m, n = A.shape + n, p = B.shape + for i in range(m): + for j in range(p): + C[i, j] = 0 + for k in range(n): + C[i, j] += A[i, k] * B[k, j] + + +def axpy(a, x, y, out): + out[0] = a * x + y + + +class TestGUFunc(MemoryLeakMixin, TestCase): + target = 'cpu' + + def check_matmul_gufunc(self, gufunc): + matrix_ct = 1001 + A = np.arange(matrix_ct * 2 * 4, dtype=np.float32).reshape(matrix_ct, 2, 4) + B = np.arange(matrix_ct * 4 * 5, dtype=np.float32).reshape(matrix_ct, 4, 5) + + C = gufunc(A, B) + Gold = np.matmul(A, B) + + np.testing.assert_allclose(C, Gold, rtol=1e-5, atol=1e-8) + + def test_gufunc(self): + gufunc = GUVectorize(matmulcore, '(m,n),(n,p)->(m,p)', + target=self.target) + gufunc.add((float32[:, :], float32[:, :], float32[:, :])) + gufunc = gufunc.build_ufunc() + + self.check_matmul_gufunc(gufunc) + + def test_guvectorize_decor(self): + gufunc = guvectorize([void(float32[:,:], float32[:,:], float32[:,:])], + '(m,n),(n,p)->(m,p)', + target=self.target)(matmulcore) + + self.check_matmul_gufunc(gufunc) + + def test_ufunc_like(self): + # Test problem that the stride of "scalar" gufunc argument not properly + # handled when the actual argument is an array, + # causing the same value (first value) being repeated. + gufunc = GUVectorize(axpy, '(), (), () -> ()', target=self.target) + gufunc.add('(intp, intp, intp, intp[:])') + gufunc = gufunc.build_ufunc() + + x = np.arange(10, dtype=np.intp) + out = gufunc(x, x, x) + + np.testing.assert_equal(out, x * x + x) + + def test_axis(self): + # issue https://github.com/numba/numba/issues/6773 + @guvectorize(["f8[:],f8[:]"], "(n)->(n)") + def my_cumsum(x, res): + acc = 0 + for i in range(x.shape[0]): + acc += x[i] + res[i] = acc + + x = np.ones((20, 30)) + # Check regular call + y = my_cumsum(x, axis=0) + expected = np.cumsum(x, axis=0) + np.testing.assert_equal(y, expected) + # Check "out" kw + out_kw = np.zeros_like(y) + my_cumsum(x, out=out_kw, axis=0) + np.testing.assert_equal(out_kw, expected) + + def test_docstring(self): + @guvectorize([(int64[:], int64, int64[:])], '(n),()->(n)') + def gufunc(x, y, res): + "docstring for gufunc" + for i in range(x.shape[0]): + res[i] = x[i] + y + + self.assertEqual("numba.tests.npyufunc.test_gufunc", gufunc.__module__) + self.assertEqual("gufunc", gufunc.__name__) + self.assertEqual("TestGUFunc.test_docstring..gufunc", gufunc.__qualname__) + self.assertEqual("docstring for gufunc", gufunc.__doc__) + + +class TestMultipleOutputs(MemoryLeakMixin, TestCase): + target = 'cpu' + + def test_multiple_outputs_same_type_passed_in(self): + @guvectorize('(x)->(x),(x)', + target=self.target) + def copy(A, B, C): + for i in range(B.size): + B[i] = A[i] + C[i] = A[i] + + A = np.arange(10, dtype=np.float32) + 1 + B = np.zeros_like(A) + C = np.zeros_like(A) + copy(A, B, C) + np.testing.assert_allclose(A, B) + np.testing.assert_allclose(A, C) + + def test_multiple_outputs_distinct_values(self): + + @guvectorize('(x)->(x),(x)', + target=self.target) + def copy_and_double(A, B, C): + for i in range(B.size): + B[i] = A[i] + C[i] = A[i] * 2 + + A = np.arange(10, dtype=np.float32) + 1 + B = np.zeros_like(A) + C = np.zeros_like(A) + copy_and_double(A, B, C) + np.testing.assert_allclose(A, B) + np.testing.assert_allclose(A * 2, C) + + def test_multiple_output_dtypes(self): + + @guvectorize('(x)->(x),(x)', + target=self.target) + def copy_and_multiply(A, B, C): + for i in range(B.size): + B[i] = A[i] + C[i] = A[i] * 1.5 + + A = np.arange(10, dtype=np.int32) + 1 + B = np.zeros_like(A) + C = np.zeros_like(A, dtype=np.float64) + copy_and_multiply(A, B, C) + np.testing.assert_allclose(A, B) + np.testing.assert_allclose(A * np.float64(1.5), C) + + def test_incorrect_number_of_pos_args(self): + @guvectorize('(m),(m)->(m),(m)', target=self.target) + def f(x, y, z, w): + pass + + arr = np.arange(5, dtype=np.int32) + + # Inputs only, too few + msg = "Too few arguments for function 'f'" + with self.assertRaises(TypeError) as te: + f(arr) + self.assertIn(msg, str(te.exception)) + + # Inputs and outputs, too many + with self.assertRaises(TypeError) as te: + f(arr, arr, arr, arr, arr) + self.assertIn(msg, str(te.exception)) + + +class TestGUFuncParallel(TestGUFunc): + _numba_parallel_test_ = False + target = 'parallel' + + +class TestDynamicGUFunc(MemoryLeakMixin, TestCase): + target = 'cpu' + + def test_dynamic_matmul(self): + + def check_matmul_gufunc(gufunc, A, B, C): + Gold = np.matmul(A, B) + gufunc(A, B, C) + np.testing.assert_allclose(C, Gold, rtol=1e-5, atol=1e-8) + + gufunc = GUVectorize(matmulcore, '(m,n),(n,p)->(m,p)', + target=self.target, is_dynamic=True) + matrix_ct = 10 + Ai64 = np.arange(matrix_ct * 2 * 4, dtype=np.int64).reshape(matrix_ct, 2, 4) + Bi64 = np.arange(matrix_ct * 4 * 5, dtype=np.int64).reshape(matrix_ct, 4, 5) + Ci64 = np.arange(matrix_ct * 2 * 5, dtype=np.int64).reshape(matrix_ct, 2, 5) + check_matmul_gufunc(gufunc, Ai64, Bi64, Ci64) + + A = np.arange(matrix_ct * 2 * 4, dtype=np.float32).reshape(matrix_ct, 2, 4) + B = np.arange(matrix_ct * 4 * 5, dtype=np.float32).reshape(matrix_ct, 4, 5) + C = np.arange(matrix_ct * 2 * 5, dtype=np.float32).reshape(matrix_ct, 2, 5) + check_matmul_gufunc(gufunc, A, B, C) # trigger compilation + + self.assertEqual(len(gufunc.types), 2) # ensure two versions of gufunc + + + def test_dynamic_ufunc_like(self): + + def check_ufunc_output(gufunc, x): + out = np.zeros(10, dtype=x.dtype) + out_kw = np.zeros(10, dtype=x.dtype) + gufunc(x, x, x, out) + gufunc(x, x, x, out=out_kw) + golden = x * x + x + np.testing.assert_equal(out, golden) + np.testing.assert_equal(out_kw, golden) + + # Test problem that the stride of "scalar" gufunc argument not properly + # handled when the actual argument is an array, + # causing the same value (first value) being repeated. + gufunc = GUVectorize(axpy, '(), (), () -> ()', target=self.target, + is_dynamic=True) + x = np.arange(10, dtype=np.intp) + check_ufunc_output(gufunc, x) + + + def test_dynamic_scalar_output(self): + """ + Note that scalar output is a 0-dimension array that acts as + a pointer to the output location. + """ + + @guvectorize('(n)->()', target=self.target, nopython=True) + def sum_row(inp, out): + tmp = 0. + for i in range(inp.shape[0]): + tmp += inp[i] + out[()] = tmp + + # inp is (10000, 3) + # out is (10000) + # The outer (leftmost) dimension must match or numpy broadcasting is performed. + + self.assertTrue(sum_row.is_dynamic) + inp = np.arange(30000, dtype=np.int32).reshape(10000, 3) + out = np.zeros(10000, dtype=np.int32) + sum_row(inp, out) + + # verify result + for i in range(inp.shape[0]): + self.assertEqual(out[i], inp[i].sum()) + + msg = "Too few arguments for function 'sum_row'." + with self.assertRaisesRegex(TypeError, msg): + sum_row(inp) + + def test_axis(self): + # issue https://github.com/numba/numba/issues/6773 + @guvectorize("(n)->(n)") + def my_cumsum(x, res): + acc = 0 + for i in range(x.shape[0]): + acc += x[i] + res[i] = acc + + x = np.ones((20, 30)) + expected = np.cumsum(x, axis=0) + # Check regular call + y = np.zeros_like(expected) + my_cumsum(x, y, axis=0) + np.testing.assert_equal(y, expected) + # Check "out" kw + out_kw = np.zeros_like(y) + my_cumsum(x, out=out_kw, axis=0) + np.testing.assert_equal(out_kw, expected) + + def test_gufunc_attributes(self): + @guvectorize("(n)->(n)") + def gufunc(x, res): + acc = 0 + for i in range(x.shape[0]): + acc += x[i] + res[i] = acc + + # ensure gufunc exports attributes + attrs = ['signature', 'accumulate', 'at', 'outer', 'reduce', 'reduceat'] + for attr in attrs: + contains = hasattr(gufunc, attr) + self.assertTrue(contains, 'dynamic gufunc not exporting "%s"' % (attr,)) + + a = np.array([1, 2, 3, 4]) + res = np.array([0, 0, 0, 0]) + gufunc(a, res) # trigger compilation + self.assertPreciseEqual(res, np.array([1, 3, 6, 10])) + + # other attributes are not callable from a gufunc with signature + # see: https://github.com/numba/numba/issues/2794 + # note: this is a limitation in NumPy source code! + self.assertEqual(gufunc.signature, "(n)->(n)") + + with self.assertRaises(RuntimeError) as raises: + gufunc.accumulate(a) + self.assertEqual(str(raises.exception), "Reduction not defined on ufunc with signature") + + with self.assertRaises(RuntimeError) as raises: + gufunc.reduce(a) + self.assertEqual(str(raises.exception), "Reduction not defined on ufunc with signature") + + with self.assertRaises(RuntimeError) as raises: + gufunc.reduceat(a, [0, 2]) + self.assertEqual(str(raises.exception), "Reduction not defined on ufunc with signature") + + with self.assertRaises(TypeError) as raises: + gufunc.outer(a, a) + self.assertEqual(str(raises.exception), "method outer is not allowed in ufunc with non-trivial signature") + + def test_gufunc_attributes2(self): + @guvectorize('(),()->()') + def add(x, y, res): + res[0] = x + y + + # add signature "(),() -> ()" is evaluated to None + self.assertIsNone(add.signature) + + a = np.array([1, 2, 3, 4]) + b = np.array([4, 3, 2, 1]) + res = np.array([0, 0, 0, 0]) + add(a, b, res) # trigger compilation + self.assertPreciseEqual(res, np.array([5, 5, 5, 5])) + + # now test other attributes + self.assertIsNone(add.signature) + self.assertEqual(add.reduce(a), 10) + self.assertPreciseEqual(add.accumulate(a), np.array([1, 3, 6, 10])) + self.assertPreciseEqual(add.outer([0, 1], [1, 2]), np.array([[1, 2], [2, 3]])) + self.assertPreciseEqual(add.reduceat(a, [0, 2]), np.array([3, 7])) + + x = np.array([1, 2, 3, 4]) + y = np.array([1, 2]) + add.at(x, [0, 1], y) + self.assertPreciseEqual(x, np.array([2, 4, 3, 4])) + + +class TestGUVectorizeScalar(MemoryLeakMixin, TestCase): + """ + Nothing keeps user from out-of-bound memory access + """ + target = 'cpu' + + def test_scalar_output(self): + """ + Note that scalar output is a 0-dimension array that acts as + a pointer to the output location. + """ + + @guvectorize(['void(int32[:], int32[:])'], '(n)->()', + target=self.target, nopython=True) + def sum_row(inp, out): + tmp = 0. + for i in range(inp.shape[0]): + tmp += inp[i] + out[()] = tmp + + # inp is (10000, 3) + # out is (10000) + # The outer (leftmost) dimension must match or numpy broadcasting is performed. + + inp = np.arange(30000, dtype=np.int32).reshape(10000, 3) + out = sum_row(inp) + + # verify result + for i in range(inp.shape[0]): + self.assertEqual(out[i], inp[i].sum()) + + def test_scalar_input(self): + + @guvectorize(['int32[:], int32[:], int32[:]'], '(n),()->(n)', + target=self.target, nopython=True) + def foo(inp, n, out): + for i in range(inp.shape[0]): + out[i] = inp[i] * n[0] + + inp = np.arange(3 * 10, dtype=np.int32).reshape(10, 3) + # out = np.empty_like(inp) + out = foo(inp, 2) + + # verify result + self.assertPreciseEqual(inp * 2, out) + + def test_scalar_input_core_type(self): + def pyfunc(inp, n, out): + for i in range(inp.size): + out[i] = n * (inp[i] + 1) + + my_gufunc = guvectorize(['int32[:], int32, int32[:]'], + '(n),()->(n)', + target=self.target)(pyfunc) + + # test single core loop execution + arr = np.arange(10).astype(np.int32) + got = my_gufunc(arr, 2) + + expected = np.zeros_like(got) + pyfunc(arr, 2, expected) + + np.testing.assert_equal(got, expected) + + # test multiple core loop execution + arr = np.arange(20).astype(np.int32).reshape(10, 2) + got = my_gufunc(arr, 2) + + expected = np.zeros_like(got) + for ax in range(expected.shape[0]): + pyfunc(arr[ax], 2, expected[ax]) + + np.testing.assert_equal(got, expected) + + def test_scalar_input_core_type_error(self): + with self.assertRaises(TypeError) as raises: + @guvectorize(['int32[:], int32, int32[:]'], '(n),(n)->(n)', + target=self.target) + def pyfunc(a, b, c): + pass + self.assertEqual("scalar type int32 given for non scalar argument #2", + str(raises.exception)) + + def test_ndim_mismatch(self): + with self.assertRaises(TypeError) as raises: + @guvectorize(['int32[:], int32[:]'], '(m,n)->(n)', + target=self.target) + def pyfunc(a, b): + pass + self.assertEqual("type and shape signature mismatch for arg #1", + str(raises.exception)) + + +class TestGUVectorizeScalarParallel(TestGUVectorizeScalar): + _numba_parallel_test_ = False + target = 'parallel' + + +class TestGUVectorizePickling(MemoryLeakMixin, TestCase): + def test_pickle_gufunc_non_dyanmic(self): + """Non-dynamic gufunc. + """ + @guvectorize(["f8,f8[:]"], "()->()") + def double(x, out): + out[:] = x * 2 + + # pickle + ser = pickle.dumps(double) + cloned = pickle.loads(ser) + + # attributes carried over + self.assertEqual(cloned._frozen, double._frozen) + self.assertEqual(cloned.identity, double.identity) + self.assertEqual(cloned.is_dynamic, double.is_dynamic) + self.assertEqual(cloned.gufunc_builder._sigs, + double.gufunc_builder._sigs) + # expected value of attributes + self.assertTrue(cloned._frozen) + + cloned.disable_compile() + self.assertTrue(cloned._frozen) + + # scalar version + self.assertPreciseEqual(double(0.5), cloned(0.5)) + # array version + arr = np.arange(10) + self.assertPreciseEqual(double(arr), cloned(arr)) + + def test_pickle_gufunc_dyanmic_null_init(self): + """Dynamic gufunc w/o prepopulating before pickling. + """ + @guvectorize("()->()", identity=1) + def double(x, out): + out[:] = x * 2 + + # pickle + ser = pickle.dumps(double) + cloned = pickle.loads(ser) + + # attributes carried over + self.assertEqual(cloned._frozen, double._frozen) + self.assertEqual(cloned.identity, double.identity) + self.assertEqual(cloned.is_dynamic, double.is_dynamic) + self.assertEqual(cloned.gufunc_builder._sigs, + double.gufunc_builder._sigs) + # expected value of attributes + self.assertFalse(cloned._frozen) + + # scalar version + expect = np.zeros(1) + got = np.zeros(1) + double(0.5, out=expect) + cloned(0.5, out=got) + self.assertPreciseEqual(expect, got) + # array version + arr = np.arange(10) + expect = np.zeros_like(arr) + got = np.zeros_like(arr) + double(arr, out=expect) + cloned(arr, out=got) + self.assertPreciseEqual(expect, got) + + def test_pickle_gufunc_dynamic_initialized(self): + """Dynamic gufunc prepopulated before pickling. + + Once unpickled, we disable compilation to verify that the gufunc + compilation state is carried over. + """ + @guvectorize("()->()", identity=1) + def double(x, out): + out[:] = x * 2 + + # prepopulate scalar + expect = np.zeros(1) + got = np.zeros(1) + double(0.5, out=expect) + # prepopulate array + arr = np.arange(10) + expect = np.zeros_like(arr) + got = np.zeros_like(arr) + double(arr, out=expect) + + # pickle + ser = pickle.dumps(double) + cloned = pickle.loads(ser) + + # attributes carried over + self.assertEqual(cloned._frozen, double._frozen) + self.assertEqual(cloned.identity, double.identity) + self.assertEqual(cloned.is_dynamic, double.is_dynamic) + self.assertEqual(cloned.gufunc_builder._sigs, + double.gufunc_builder._sigs) + # expected value of attributes + self.assertFalse(cloned._frozen) + + # disable compilation + cloned.disable_compile() + self.assertTrue(cloned._frozen) + # scalar version + expect = np.zeros(1) + got = np.zeros(1) + double(0.5, out=expect) + cloned(0.5, out=got) + self.assertPreciseEqual(expect, got) + # array version + expect = np.zeros_like(arr) + got = np.zeros_like(arr) + double(arr, out=expect) + cloned(arr, out=got) + self.assertPreciseEqual(expect, got) + + +class TestGUVectorizeJit(MemoryLeakMixin, TestCase): + target = 'cpu' + + def check_add_gufunc(self, gufunc): + @jit(nopython=True) + def jit_add(x, y, res): + gufunc(x, y, res) + + x = np.arange(40, dtype='i8').reshape(4, 2, 5) + y = np.int32(100) + res = np.zeros_like(x) + jit_add(x, y, res) + self.assertPreciseEqual(res, x + y) + + def test_add_static(self): + @guvectorize('int64[:], int64, int64[:]', '(n),()->(n)', + target=self.target) + def add(x, y, res): + for i in range(x.shape[0]): + res[i] = x[i] + y + + self.check_add_gufunc(add) + + def test_add_static_cast_args(self): + # cast the second argument from i32 -> i64 + @guvectorize('int64[:], int64, int64[:]', '(n),()->(n)', + target=self.target) + def add(x, y, res): + for i in range(x.shape[0]): + res[i] = x[i] + y + + self.check_add_gufunc(add) + + def test_add_dynamic(self): + @guvectorize('(n),()->(n)', target=self.target) + def add(x, y, res): + for i in range(x.shape[0]): + res[i] = x[i] + y + + self.check_add_gufunc(add) + + @unittest.expectedFailure + def test_object_mode(self): + @guvectorize('(n),()->(n)', target=self.target, forceobj=True) + def add(x, y, res): + for i in range(x.shape[0]): + res[i] = x[i] + y + + self.check_add_gufunc(add) + + def check_matmul(self, jit_func): + matrix_ct = 1001 + A = np.arange(matrix_ct * 2 * 4, dtype=np.float32).reshape(matrix_ct, 2, 4) + B = np.arange(matrix_ct * 4 * 5, dtype=np.float32).reshape(matrix_ct, 4, 5) + C = np.arange(matrix_ct * 2 * 5, dtype=np.float32).reshape(matrix_ct, 2, 5) + + jit_func(A, B, C) + Gold = np.matmul(A, B) + + np.testing.assert_allclose(C, Gold, rtol=1e-5, atol=1e-8) + + def test_njit_matmul_call(self): + + gufunc = guvectorize('(m,n),(n,p)->(m,p)', + target=self.target)(matmulcore) + + @jit(nopython=True) + def matmul_jit(A, B, C): + return gufunc(A, B, C) + + self.check_matmul(matmul_jit) + + def test_axpy(self): + gufunc = GUVectorize(axpy, '(),(),() -> ()', target=self.target, + is_dynamic=True) + + @jit(nopython=True) + def axpy_jit(a, x, y, out): + gufunc(a, x, y, out) + + x = np.arange(10, dtype=np.intp) + out = np.zeros_like(x) + axpy_jit(x, x, x, out) + self.assertPreciseEqual(out, x * x + x) + + def test_output_scalar(self): + + @guvectorize('(n),(m) -> ()') + def gufunc(x, y, res): + res[0] = x.sum() + y.sum() + + @jit(nopython=True) + def jit_func(x, y, res): + gufunc(x, y, res) + + x = np.arange(40, dtype='i8').reshape(4, 10) + y = np.arange(20, dtype='i8') + res = np.zeros(4, dtype='i8') + jit_func(x, y, res) + expected = np.zeros_like(res) + gufunc(x, y, expected) + self.assertPreciseEqual(res, expected) + + def test_input_scalar(self): + + @guvectorize('() -> ()') + def gufunc(x, res): + res[0] = x + 100 + + @jit(nopython=True) + def jit_func(x, res): + gufunc(x, res) + + x = np.arange(40, dtype='i8').reshape(5, 2, 4) + res = np.zeros_like(x) + jit_func(x, res) + expected = np.zeros_like(res) + gufunc(x, expected) + self.assertPreciseEqual(res, expected) + + def test_gufunc_ndim_mismatch(self): + signature = "(n, m), (n, n, n) -> (m), (n, n)" + @guvectorize(signature) + def bar(x, y, res, out): + res[0] = 123 + out[0] = 456 + + @jit(nopython=True) + def foo(x, y, res, out): + bar(x, y, res, out) + + N, M = 2, 3 + x = np.arange(N**2).reshape(N, N) + y = np.arange(N**3).reshape(N, N, N) + res = np.arange(M) + out = np.arange(N**2).reshape(N, N) + + # calling with a 1d array should result in an error + with self.assertRaises(TypingError) as raises: + x_ = np.arange(N * N) + foo(x_, y, res, out) + msg = ('bar: Input operand 0 does not have enough dimensions (has ' + f'1, gufunc core with signature {signature} requires 2)') + self.assertIn(msg, str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + y_ = np.arange(N * N).reshape(N, N) + foo(x, y_, res, out) + msg = ('bar: Input operand 1 does not have enough dimensions (has ' + f'2, gufunc core with signature {signature} requires 3)') + self.assertIn(msg, str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + res_ = np.array(3) + foo(x, y, res_, out) + msg = ('bar: Output operand 0 does not have enough dimensions (has ' + f'0, gufunc core with signature {signature} requires 1)') + self.assertIn(msg, str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + out_ = np.arange(N) + foo(x, y, res, out_) + msg = ('bar: Output operand 1 does not have enough dimensions (has ' + f'1, gufunc core with signature {signature} requires 2)') + self.assertIn(msg, str(raises.exception)) + + def test_mismatch_inner_dimensions(self): + @guvectorize('(n),(n) -> ()') + def bar(x, y, res): + res[0] = 123 + + @jit(nopython=True) + def foo(x, y, res): + bar(x, y, res) + + N = 2 + M = 3 + x = np.empty((5, 3, N)) + y = np.empty((M,)) + res = np.zeros((5, 3)) + + # ensure that NumPy raises an exception + with self.assertRaises(ValueError) as np_raises: + bar(x, y, res) + msg = ('Input operand 1 has a mismatch in its core dimension 0, with ' + 'gufunc signature (n),(n) -> () (size 3 is different from 2)') + self.assertIn(msg, str(np_raises.exception)) + + with self.assertRaises(ValueError) as raises: + foo(x, y, res) + msg = ('Operand has a mismatch in one of its core dimensions') + self.assertIn(msg, str(raises.exception)) + + def test_mismatch_inner_dimensions_input_output(self): + @guvectorize('(n),(m) -> (n)') + def bar(x, y, res): + res[0] = 123 + + @jit(nopython=True) + def foo(x, y, res): + bar(x, y, res) + + N = 2 + M = 3 + x = np.empty((5, 3, N)) + y = np.empty((M,)) + res = np.zeros((5, 3)) + + # ensure that NumPy raises an exception + with self.assertRaises(ValueError) as np_raises: + bar(x, y, res) + msg = ('Output operand 0 has a mismatch in its core dimension 0, with ' + 'gufunc signature (n),(m) -> (n) (size 3 is different from 2)') + self.assertIn(msg, str(np_raises.exception)) + + with self.assertRaises(ValueError) as raises: + foo(x, y, res) + msg = ('Operand has a mismatch in one of its core dimensions') + self.assertIn(msg, str(raises.exception)) + + def test_mismatch_inner_dimensions_output(self): + @guvectorize('(n),(m) -> (m),(m)') + def bar(x, y, res, out): + res[0] = 123 + out[0] = 456 + + @jit(nopython=True) + def foo(x, y, res, out): + bar(x, y, res, out) + + N = 2 + M = 3 + x = np.empty((N,)) + y = np.empty((M,)) + res = np.zeros((N,)) + out = np.zeros((M,)) + + # ensure that NumPy raises an exception + with self.assertRaises(ValueError) as np_raises: + bar(x, y, res, out) + msg = ('Output operand 0 has a mismatch in its core dimension 0, with ' + 'gufunc signature (n),(m) -> (m),(m) (size 2 is different from 3)') + self.assertIn(msg, str(np_raises.exception)) + + with self.assertRaises(ValueError) as raises: + foo(x, y, res, out) + msg = ('Operand has a mismatch in one of its core dimensions') + self.assertIn(msg, str(raises.exception)) + + def test_mismatch_loop_shape(self): + @guvectorize('(n),(n) -> ()') + def bar(x, y, res): + res[0] = 123 + + @jit(nopython=True) + def foo(x, y, res): + bar(x, y, res) + + N = 2 + x = np.empty((1, 5, 3, N,)) + y = np.empty((5, 3, N,)) + res = np.zeros((5, 3)) + + with self.assertRaises(ValueError) as raises: + foo(x, y, res) + msg = ('Loop and array shapes are incompatible') + self.assertIn(msg, str(raises.exception)) + + def test_mismatch_loop_shape_2(self): + @guvectorize('(n),(n) -> (), (n)') + def gufunc(x, y, res, out): + res[0] = x.sum() + for i in range(x.shape[0]): + out[i] += x[i] + y.sum() + + @jit + def jit_func(x, y, res, out): + gufunc(x, y, res, out) + + N = 2 + + x = np.arange(4*N).reshape((4, N)) + y = np.arange(N) + res = np.empty((3,)) + out = np.zeros((3, N)) + + # ensure that NumPy raises an exception + with self.assertRaises(ValueError) as np_raises: + gufunc(x, y, res, out) + msg = ('operands could not be broadcast together with remapped shapes ' + '[original->remapped]: (4,2)->(4,newaxis) (2,)->() ' + '(3,)->(3,newaxis) (3,2)->(3,2) and requested shape (2)') + self.assertIn(msg, str(np_raises.exception)) + + with self.assertRaises(ValueError) as raises: + jit_func(x, y, res, out) + msg = ('Loop and array shapes are incompatible') + self.assertIn(msg, str(raises.exception)) + + def test_issue_10287(self): + @guvectorize([(float64[:], int64, float64[:])], "(n),()->(n)") + def guve(x, n, res): + pass + + + @jit + def njit_guve(x, n): + res = np.zeros_like(x) + guve(x, n, res) + return res + + + rng = np.random.default_rng(69) + + for _ in range(20000): + x = rng.random(65) + y = np.repeat(x[None], 130, axis=0) + njit_guve(y, 5) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_parallel_env_variable.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_parallel_env_variable.py new file mode 100644 index 0000000000000000000000000000000000000000..7d11692ad34250e1056121e570d4c18d86f93183 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_parallel_env_variable.py @@ -0,0 +1,38 @@ +from numba.np.ufunc.parallel import get_thread_count +from os import environ as env +from numba.core import config +import unittest + + +class TestParallelEnvVariable(unittest.TestCase): + """ + Tests environment variables related to the underlying "parallel" + functions for npyufuncs. + """ + + _numba_parallel_test_ = False + + def test_num_threads_variable(self): + """ + Tests the NUMBA_NUM_THREADS env variable behaves as expected. + """ + key = 'NUMBA_NUM_THREADS' + current = str(getattr(env, key, config.NUMBA_NUM_THREADS)) + threads = "3154" + env[key] = threads + try: + config.reload_config() + except RuntimeError as e: + # This test should fail if threads have already been launched + self.assertIn("Cannot set NUMBA_NUM_THREADS", e.args[0]) + else: + self.assertEqual(threads, str(get_thread_count())) + self.assertEqual(threads, str(config.NUMBA_NUM_THREADS)) + finally: + # reset the env variable/set to default. Should not fail even if + # threads are launched because the value is the same. + env[key] = current + config.reload_config() + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_parallel_low_work.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_parallel_low_work.py new file mode 100644 index 0000000000000000000000000000000000000000..cab4d42749f643ca1b38f74f3f6ef400661c5023 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_parallel_low_work.py @@ -0,0 +1,44 @@ +""" +There was a deadlock problem when work count is smaller than number of threads. +""" + +import numpy as np + +from numba import float32, float64, int32, uint32 +from numba.np.ufunc import Vectorize +import unittest + + +def vector_add(a, b): + return a + b + + +class TestParallelLowWorkCount(unittest.TestCase): + + _numba_parallel_test_ = False + + def test_low_workcount(self): + # build parallel native code ufunc + pv = Vectorize(vector_add, target='parallel') + for ty in (int32, uint32, float32, float64): + pv.add(ty(ty, ty)) + para_ufunc = pv.build_ufunc() + + # build python ufunc + np_ufunc = np.vectorize(vector_add) + + # test it out + def test(ty): + data = np.arange(1).astype(ty) # just one item + result = para_ufunc(data, data) + gold = np_ufunc(data, data) + np.testing.assert_allclose(gold, result) + + test(np.double) + test(np.float32) + test(np.int32) + test(np.uint32) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_parallel_ufunc_issues.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_parallel_ufunc_issues.py new file mode 100644 index 0000000000000000000000000000000000000000..5f849912153198e602d589d1cdb7b16038bfa18a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_parallel_ufunc_issues.py @@ -0,0 +1,130 @@ +import time +import ctypes + +import numpy as np + +from numba.tests.support import captured_stdout, skip_if_freethreading +from numba import vectorize, guvectorize +import unittest + + +class TestParUfuncIssues(unittest.TestCase): + + _numba_parallel_test_ = False + + def test_thread_response(self): + """ + Related to #89. + This does not test #89 but tests the fix for it. + We want to make sure the worker threads can be used multiple times + and with different time gap between each execution. + """ + + @vectorize('float64(float64, float64)', target='parallel') + def fnv(a, b): + return a + b + + sleep_time = 1 # 1 second + while sleep_time > 0.00001: # 10us + time.sleep(sleep_time) + a = b = np.arange(10**5) + np.testing.assert_equal(a + b, fnv(a, b)) + # Reduce sleep time + sleep_time /= 2 + + @skip_if_freethreading + def test_gil_reacquire_deadlock(self): + """ + Testing issue #1998 due to GIL reacquiring + """ + # make a ctypes callback that requires the GIL + proto = ctypes.CFUNCTYPE(None, ctypes.c_int32) + characters = 'abcdefghij' + + def bar(x): + print(characters[x]) + + cbar = proto(bar) + + # our unit under test + @vectorize(['int32(int32)'], target='parallel', nopython=True) + def foo(x): + print(x % 10) # this reacquires the GIL + cbar(x % 10) # this reacquires the GIL + return x * 2 + + # Numpy ufunc has a heuristic to determine whether to release the GIL + # during execution. Small input size (10) seems to not release the GIL. + # Large input size (1000) seems to release the GIL. + for nelem in [1, 10, 100, 1000]: + # inputs + a = np.arange(nelem, dtype=np.int32) + acopy = a.copy() + # run and capture stdout + with captured_stdout() as buf: + got = foo(a) + stdout = buf.getvalue() + buf.close() + # process outputs from print + got_output = sorted(map(lambda x: x.strip(), stdout.splitlines())) + # build expected output + expected_output = [str(x % 10) for x in range(nelem)] + expected_output += [characters[x % 10] for x in range(nelem)] + expected_output = sorted(expected_output) + # verify + self.assertEqual(got_output, expected_output) + np.testing.assert_equal(got, 2 * acopy) + + + +class TestParGUfuncIssues(unittest.TestCase): + + _numba_parallel_test_ = False + + @skip_if_freethreading + def test_gil_reacquire_deadlock(self): + """ + Testing similar issue to #1998 due to GIL reacquiring for Gufunc + """ + # make a ctypes callback that requires the GIL + proto = ctypes.CFUNCTYPE(None, ctypes.c_int32) + characters = 'abcdefghij' + + def bar(x): + print(characters[x]) + + cbar = proto(bar) + + # our unit under test + @guvectorize(['(int32, int32[:])'], "()->()", + target='parallel', nopython=True) + def foo(x, out): + print(x % 10) # this reacquires the GIL + cbar(x % 10) # this reacquires the GIL + out[0] = x * 2 + + # Numpy ufunc has a heuristic to determine whether to release the GIL + # during execution. Small input size (10) seems to not release the GIL. + # Large input size (1000) seems to release the GIL. + for nelem in [1, 10, 100, 1000]: + # inputs + a = np.arange(nelem, dtype=np.int32) + acopy = a.copy() + # run and capture stdout + with captured_stdout() as buf: + got = foo(a) + stdout = buf.getvalue() + buf.close() + # process outputs from print + got_output = sorted(map(lambda x: x.strip(), stdout.splitlines())) + # build expected output + expected_output = [str(x % 10) for x in range(nelem)] + expected_output += [characters[x % 10] for x in range(nelem)] + expected_output = sorted(expected_output) + # verify + self.assertEqual(got_output, expected_output) + np.testing.assert_equal(got, 2 * acopy) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_ufunc.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_ufunc.py new file mode 100644 index 0000000000000000000000000000000000000000..16020d8ebc4f8f7c2ecc9ff492d490ae7caa90cd --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_ufunc.py @@ -0,0 +1,173 @@ +import numpy as np + +from numba import float32, jit, njit +from numba.np.ufunc import Vectorize +from numba.core.errors import TypingError +from numba.tests.support import TestCase +import unittest + + +dtype = np.float32 +a = np.arange(80, dtype=dtype).reshape(8, 10) +b = a.copy() +c = a.copy(order='F') +d = np.arange(16 * 20, dtype=dtype).reshape(16, 20)[::2, ::2] + + +def add(a, b): + return a + b + + +def add_multiple_args(a, b, c, d): + return a + b + c + d + + +def gufunc_add(a, b): + result = 0.0 + for i in range(a.shape[0]): + result += a[i] * b[i] + + return result + + +def ufunc_reduce(ufunc, arg): + for i in range(arg.ndim): + arg = ufunc.reduce(arg) + return arg + + +vectorizers = [ + Vectorize, + # ParallelVectorize, + # StreamVectorize, + # CudaVectorize, + # GUFuncVectorize, +] + + +class TestUFuncs(TestCase): + + def _test_ufunc_attributes(self, cls, a, b, *args): + "Test ufunc attributes" + vectorizer = cls(add, *args) + vectorizer.add(float32(float32, float32)) + ufunc = vectorizer.build_ufunc() + + info = (cls, a.ndim) + self.assertPreciseEqual(ufunc(a, b), a + b, msg=info) + self.assertPreciseEqual(ufunc_reduce(ufunc, a), np.sum(a), msg=info) + self.assertPreciseEqual(ufunc.accumulate(a), np.add.accumulate(a), + msg=info) + self.assertPreciseEqual(ufunc.outer(a, b), np.add.outer(a, b), msg=info) + + def _test_broadcasting(self, cls, a, b, c, d): + "Test multiple args" + vectorizer = cls(add_multiple_args) + vectorizer.add(float32(float32, float32, float32, float32)) + ufunc = vectorizer.build_ufunc() + + info = (cls, a.shape) + self.assertPreciseEqual(ufunc(a, b, c, d), a + b + c + d, msg=info) + + def test_ufunc_attributes(self): + for v in vectorizers: # 1D + self._test_ufunc_attributes(v, a[0], b[0]) + for v in vectorizers: # 2D + self._test_ufunc_attributes(v, a, b) + for v in vectorizers: # 3D + self._test_ufunc_attributes(v, a[:, np.newaxis, :], + b[np.newaxis, :, :]) + + def test_broadcasting(self): + for v in vectorizers: # 1D + self._test_broadcasting(v, a[0], b[0], c[0], d[0]) + for v in vectorizers: # 2D + self._test_broadcasting(v, a, b, c, d) + for v in vectorizers: # 3D + self._test_broadcasting(v, a[:, np.newaxis, :], b[np.newaxis, :, :], + c[:, np.newaxis, :], d[np.newaxis, :, :]) + + def test_implicit_broadcasting(self): + for v in vectorizers: + vectorizer = v(add) + vectorizer.add(float32(float32, float32)) + ufunc = vectorizer.build_ufunc() + + broadcasting_b = b[np.newaxis, :, np.newaxis, np.newaxis, :] + self.assertPreciseEqual(ufunc(a, broadcasting_b), + a + broadcasting_b) + + def test_ufunc_exception_on_write_to_readonly(self): + z = np.ones(10) + z.flags.writeable = False # flip write bit + + tests = [] + expect = "ufunc 'sin' called with an explicit output that is read-only" + tests.append((jit(nopython=True), TypingError, expect)) + tests.append((jit(forceobj=True), ValueError, + "output array is read-only")) + + for dec, exc, msg in tests: + def test(x): + a = np.ones(x.shape, x.dtype) # do not copy RO attribute from x + np.sin(a, x) + + with self.assertRaises(exc) as raises: + dec(test)(z) + + self.assertIn(msg, str(raises.exception)) + + def test_optional_type_handling(self): + # Tests ufunc compilation with Optional type + + @njit + def inner(x, y): + if y > 2: + z = None + else: + z = np.ones(4) + return np.add(x, z) + + # This causes `z` to be np.ones(4) at runtime, success + self.assertPreciseEqual(inner(np.arange(4), 1), + np.arange(1, 5).astype(np.float64)) + + with self.assertRaises(TypeError) as raises: + # This causes `z` to be None at runtime, TypeError raised on the + # type cast of the Optional. + inner(np.arange(4), 3) + + msg = "expected array(float64, 1d, C), got None" + self.assertIn(msg, str(raises.exception)) + + +class TestUFuncsMisc(TestCase): + # Test for miscellaneous ufunc issues + + def test_exp2(self): + # See issue #8898, and TargetLibraryInfo based fix in #9336 + @njit + def foo(x): + return np.exp2(x) + + for ty in (np.int8, np.uint16): + x = ty(2) + expected = foo.py_func(x) + got = foo(x) + self.assertPreciseEqual(expected, got) + + def test_log2(self): + # See issue #8898, and TargetLibraryInfo based fix in #9336 + @njit + def foo(x): + return np.log2(x) + + for ty in (np.int8, np.uint16): + x = ty(2) + expected = foo.py_func(x) + got = foo(x) + self.assertPreciseEqual(expected, got) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_ufuncbuilding.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_ufuncbuilding.py new file mode 100644 index 0000000000000000000000000000000000000000..df6e37dcd5c69e122c87629e410ee2ee38b2acec --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_ufuncbuilding.py @@ -0,0 +1,471 @@ +import pickle +import unittest + +import numpy as np +from numpy.testing import assert_array_equal + +from numba.np.ufunc.ufuncbuilder import GUFuncBuilder +from numba import vectorize, guvectorize +from numba.np.ufunc import PyUFunc_One +from numba.np.ufunc.dufunc import DUFunc as UFuncBuilder +from numba.tests.support import tag, TestCase +from numba.core import config + + +class TestUfuncBuilding(TestCase): + + def test_basic_ufunc(self): + from numba.tests.npyufunc.ufuncbuilding_usecases import add + ufb = UFuncBuilder(add) + cres = ufb.add("int32(int32, int32)") + self.assertFalse(cres.objectmode) + cres = ufb.add("int64(int64, int64)") + self.assertFalse(cres.objectmode) + ufunc = ufb.build_ufunc() + + def check(a): + b = ufunc(a, a) + self.assertPreciseEqual(a + a, b) + self.assertEqual(b.dtype, a.dtype) + + a = np.arange(12, dtype='int32') + check(a) + # Non-contiguous dimension + a = a[::2] + check(a) + a = a.reshape((2, 3)) + check(a) + + # Metadata + self.assertEqual(ufunc.__name__, "add") + self.assertIn("An addition", ufunc.__doc__) + + def test_ufunc_struct(self): + from numba.tests.npyufunc.ufuncbuilding_usecases import add + ufb = UFuncBuilder(add) + cres = ufb.add("complex64(complex64, complex64)") + self.assertFalse(cres.objectmode) + ufunc = ufb.build_ufunc() + + def check(a): + b = ufunc(a, a) + self.assertPreciseEqual(a + a, b) + self.assertEqual(b.dtype, a.dtype) + + a = np.arange(12, dtype='complex64') + 1j + check(a) + # Non-contiguous dimension + a = a[::2] + check(a) + a = a.reshape((2, 3)) + check(a) + + def test_ufunc_forceobj(self): + from numba.tests.npyufunc.ufuncbuilding_usecases import add + ufb = UFuncBuilder(add, targetoptions={'forceobj': True}) + cres = ufb.add("int32(int32, int32)") + self.assertTrue(cres.objectmode) + ufunc = ufb.build_ufunc() + + a = np.arange(10, dtype='int32') + b = ufunc(a, a) + self.assertPreciseEqual(a + a, b) + + def test_nested_call(self): + """ + Check nested call to an implicitly-typed ufunc. + """ + from numba.tests.npyufunc.ufuncbuilding_usecases import outer + builder = UFuncBuilder(outer, + targetoptions={'nopython': True}) + builder.add("(int64, int64)") + ufunc = builder.build_ufunc() + self.assertEqual(ufunc(-1, 3), 2) + + def test_nested_call_explicit(self): + """ + Check nested call to an explicitly-typed ufunc. + """ + from numba.tests.npyufunc.ufuncbuilding_usecases import outer_explicit + builder = UFuncBuilder(outer_explicit, + targetoptions={'nopython': True}) + builder.add("(int64, int64)") + ufunc = builder.build_ufunc() + self.assertEqual(ufunc(-1, 3), 2) + + +class TestUfuncBuildingJitDisabled(TestUfuncBuilding): + + def setUp(self): + self.old_disable_jit = config.DISABLE_JIT + config.DISABLE_JIT = False + + def tearDown(self): + config.DISABLE_JIT = self.old_disable_jit + + +class TestGUfuncBuilding(TestCase): + + def test_basic_gufunc(self): + from numba.tests.npyufunc.ufuncbuilding_usecases import guadd + gufb = GUFuncBuilder(guadd, "(x, y),(x, y)->(x, y)") + cres = gufb.add("void(int32[:,:], int32[:,:], int32[:,:])") + self.assertFalse(cres.objectmode) + ufunc = gufb.build_ufunc() + + a = np.arange(10, dtype="int32").reshape(2, 5) + b = ufunc(a, a) + + self.assertPreciseEqual(a + a, b) + self.assertEqual(b.dtype, np.dtype('int32')) + + # Metadata + self.assertEqual(ufunc.__name__, "guadd") + self.assertIn("A generalized addition", ufunc.__doc__) + + def test_gufunc_struct(self): + from numba.tests.npyufunc.ufuncbuilding_usecases import guadd + gufb = GUFuncBuilder(guadd, "(x, y),(x, y)->(x, y)") + cres = gufb.add("void(complex64[:,:], complex64[:,:], complex64[:,:])") + self.assertFalse(cres.objectmode) + ufunc = gufb.build_ufunc() + + a = np.arange(10, dtype="complex64").reshape(2, 5) + 1j + b = ufunc(a, a) + + self.assertPreciseEqual(a + a, b) + + def test_gufunc_struct_forceobj(self): + from numba.tests.npyufunc.ufuncbuilding_usecases import guadd + gufb = GUFuncBuilder(guadd, "(x, y),(x, y)->(x, y)", + targetoptions=dict(forceobj=True)) + cres = gufb.add("void(complex64[:,:], complex64[:,:], complex64[:," + ":])") + self.assertTrue(cres.objectmode) + ufunc = gufb.build_ufunc() + + a = np.arange(10, dtype="complex64").reshape(2, 5) + 1j + b = ufunc(a, a) + + self.assertPreciseEqual(a + a, b) + + +class TestGUfuncBuildingJitDisabled(TestGUfuncBuilding): + + def setUp(self): + self.old_disable_jit = config.DISABLE_JIT + config.DISABLE_JIT = False + + def tearDown(self): + config.DISABLE_JIT = self.old_disable_jit + + +class TestVectorizeDecor(TestCase): + + _supported_identities = [0, 1, None, "reorderable"] + + def test_vectorize(self): + from numba.tests.npyufunc.ufuncbuilding_usecases import add + ufunc = vectorize(['int32(int32, int32)'])(add) + a = np.arange(10, dtype='int32') + b = ufunc(a, a) + self.assertPreciseEqual(a + a, b) + + def test_vectorize_objmode(self): + from numba.tests.npyufunc.ufuncbuilding_usecases import add + ufunc = vectorize(['int32(int32, int32)'], forceobj=True)(add) + a = np.arange(10, dtype='int32') + b = ufunc(a, a) + self.assertPreciseEqual(a + a, b) + + def test_vectorize_bool_return(self): + from numba.tests.npyufunc.ufuncbuilding_usecases import equals + ufunc = vectorize(['bool_(int32, int32)'])(equals) + a = np.arange(10, dtype='int32') + r = ufunc(a,a) + self.assertPreciseEqual(r, np.ones(r.shape, dtype=np.bool_)) + + def test_vectorize_identity(self): + from numba.tests.npyufunc.ufuncbuilding_usecases import add + sig = 'int32(int32, int32)' + for identity in self._supported_identities: + ufunc = vectorize([sig], identity=identity)(add) + expected = None if identity == 'reorderable' else identity + self.assertEqual(ufunc.identity, expected) + # Default value is None + ufunc = vectorize([sig])(add) + self.assertIs(ufunc.identity, None) + # Invalid values + with self.assertRaises(ValueError): + vectorize([sig], identity='none')(add) + with self.assertRaises(ValueError): + vectorize([sig], identity=2)(add) + + def test_vectorize_no_args(self): + from numba.tests.npyufunc.ufuncbuilding_usecases import add + a = np.linspace(0,1,10) + b = np.linspace(1,2,10) + ufunc = vectorize(add) + self.assertPreciseEqual(ufunc(a,b), a + b) + ufunc2 = vectorize(add) + c = np.empty(10) + ufunc2(a, b, c) + self.assertPreciseEqual(c, a + b) + + def test_vectorize_only_kws(self): + from numba.tests.npyufunc.ufuncbuilding_usecases import mul + a = np.linspace(0,1,10) + b = np.linspace(1,2,10) + ufunc = vectorize(identity=PyUFunc_One, nopython=True)(mul) + self.assertPreciseEqual(ufunc(a,b), a * b) + + def test_vectorize_output_kwarg(self): + """ + Passing the output array as a keyword argument (issue #1867). + """ + def check(ufunc): + a = np.arange(10, 16, dtype='int32') + out = np.zeros_like(a) + got = ufunc(a, a, out=out) + self.assertIs(got, out) + self.assertPreciseEqual(out, a + a) + with self.assertRaises(TypeError): + ufunc(a, a, zzz=out) + + # With explicit sigs + from numba.tests.npyufunc.ufuncbuilding_usecases import add + ufunc = vectorize(['int32(int32, int32)'], nopython=True)(add) + check(ufunc) + # With implicit sig + ufunc = vectorize(nopython=True)(add) + check(ufunc) # compiling + check(ufunc) # after compiling + + def test_guvectorize(self): + from numba.tests.npyufunc.ufuncbuilding_usecases import guadd + ufunc = guvectorize(['(int32[:,:], int32[:,:], int32[:,:])'], + "(x,y),(x,y)->(x,y)")(guadd) + a = np.arange(10, dtype='int32').reshape(2, 5) + b = ufunc(a, a) + self.assertPreciseEqual(a + a, b) + + def test_guvectorize_no_output(self): + from numba.tests.npyufunc.ufuncbuilding_usecases import guadd + ufunc = guvectorize(['(int32[:,:], int32[:,:], int32[:,:])'], + "(x,y),(x,y),(x,y)")(guadd) + a = np.arange(10, dtype='int32').reshape(2, 5) + out = np.zeros_like(a) + ufunc(a, a, out) + self.assertPreciseEqual(a + a, out) + + def test_guvectorize_objectmode(self): + from numba.tests.npyufunc.ufuncbuilding_usecases import guadd_obj + ufunc = guvectorize(['(int32[:,:], int32[:,:], int32[:,:])'], + "(x,y),(x,y)->(x,y)", forceobj=True)(guadd_obj) + a = np.arange(10, dtype='int32').reshape(2, 5) + b = ufunc(a, a) + self.assertPreciseEqual(a + a, b) + + def test_guvectorize_scalar_objectmode(self): + """ + Test passing of scalars to object mode gufuncs. + """ + from numba.tests.npyufunc.ufuncbuilding_usecases import guadd_scalar_obj + ufunc = guvectorize(['(int32[:,:], int32, int32[:,:])'], + "(x,y),()->(x,y)", forceobj=True)(guadd_scalar_obj) + a = np.arange(10, dtype='int32').reshape(2, 5) + b = ufunc(a, 3) + self.assertPreciseEqual(a + 3, b) + + def test_guvectorize_error_in_objectmode(self): + from numba.tests.npyufunc.ufuncbuilding_usecases import guerror, \ + MyException + ufunc = guvectorize(['(int32[:,:], int32[:,:], int32[:,:])'], + "(x,y),(x,y)->(x,y)", forceobj=True)(guerror) + a = np.arange(10, dtype='int32').reshape(2, 5) + with self.assertRaises(MyException): + ufunc(a, a) + + def test_guvectorize_identity(self): + from numba.tests.npyufunc.ufuncbuilding_usecases import add, guadd + args = (['(int32[:,:], int32[:,:], int32[:,:])'], "(x,y),(x,y)->(x,y)") + for identity in self._supported_identities: + ufunc = guvectorize(*args, identity=identity)(guadd) + expected = None if identity == 'reorderable' else identity + self.assertEqual(ufunc.identity, expected) + # Default value is None + ufunc = guvectorize(*args)(guadd) + self.assertIs(ufunc.identity, None) + # Invalid values + with self.assertRaises(ValueError): + guvectorize(*args, identity='none')(add) + with self.assertRaises(ValueError): + guvectorize(*args, identity=2)(add) + + def test_guvectorize_invalid_layout(self): + from numba.tests.npyufunc.ufuncbuilding_usecases import guadd + sigs = ['(int32[:,:], int32[:,:], int32[:,:])'] + # Syntax error + with self.assertRaises(ValueError) as raises: + guvectorize(sigs, ")-:")(guadd) + self.assertIn("bad token in signature", str(raises.exception)) + # Output shape can't be inferred from inputs + with self.assertRaises(NameError) as raises: + guvectorize(sigs, "(x,y),(x,y)->(x,z,v)")(guadd) + self.assertEqual(str(raises.exception), + "undefined output symbols: v,z") + # Arrow but no outputs + with self.assertRaises(ValueError) as raises: + guvectorize(sigs, "(x,y),(x,y),(x,y)->")(guadd) + # (error message depends on Numpy version) + + +class NEP13Array: + """https://numpy.org/neps/nep-0013-ufunc-overrides.html""" + def __init__(self, array): + self.array = array + + def __array__(self): + return self.array + + def tolist(self): + return self.array.tolist() + + def __array_ufunc__(self, ufunc, method, *args, **kwargs): + if method != "__call__": + return NotImplemented + + return NEP13Array(ufunc(*[np.asarray(x) for x in args], **kwargs)) + + +class FakeDaskArray: + """This class defines both the NEP13 protocol and the dask collection protocol + (https://docs.dask.org/en/stable/custom-collections.html). This is a stand-in for + dask array, dask dataframe, and for any wrapper around them (e.g. xarray or pint). + """ + + def __init__(self, array): + self.array = array + + def __array_ufunc__(self, ufunc, method, *args, **kwargs): + if method != "__call__": + return NotImplemented + + # Simulate sending the ufunc over the network and applying it on a remote worker + ufunc = pickle.loads(pickle.dumps(ufunc)) + args = [x.array if isinstance(x, FakeDaskArray) else x for x in args] + return FakeDaskArray(ufunc(*args, **kwargs)) + + def _dask_method(self, *args, **kwargs): + raise AssertionError("called potentially expensive method") + + __array__ = _dask_method + __dask_graph__ = _dask_method + __dask_keys__ = _dask_method + __dask_optimize__ = _dask_method + __dask_postcompute__ = _dask_method + __dask_postpersist__ = _dask_method + __dask_scheduler__ = _dask_method + __dask_tokenize__ = _dask_method + compute = _dask_method + persist = _dask_method + visualize = _dask_method + + +class TestNEP13WithoutSignature(TestCase): + + def test_all(self): + + # note: no signatures specified + @vectorize(nopython=True) + def new_ufunc(hundreds, tens, ones): + return 100*hundreds + 10*tens + ones + + # give it integers + a = np.array([1, 2, 3], dtype=np.int64) + b = np.array([4, 5, 6], dtype=np.int64) + c = np.array([7, 8, 9], dtype=np.int64) + + all_np = new_ufunc(a, b, c) + self.assertIsInstance(all_np, np.ndarray) + self.assertEqual(all_np.tolist(), [147, 258, 369]) + + nep13_1 = new_ufunc(NEP13Array(a), b, c) + self.assertIsInstance(nep13_1, NEP13Array) + self.assertEqual(nep13_1.tolist(), [147, 258, 369]) + + nep13_2 = new_ufunc(a, NEP13Array(b), c) + self.assertIsInstance(nep13_2, NEP13Array) + self.assertEqual(nep13_2.tolist(), [147, 258, 369]) + + nep13_3 = new_ufunc(a, b, NEP13Array(c)) + self.assertIsInstance(nep13_3, NEP13Array) + self.assertEqual(nep13_3.tolist(), [147, 258, 369]) + + # give it floats + a = np.array([1.1, 2.2, 3.3], dtype=np.float64) + b = np.array([4.4, 5.5, 6.6], dtype=np.float64) + c = np.array([7.7, 8.8, 9.9], dtype=np.float64) + + all_np = new_ufunc(a, b, c) + self.assertIsInstance(all_np, np.ndarray) + self.assertEqual(all_np.tolist(), [161.7, 283.8, 405.9]) + + nep13_1 = new_ufunc(NEP13Array(a), b, c) + self.assertIsInstance(nep13_1, NEP13Array) + self.assertEqual(nep13_1.tolist(), [161.7, 283.8, 405.9]) + + nep13_2 = new_ufunc(a, NEP13Array(b), c) + self.assertIsInstance(nep13_2, NEP13Array) + self.assertEqual(nep13_2.tolist(), [161.7, 283.8, 405.9]) + + nep13_3 = new_ufunc(a, b, NEP13Array(c)) + self.assertIsInstance(nep13_3, NEP13Array) + self.assertEqual(nep13_3.tolist(), [161.7, 283.8, 405.9]) + + +class TestDask(unittest.TestCase): + """Test that numba ufuncs are compatible with dask collections and wrappers around + dask (e.g. xarray or pint) and that they can be serialized, sent over the network, + deserialized on a different host and applied remotely. + """ + + def test_dask_array(self): + a = FakeDaskArray(np.arange(4, dtype=np.float64)) + expect = np.arange(4, dtype=np.float64) * 2 + + @vectorize(["f8(f8)"]) + def double_static_vectorize(x): + return x * 2 + + @vectorize() + def double_dynamic_vectorize(x): + return x * 2 + + @guvectorize(["f8,f8[:]"], "()->()") + def double_guvectorize(x, out): + out[:] = x * 2 + + for func in ( + double_static_vectorize, + double_dynamic_vectorize, + double_guvectorize, + ): + with self.subTest(func): + b = func(a) + assert isinstance(b, FakeDaskArray) + assert_array_equal(b.array, expect) + + +class TestVectorizeDecorJitDisabled(TestVectorizeDecor): + + def setUp(self): + self.old_disable_jit = config.DISABLE_JIT + config.DISABLE_JIT = False + + def tearDown(self): + config.DISABLE_JIT = self.old_disable_jit + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_update_inplace.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_update_inplace.py new file mode 100644 index 0000000000000000000000000000000000000000..97bc39226d3f0f7e8021dd9be993666a5b9ec3b0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_update_inplace.py @@ -0,0 +1,122 @@ +# -*- coding: utf-8 -*- +from __future__ import print_function, absolute_import, division + +import unittest + +import numpy as np +from numba import guvectorize +from numba.tests.support import TestCase + + +def py_replace_2nd(x_t, y_1): + for t in range(0, x_t.shape[0], 2): + x_t[t] = y_1[0] + + +def py_update_3(x0_t, x1_t, x2_t, y_1): + for t in range(0, x0_t.shape[0]): + x0_t[t] = y_1[0] + x1_t[t] = 2 * y_1[0] + x2_t[t] = 3 * y_1[0] + + +class TestUpdateInplace(TestCase): + + def _run_test_for_gufunc(self, gufunc, py_func, expect_f4_to_pass=True, + z=2): + for dtype, expect_to_pass in [('f8', True), ('f4', expect_f4_to_pass)]: + inputs = [np.zeros(10, dtype) for _ in range(gufunc.nin - 1)] + ex_inputs = [x_t.copy() for x_t in inputs] + + gufunc(*inputs, z) + py_func(*ex_inputs, np.array([z])) + + for i, (x_t, ex_x_t) in enumerate(zip(inputs, ex_inputs)): + if expect_to_pass: + np.testing.assert_equal(x_t, ex_x_t, err_msg='input %s' % i) + else: + self.assertFalse((x_t == ex_x_t).all(), msg='input %s' % i) + + def test_update_inplace(self): + # test without writable_args + gufunc = guvectorize(['void(f8[:], f8[:])'], '(t),()', + nopython=True)(py_replace_2nd) + self._run_test_for_gufunc(gufunc, py_replace_2nd, + expect_f4_to_pass=False) + + # test with writable_args + gufunc = guvectorize(['void(f8[:], f8[:])'], '(t),()', + nopython=True, writable_args=(0,))(py_replace_2nd) + self._run_test_for_gufunc(gufunc, py_replace_2nd) + + # test with writable_args as strings + gufunc = guvectorize(['void(f8[:], f8[:])'], '(t),()', nopython=True, + writable_args=('x_t',))(py_replace_2nd) + self._run_test_for_gufunc(gufunc, py_replace_2nd) + + def test_update_inplace_with_cache(self): + # test with writable_args + gufunc = guvectorize(['void(f8[:], f8[:])'], '(t),()', + nopython=True, writable_args=(0,), + cache=True)(py_replace_2nd) + # 2nd time it is loaded from cache + gufunc = guvectorize(['void(f8[:], f8[:])'], '(t),()', + nopython=True, writable_args=(0,), + cache=True)(py_replace_2nd) + self._run_test_for_gufunc(gufunc, py_replace_2nd) + + def test_update_inplace_parallel(self): + # test with writable_args + gufunc = guvectorize(['void(f8[:], f8[:])'], '(t),()', + nopython=True, writable_args=(0,), + target='parallel')(py_replace_2nd) + self._run_test_for_gufunc(gufunc, py_replace_2nd) + + def test_update_inplace_3(self): + # test without writable_args + gufunc = guvectorize(['void(f8[:], f8[:], f8[:], f8[:])'], + '(t),(t),(t),()', + nopython=True)(py_update_3) + self._run_test_for_gufunc(gufunc, py_update_3, expect_f4_to_pass=False) + + # test with writable_args + gufunc = guvectorize(['void(f8[:], f8[:], f8[:], f8[:])'], + '(t),(t),(t),()', nopython=True, + writable_args=(0, 1, 2))(py_update_3) + self._run_test_for_gufunc(gufunc, py_update_3) + + # test with writable_args as mix of strings and ints + gufunc = guvectorize(['void(f8[:], f8[:], f8[:], f8[:])'], + '(t),(t),(t),()', nopython=True, + writable_args=('x0_t', 'x1_t', 2))(py_update_3) + self._run_test_for_gufunc(gufunc, py_update_3) + + def test_exceptions(self): + # check that len(writable_args) <= nin + with self.assertRaises(ValueError): + guvectorize(['void(f8[:], f8[:])'], '(t),()', nopython=True, + writable_args=(0, 1, 2, 5))(py_replace_2nd) + + # check that all values in writable_args are between 0 and nin + with self.assertRaises(ValueError): + guvectorize(['void(f8[:], f8[:])'], '(t),()', + nopython=True, writable_args=(5,))(py_replace_2nd) + + with self.assertRaises(ValueError): + guvectorize(['void(f8[:], f8[:])'], '(t),()', + nopython=True, writable_args=(-1,))(py_replace_2nd) + + # check that exception is raised when passing non-existing argument name + with self.assertRaises(RuntimeError): + guvectorize(['void(f8[:], f8[:])'], '(t),()', + nopython=True, writable_args=('z_t',))(py_replace_2nd) + + # writable_args are not supported for target='cuda' + with self.assertRaises(TypeError): + guvectorize(['void(f8[:], f8[:])'], '(t),()', + nopython=True, writable_args=(0,), + target='cuda')(py_replace_2nd) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_vectorize_decor.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_vectorize_decor.py new file mode 100644 index 0000000000000000000000000000000000000000..6eb984d8c04a07c12b0d690a2003b0a61defd058 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/test_vectorize_decor.py @@ -0,0 +1,151 @@ +import math + +import numpy as np + +from numba import int32, uint32, float32, float64, jit, vectorize +from numba.tests.support import tag, CheckWarningsMixin +import unittest + + +pi = math.pi + + +def sinc(x): + if x == 0.0: + return 1.0 + else: + return math.sin(x * pi) / (pi * x) + +def scaled_sinc(x, scale): + if x == 0.0: + return scale + else: + return scale * (math.sin(x * pi) / (pi * x)) + +def vector_add(a, b): + return a + b + + +class BaseVectorizeDecor(object): + target = None + wrapper = None + funcs = { + 'func1': sinc, + 'func2': scaled_sinc, + 'func3': vector_add, + } + + @classmethod + def _run_and_compare(cls, func, sig, A, *args, **kwargs): + if cls.wrapper is not None: + func = cls.wrapper(func) + numba_func = vectorize(sig, target=cls.target)(func) + numpy_func = np.vectorize(func) + result = numba_func(A, *args) + gold = numpy_func(A, *args) + np.testing.assert_allclose(result, gold, **kwargs) + + def test_1(self): + sig = ['float64(float64)', 'float32(float32)'] + func = self.funcs['func1'] + A = np.arange(100, dtype=np.float64) + self._run_and_compare(func, sig, A) + + def test_2(self): + sig = [float64(float64), float32(float32)] + func = self.funcs['func1'] + A = np.arange(100, dtype=np.float64) + self._run_and_compare(func, sig, A) + + def test_3(self): + sig = ['float64(float64, uint32)'] + func = self.funcs['func2'] + A = np.arange(100, dtype=np.float64) + scale = np.uint32(3) + self._run_and_compare(func, sig, A, scale, atol=1e-8) + + def test_4(self): + sig = [ + int32(int32, int32), + uint32(uint32, uint32), + float32(float32, float32), + float64(float64, float64), + ] + func = self.funcs['func3'] + A = np.arange(100, dtype=np.float64) + self._run_and_compare(func, sig, A, A) + A = A.astype(np.float32) + self._run_and_compare(func, sig, A, A) + A = A.astype(np.int32) + self._run_and_compare(func, sig, A, A) + A = A.astype(np.uint32) + self._run_and_compare(func, sig, A, A) + + +class TestCPUVectorizeDecor(unittest.TestCase, BaseVectorizeDecor): + target = 'cpu' + + +class TestParallelVectorizeDecor(unittest.TestCase, BaseVectorizeDecor): + _numba_parallel_test_ = False + target = 'parallel' + + +class TestCPUVectorizeJitted(unittest.TestCase, BaseVectorizeDecor): + target = 'cpu' + wrapper = jit(nopython=True) + + +class BaseVectorizeNopythonArg(unittest.TestCase, CheckWarningsMixin): + """ + Test passing the nopython argument to the vectorize decorator. + """ + def _test_target_nopython(self, target, warnings, with_sig=True): + a = np.array([2.0], dtype=np.float32) + b = np.array([3.0], dtype=np.float32) + sig = [float32(float32, float32)] + args = with_sig and [sig] or [] + with self.check_warnings(warnings): + f = vectorize(*args, target=target, nopython=True)(vector_add) + f(a, b) + +class TestVectorizeNopythonArg(BaseVectorizeNopythonArg): + def test_target_cpu_nopython(self): + self._test_target_nopython('cpu', []) + + def test_target_cpu_nopython_no_sig(self): + self._test_target_nopython('cpu', [], False) + + def test_target_parallel_nopython(self): + self._test_target_nopython('parallel', []) + + +class BaseVectorizeUnrecognizedArg(unittest.TestCase, CheckWarningsMixin): + """ + Test passing an unrecognized argument to the vectorize decorator. + """ + def _test_target_unrecognized_arg(self, target, with_sig=True): + a = np.array([2.0], dtype=np.float32) + b = np.array([3.0], dtype=np.float32) + sig = [float32(float32, float32)] + args = with_sig and [sig] or [] + with self.assertRaises(KeyError) as raises: + f = vectorize(*args, target=target, nonexistent=2)(vector_add) + f(a, b) + self.assertIn("Unrecognized options", str(raises.exception)) + +class TestVectorizeUnrecognizedArg(BaseVectorizeUnrecognizedArg): + def test_target_cpu_unrecognized_arg(self): + self._test_target_unrecognized_arg('cpu') + + def test_target_cpu_unrecognized_arg_no_sig(self): + self._test_target_unrecognized_arg('cpu', False) + + def test_target_parallel_unrecognized_arg(self): + self._test_target_unrecognized_arg('parallel') + + + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/ufuncbuilding_usecases.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/ufuncbuilding_usecases.py new file mode 100644 index 0000000000000000000000000000000000000000..0e96dc300cf3642ee3a042bf55cda4885a98c547 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/npyufunc/ufuncbuilding_usecases.py @@ -0,0 +1,69 @@ +from numba import vectorize + + +def add(a, b): + """An addition""" + return a + b + + +def equals(a, b): + return a == b + + +def mul(a, b): + """A multiplication""" + return a * b + + +def guadd(a, b, c): + """A generalized addition""" + x, y = c.shape + for i in range(x): + for j in range(y): + c[i, j] = a[i, j] + b[i, j] + + +@vectorize(nopython=True) +def inner(a, b): + return a + b + + +@vectorize(["int64(int64, int64)"], nopython=True) +def inner_explicit(a, b): + return a + b + + +def outer(a, b): + return inner(a, b) + + +def outer_explicit(a, b): + return inner_explicit(a, b) + + +class Dummy: + pass + + +def guadd_obj(a, b, c): + Dummy() # to force object mode + x, y = c.shape + for i in range(x): + for j in range(y): + c[i, j] = a[i, j] + b[i, j] + + +def guadd_scalar_obj(a, b, c): + Dummy() # to force object mode + x, y = c.shape + for i in range(x): + for j in range(y): + c[i, j] = a[i, j] + b + + +class MyException(Exception): + pass + + +def guerror(a, b, c): + raise MyException diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/orphaned_semaphore_usecase.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/orphaned_semaphore_usecase.py new file mode 100644 index 0000000000000000000000000000000000000000..e9101e2f2b541b55a91a24d62031f29bcf114af0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/orphaned_semaphore_usecase.py @@ -0,0 +1,24 @@ +# See issue: https://github.com/numba/numba/issues/4348 +# this file must be run in isolation to replicate, test: +# numba.tests.test_parallel_backend.TestInitSafetyIssues.test_orphaned_semaphore +# does this to check semaphores are not leaking. + +import multiprocessing as mp + +import numba # noqa, deliberately unused, here to test import is safe + + +def w(): + pass + + +def main(): + ps = [mp.Process(target=w) for _ in range(4)] + [p.start() for p in ps] + [p.join() for p in ps] + + +if __name__ == '__main__': + p = mp.get_context('spawn').Process(target=main) + p.start() + p.join() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/overload_usecases.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/overload_usecases.py new file mode 100644 index 0000000000000000000000000000000000000000..fe1ca5799e847dbb37c63b2706e6477cd3ba8947 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/overload_usecases.py @@ -0,0 +1,28 @@ +# Python 3 syntax only use cases, used in test_extending.py + +# arg name is different, and there's no arg name to match before *args + + +def impl4(z, *args, kw=None): + if z > 10: + return 1 + else: + return -1 + +# arg name is different but at a detectable location, with *args + + +def impl5(z, b, *args, kw=None): + if z > 10: + return 1 + else: + return -1 + + +def var_positional_impl(a, *star_args_token, kw=None, kw1=12): + def impl(a, b, f, kw=None, kw1=12): + if a > 10: + return 1 + else: + return -1 + return impl diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/pdlike_usecase.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/pdlike_usecase.py new file mode 100644 index 0000000000000000000000000000000000000000..75ac00b6ffa199e236dfe09d8af2628da393e850 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/pdlike_usecase.py @@ -0,0 +1,306 @@ +""" +Implementation of a minimal Pandas-like API. +""" + +import numpy as np + +from numba.core import types, cgutils +from numba.core.datamodel import models +from numba.core.extending import ( + typeof_impl, type_callable, register_model, + lower_builtin, box, unbox, NativeValue, + overload, overload_attribute, overload_method, make_attribute_wrapper) +from numba.core.imputils import impl_ret_borrowed + + +class Index(object): + """ + A minimal pandas.Index-like object. + """ + + def __init__(self, data): + assert isinstance(data, np.ndarray) + assert data.ndim == 1 + self._data = data + + def __iter__(self): + return iter(self._data) + + @property + def dtype(self): + return self._data.dtype + + @property + def flags(self): + return self._data.flags + + +class IndexType(types.Buffer): + """ + The type class for Index objects. + """ + array_priority = 1000 + + def __init__(self, dtype, layout, pyclass): + self.pyclass = pyclass + super(IndexType, self).__init__(dtype, 1, layout) + + @property + def key(self): + return self.pyclass, self.dtype, self.layout + + @property + def as_array(self): + return types.Array(self.dtype, 1, self.layout) + + def copy(self, dtype=None, ndim=1, layout=None): + assert ndim == 1 + if dtype is None: + dtype = self.dtype + layout = layout or self.layout + return type(self)(dtype, layout, self.pyclass) + + +class Series(object): + """ + A minimal pandas.Series-like object. + """ + + def __init__(self, data, index): + assert isinstance(data, np.ndarray) + assert isinstance(index, Index) + assert data.ndim == 1 + self._values = data + self._index = index + + def __iter__(self): + return iter(self._values) + + @property + def dtype(self): + return self._values.dtype + + @property + def flags(self): + return self._values.flags + + +class SeriesType(types.ArrayCompatible): + """ + The type class for Series objects. + """ + array_priority = 1000 + + def __init__(self, dtype, index): + assert isinstance(index, IndexType) + self.dtype = dtype + self.index = index + self.values = types.Array(self.dtype, 1, 'C') + name = "series(%s, %s)" % (dtype, index) + super(SeriesType, self).__init__(name) + + @property + def key(self): + return self.dtype, self.index + + @property + def as_array(self): + return self.values + + def copy(self, dtype=None, ndim=1, layout='C'): + assert ndim == 1 + assert layout == 'C' + if dtype is None: + dtype = self.dtype + return type(self)(dtype, self.index) + + +@typeof_impl.register(Index) +def typeof_index(val, c): + arrty = typeof_impl(val._data, c) + assert arrty.ndim == 1 + return IndexType(arrty.dtype, arrty.layout, type(val)) + +@typeof_impl.register(Series) +def typeof_series(val, c): + index = typeof_impl(val._index, c) + arrty = typeof_impl(val._values, c) + assert arrty.ndim == 1 + assert arrty.layout == 'C' + return SeriesType(arrty.dtype, index) + +@type_callable('__array_wrap__') +def type_array_wrap(context): + def typer(input_type, result): + if isinstance(input_type, (IndexType, SeriesType)): + return input_type.copy(dtype=result.dtype, + ndim=result.ndim, + layout=result.layout) + + return typer + +@type_callable(Series) +def type_series_constructor(context): + def typer(data, index): + if isinstance(index, IndexType) and isinstance(data, types.Array): + assert data.layout == 'C' + assert data.ndim == 1 + return SeriesType(data.dtype, index) + + return typer + + +# Backend extensions for Index and Series + +@register_model(IndexType) +class IndexModel(models.StructModel): + def __init__(self, dmm, fe_type): + members = [('data', fe_type.as_array)] + models.StructModel.__init__(self, dmm, fe_type, members) + +@register_model(SeriesType) +class SeriesModel(models.StructModel): + def __init__(self, dmm, fe_type): + members = [ + ('index', fe_type.index), + ('values', fe_type.as_array), + ] + models.StructModel.__init__(self, dmm, fe_type, members) + +make_attribute_wrapper(IndexType, 'data', '_data') +make_attribute_wrapper(SeriesType, 'index', '_index') +make_attribute_wrapper(SeriesType, 'values', '_values') + +def make_index(context, builder, typ, **kwargs): + return cgutils.create_struct_proxy(typ)(context, builder, **kwargs) + +def make_series(context, builder, typ, **kwargs): + return cgutils.create_struct_proxy(typ)(context, builder, **kwargs) + +@lower_builtin('__array__', IndexType) +def index_as_array(context, builder, sig, args): + val = make_index(context, builder, sig.args[0], ref=args[0]) + return val._get_ptr_by_name('data') + +@lower_builtin('__array__', SeriesType) +def series_as_array(context, builder, sig, args): + val = make_series(context, builder, sig.args[0], ref=args[0]) + return val._get_ptr_by_name('values') + +@lower_builtin('__array_wrap__', IndexType, types.Array) +def index_wrap_array(context, builder, sig, args): + dest = make_index(context, builder, sig.return_type) + dest.data = args[1] + return impl_ret_borrowed(context, builder, sig.return_type, dest._getvalue()) + +@lower_builtin('__array_wrap__', SeriesType, types.Array) +def series_wrap_array(context, builder, sig, args): + src = make_series(context, builder, sig.args[0], value=args[0]) + dest = make_series(context, builder, sig.return_type) + dest.values = args[1] + dest.index = src.index + return impl_ret_borrowed(context, builder, sig.return_type, dest._getvalue()) + +@lower_builtin(Series, types.Array, IndexType) +def pdseries_constructor(context, builder, sig, args): + data, index = args + series = make_series(context, builder, sig.return_type) + series.index = index + series.values = data + return impl_ret_borrowed(context, builder, sig.return_type, series._getvalue()) + + +@unbox(IndexType) +def unbox_index(typ, obj, c): + """ + Convert a Index object to a native structure. + """ + data = c.pyapi.object_getattr_string(obj, "_data") + index = make_index(c.context, c.builder, typ) + index.data = c.unbox(typ.as_array, data).value + + return NativeValue(index._getvalue()) + +@unbox(SeriesType) +def unbox_series(typ, obj, c): + """ + Convert a Series object to a native structure. + """ + index = c.pyapi.object_getattr_string(obj, "_index") + values = c.pyapi.object_getattr_string(obj, "_values") + series = make_series(c.context, c.builder, typ) + series.index = c.unbox(typ.index, index).value + series.values = c.unbox(typ.values, values).value + + return NativeValue(series._getvalue()) + + +@box(IndexType) +def box_index(typ, val, c): + """ + Convert a native index structure to a Index object. + """ + # First build a Numpy array object, then wrap it in a Index + index = make_index(c.context, c.builder, typ, value=val) + classobj = c.pyapi.unserialize(c.pyapi.serialize_object(typ.pyclass)) + arrayobj = c.box(typ.as_array, index.data) + indexobj = c.pyapi.call_function_objargs(classobj, (arrayobj,)) + return indexobj + +@box(SeriesType) +def box_series(typ, val, c): + """ + Convert a native series structure to a Series object. + """ + series = make_series(c.context, c.builder, typ, value=val) + classobj = c.pyapi.unserialize(c.pyapi.serialize_object(Series)) + indexobj = c.box(typ.index, series.index) + arrayobj = c.box(typ.as_array, series.values) + seriesobj = c.pyapi.call_function_objargs(classobj, (arrayobj, indexobj)) + return seriesobj + + +@overload_attribute(IndexType, 'is_monotonic_increasing') +def index_is_monotonic_increasing(index): + """ + Index.is_monotonic_increasing + """ + def getter(index): + data = index._data + if len(data) == 0: + return True + u = data[0] + for v in data: + if v < u: + return False + v = u + return True + + return getter + +@overload(len) +def series_len(series): + """ + len(Series) + """ + if isinstance(series, SeriesType): + def len_impl(series): + return len(series._values) + return len_impl + +@overload_method(SeriesType, 'clip') +def series_clip(series, lower, upper): + """ + Series.clip(...) + """ + def clip_impl(series, lower, upper): + data = series._values.copy() + for i in range(len(data)): + v = data[i] + if v < lower: + data[i] = lower + elif v > upper: + data[i] = upper + return Series(data, series._index) + + return clip_impl diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/pycc_distutils_usecase/__init__.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/pycc_distutils_usecase/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/pycc_distutils_usecase/setup_distutils.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/pycc_distutils_usecase/setup_distutils.py new file mode 100644 index 0000000000000000000000000000000000000000..3976af72db2547bd15da9d4ac60169f7014a8223 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/pycc_distutils_usecase/setup_distutils.py @@ -0,0 +1,13 @@ +from setuptools import distutils +from source_module import cc + + +setup = distutils.core.setup + + +def run_setup(): + setup(ext_modules=[cc.distutils_extension()]) + + +if __name__ == '__main__': + run_setup() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/pycc_distutils_usecase/setup_distutils_nested.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/pycc_distutils_usecase/setup_distutils_nested.py new file mode 100644 index 0000000000000000000000000000000000000000..750551ba51d5871d03f737b54bd9656da83c0116 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/pycc_distutils_usecase/setup_distutils_nested.py @@ -0,0 +1,14 @@ +from setuptools import distutils + +from nested.source_module import cc + + +setup = distutils.core.setup + + +def run_setup(): + setup(ext_modules=[cc.distutils_extension()]) + + +if __name__ == '__main__': + run_setup() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/pycc_distutils_usecase/setup_setuptools.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/pycc_distutils_usecase/setup_setuptools.py new file mode 100644 index 0000000000000000000000000000000000000000..ecfe9decd3213dfff402a5818acf09129250081a --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/pycc_distutils_usecase/setup_setuptools.py @@ -0,0 +1,11 @@ +from setuptools import setup + +from source_module import cc + + +def run_setup(): + setup(ext_modules=[cc.distutils_extension()]) + + +if __name__ == '__main__': + run_setup() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/pycc_distutils_usecase/setup_setuptools_nested.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/pycc_distutils_usecase/setup_setuptools_nested.py new file mode 100644 index 0000000000000000000000000000000000000000..c4381fc5560e0f04a8b3ed5c8f40ac52d33ef74c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/pycc_distutils_usecase/setup_setuptools_nested.py @@ -0,0 +1,11 @@ +from setuptools import setup + +from nested.source_module import cc + + +def run_setup(): + setup(ext_modules=[cc.distutils_extension()]) + + +if __name__ == '__main__': + run_setup() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/pycc_distutils_usecase/source_module.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/pycc_distutils_usecase/source_module.py new file mode 100644 index 0000000000000000000000000000000000000000..e5e6ea82f3b2ac5be2569c915ce742f40d62dfa6 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/pycc_distutils_usecase/source_module.py @@ -0,0 +1,18 @@ +import numpy as np + +from numba.pycc import CC + + +cc = CC('pycc_compiled_module') + +_const = 42 + +# This ones references a global variable at compile time +@cc.export('get_const', 'i8()') +def get_const(): + return _const + +# This one needs NRT and an environment +@cc.export('ones', 'f8[:](i4)') +def ones(n): + return np.ones(n) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_array_analysis.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_array_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..e7afadaa71d1954e0ad5f015cb4cd5f7b6052fe1 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_array_analysis.py @@ -0,0 +1,1146 @@ +import itertools + +import numpy as np +import sys +from collections import namedtuple +from io import StringIO + +from numba import njit, typeof, prange +from numba.core import ( + types, + typing, + ir, + bytecode, + postproc, + cpu, + registry, + utils, +) +from numba.tests.support import (TestCase, tag, skip_parfors_unsupported, + skip_unless_scipy) +from numba.parfors.array_analysis import EquivSet, ArrayAnalysis +from numba.core.compiler import Compiler, Flags, PassManager +from numba.core.ir_utils import remove_dead +from numba.core.untyped_passes import (ExtractByteCode, TranslateByteCode, FixupArgs, + IRProcessing, DeadBranchPrune, + RewriteSemanticConstants, GenericRewrites, + WithLifting, PreserveIR, InlineClosureLikes) + +from numba.core.typed_passes import (NopythonTypeInference, AnnotateTypes, + NopythonRewrites, IRLegalization) + +from numba.core.compiler_machinery import FunctionPass, PassManager, register_pass +from numba.experimental import jitclass +import unittest + + +skip_unsupported = skip_parfors_unsupported + + +# test class for #3700 +@jitclass([('L', types.int32), ('T', types.int32)]) +class ExampleClass3700(object): + def __init__(self, n): + self.L = n + self.T = n + 1 + + +# test value for test_global_tuple +GVAL = (1.2,) +GVAL2 = (3, 4) + + +class TestEquivSet(TestCase): + + """ + Test array_analysis.EquivSet. + """ + def test_insert_equiv(self): + s1 = EquivSet() + s1.insert_equiv('a', 'b') + self.assertTrue(s1.is_equiv('a', 'b')) + self.assertTrue(s1.is_equiv('b', 'a')) + s1.insert_equiv('c', 'd') + self.assertTrue(s1.is_equiv('c', 'd')) + self.assertFalse(s1.is_equiv('c', 'a')) + s1.insert_equiv('a', 'c') + self.assertTrue(s1.is_equiv('a', 'b', 'c', 'd')) + self.assertFalse(s1.is_equiv('a', 'e')) + + def test_intersect(self): + s1 = EquivSet() + s2 = EquivSet() + r = s1.intersect(s2) + self.assertTrue(r.is_empty()) + s1.insert_equiv('a', 'b') + r = s1.intersect(s2) + self.assertTrue(r.is_empty()) + s2.insert_equiv('b', 'c') + r = s1.intersect(s2) + self.assertTrue(r.is_empty()) + s2.insert_equiv('d', 'a') + r = s1.intersect(s2) + self.assertTrue(r.is_empty()) + s1.insert_equiv('a', 'e') + s2.insert_equiv('c', 'd') + r = s1.intersect(s2) + self.assertTrue(r.is_equiv('a', 'b')) + self.assertFalse(r.is_equiv('a', 'e')) + self.assertFalse(r.is_equiv('c', 'd')) + + +@register_pass(analysis_only=False, mutates_CFG=True) +class ArrayAnalysisPass(FunctionPass): + _name = "array_analysis_pass" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + state.array_analysis = ArrayAnalysis(state.typingctx, state.func_ir, + state.typemap, state.calltypes) + state.array_analysis.run(state.func_ir.blocks) + post_proc = postproc.PostProcessor(state.func_ir) + post_proc.run() + state.func_ir_copies.append(state.func_ir.copy()) + if state.test_idempotence and len(state.func_ir_copies) > 1: + state.test_idempotence(state.func_ir_copies) + return False + + +class ArrayAnalysisTester(Compiler): + + @classmethod + def mk_pipeline(cls, args, return_type=None, flags=None, locals=None, + library=None, typing_context=None, target_context=None): + if locals is None: + locals = {} + if not flags: + flags = Flags() + flags.nrt = True + if typing_context is None: + typing_context = registry.cpu_target.typing_context + if target_context is None: + target_context = registry.cpu_target.target_context + return cls(typing_context, target_context, library, args, return_type, + flags, locals) + + def compile_to_ir(self, func, test_idempotence=None): + """ + Populate and run compiler pipeline + """ + self.state.func_id = bytecode.FunctionIdentity.from_function(func) + ExtractByteCode().run_pass(self.state) + + self.state.lifted = () + self.state.lifted_from = None + state = self.state + state.func_ir_copies = [] + state.test_idempotence = test_idempotence + + name = 'array_analysis_testing' + pm = PassManager(name) + pm.add_pass(TranslateByteCode, "analyzing bytecode") + pm.add_pass(FixupArgs, "fix up args") + pm.add_pass(IRProcessing, "processing IR") + # pre typing + if not state.flags.no_rewrites: + pm.add_pass(GenericRewrites, "nopython rewrites") + pm.add_pass(RewriteSemanticConstants, "rewrite semantic constants") + pm.add_pass(DeadBranchPrune, "dead branch pruning") + pm.add_pass(InlineClosureLikes, + "inline calls to locally defined closures") + # typing + pm.add_pass(NopythonTypeInference, "nopython frontend") + + if not state.flags.no_rewrites: + pm.add_pass(NopythonRewrites, "nopython rewrites") + + # Array Analysis pass + pm.add_pass(ArrayAnalysisPass, "array analysis") + if test_idempotence: + # Do another pass of array analysis to test idempotence + pm.add_pass(ArrayAnalysisPass, "idempotence array analysis") + # legalise + pm.add_pass(IRLegalization, "ensure IR is legal prior to lowering") + pm.add_pass(AnnotateTypes, "annotate types") + + # partial compile + pm.finalize() + pm.run(state) + return state.array_analysis + + +class TestArrayAnalysis(TestCase): + + def compare_ir(self, ir_list): + outputs = [] + for func_ir in ir_list: + remove_dead(func_ir.blocks, func_ir.arg_names, func_ir) + output = StringIO() + func_ir.dump(file=output) + outputs.append(output.getvalue()) + self.assertTrue(len(set(outputs)) == 1) # assert all outputs are equal + + def _compile_and_test(self, fn, arg_tys, asserts=None, equivs=None, idempotent=True): + """ + Compile the given function and get its IR. + """ + if asserts is None: + asserts = [] + if equivs is None: + equivs = [] + test_pipeline = ArrayAnalysisTester.mk_pipeline(arg_tys) + test_idempotence = self.compare_ir if idempotent else lambda x:() + analysis = test_pipeline.compile_to_ir(fn, test_idempotence) + if equivs: + for func in equivs: + # only test the equiv_set of the first block + func(analysis.equiv_sets[0]) + if asserts is None: + self.assertTrue(self._has_no_assertcall(analysis.func_ir)) + else: + for func in asserts: + func(analysis.func_ir, analysis.typemap) + + def _has_assertcall(self, func_ir, typemap, args): + msg = "Sizes of {} do not match".format(', '.join(args)) + for label, block in func_ir.blocks.items(): + for expr in block.find_exprs(op='call'): + fn = func_ir.get_definition(expr.func.name) + if isinstance(fn, ir.Global) and fn.name == 'assert_equiv': + typ = typemap[expr.args[0].name] + if typ.literal_value.startswith(msg): + return True + return False + + def _has_shapecall(self, func_ir, x): + for label, block in func_ir.blocks.items(): + for expr in block.find_exprs(op='getattr'): + if expr.attr == 'shape': + y = func_ir.get_definition(expr.value, lhs_only=True) + z = func_ir.get_definition(x, lhs_only=True) + y = y.name if isinstance(y, ir.Var) else y + z = z.name if isinstance(z, ir.Var) else z + if y == z: + return True + return False + + def _has_no_assertcall(self, func_ir): + for label, block in func_ir.blocks.items(): + for expr in block.find_exprs(op='call'): + fn = func_ir.get_definition(expr.func.name) + if isinstance(fn, ir.Global) and fn.name == 'assert_equiv': + return False + return True + + def with_assert(self, *args): + return lambda func_ir, typemap: self.assertTrue( + self._has_assertcall(func_ir, typemap, args)) + + def without_assert(self, *args): + return lambda func_ir, typemap: self.assertFalse( + self._has_assertcall(func_ir, typemap, args)) + + def with_equiv(self, *args): + def check(equiv_set): + n = len(args) + for i in range(n - 1): + if not equiv_set.is_equiv(args[i], args[n - 1]): + return False + return True + return lambda equiv_set: self.assertTrue(check(equiv_set)) + + def without_equiv(self, *args): + def check(equiv_set): + n = len(args) + for i in range(n - 1): + if equiv_set.is_equiv(args[i], args[n - 1]): + return False + return True + return lambda equiv_set: self.assertTrue(check(equiv_set)) + + def with_shapecall(self, x): + return lambda func_ir, s: self.assertTrue(self._has_shapecall(func_ir, x)) + + def without_shapecall(self, x): + return lambda func_ir, s: self.assertFalse(self._has_shapecall(func_ir, x)) + + def test_base_cases(self): + def test_0(): + a = np.zeros(0) + b = np.zeros(1) + m = 0 + n = 1 + c = np.zeros((m, n)) + return + self._compile_and_test(test_0, (), + equivs=[self.with_equiv('a', (0,)), + self.with_equiv('b', (1,)), + self.with_equiv('c', (0, 1))]) + + def test_1(n): + a = np.zeros(n) + b = np.zeros(n) + return a + b + self._compile_and_test(test_1, (types.intp,), asserts=None) + + def test_2(m, n): + a = np.zeros(n) + b = np.zeros(m) + return a + b + self._compile_and_test(test_2, (types.intp, types.intp), + asserts=[self.with_assert('a', 'b')]) + + def test_3(n): + a = np.zeros(n) + return a + n + self._compile_and_test(test_3, (types.intp,), asserts=None) + + def test_4(n): + a = np.zeros(n) + b = a + 1 + c = a + 2 + return a + c + self._compile_and_test(test_4, (types.intp,), asserts=None) + + def test_5(n): + a = np.zeros((n, n)) + m = n + b = np.zeros((m, n)) + return a + b + self._compile_and_test(test_5, (types.intp,), asserts=None) + + def test_6(m, n): + a = np.zeros(n) + b = np.zeros(m) + d = a + b + e = a - b + return d + e + self._compile_and_test(test_6, (types.intp, types.intp), + asserts=[self.with_assert('a', 'b'), + self.without_assert('d', 'e')]) + + def test_7(m, n): + a = np.zeros(n) + b = np.zeros(m) + if m == 10: + d = a + b + else: + d = a - b + return d + a + self._compile_and_test(test_7, (types.intp, types.intp), + asserts=[self.with_assert('a', 'b'), + self.without_assert('d', 'a')]) + + def test_8(m, n): + a = np.zeros(n) + b = np.zeros(m) + if m == 10: + d = b + a + else: + d = a + a + return b + d + self._compile_and_test(test_8, (types.intp, types.intp), + asserts=[self.with_assert('b', 'a'), + self.with_assert('b', 'd')]) + + def test_9(m): + A = np.ones(m) + s = 0 + while m < 2: + m += 1 + B = np.ones(m) + s += np.sum(A + B) + return s + self._compile_and_test(test_9, (types.intp,), + asserts=[self.with_assert('A', 'B')]) + + def test_10(m, n): + p = m - 1 + q = n + 1 + r = q + 1 + A = np.zeros(p) + B = np.zeros(q) + C = np.zeros(r) + D = np.zeros(m) + s = np.sum(A + B) + t = np.sum(C + D) + return s + t + self._compile_and_test(test_10, (types.intp,types.intp,), + asserts=[self.with_assert('A', 'B'), + self.without_assert('C', 'D')]) + + def test_11(): + a = np.ones(5) + b = np.ones(5) + c = a[1:] + d = b[:-1] + e = len(c) + f = len(d) + return e == f + self._compile_and_test(test_11, (), + equivs=[self.with_equiv('e', 'f')]) + + def test_12(): + a = np.ones(25).reshape((5,5)) + b = np.ones(25).reshape((5,5)) + c = a[1:,:] + d = b[:-1,:] + e = c.shape[0] + f = d.shape[0] + g = len(d) + return e == f + self._compile_and_test(test_12, (), + equivs=[self.with_equiv('e', 'f', 'g')]) + + def test_tup_arg(T): + T2 = T + return T2[0] + + int_arr_typ = types.Array(types.intp, 1, 'C') + self._compile_and_test(test_tup_arg, + (types.Tuple((int_arr_typ, int_arr_typ)),), asserts=None) + + def test_arr_in_tup(m): + A = np.ones(m) + S = (A,) + B = np.ones(len(S[0])) + return B + + self._compile_and_test(test_arr_in_tup, (types.intp,), + equivs=[self.with_equiv("A", "B")]) + + T = namedtuple("T", ['a','b']) + def test_namedtuple(n): + r = T(n, n) + return r[0] + self._compile_and_test(test_namedtuple, (types.intp,), + equivs=[self.with_equiv('r', ('n', 'n'))],) + + # np.where is tricky since it returns tuple of arrays + def test_np_where_tup_return(A): + c = np.where(A) + return len(c[0]) + + self._compile_and_test(test_np_where_tup_return, + (types.Array(types.intp, 1, 'C'),), asserts=None) + + def test_shape(A): + (m, n) = A.shape + B = np.ones((m, n)) + return A + B + self._compile_and_test(test_shape, (types.Array(types.intp, 2, 'C'),), + asserts=None) + + def test_cond(l, m, n): + A = np.ones(l) + B = np.ones(m) + C = np.ones(n) + if l == m: + r = np.sum(A + B) + else: + r = 0 + if m != n: + s = 0 + else: + s = np.sum(B + C) + t = 0 + if l == m: + if m == n: + t = np.sum(A + B + C) + return r + s + t + self._compile_and_test(test_cond, (types.intp, types.intp, types.intp), + asserts=None) + + def test_assert_1(m, n): + assert(m == n) + A = np.ones(m) + B = np.ones(n) + return np.sum(A + B) + self._compile_and_test(test_assert_1, (types.intp, types.intp), + asserts=None) + + def test_assert_2(A, B): + assert(A.shape == B.shape) + return np.sum(A + B) + + self._compile_and_test(test_assert_2, (types.Array(types.intp, 1, 'C'), + types.Array(types.intp, 1, 'C'),), + asserts=None) + self._compile_and_test(test_assert_2, (types.Array(types.intp, 2, 'C'), + types.Array(types.intp, 2, 'C'),), + asserts=None) + # expected failure + with self.assertRaises(AssertionError) as raises: + self._compile_and_test(test_assert_2, (types.Array(types.intp, 1, 'C'), + types.Array(types.intp, 2, 'C'),), + asserts=None) + msg = "Dimension mismatch" + self.assertIn(msg, str(raises.exception)) + + + def test_stencilcall(self): + from numba.stencils.stencil import stencil + @stencil + def kernel_1(a): + return 0.25 * (a[0,1] + a[1,0] + a[0,-1] + a[-1,0]) + + def test_1(n): + a = np.ones((n,n)) + b = kernel_1(a) + return a + b + + self._compile_and_test(test_1, (types.intp,), + equivs=[self.with_equiv('a', 'b')], + asserts=[self.without_assert('a', 'b')]) + + def test_2(n): + a = np.ones((n,n)) + b = np.ones((n+1,n+1)) + kernel_1(a, out=b) + return a + + self._compile_and_test(test_2, (types.intp,), + equivs=[self.without_equiv('a', 'b')]) + + @stencil(standard_indexing=('c',)) + def kernel_2(a, b, c): + return a[0,1,0] + b[0,-1,0] + c[0] + + def test_3(n): + a = np.arange(64).reshape(4,8,2) + b = np.arange(64).reshape(n,8,2) + u = np.zeros(1) + v = kernel_2(a, b, u) + return v + + # standard indexed arrays are not considered in size equivalence + self._compile_and_test(test_3, (types.intp,), + equivs=[self.with_equiv('a', 'b', 'v'), + self.without_equiv('a', 'u')], + asserts=[self.with_assert('a', 'b')]) + + def test_slice(self): + def test_1(m, n): + A = np.zeros(m) + B = np.zeros(n) + s = np.sum(A + B) + C = A[1:m-1] + D = B[1:n-1] + t = np.sum(C + D) + return s + t + self._compile_and_test(test_1, (types.intp,types.intp,), + asserts=[self.with_assert('A', 'B'), + self.without_assert('C', 'D')], + idempotent=False) + + def test_2(m): + A = np.zeros(m) + B = A[0:m-3] + C = A[1:m-2] + D = A[2:m-1] + E = B + C + return D + E + self._compile_and_test(test_2, (types.intp,), + asserts=[self.without_assert('B', 'C'), + self.without_assert('D', 'E')], + idempotent=False) + + def test_3(m): + A = np.zeros((m,m)) + B = A[0:m-2,0:m-2] + C = A[1:m-1,1:m-1] + E = B + C + return E + self._compile_and_test(test_3, (types.intp,), + asserts=[self.without_assert('B', 'C')], + idempotent=False) + + def test_4(m): + A = np.zeros((m,m)) + B = A[0:m-2,:] + C = A[1:m-1,:] + E = B + C + return E + self._compile_and_test(test_4, (types.intp,), + asserts=[self.without_assert('B', 'C')], + idempotent=False) + + def test_5(m,n): + A = np.zeros(m) + B = np.zeros(m) + B[0:m-2] = A[1:m-1] + C = np.zeros(n) + D = A[1:m-1] + C[0:n-2] = D + # B and C are not necessarily of the same size because we can't + # derive m == n from (m-2) % m == (n-2) % n + return B + C + self._compile_and_test(test_5, (types.intp,types.intp), + asserts=[self.without_assert('B', 'A'), + self.with_assert('C', 'D'), + self.with_assert('B', 'C')], + idempotent=False) + + def test_6(m): + A = np.zeros((m,m)) + B = A[0:m-2,:-1] + C = A[1:m-1,:-1] + E = B + C + return E + self._compile_and_test(test_6, (types.intp,), + asserts=[self.without_assert('B', 'C')], + idempotent=False) + + def test_7(m): + A = np.zeros((m,m)) + B = A[0:m-2,-3:-1] + C = A[1:m-1,-4:-2] + E = B + C + return E + self._compile_and_test(test_7, (types.intp,), + asserts=[self.with_assert('B', 'C')], + idempotent=False) + + def test_8(m): + A = np.zeros((m,m)) + B = A[:m-2,0:] + C = A[1:-1,:] + E = B + C + return E + self._compile_and_test(test_8, (types.intp,), + asserts=[self.without_assert('B', 'C')], + idempotent=False) + + def test_9(m): + # issues #3461 and #3554, checks equivalence on empty slices + # and across binop + A = np.zeros((m)) + B = A[:0] # B = array([], dtype=int64) + C = A[1:] + D = A[:-1:-1] # D = array([], dtype=int64) + E = B + D + F = E + F += 1 # F = array([], dtype=int64) + return A, C, F + self._compile_and_test(test_9, (types.intp,), + equivs=[self.without_equiv('B', 'C'), + self.with_equiv('A', 'm'), + self.with_equiv('B', 'D'), + self.with_equiv('F', 'D'),], + idempotent=False) + + @skip_unless_scipy + def test_numpy_calls(self): + def test_zeros(n): + a = np.zeros(n) + b = np.zeros((n, n)) + c = np.zeros(shape=(n, n)) + self._compile_and_test(test_zeros, (types.intp,), + equivs=[self.with_equiv('a', 'n'), + self.with_equiv('b', ('n', 'n')), + self.with_equiv('b', 'c')]) + + def test_0d_array(n): + a = np.array(1) + b = np.ones(2) + return a + b + self._compile_and_test(test_0d_array, (types.intp,), + equivs=[self.without_equiv('a', 'b')], + asserts=[self.without_shapecall('a')]) + + def test_ones(n): + a = np.ones(n) + b = np.ones((n, n)) + c = np.ones(shape=(n, n)) + self._compile_and_test(test_ones, (types.intp,), + equivs=[self.with_equiv('a', 'n'), + self.with_equiv('b', ('n', 'n')), + self.with_equiv('b', 'c')]) + + def test_empty(n): + a = np.empty(n) + b = np.empty((n, n)) + c = np.empty(shape=(n, n)) + self._compile_and_test(test_empty, (types.intp,), + equivs=[self.with_equiv('a', 'n'), + self.with_equiv('b', ('n', 'n')), + self.with_equiv('b', 'c')]) + + def test_eye(n): + a = np.eye(n) + b = np.eye(N=n) + c = np.eye(N=n, M=n) + d = np.eye(N=n, M=n + 1) + self._compile_and_test(test_eye, (types.intp,), + equivs=[self.with_equiv('a', ('n', 'n')), + self.with_equiv('b', ('n', 'n')), + self.with_equiv('b', 'c'), + self.without_equiv('b', 'd')]) + + def test_identity(n): + a = np.identity(n) + self._compile_and_test(test_identity, (types.intp,), + equivs=[self.with_equiv('a', ('n', 'n'))]) + + def test_diag(n): + a = np.identity(n) + b = np.diag(a) + c = np.diag(b) + d = np.diag(a, k=1) + self._compile_and_test(test_diag, (types.intp,), + equivs=[self.with_equiv('b', ('n',)), + self.with_equiv('c', ('n', 'n'))], + asserts=[self.with_shapecall('d'), + self.without_shapecall('c')]) + + def test_array_like(a): + b = np.empty_like(a) + c = np.zeros_like(a) + d = np.ones_like(a) + e = np.full_like(a, 1) + f = np.asfortranarray(a) + + self._compile_and_test(test_array_like, (types.Array(types.intp, 2, 'C'),), + equivs=[ + self.with_equiv('a', 'b', 'd', 'e', 'f')], + asserts=[self.with_shapecall('a'), + self.without_shapecall('b')]) + + def test_reshape(n): + a = np.ones(n * n) + b = a.reshape((n, n)) + return a.sum() + b.sum() + self._compile_and_test(test_reshape, (types.intp,), + equivs=[self.with_equiv('b', ('n', 'n'))], + asserts=[self.without_shapecall('b')]) + + + def test_transpose(m, n): + a = np.ones((m, n)) + b = a.T + c = a.transpose() + # Numba njit cannot compile explicit transpose call! + # c = np.transpose(b) + self._compile_and_test(test_transpose, (types.intp, types.intp), + equivs=[self.with_equiv('a', ('m', 'n')), + self.with_equiv('b', ('n', 'm')), + self.with_equiv('c', ('n', 'm'))]) + + + def test_transpose_3d(m, n, k): + a = np.ones((m, n, k)) + b = a.T + c = a.transpose() + d = a.transpose(2,0,1) + dt = a.transpose((2,0,1)) + e = a.transpose(0,2,1) + et = a.transpose((0,2,1)) + # Numba njit cannot compile explicit transpose call! + # c = np.transpose(b) + self._compile_and_test(test_transpose_3d, (types.intp, types.intp, types.intp), + equivs=[self.with_equiv('a', ('m', 'n', 'k')), + self.with_equiv('b', ('k', 'n', 'm')), + self.with_equiv('c', ('k', 'n', 'm')), + self.with_equiv('d', ('k', 'm', 'n')), + self.with_equiv('dt', ('k', 'm', 'n')), + self.with_equiv('e', ('m', 'k', 'n')), + self.with_equiv('et', ('m', 'k', 'n'))]) + + def test_real_imag_attr(m, n): + a = np.ones((m, n)) + b = a.real + c = a.imag + + self._compile_and_test(test_real_imag_attr, (types.intp, types.intp), + equivs=[self.with_equiv('a', ('m', 'n')), + self.with_equiv('b', ('m', 'n')), + self.with_equiv('c', ('m', 'n')), + ]) + + def test_random(n): + a0 = np.random.rand(n) + a1 = np.random.rand(n, n) + b0 = np.random.randn(n) + b1 = np.random.randn(n, n) + c0 = np.random.ranf(n) + c1 = np.random.ranf((n, n)) + c2 = np.random.ranf(size=(n, n)) + d0 = np.random.random_sample(n) + d1 = np.random.random_sample((n, n)) + d2 = np.random.random_sample(size=(n, n)) + e0 = np.random.sample(n) + e1 = np.random.sample((n, n)) + e2 = np.random.sample(size=(n, n)) + f0 = np.random.random(n) + f1 = np.random.random((n, n)) + f2 = np.random.random(size=(n, n)) + g0 = np.random.standard_normal(n) + g1 = np.random.standard_normal((n, n)) + g2 = np.random.standard_normal(size=(n, n)) + h0 = np.random.chisquare(10, n) + h1 = np.random.chisquare(10, (n, n)) + h2 = np.random.chisquare(10, size=(n, n)) + i0 = np.random.weibull(10, n) + i1 = np.random.weibull(10, (n, n)) + i2 = np.random.weibull(10, size=(n, n)) + j0 = np.random.power(10, n) + j1 = np.random.power(10, (n, n)) + j2 = np.random.power(10, size=(n, n)) + k0 = np.random.geometric(0.1, n) + k1 = np.random.geometric(0.1, (n, n)) + k2 = np.random.geometric(0.1, size=(n, n)) + l0 = np.random.exponential(10, n) + l1 = np.random.exponential(10, (n, n)) + l2 = np.random.exponential(10, size=(n, n)) + m0 = np.random.poisson(10, n) + m1 = np.random.poisson(10, (n, n)) + m2 = np.random.poisson(10, size=(n, n)) + n0 = np.random.rayleigh(10, n) + n1 = np.random.rayleigh(10, (n, n)) + n2 = np.random.rayleigh(10, size=(n, n)) + o0 = np.random.normal(0, 1, n) + o1 = np.random.normal(0, 1, (n, n)) + o2 = np.random.normal(0, 1, size=(n, n)) + p0 = np.random.uniform(0, 1, n) + p1 = np.random.uniform(0, 1, (n, n)) + p2 = np.random.uniform(0, 1, size=(n, n)) + q0 = np.random.beta(0.1, 1, n) + q1 = np.random.beta(0.1, 1, (n, n)) + q2 = np.random.beta(0.1, 1, size=(n, n)) + r0 = np.random.binomial(0, 1, n) + r1 = np.random.binomial(0, 1, (n, n)) + r2 = np.random.binomial(0, 1, size=(n, n)) + s0 = np.random.f(0.1, 1, n) + s1 = np.random.f(0.1, 1, (n, n)) + s2 = np.random.f(0.1, 1, size=(n, n)) + t0 = np.random.gamma(0.1, 1, n) + t1 = np.random.gamma(0.1, 1, (n, n)) + t2 = np.random.gamma(0.1, 1, size=(n, n)) + u0 = np.random.lognormal(0, 1, n) + u1 = np.random.lognormal(0, 1, (n, n)) + u2 = np.random.lognormal(0, 1, size=(n, n)) + v0 = np.random.laplace(0, 1, n) + v1 = np.random.laplace(0, 1, (n, n)) + v2 = np.random.laplace(0, 1, size=(n, n)) + w0 = np.random.randint(0, 10, n) + w1 = np.random.randint(0, 10, (n, n)) + w2 = np.random.randint(0, 10, size=(n, n)) + x0 = np.random.triangular(-3, 0, 10, n) + x1 = np.random.triangular(-3, 0, 10, (n, n)) + x2 = np.random.triangular(-3, 0, 10, size=(n, n)) + + last = ord('x') + 1 + vars1d = [('n',)] + [chr(x) + '0' for x in range(ord('a'), last)] + vars2d = [('n', 'n')] + [chr(x) + '1' for x in range(ord('a'), last)] + vars2d += [chr(x) + '1' for x in range(ord('c'), last)] + self._compile_and_test(test_random, (types.intp,), + equivs=[self.with_equiv(*vars1d), + self.with_equiv(*vars2d)]) + + def test_concatenate(m, n): + a = np.ones(m) + b = np.ones(n) + c = np.concatenate((a, b)) + d = np.ones((2, n)) + e = np.ones((3, n)) + f = np.concatenate((d, e)) + # Numba njit cannot compile concatenate with single array! + # g = np.ones((3,4,5)) + # h = np.concatenate(g) + i = np.ones((m, 2)) + j = np.ones((m, 3)) + k = np.concatenate((i, j), axis=1) + l = np.ones((m, n)) + o = np.ones((m, n)) + p = np.concatenate((l, o)) + # Numba njit cannot support list argument! + # q = np.concatenate([d, e]) + self._compile_and_test(test_concatenate, (types.intp, types.intp), + equivs=[self.with_equiv('f', (5, 'n')), + #self.with_equiv('h', (3 + 4 + 5, )), + self.with_equiv('k', ('m', 5))], + asserts=[self.with_shapecall('c'), + self.without_shapecall('f'), + self.without_shapecall('k'), + self.with_shapecall('p')]) + + def test_vsd_stack(): + k = np.ones((2,)) + l = np.ones((2, 3)) + o = np.ones((2, 3, 4)) + p = np.vstack((k, k)) + q = np.vstack((l, l)) + r = np.hstack((k, k)) + s = np.hstack((l, l)) + t = np.dstack((k, k)) + u = np.dstack((l, l)) + v = np.dstack((o, o)) + + self._compile_and_test(test_vsd_stack, (), + equivs=[self.with_equiv('p', (2, 2)), + self.with_equiv('q', (4, 3)), + self.with_equiv('r', (4,)), + self.with_equiv('s', (2, 6)), + self.with_equiv('t', (1, 2, 2)), + self.with_equiv('u', (2, 3, 2)), + self.with_equiv('v', (2, 3, 8)), + ]) + + def test_stack(m, n): + a = np.ones(m) + b = np.ones(n) + c = np.stack((a, b)) + d = np.ones((m, n)) + e = np.ones((m, n)) + f = np.stack((d, e)) + g = np.stack((d, e), axis=0) + h = np.stack((d, e), axis=1) + i = np.stack((d, e), axis=2) + j = np.stack((d, e), axis=-1) + + self._compile_and_test(test_stack, (types.intp, types.intp), + equivs=[self.with_equiv('m', 'n'), + self.with_equiv('c', (2, 'm')), + self.with_equiv( + 'f', 'g', (2, 'm', 'n')), + self.with_equiv( + 'h', ('m', 2, 'n')), + self.with_equiv( + 'i', 'j', ('m', 'n', 2)), + ]) + + def test_linspace(m, n): + a = np.linspace(m, n) + b = np.linspace(m, n, 10) + # Numba njit does not support num keyword to linspace call! + # c = np.linspace(m,n,num=10) + self._compile_and_test(test_linspace, (types.float64, types.float64), + equivs=[self.with_equiv('a', (50,)), + self.with_equiv('b', (10,))]) + + def test_dot(l, m, n): + a = np.dot(np.ones(1), np.ones(1)) + b = np.dot(np.ones(2), np.ones((2, 3))) + # Numba njit does not support higher dimensional inputs + #c = np.dot(np.ones(2),np.ones((3,2,4))) + #d = np.dot(np.ones(2),np.ones((3,5,2,4))) + e = np.dot(np.ones((1, 2)), np.ones(2,)) + #f = np.dot(np.ones((1,2,3)),np.ones(3,)) + #g = np.dot(np.ones((1,2,3,4)),np.ones(4,)) + h = np.dot(np.ones((2, 3)), np.ones((3, 4))) + i = np.dot(np.ones((m, n)), np.ones((n, m))) + j = np.dot(np.ones((m, m)), np.ones((l, l))) + + self._compile_and_test(test_dot, (types.intp, types.intp, types.intp), + equivs=[self.without_equiv('a', (1,)), # not array + self.with_equiv('b', (3,)), + self.with_equiv('e', (1,)), + self.with_equiv('h', (2, 4)), + self.with_equiv('i', ('m', 'm')), + self.with_equiv('j', ('m', 'm')), + ], + asserts=[self.with_assert('m', 'l')]) + + def test_broadcast(m, n): + a = np.ones((m, n)) + b = np.ones(n) + c = a + b + d = np.ones((1, n)) + e = a + c - d + self._compile_and_test(test_broadcast, (types.intp, types.intp), + equivs=[self.with_equiv('a', 'c', 'e')], + asserts=None) + + # make sure shape of a global tuple of ints is handled properly + def test_global_tuple(): + a = np.ones(GVAL2) + b = np.ones(GVAL2) + + self._compile_and_test(test_global_tuple, (), + equivs=[self.with_equiv('a', 'b')], + asserts=None) + + +class TestArrayAnalysisParallelRequired(TestCase): + """This is to just split out tests that need the parallel backend and + therefore serialised execution. + """ + + _numba_parallel_test_ = False + + @skip_unsupported + def test_misc(self): + + @njit + def swap(x, y): + return(y, x) + + def test_bug2537(m): + a = np.ones(m) + b = np.ones(m) + for i in range(m): + a[i], b[i] = swap(a[i], b[i]) + + try: + njit(test_bug2537, parallel=True)(10) + except IndexError: + self.fail("test_bug2537 raised IndexError!") + + @skip_unsupported + def test_global_namedtuple(self): + Row = namedtuple('Row', ['A']) + row = Row(3) + + def test_impl(): + rr = row + res = rr.A + if res == 2: + res = 3 + return res + + self.assertEqual(njit(test_impl, parallel=True)(), test_impl()) + + @skip_unsupported + def test_array_T_issue_3700(self): + + def test_impl(t_obj, X): + for i in prange(t_obj.T): + X[i] = i + return X.sum() + + n = 5 + t_obj = ExampleClass3700(n) + X1 = np.zeros(t_obj.T) + X2 = np.zeros(t_obj.T) + self.assertEqual( + njit(test_impl, parallel=True)(t_obj, X1), test_impl(t_obj, X2)) + + @skip_unsupported + def test_slice_shape_issue_3380(self): + # these tests shouldn't throw error in array analysis + def test_impl1(): + a = slice(None, None) + return True + + self.assertEqual(njit(test_impl1, parallel=True)(), test_impl1()) + + def test_impl2(A, a): + b = a + return A[b] + + A = np.arange(10) + a = slice(None) + np.testing.assert_array_equal( + njit(test_impl2, parallel=True)(A, a), test_impl2(A, a)) + + @skip_unsupported + def test_slice_dtype_issue_5056(self): + # see issue 5056 + + @njit(parallel=True) + def test_impl(data): + N = data.shape[0] + sums = np.zeros(N) + for i in prange(N): + sums[i] = np.sum(data[np.int32(0):np.int32(1)]) + return sums + + data = np.arange(10.) + np.testing.assert_array_equal(test_impl(data), test_impl.py_func(data)) + + @skip_unsupported + def test_global_tuple(self): + """make sure a global tuple with non-integer values does not cause errors + (test for #6726). + """ + + def test_impl(): + d = GVAL[0] + return d + + self.assertEqual(njit(test_impl, parallel=True)(), test_impl()) + + +class TestArrayAnalysisInterface(TestCase): + def test_analyze_op_call_interface(self): + # gather _analyze_op_call_* + aoc = {} + for fname in dir(ArrayAnalysis): + if fname.startswith('_analyze_op_call_'): + aoc[fname] = getattr(ArrayAnalysis, fname) + # check interface + def iface_stub(self, scope, equiv_set, loc, args, kws): + pass + expected = utils.pysignature(iface_stub) + for k, v in aoc.items(): + got = utils.pysignature(v) + with self.subTest(fname=k, sig=got): + self.assertEqual(got, expected) + + @skip_unsupported + def test_array_analysis_extensions(self): + # Test that the `array_analysis` object in `array_analysis_extensions` + # can perform analysis on the scope using `equiv_sets`. + from numba.parfors.parfor import Parfor + from numba.parfors import array_analysis + + orig_parfor = array_analysis.array_analysis_extensions[Parfor] + + shared = {'counter': 0} + + def testcode(array_analysis): + # Find call node corresponding to the ``A = empty(n)`` + func_ir = array_analysis.func_ir + for call in func_ir.blocks[0].find_exprs('call'): + callee = func_ir.get_definition(call.func) + if getattr(callee, "value", None) is empty: + if getattr(call.args[0], 'name', None) == 'n': + break + else: + return + + variable_A = func_ir.get_assignee(call) + # n must be equiv to + es = array_analysis.equiv_sets[0] + self.assertTrue(es.is_equiv('n', variable_A.name)) + shared['counter'] += 1 + + def new_parfor(parfor, equiv_set, typemap, array_analysis): + """Recursive array analysis for parfor nodes. + """ + testcode(array_analysis) + # Call original + return orig_parfor( + parfor, equiv_set, typemap, array_analysis, + ) + + try: + # Replace the array-analysis extension for Parfor node + array_analysis.array_analysis_extensions[Parfor] = new_parfor + + empty = np.empty # avoid scanning a getattr in the IR + def f(n): + A = empty(n) + for i in prange(n): + S = np.arange(i) + A[i] = S.sum() + return A + 1 + + got = njit(parallel=True)(f)(10) + executed_count = shared['counter'] + self.assertGreater(executed_count, 0) + finally: + # Re-install the original handler + array_analysis.array_analysis_extensions[Parfor] = orig_parfor + + # Check normal execution + expected = njit(parallel=True)(f)(10) + self.assertPreciseEqual(got, expected) + # Make sure we have uninstalled the handler + self.assertEqual(executed_count, shared['counter']) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_array_manipulation.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_array_manipulation.py new file mode 100644 index 0000000000000000000000000000000000000000..2539319fd560a759004484e715c31b9ed076a68e --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_array_manipulation.py @@ -0,0 +1,1588 @@ +from functools import partial +from itertools import permutations + +import numpy as np + +import unittest +from numba import jit, njit, from_dtype, typeof +from numba.core.errors import TypingError +from numba.core import types, errors +from numba.tests.support import TestCase, MemoryLeakMixin + +enable_pyobj_flags = {'forceobj': True} + +no_pyobj_flags = {'_nrt': True, 'nopython': True} + + +def from_generic(pyfuncs_to_use): + """Decorator for generic check functions. + Iterates over 'pyfuncs_to_use', calling 'func' with the iterated + item as first argument. Example: + + @from_generic(numpy_array_reshape, array_reshape) + def check_only_shape(pyfunc, arr, shape, expected_shape): + # Only check Numba result to avoid Numpy bugs + self.memory_leak_setup() + got = generic_run(pyfunc, arr, shape) + self.assertEqual(got.shape, expected_shape) + self.assertEqual(got.size, arr.size) + del got + self.memory_leak_teardown() + """ + def decorator(func): + def result(*args, **kwargs): + return [func(pyfunc, *args, **kwargs) for pyfunc in pyfuncs_to_use] + return result + return decorator + + +@njit +def array_reshape(arr, newshape): + return arr.reshape(newshape) + +@njit +def numpy_array_reshape(arr, newshape): + return np.reshape(arr, newshape) + + +def numpy_broadcast_to(arr, shape): + return np.broadcast_to(arr, shape) + + +def numpy_broadcast_shapes(*args): + return np.broadcast_shapes(*args) + + +def numpy_broadcast_arrays(*args): + return np.broadcast_arrays(*args) + + +def numpy_broadcast_to_indexing(arr, shape, idx): + return np.broadcast_to(arr, shape)[idx] + + +def flatten_array(a): + return a.flatten() + + +def ravel_array(a): + return a.ravel() + + +def ravel_array_size(a): + return a.ravel().size + + +def numpy_ravel_array(a): + return np.ravel(a) + + +def transpose_array(a): + return a.transpose() + + +def numpy_transpose_array(a): + return np.transpose(a) + + +@njit +def numpy_transpose_array_axes_kwarg(arr, axes): + return np.transpose(arr, axes=axes) + + +@njit +def numpy_transpose_array_axes_kwarg_copy(arr, axes): + return np.transpose(arr, axes=axes).copy() + + +@njit +def array_transpose_axes(arr, axes): + return arr.transpose(axes) + + +@njit +def array_transpose_axes_copy(arr, axes): + return arr.transpose(axes).copy() + + +@njit +def transpose_issue_4708(m, n): + r1 = np.reshape(np.arange(m * n * 3), (m, 3, n)) + r2 = np.reshape(np.arange(n * 3), (n, 3)) + r_dif = (r1 - r2.T).T + r_dif = np.transpose(r_dif, (2, 0, 1)) + z = r_dif + 1 + return z + + +def squeeze_array(a): + return a.squeeze() + + +def expand_dims(a, axis): + return np.expand_dims(a, axis) + + +def atleast_1d(*args): + return np.atleast_1d(*args) + + +def atleast_2d(*args): + return np.atleast_2d(*args) + + +def atleast_3d(*args): + return np.atleast_3d(*args) + + +def as_strided1(a): + # as_strided() with implicit shape + strides = (a.strides[0] // 2,) + a.strides[1:] + return np.lib.stride_tricks.as_strided(a, strides=strides) + + +def as_strided2(a): + # Rolling window example as in https://github.com/numba/numba/issues/1884 + window = 3 + shape = a.shape[:-1] + (a.shape[-1] - window + 1, window) + strides = a.strides + (a.strides[-1],) + return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides) + + +@njit +def sliding_window_view(x, window_shape, axis=None): + return np.lib.stride_tricks.sliding_window_view(x, window_shape, axis=axis) + + +def bad_index(arr, arr2d): + x = arr.x, + y = arr.y + # note that `x` is a tuple, which causes a new axis to be created. + arr2d[x, y] = 1.0 + + +def bad_float_index(arr): + # 2D index required for this function because 1D index + # fails typing + return arr[1, 2.0] + + +def numpy_fill_diagonal(arr, val, wrap=False): + return np.fill_diagonal(arr, val, wrap) + + +def numpy_shape(arr): + return np.shape(arr) + +def numpy_size(arr): + return np.size(arr) + + +def numpy_flatnonzero(a): + return np.flatnonzero(a) + + +def numpy_argwhere(a): + return np.argwhere(a) + +def numpy_resize(a, new_shape): + return np.resize(a, new_shape) + + +class TestArrayManipulation(MemoryLeakMixin, TestCase): + """ + Check shape-changing operations on arrays. + """ + def test_array_reshape(self): + pyfuncs_to_use = [array_reshape, numpy_array_reshape] + + def generic_run(pyfunc, arr, shape): + return pyfunc(arr, shape) + + @from_generic(pyfuncs_to_use) + def check(pyfunc, arr, shape): + expected = pyfunc.py_func(arr, shape) + self.memory_leak_setup() + got = generic_run(pyfunc, arr, shape) + self.assertPreciseEqual(got, expected) + del got + self.memory_leak_teardown() + + @from_generic(pyfuncs_to_use) + def check_only_shape(pyfunc, arr, shape, expected_shape): + # Only check Numba result to avoid Numpy bugs + self.memory_leak_setup() + got = generic_run(pyfunc, arr, shape) + self.assertEqual(got.shape, expected_shape) + self.assertEqual(got.size, arr.size) + del got + self.memory_leak_teardown() + + @from_generic(pyfuncs_to_use) + def check_err_shape(pyfunc, arr, shape): + with self.assertRaises(NotImplementedError) as raises: + generic_run(pyfunc, arr, shape) + self.assertEqual(str(raises.exception), + "incompatible shape for array") + + @from_generic(pyfuncs_to_use) + def check_err_size(pyfunc, arr, shape): + with self.assertRaises(ValueError) as raises: + generic_run(pyfunc, arr, shape) + self.assertEqual(str(raises.exception), + "total size of new array must be unchanged") + + @from_generic(pyfuncs_to_use) + def check_err_multiple_negative(pyfunc, arr, shape): + with self.assertRaises(ValueError) as raises: + generic_run(pyfunc, arr, shape) + self.assertEqual(str(raises.exception), + "multiple negative shape values") + + + # C-contiguous + arr = np.arange(24) + check(arr, (24,)) + check(arr, (4, 6)) + check(arr, (8, 3)) + check(arr, (8, 1, 3)) + check(arr, (1, 8, 1, 1, 3, 1)) + arr = np.arange(24).reshape((2, 3, 4)) + check(arr, (24,)) + check(arr, (4, 6)) + check(arr, (8, 3)) + check(arr, (8, 1, 3)) + check(arr, (1, 8, 1, 1, 3, 1)) + check_err_size(arr, ()) + check_err_size(arr, (25,)) + check_err_size(arr, (8, 4)) + arr = np.arange(24).reshape((1, 8, 1, 1, 3, 1)) + check(arr, (24,)) + check(arr, (4, 6)) + check(arr, (8, 3)) + check(arr, (8, 1, 3)) + + # F-contiguous + arr = np.arange(24).reshape((2, 3, 4)).T + check(arr, (4, 3, 2)) + check(arr, (1, 4, 1, 3, 1, 2, 1)) + check_err_shape(arr, (2, 3, 4)) + check_err_shape(arr, (6, 4)) + check_err_shape(arr, (2, 12)) + + # Test negative shape value + arr = np.arange(25).reshape(5,5) + check(arr, -1) + check(arr, (-1,)) + check(arr, (-1, 5)) + check(arr, (5, -1, 5)) + check(arr, (5, 5, -1)) + check_err_size(arr, (-1, 4)) + check_err_multiple_negative(arr, (-1, -2, 5, 5)) + check_err_multiple_negative(arr, (5, 5, -1, -1)) + + # 0-sized arrays + def check_empty(arr): + check(arr, 0) + check(arr, (0,)) + check(arr, (1, 0, 2)) + check(arr, (0, 55, 1, 0, 2)) + # -1 is buggy in Numpy with 0-sized arrays + check_only_shape(arr, -1, (0,)) + check_only_shape(arr, (-1,), (0,)) + check_only_shape(arr, (0, -1), (0, 0)) + check_only_shape(arr, (4, -1), (4, 0)) + check_only_shape(arr, (-1, 0, 4), (0, 0, 4)) + check_err_size(arr, ()) + check_err_size(arr, 1) + check_err_size(arr, (1, 2)) + + arr = np.array([]) + check_empty(arr) + check_empty(arr.reshape((3, 2, 0))) + + # Exceptions leak references + self.disable_leak_check() + + def test_array_transpose_axes(self): + pyfuncs_to_use = [numpy_transpose_array_axes_kwarg, + numpy_transpose_array_axes_kwarg_copy, + array_transpose_axes, + array_transpose_axes_copy] + + @from_generic(pyfuncs_to_use) + def check(pyfunc, arr, axes): + expected = pyfunc.py_func(arr, axes) + got = pyfunc(arr, axes) + self.assertPreciseEqual(got, expected) + self.assertEqual(got.flags.f_contiguous, + expected.flags.f_contiguous) + self.assertEqual(got.flags.c_contiguous, + expected.flags.c_contiguous) + + @from_generic(pyfuncs_to_use) + def check_err_axis_repeated(pyfunc, arr, axes): + with self.assertRaises(ValueError) as raises: + pyfunc(arr, axes) + self.assertEqual(str(raises.exception), + "repeated axis in transpose") + + @from_generic(pyfuncs_to_use) + def check_err_axis_oob(pyfunc, arr, axes): + with self.assertRaises(ValueError) as raises: + pyfunc(arr, axes) + self.assertEqual(str(raises.exception), + "axis is out of bounds for array of given dimension") + + @from_generic(pyfuncs_to_use) + def check_err_invalid_args(pyfunc, arr, axes): + with self.assertRaises((TypeError, TypingError)): + pyfunc(arr, axes) + + arrs = [np.arange(24), + np.arange(24).reshape(4, 6), + np.arange(24).reshape(2, 3, 4), + np.arange(24).reshape(1, 2, 3, 4), + np.arange(64).reshape(8, 4, 2)[::3,::2,:]] + + for i in range(len(arrs)): + # First check `None`, the default, which is to reverse dims + check(arrs[i], None) + # Check supplied axis permutations + for axes in permutations(tuple(range(arrs[i].ndim))): + ndim = len(axes) + neg_axes = tuple([x - ndim for x in axes]) + check(arrs[i], axes) + check(arrs[i], neg_axes) + + @from_generic([transpose_issue_4708]) + def check_issue_4708(pyfunc, m, n): + expected = pyfunc.py_func(m, n) + got = pyfunc(m, n) + # values in arrays are equals, + # but stronger assertions not hold (layout and strides equality) + np.testing.assert_equal(got, expected) + + check_issue_4708(3, 2) + check_issue_4708(2, 3) + check_issue_4708(5, 4) + + # Exceptions leak references + self.disable_leak_check() + + check_err_invalid_args(arrs[1], "foo") + check_err_invalid_args(arrs[1], ("foo",)) + check_err_invalid_args(arrs[1], 5.3) + check_err_invalid_args(arrs[2], (1.2, 5)) + + check_err_axis_repeated(arrs[1], (0, 0)) + check_err_axis_repeated(arrs[2], (2, 0, 0)) + check_err_axis_repeated(arrs[3], (3, 2, 1, 1)) + + check_err_axis_oob(arrs[0], (1,)) + check_err_axis_oob(arrs[0], (-2,)) + check_err_axis_oob(arrs[1], (0, 2)) + check_err_axis_oob(arrs[1], (-3, 2)) + check_err_axis_oob(arrs[1], (0, -3)) + check_err_axis_oob(arrs[2], (3, 1, 2)) + check_err_axis_oob(arrs[2], (-4, 1, 2)) + check_err_axis_oob(arrs[3], (3, 1, 2, 5)) + check_err_axis_oob(arrs[3], (3, 1, 2, -5)) + + with self.assertRaises(TypingError) as e: + jit(nopython=True)(numpy_transpose_array)((np.array([0, 1]),)) + self.assertIn("np.transpose does not accept tuples", + str(e.exception)) + + def test_numpy_resize_basic(self): + pyfunc = numpy_resize + cfunc = njit(pyfunc) + def inputs(): + # Taken from https://github.com/numpy/numpy/blob/f0b2fca91a1f5f50ff696895072f6fe9e69c1466/numpy/core/tests/test_numeric.py#L24-L64 noqa: E501 + yield np.array([[1, 2], [3, 4]]), (2, 4) + yield np.array([[1, 2], [3, 4]]), (4, 2) + yield np.array([[1, 2], [3, 4]]), (4, 3) + yield np.array([[1, 2], [3, 4]]), (0,) + yield np.array([[1, 2], [3, 4]]), (0, 2) + yield np.array([[1, 2], [3, 4]]), (2, 0) + yield np.zeros(0, dtype = float), (2, 1) + # other + yield np.array([[1, 2], [3, 4]]), (4,) + yield np.array([[1, 2], [3, 4]]), 4 + yield np.zeros((1, 3), dtype = int), (2, 1) + yield np.array([], dtype = float), (4, 2) + yield [0, 1, 2, 3], (2, 3) + yield 4, (2, 3) + + for a, new_shape in inputs(): + self.assertPreciseEqual(pyfunc(a, new_shape), cfunc(a, new_shape)) + + def test_numpy_resize_exception(self): + # Exceptions leak references + self.disable_leak_check() + + cfunc = njit(numpy_resize) + + with self.assertRaises(TypingError) as raises: + cfunc("abc", (2, 3)) + self.assertIn(('The argument "a" must be array-like'), + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc(np.array([[0,1],[2,3]]), "abc") + self.assertIn(('The argument "new_shape" must be an integer or ' + 'a tuple of integers'), + str(raises.exception)) + + with self.assertRaises(ValueError) as raises: + cfunc(np.array([[0,1],[2,3]]), (-2, 3)) + self.assertIn(('All elements of `new_shape` must be non-negative'), + str(raises.exception)) + + with self.assertRaises(ValueError) as raises: + cfunc(np.array([[0,1],[2,3]]), -4) + self.assertIn(('All elements of `new_shape` must be non-negative'), + str(raises.exception)) + + def test_expand_dims(self): + pyfunc = expand_dims + cfunc = njit(pyfunc) + + def check(arr, axis): + expected = pyfunc(arr, axis) + self.memory_leak_setup() + got = cfunc(arr, axis) + self.assertPreciseEqual(got, expected) + del got + self.memory_leak_teardown() + + def check_all_axes(arr): + for axis in range(-arr.ndim - 1, arr.ndim + 1): + check(arr, axis) + + # 1d + arr = np.arange(5) + check_all_axes(arr) + # 3d (C, F, A) + arr = np.arange(24).reshape((2, 3, 4)) + check_all_axes(arr) + check_all_axes(arr.T) + check_all_axes(arr[::-1]) + # 0d + arr = np.array(42) + check_all_axes(arr) + + def test_expand_dims_exceptions(self): + pyfunc = expand_dims + cfunc = jit(nopython=True)(pyfunc) + arr = np.arange(5) + + with self.assertTypingError() as raises: + cfunc('hello', 3) + self.assertIn('First argument "a" must be an array', str(raises.exception)) + + with self.assertTypingError() as raises: + cfunc(arr, 'hello') + self.assertIn('Argument "axis" must be an integer', str(raises.exception)) + + + def check_atleast_nd(self, pyfunc, cfunc): + def check_result(got, expected): + # We would like to check the result has the same contiguity, + # but we can't rely on the "flags" attribute when there are + # 1-sized dimensions. + self.assertStridesEqual(got, expected) + self.assertPreciseEqual(got.flatten(), expected.flatten()) + + def check_single(arg): + check_result(cfunc(arg), pyfunc(arg)) + + def check_tuple(*args): + expected_tuple = pyfunc(*args) + got_tuple = cfunc(*args) + self.assertEqual(len(got_tuple), len(expected_tuple)) + for got, expected in zip(got_tuple, expected_tuple): + check_result(got, expected) + + # 0d + a1 = np.array(42) + a2 = np.array(5j) + check_single(a1) + check_tuple(a1, a2) + # 1d + b1 = np.arange(5) + b2 = np.arange(6) + 1j + b3 = b1[::-1] + check_single(b1) + check_tuple(b1, b2, b3) + # 2d + c1 = np.arange(6).reshape((2, 3)) + c2 = c1.T + c3 = c1[::-1] + check_single(c1) + check_tuple(c1, c2, c3) + # 3d + d1 = np.arange(24).reshape((2, 3, 4)) + d2 = d1.T + d3 = d1[::-1] + check_single(d1) + check_tuple(d1, d2, d3) + # 4d + e = np.arange(16).reshape((2, 2, 2, 2)) + check_single(e) + # mixed dimensions + check_tuple(a1, b2, c3, d2) + + def test_atleast_1d(self): + pyfunc = atleast_1d + cfunc = jit(nopython=True)(pyfunc) + self.check_atleast_nd(pyfunc, cfunc) + + def test_atleast_2d(self): + pyfunc = atleast_2d + cfunc = jit(nopython=True)(pyfunc) + self.check_atleast_nd(pyfunc, cfunc) + + def test_atleast_3d(self): + pyfunc = atleast_3d + cfunc = jit(nopython=True)(pyfunc) + self.check_atleast_nd(pyfunc, cfunc) + + def check_as_strided(self, pyfunc): + cfunc = njit(pyfunc) + + def check(arr): + expected = pyfunc(arr) + got = cfunc(arr) + self.assertPreciseEqual(got, expected) + + arr = np.arange(24) + check(arr) + check(arr.reshape((6, 4))) + check(arr.reshape((4, 1, 6))) + + def test_as_strided(self): + self.check_as_strided(as_strided1) + self.check_as_strided(as_strided2) + + def test_as_strided_stride_none(self): + + @jit + def foo(): + arr = np.arange(24).reshape((6, 4)) + return np.lib.stride_tricks.as_strided(arr, strides=None) + + with self.assertRaises(errors.TypingError) as raises: + foo() + + msg = "strides argument cannot be None" + self.assertIn(msg, str(raises.exception)) + + def test_sliding_window_view(self): + def check(arr, window_shape, axis): + # Our version is always writeable (NumPy default is False). + expected = np.lib.stride_tricks.sliding_window_view( + arr, window_shape, axis, writeable=True + ) + got = sliding_window_view(arr, window_shape, axis) + self.assertPreciseEqual(got, expected) + + # 1d array, different ways of specifying the axis. + arr1 = np.arange(24) + for axis in [None, 0, -1, (0,)]: + with self.subTest(f"1d array, axis={axis}"): + check(arr1, 5, axis) + + # 2d array, 1d window. + arr2 = np.arange(200).reshape(10, 20) + for axis in [0, -1]: + with self.subTest(f"2d array, axis={axis}"): + check(arr2, 5, axis) + + # 2d array, 2d window. + for axis in [None, (0, 1), (1, 0), (1, -2)]: + with self.subTest(f"2d array, axis={axis}"): + check(arr2, (5, 8), axis) + + # 4d array, 2d window. + arr4 = np.arange(200).reshape(4, 5, 5, 2) + for axis in [(1, 2), (-2, -3)]: + with self.subTest(f"4d array, axis={axis}"): + check(arr4, (3, 2), axis) + + # Repeated axis. + with self.subTest("2d array, repeated axes"): + check(arr2, (5, 3, 3), (0, 1, 0)) + + def test_sliding_window_view_errors(self): + def _raises(msg, *args): + with self.assertRaises(ValueError) as raises: + sliding_window_view(*args) + self.assertIn(msg, str(raises.exception)) + + def _typing_error(msg, *args): + with self.assertRaises(errors.TypingError) as raises: + sliding_window_view(*args) + self.assertIn(msg, str(raises.exception)) + + # Exceptions leak references + self.disable_leak_check() + + arr1 = np.arange(24) + arr2 = np.arange(200).reshape(10, 20) + + # Window shape cannot be larger than dimension or negative. + with self.subTest("1d window shape too large"): + _raises("window_shape cannot be larger", arr1, 25, None) + with self.subTest("2d window shape too large"): + _raises("window_shape cannot be larger", arr2, (4, 21), None) + with self.subTest("1d window negative size"): + _raises("`window_shape` cannot contain negative", arr1, -1, None) + with self.subTest("2d window with a negative size"): + _raises("`window_shape` cannot contain negative", arr2, (4, -3), None) + + # window_shape and axis parameters must be compatible. + with self.subTest("1d array, 2d window shape"): + _raises("matching length window_shape and axis", arr1, (10, 2), None) + with self.subTest("2d window shape, only one axis given"): + _raises("matching length window_shape and axis", arr2, (10, 2), 1) + with self.subTest("1d window shape, 2 axes given"): + _raises("matching length window_shape and axis", arr1, 5, (0, 0)) + + # Axis values out of bounds. + with self.subTest("1d array, second axis"): + _raises("Argument axis out of bounds", arr1, 4, 1) + with self.subTest("1d array, axis -2"): + _raises("Argument axis out of bounds", arr1, 4, -2) + with self.subTest("2d array, fourth axis"): + _raises("Argument axis out of bounds", arr2, (4, 4), (0, 3)) + with self.subTest("2d array, axis -3"): + _raises("Argument axis out of bounds", arr2, (4, 4), (0, -3)) + + # Useful messages for unsupported types. + with self.subTest("window_shape=None"): + _typing_error( + "window_shape must be an integer or tuple of integer", arr1, None + ) + with self.subTest("window_shape=float"): + _typing_error( + "window_shape must be an integer or tuple of integer", arr1, 3.1 + ) + with self.subTest("window_shape=tuple(float)"): + _typing_error( + "window_shape must be an integer or tuple of integer", arr1, (3.1,) + ) + with self.subTest("axis=float"): + _typing_error( + "axis must be None, an integer or tuple of integer", arr1, 4, 3.1 + ) + with self.subTest("axis=tuple(float)"): + _typing_error( + "axis must be None, an integer or tuple of integer", arr1, 4, (3.1,) + ) + + + def test_flatten_array(self, flags=enable_pyobj_flags, layout='C'): + a = np.arange(9).reshape(3, 3) + if layout == 'F': + a = a.T + + pyfunc = flatten_array + arraytype1 = typeof(a) + if layout == 'A': + # Force A layout + arraytype1 = arraytype1.copy(layout='A') + + self.assertEqual(arraytype1.layout, layout) + cfunc = jit((arraytype1,), **flags)(pyfunc) + + expected = pyfunc(a) + got = cfunc(a) + np.testing.assert_equal(expected, got) + + def test_flatten_array_npm(self): + self.test_flatten_array(flags=no_pyobj_flags) + self.test_flatten_array(flags=no_pyobj_flags, layout='F') + self.test_flatten_array(flags=no_pyobj_flags, layout='A') + + def test_ravel_array(self, flags=enable_pyobj_flags): + def generic_check(pyfunc, a, assume_layout): + # compile + arraytype1 = typeof(a) + self.assertEqual(arraytype1.layout, assume_layout) + cfunc = jit((arraytype1,), **flags)(pyfunc) + + expected = pyfunc(a) + got = cfunc(a) + # Check result matches + np.testing.assert_equal(expected, got) + # Check copying behavior + py_copied = (a.ctypes.data != expected.ctypes.data) + nb_copied = (a.ctypes.data != got.ctypes.data) + self.assertEqual(py_copied, assume_layout != 'C') + self.assertEqual(py_copied, nb_copied) + + check_method = partial(generic_check, ravel_array) + check_function = partial(generic_check, numpy_ravel_array) + + def check(*args, **kwargs): + check_method(*args, **kwargs) + check_function(*args, **kwargs) + + # Check 2D + check(np.arange(9).reshape(3, 3), assume_layout='C') + check(np.arange(9).reshape(3, 3, order='F'), assume_layout='F') + check(np.arange(18).reshape(3, 3, 2)[:, :, 0], assume_layout='A') + + # Check 3D + check(np.arange(18).reshape(2, 3, 3), assume_layout='C') + check(np.arange(18).reshape(2, 3, 3, order='F'), assume_layout='F') + check(np.arange(36).reshape(2, 3, 3, 2)[:, :, :, 0], assume_layout='A') + + def test_ravel_array_size(self, flags=enable_pyobj_flags): + a = np.arange(9).reshape(3, 3) + + pyfunc = ravel_array_size + arraytype1 = typeof(a) + cfunc = jit((arraytype1,), **flags)(pyfunc) + + expected = pyfunc(a) + got = cfunc(a) + np.testing.assert_equal(expected, got) + + def test_ravel_array_npm(self): + self.test_ravel_array(flags=no_pyobj_flags) + + def test_ravel_array_size_npm(self): + self.test_ravel_array_size(flags=no_pyobj_flags) + + def test_transpose_array(self, flags=enable_pyobj_flags): + @from_generic([transpose_array, numpy_transpose_array]) + def check(pyfunc): + a = np.arange(9).reshape(3, 3) + + arraytype1 = typeof(a) + cfunc = jit((arraytype1,), **flags)(pyfunc) + + expected = pyfunc(a) + got = cfunc(a) + np.testing.assert_equal(expected, got) + + check() + + def test_transpose_array_npm(self): + self.test_transpose_array(flags=no_pyobj_flags) + + def test_squeeze_array(self, flags=enable_pyobj_flags): + a = np.arange(2 * 1 * 3 * 1 * 4).reshape(2, 1, 3, 1, 4) + + pyfunc = squeeze_array + arraytype1 = typeof(a) + cfunc = jit((arraytype1,), **flags)(pyfunc) + + expected = pyfunc(a) + got = cfunc(a) + np.testing.assert_equal(expected, got) + + def test_squeeze_array_npm(self): + with self.assertRaises(errors.TypingError) as raises: + self.test_squeeze_array(flags=no_pyobj_flags) + + self.assertIn("squeeze", str(raises.exception)) + + def test_add_axis(self): + @njit + def np_new_axis_getitem(a, idx): + return a[idx] + + @njit + def np_new_axis_setitem(a, idx, item): + a[idx] = item + return a + + a = np.arange(4 * 5 * 6 * 7).reshape((4, 5, 6, 7)) + idx_cases = [ + (slice(None), np.newaxis), + (np.newaxis, slice(None)), + (slice(1), np.newaxis, 1), + (np.newaxis, 2, slice(None)), + (slice(1), Ellipsis, np.newaxis, 1), + (1, np.newaxis, Ellipsis), + (np.newaxis, slice(1), np.newaxis, 1), + (1, Ellipsis, None, np.newaxis), + (np.newaxis, slice(1), Ellipsis, np.newaxis, 1), + (1, np.newaxis, np.newaxis, Ellipsis), + (np.newaxis, 1, np.newaxis, Ellipsis), + (slice(3), 1, np.newaxis, None), + (np.newaxis, 1, Ellipsis, None), + ] + pyfunc_getitem = np_new_axis_getitem.py_func + cfunc_getitem = np_new_axis_getitem + + pyfunc_setitem = np_new_axis_setitem.py_func + cfunc_setitem = np_new_axis_setitem + + for idx in idx_cases: + expected = pyfunc_getitem(a, idx) + got = cfunc_getitem(a, idx) + np.testing.assert_equal(expected, got) + + a_empty = np.zeros_like(a) + item = a[idx] + + expected = pyfunc_setitem(a_empty.copy(), idx, item) + got = cfunc_setitem(a_empty.copy(), idx, item) + np.testing.assert_equal(expected, got) + + def test_bad_index_npm(self): + with self.assertTypingError() as raises: + arraytype1 = from_dtype(np.dtype([('x', np.int32), + ('y', np.int32)])) + arraytype2 = types.Array(types.int32, 2, 'C') + njit((arraytype1, arraytype2))(bad_index) + self.assertIn('Unsupported array index type', str(raises.exception)) + + def test_bad_float_index_npm(self): + with self.assertTypingError() as raises: + njit((types.Array(types.float64, 2, 'C'),))(bad_float_index) + self.assertIn('Unsupported array index type float64', + str(raises.exception)) + + def test_fill_diagonal_basic(self): + pyfunc = numpy_fill_diagonal + cfunc = jit(nopython=True)(pyfunc) + + def _shape_variations(n): + # square + yield (n, n) + # tall and thin + yield (2 * n, n) + # short and fat + yield (n, 2 * n) + # a bit taller than wide; odd numbers of rows and cols + yield ((2 * n + 1), (2 * n - 1)) + # 4d, all dimensions same + yield (n, n, n, n) + # weird edge case + yield (1, 1, 1) + + def _val_variations(): + yield 1 + yield 3.142 + yield np.nan + yield -np.inf + yield True + yield np.arange(4) + yield (4,) + yield [8, 9] + yield np.arange(54).reshape(9, 3, 2, 1) # contiguous C + yield np.asfortranarray(np.arange(9).reshape(3, 3)) # contiguous F + yield np.arange(9).reshape(3, 3)[::-1] # non-contiguous + + # contiguous arrays + def _multi_dimensional_array_variations(n): + for shape in _shape_variations(n): + yield np.zeros(shape, dtype=np.float64) + yield np.asfortranarray(np.ones(shape, dtype=np.float64)) + + # non-contiguous arrays + def _multi_dimensional_array_variations_strided(n): + for shape in _shape_variations(n): + tmp = np.zeros(tuple([x * 2 for x in shape]), dtype=np.float64) + slicer = tuple(slice(0, x * 2, 2) for x in shape) + yield tmp[slicer] + + def _check_fill_diagonal(arr, val): + for wrap in None, True, False: + a = arr.copy() + b = arr.copy() + + if wrap is None: + params = {} + else: + params = {'wrap': wrap} + + pyfunc(a, val, **params) + cfunc(b, val, **params) + self.assertPreciseEqual(a, b) + + for arr in _multi_dimensional_array_variations(3): + for val in _val_variations(): + _check_fill_diagonal(arr, val) + + for arr in _multi_dimensional_array_variations_strided(3): + for val in _val_variations(): + _check_fill_diagonal(arr, val) + + # non-numeric input arrays + arr = np.array([True] * 9).reshape(3, 3) + _check_fill_diagonal(arr, False) + _check_fill_diagonal(arr, [False, True, False]) + _check_fill_diagonal(arr, np.array([True, False, True])) + + def test_fill_diagonal_exception_cases(self): + pyfunc = numpy_fill_diagonal + cfunc = jit(nopython=True)(pyfunc) + val = 1 + + # Exceptions leak references + self.disable_leak_check() + + # first argument unsupported number of dimensions + for a in np.array([]), np.ones(5): + with self.assertRaises(TypingError) as raises: + cfunc(a, val) + assert "The first argument must be at least 2-D" in str(raises.exception) + + # multi-dimensional input where dimensions are not all equal + with self.assertRaises(ValueError) as raises: + a = np.zeros((3, 3, 4)) + cfunc(a, val) + self.assertEqual("All dimensions of input must be of equal length", str(raises.exception)) + + # cases where val has incompatible type / value + def _assert_raises(arr, val): + with self.assertRaises(ValueError) as raises: + cfunc(arr, val) + self.assertEqual("Unable to safely conform val to a.dtype", str(raises.exception)) + + arr = np.zeros((3, 3), dtype=np.int32) + val = np.nan + _assert_raises(arr, val) + + val = [3.3, np.inf] + _assert_raises(arr, val) + + val = np.array([1, 2, 1e10], dtype=np.int64) + _assert_raises(arr, val) + + arr = np.zeros((3, 3), dtype=np.float32) + val = [1.4, 2.6, -1e100] + _assert_raises(arr, val) + + val = 1.1e100 + _assert_raises(arr, val) + + val = np.array([-1e100]) + _assert_raises(arr, val) + + def test_broadcast_to(self): + pyfunc = numpy_broadcast_to + cfunc = jit(nopython=True)(pyfunc) + + # Tests taken from + # https://github.com/numpy/numpy/blob/75f852edf94a7293e7982ad516bee314d7187c2d/numpy/lib/tests/test_stride_tricks.py#L234-L257 # noqa: E501 + data = [ + [np.array(0), (0,)], + [np.array(0), (1,)], + [np.array(0), (3,)], + [np.ones(1), (1,)], + [np.ones(1), (2,)], + [np.ones(1), (1, 2, 3)], + [np.arange(3), (3,)], + [np.arange(3), (1, 3)], + [np.arange(3), (2, 3)], + # test if shape is not a tuple + [np.ones(0), 0], + [np.ones(1), 1], + [np.ones(1), 2], + # these cases with size 0 are strange, but they reproduce the behavior + # of broadcasting with ufuncs + [np.ones(1), (0,)], + [np.ones((1, 2)), (0, 2)], + [np.ones((2, 1)), (2, 0)], + # numpy accepts scalar values as first argument to np.broadcast_to + [2, (2, 2)], + # tuple input + [(1, 2), (2, 2)], + ] + for input_array, shape in data: + expected = pyfunc(input_array, shape) + got = cfunc(input_array, shape) + self.assertPreciseEqual(got, expected) + + def test_broadcast_to_0d_array(self): + pyfunc = numpy_broadcast_to + cfunc = jit(nopython=True)(pyfunc) + + inputs = [ + np.array(123), + 123, + True, + # can't do np.asarray() on the types below + # 'hello', + # np.timedelta64(10, 'Y'), + # np.datetime64(10, 'Y'), + ] + + shape = () + for arr in inputs: + expected = pyfunc(arr, shape) + got = cfunc(arr, shape) + self.assertPreciseEqual(expected, got) + # ensure that np.broadcast_to returned a read-only array + self.assertFalse(got.flags['WRITEABLE']) + + def test_broadcast_to_raises(self): + pyfunc = numpy_broadcast_to + cfunc = jit(nopython=True)(pyfunc) + + # Tests taken from + # https://github.com/numpy/numpy/blob/75f852edf94a7293e7982ad516bee314d7187c2d/numpy/lib/tests/test_stride_tricks.py#L260-L276 # noqa: E501 + data = [ + [np.zeros((0,)), (), TypingError, + 'Cannot broadcast a non-scalar to a scalar array'], + [np.zeros((1,)), (), TypingError, + 'Cannot broadcast a non-scalar to a scalar array'], + [np.zeros((3,)), (), TypingError, + 'Cannot broadcast a non-scalar to a scalar array'], + [(), (), TypingError, + 'Cannot broadcast a non-scalar to a scalar array'], + [(123,), (), TypingError, + 'Cannot broadcast a non-scalar to a scalar array'], + [np.zeros((3,)), (1,), ValueError, + 'operands could not be broadcast together with remapped shapes'], + [np.zeros((3,)), (2,), ValueError, + 'operands could not be broadcast together with remapped shapes'], + [np.zeros((3,)), (4,), ValueError, + 'operands could not be broadcast together with remapped shapes'], + [np.zeros((1, 2)), (2, 1), ValueError, + 'operands could not be broadcast together with remapped shapes'], + [np.zeros((1, 1)), (1,), ValueError, + 'input operand has more dimensions than allowed by the axis remapping'], + [np.zeros((2, 2)), (3,), ValueError, + 'input operand has more dimensions than allowed by the axis remapping'], + [np.zeros((1,)), -1, ValueError, + 'all elements of broadcast shape must be non-negative'], + [np.zeros((1,)), (-1,), ValueError, + 'all elements of broadcast shape must be non-negative'], + [np.zeros((1, 2)), (-1, 2), ValueError, + 'all elements of broadcast shape must be non-negative'], + [np.zeros((1, 2)), (1.1, 2.2), TypingError, + 'The second argument "shape" must be a tuple of integers'], + ['hello', (3,), TypingError, + 'The first argument "array" must be array-like'], + [3, (2, 'a'), TypingError, + 'object cannot be interpreted as an integer'], + ] + self.disable_leak_check() + for arr, target_shape, err, msg in data: + with self.assertRaises(err) as raises: + cfunc(arr, target_shape) + self.assertIn(msg, str(raises.exception)) + + def test_broadcast_to_corner_cases(self): + @njit + def _broadcast_to_1(): + return np.broadcast_to('a', (2, 3)) + + expected = _broadcast_to_1.py_func() + got = _broadcast_to_1() + self.assertPreciseEqual(expected, got) + + def test_broadcast_to_change_view(self): + pyfunc = numpy_broadcast_to + cfunc = jit(nopython=True)(pyfunc) + input_array = np.zeros(2, dtype=np.int32) + shape = (2, 2) + view = cfunc(input_array, shape) + input_array[0] = 10 + + self.assertEqual(input_array.sum(), 10) + self.assertEqual(view.sum(), 20) + + def test_broadcast_to_indexing(self): + pyfunc = numpy_broadcast_to_indexing + cfunc = jit(nopython=True)(pyfunc) + data = [ + [np.ones(2), (2, 2), (1,)], + ] + for input_array, shape, idx in data: + expected = pyfunc(input_array, shape, idx) + got = cfunc(input_array, shape, idx) + self.assertPreciseEqual(got, expected) + + def test_broadcast_to_array_attrs(self): + # See issue #8534. This tests that broadcast array attributes have the + # correct value when accessed. + @njit + def foo(arr): + ret = np.broadcast_to(arr, (2, 3)) + return ret, ret.size, ret.shape, ret.strides + + arr = np.arange(3) + + expected = foo.py_func(arr) + got = foo(arr) + self.assertPreciseEqual(expected, got) + + def test_broadcast_shapes(self): + pyfunc = numpy_broadcast_shapes + cfunc = jit(nopython=True)(pyfunc) + + # Tests taken from + # https://github.com/numpy/numpy/blob/623bc1fae1d47df24e7f1e29321d0c0ba2771ce0/numpy/lib/tests/test_stride_tricks.py#L296-L334 + data = [ + # [[], ()], # cannot compute fingerprint of empty list + [()], + [(), ()], + [(7,)], + [(1, 2),], + [(1, 1)], + [(1, 1), (3, 4)], + [(6, 7), (5, 6, 1), (7,), (5, 1, 7)], + [(5, 6, 1)], + [(1, 3), (3, 1)], + [(1, 0), (0, 0)], + [(0, 1), (0, 0)], + [(1, 0), (0, 1)], + [(1, 1), (0, 0)], + [(1, 1), (1, 0)], + [(1, 1), (0, 1)], + [(), (0,)], + [(0,), (0, 0)], + [(0,), (0, 1)], + [(1,), (0, 0)], + [(), (0, 0)], + [(1, 1), (0,)], + [(1,), (0, 1)], + [(1,), (1, 0)], + [(), (1, 0)], + [(), (0, 1)], + [(1,), (3,)], + [2, (3, 2)], + ] + for input_shape in data: + expected = pyfunc(*input_shape) + got = cfunc(*input_shape) + self.assertIsInstance(got, tuple) + self.assertPreciseEqual(expected, got) + + def test_broadcast_shapes_raises(self): + pyfunc = numpy_broadcast_shapes + cfunc = jit(nopython=True)(pyfunc) + + self.disable_leak_check() + + # Tests taken from + # https://github.com/numpy/numpy/blob/623bc1fae1d47df24e7f1e29321d0c0ba2771ce0/numpy/lib/tests/test_stride_tricks.py#L337-L351 + data = [ + [(3,), (4,)], + [(2, 3), (2,)], + [(3,), (3,), (4,)], + [(1, 3, 4), (2, 3, 3)], + [(1, 2), (3, 1), (3, 2), (10, 5)], + [2, (2, 3)], + ] + for input_shape in data: + with self.assertRaises(ValueError) as raises: + cfunc(*input_shape) + + self.assertIn("shape mismatch: objects cannot be broadcast to a single shape", + str(raises.exception)) + + def test_broadcast_shapes_negative_dimension(self): + pyfunc = numpy_broadcast_shapes + cfunc = jit(nopython=True)(pyfunc) + + self.disable_leak_check() + with self.assertRaises(ValueError) as raises: + cfunc((1, 2), (2), (-2)) + + self.assertIn("negative dimensions are not allowed", str(raises.exception)) + + def test_broadcast_shapes_invalid_type(self): + pyfunc = numpy_broadcast_shapes + cfunc = jit(nopython=True)(pyfunc) + + self.disable_leak_check() + + inps = [ + ((1, 2), ('hello',)), + (3.4,), + ('string',), + ((1.2, 'a')), + (1, ((1.2, 'a'))), + ] + + for inp in inps: + with self.assertRaises(TypingError) as raises: + cfunc(*inp) + + self.assertIn("must be either an int or tuple[int]", str(raises.exception)) + + def test_shape(self): + pyfunc = numpy_shape + cfunc = jit(nopython=True)(pyfunc) + + def check(x): + expected = pyfunc(x) + got = cfunc(x) + self.assertPreciseEqual(got, expected) + + # check arrays + for t in [(), (1,), (2, 3,), (4, 5, 6)]: + arr = np.empty(t) + check(arr) + + # check some types that go via asarray + for t in [1, False, [1,], [[1, 2,],[3, 4]], (1,), (1, 2, 3)]: + check(arr) + + with self.assertRaises(TypingError) as raises: + cfunc('a') + + self.assertIn("The argument to np.shape must be array-like", + str(raises.exception)) + + def test_size(self): + pyfunc = numpy_size + cfunc = jit(nopython=True)(pyfunc) + + def check(x): + expected = pyfunc(x) + got = cfunc(x) + self.assertPreciseEqual(got, expected) + + # check arrays + for t in [(), (1,), (2, 3,), (4, 5, 6)]: + arr = np.empty(t) + check(arr) + + # check scalar values + for t in [1, False, 3.14, np.int8(4), np.float32(2.718)]: + check(t) + + with self.assertRaises(TypingError) as raises: + cfunc('a') + + self.assertIn("The argument to np.size must be array-like", + str(raises.exception)) + + def test_flatnonzero_basic(self): + pyfunc = numpy_flatnonzero + cfunc = jit(nopython=True)(pyfunc) + + def a_variations(): + yield np.arange(-5, 5) + yield np.full(5, fill_value=0) + yield np.array([]) + a = self.random.randn(100) + a[np.abs(a) > 0.2] = 0.0 + yield a + yield a.reshape(5, 5, 4) + yield a.reshape(50, 2, order='F') + yield a.reshape(25, 4)[1::2] + yield a * 1j + + for a in a_variations(): + expected = pyfunc(a) + got = cfunc(a) + self.assertPreciseEqual(expected, got) + + def test_argwhere_basic(self): + pyfunc = numpy_argwhere + cfunc = jit(nopython=True)(pyfunc) + + def a_variations(): + yield np.arange(-5, 5) > 2 + yield np.full(5, fill_value=0) + yield np.full(5, fill_value=1) + yield np.array([]) + yield np.array([-1.0, 0.0, 1.0]) + a = self.random.randn(100) + yield a > 0.2 + yield a.reshape(5, 5, 4) > 0.5 + yield a.reshape(50, 2, order='F') > 0.5 + yield a.reshape(25, 4)[1::2] > 0.5 + yield a == a - 1 + yield a > -a + + for a in a_variations(): + expected = pyfunc(a) + got = cfunc(a) + self.assertPreciseEqual(expected, got) + + @staticmethod + def array_like_variations(): + yield ((1.1, 2.2), (3.3, 4.4), (5.5, 6.6)) + yield (0.0, 1.0, 0.0, -6.0) + yield ([0, 1], [2, 3]) + yield () + yield np.nan + yield 0 + yield 1 + yield False + yield True + yield (True, False, True) + yield 2 + 1j + # the following are not array-like, but NumPy does not raise + yield None + yield 'a_string' + yield '' + + + def test_flatnonzero_array_like(self): + pyfunc = numpy_flatnonzero + cfunc = jit(nopython=True)(pyfunc) + + for a in self.array_like_variations(): + expected = pyfunc(a) + got = cfunc(a) + self.assertPreciseEqual(expected, got) + + def test_argwhere_array_like(self): + pyfunc = numpy_argwhere + cfunc = jit(nopython=True)(pyfunc) + for a in self.array_like_variations(): + expected = pyfunc(a) + got = cfunc(a) + self.assertPreciseEqual(expected, got) + + def broadcast_arrays_assert_correct_shape(self, input_shapes, expected_shape): + # Broadcast a list of arrays with the given input shapes and check the + # common output shape. + pyfunc = numpy_broadcast_arrays + cfunc = jit(nopython=True)(pyfunc) + + inarrays = [np.zeros(s) for s in input_shapes] + outarrays = cfunc(*inarrays) + expected = [expected_shape] * len(inarrays) + got = [a.shape for a in outarrays] + self.assertPreciseEqual(expected, got) + + def test_broadcast_arrays_same_input_shapes(self): + # Tests taken from + # https://github.com/numpy/numpy/blob/623bc1fae1d47df24e7f1e29321d0c0ba2771ce0/numpy/lib/tests/test_stride_tricks.py#L83-L107 # noqa: E501 + # Check that the final shape is just the input shape. + pyfunc = numpy_broadcast_arrays + cfunc = jit(nopython=True)(pyfunc) + + data = [ + # (), + (1,), + (3,), + (0, 1), + (0, 3), + (1, 0), + (3, 0), + (1, 3), + (3, 1), + (3, 3), + ] + for shape in data: + input_shapes = [shape] + # Single input. + self.broadcast_arrays_assert_correct_shape(input_shapes, shape) + # Double input. + input_shapes2 = [shape, shape] + self.broadcast_arrays_assert_correct_shape(input_shapes2, shape) + # Triple input. + input_shapes3 = [shape, shape, shape] + self.broadcast_arrays_assert_correct_shape(input_shapes3, shape) + + def test_broadcast_arrays_two_compatible_by_ones_input_shapes(self): + # Tests taken from + # https://github.com/numpy/numpy/blob/623bc1fae1d47df24e7f1e29321d0c0ba2771ce0/numpy/lib/tests/test_stride_tricks.py#L110-L132 + # Check that two different input shapes of the same length, but some have + # ones, broadcast to the correct shape. + + data = [ + [[(1,), (3,)], (3,)], + [[(1, 3), (3, 3)], (3, 3)], + [[(3, 1), (3, 3)], (3, 3)], + [[(1, 3), (3, 1)], (3, 3)], + [[(1, 1), (3, 3)], (3, 3)], + [[(1, 1), (1, 3)], (1, 3)], + [[(1, 1), (3, 1)], (3, 1)], + [[(1, 0), (0, 0)], (0, 0)], + [[(0, 1), (0, 0)], (0, 0)], + [[(1, 0), (0, 1)], (0, 0)], + [[(1, 1), (0, 0)], (0, 0)], + [[(1, 1), (1, 0)], (1, 0)], + [[(1, 1), (0, 1)], (0, 1)], + ] + for input_shapes, expected_shape in data: + self.broadcast_arrays_assert_correct_shape(input_shapes, expected_shape) + # Reverse the input shapes since broadcasting should be symmetric. + self.broadcast_arrays_assert_correct_shape(input_shapes[::-1], expected_shape) + + def test_broadcast_arrays_two_compatible_by_prepending_ones_input_shapes(self): + # Tests taken from + # https://github.com/numpy/numpy/blob/623bc1fae1d47df24e7f1e29321d0c0ba2771ce0/numpy/lib/tests/test_stride_tricks.py#L135-L164 + # Check that two different input shapes (of different lengths) broadcast + # to the correct shape. + + data = [ + [[(), (3,)], (3,)], + [[(3,), (3, 3)], (3, 3)], + [[(3,), (3, 1)], (3, 3)], + [[(1,), (3, 3)], (3, 3)], + [[(), (3, 3)], (3, 3)], + [[(1, 1), (3,)], (1, 3)], + [[(1,), (3, 1)], (3, 1)], + [[(1,), (1, 3)], (1, 3)], + [[(), (1, 3)], (1, 3)], + [[(), (3, 1)], (3, 1)], + [[(), (0,)], (0,)], + [[(0,), (0, 0)], (0, 0)], + [[(0,), (0, 1)], (0, 0)], + [[(1,), (0, 0)], (0, 0)], + [[(), (0, 0)], (0, 0)], + [[(1, 1), (0,)], (1, 0)], + [[(1,), (0, 1)], (0, 1)], + [[(1,), (1, 0)], (1, 0)], + [[(), (1, 0)], (1, 0)], + [[(), (0, 1)], (0, 1)], + ] + for input_shapes, expected_shape in data: + self.broadcast_arrays_assert_correct_shape(input_shapes, expected_shape) + # Reverse the input shapes since broadcasting should be symmetric. + self.broadcast_arrays_assert_correct_shape(input_shapes[::-1], expected_shape) + + def test_broadcast_arrays_scalar_input(self): + pyfunc = numpy_broadcast_arrays + cfunc = jit(nopython=True)(pyfunc) + data = [ + [[True, False], (1,)], + [[1, 2], (1,)], + [[(1, 2), 2], (2,)], + ] + for inarrays, expected_shape in data: + outarrays = cfunc(*inarrays) + got = [a.shape for a in outarrays] + expected = [expected_shape] * len(inarrays) + self.assertPreciseEqual(expected, got) + + def test_broadcast_arrays_tuple_input(self): + pyfunc = numpy_broadcast_arrays + cfunc = jit(nopython=True)(pyfunc) + outarrays = cfunc((123, 456), (789,)) + expected = [(2,), (2,)] + got = [a.shape for a in outarrays] + self.assertPreciseEqual(expected, got) + + def test_broadcast_arrays_non_array_input(self): + pyfunc = numpy_broadcast_arrays + cfunc = jit(nopython=True)(pyfunc) + outarrays = cfunc(np.intp(2), np.zeros((1, 3), dtype=np.intp)) + expected = [(1, 3), (1, 3)] + got = [a.shape for a in outarrays] + self.assertPreciseEqual(expected, got) + + def test_broadcast_arrays_invalid_mixed_input_types(self): + pyfunc = numpy_broadcast_arrays + cfunc = jit(nopython=True)(pyfunc) + + self.disable_leak_check() + + with self.assertRaises(TypingError) as raises: + arr = np.arange(6).reshape((2, 3)) + b = True + cfunc(arr, b) + self.assertIn('Mismatch of argument types', str(raises.exception)) + + def test_broadcast_arrays_invalid_input(self): + pyfunc = numpy_broadcast_arrays + cfunc = jit(nopython=True)(pyfunc) + + self.disable_leak_check() + + with self.assertRaises(TypingError) as raises: + arr = np.zeros(3, dtype=np.int64) + s = 'hello world' + cfunc(arr, s) + self.assertIn('Argument "1" must be array-like', str(raises.exception)) + + def test_broadcast_arrays_incompatible_shapes_raise_valueerror(self): + # Check that a ValueError is raised for incompatible shapes. + pyfunc = numpy_broadcast_arrays + cfunc = jit(nopython=True)(pyfunc) + + self.disable_leak_check() + + data = [ + [(3,), (4,)], + [(2, 3), (2,)], + [(3,), (3,), (4,)], + [(1, 3, 4), (2, 3, 3)], + ] + for input_shapes in data: + for shape in [input_shapes, input_shapes[::-1]]: + # Reverse the input shapes since broadcasting should be symmetric. + with self.assertRaises(ValueError) as raises: + inarrays = [np.zeros(s) for s in shape] + cfunc(*inarrays) + self.assertIn("shape mismatch: objects cannot be broadcast to a single shape", + str(raises.exception)) + + def test_readonly_after_flatten(self): + # Reproduces Issue #8370 + def unfold_flatten(x, y): + r, c = x.shape + a = np.broadcast_to(x, (y, r, c)) + b = np.swapaxes(a, 0, 1) + cc = b.flatten() + d = np.reshape(cc, (-1, c)) + d[y - 1:, :] = d[: 1 - y] + return d + + pyfunc = unfold_flatten + cfunc = jit(nopython=True)(pyfunc) + + # If issue #8370 is not fixed: This will fail. + res_nb = cfunc(np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]), 2) + res_py = pyfunc(np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]), 2) + + np.testing.assert_array_equal(res_py, res_nb) + + def test_readonly_after_ravel(self): + # Reproduces another suggested problem in Issue #8370 + def unfold_ravel(x, y): + r, c = x.shape + a = np.broadcast_to(x, (y, r, c)) + b = np.swapaxes(a, 0, 1) + cc = b.ravel() + d = np.reshape(cc, (-1, c)) + d[y - 1:, :] = d[: 1 - y] + return d + + pyfunc = unfold_ravel + cfunc = jit(nopython=True)(pyfunc) + + # If issue #8370 is not fixed: This will fail. + res_nb = cfunc(np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]), 2) + res_py = pyfunc(np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]]), 2) + + np.testing.assert_array_equal(res_py, res_nb) + + def test_mutability_after_ravel(self): + # Reproduces another suggested problem in Issue #8370 + # Namely that ravel should only return a writable array + # if a copy took place... otherwise leave it as it is. + self.disable_leak_check() + a_c = np.arange(9).reshape((3, 3)).copy() + a_f = a_c.copy(order='F') + a_c.flags.writeable = False + a_f.flags.writeable = False + + def try_ravel_w_copy(a): + result = a.ravel() + return result + + pyfunc = try_ravel_w_copy + cfunc = jit(nopython=True)(pyfunc) + + ret_c = cfunc(a_c) + ret_f = cfunc(a_f) + + msg = 'No copy was performed, so the ' \ + 'resulting array must not be writeable' + self.assertTrue(not ret_c.flags.writeable, msg) + + msg = 'A copy was performed, yet the resulting array is not modifiable' + self.assertTrue(ret_f.flags.writeable, msg) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_blackscholes.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_blackscholes.py new file mode 100644 index 0000000000000000000000000000000000000000..d12846117ff793d4af3fd833187849747bf44663 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_blackscholes.py @@ -0,0 +1,125 @@ +import math + +import numpy as np + +import unittest +from numba import njit +from numba.extending import register_jitable +from numba.tests.support import TestCase + + +RISKFREE = 0.02 +VOLATILITY = 0.30 + + +A1 = 0.31938153 +A2 = -0.356563782 +A3 = 1.781477937 +A4 = -1.821255978 +A5 = 1.330274429 +RSQRT2PI = 0.39894228040143267793994605993438 + + +@register_jitable +def cnd_array(d): + K = 1.0 / (1.0 + 0.2316419 * np.abs(d)) + ret_val = (RSQRT2PI * np.exp(-0.5 * d * d) * + (K * (A1 + K * (A2 + K * (A3 + K * (A4 + K * A5)))))) + return np.where(d > 0, 1.0 - ret_val, ret_val) + + +@register_jitable +def cnd(d): + K = 1.0 / (1.0 + 0.2316419 * math.fabs(d)) + ret_val = (RSQRT2PI * math.exp(-0.5 * d * d) * + (K * (A1 + K * (A2 + K * (A3 + K * (A4 + K * A5)))))) + if d > 0: + ret_val = 1.0 - ret_val + return ret_val + + +@njit +def blackscholes_arrayexpr(stockPrice, optionStrike, optionYears, Riskfree, + Volatility): + S = stockPrice + X = optionStrike + T = optionYears + R = Riskfree + V = Volatility + sqrtT = np.sqrt(T) + d1 = (np.log(S / X) + (R + 0.5 * V * V) * T) / (V * sqrtT) + d2 = d1 - V * sqrtT + cndd1 = cnd_array(d1) + cndd2 = cnd_array(d2) + + expRT = np.exp(- R * T) + + callResult = (S * cndd1 - X * expRT * cndd2) + putResult = (X * expRT * (1.0 - cndd2) - S * (1.0 - cndd1)) + return callResult, putResult + + +@njit +def blackscholes_scalar(callResult, putResult, stockPrice, optionStrike, + optionYears, Riskfree, Volatility): + S = stockPrice + X = optionStrike + T = optionYears + R = Riskfree + V = Volatility + for i in range(len(S)): + sqrtT = math.sqrt(T[i]) + d1 = (math.log(S[i] / X[i]) + (R + 0.5 * V * V) * T[i]) / (V * sqrtT) + d2 = d1 - V * sqrtT + cndd1 = cnd(d1) + cndd2 = cnd(d2) + + expRT = math.exp((-1. * R) * T[i]) + callResult[i] = (S[i] * cndd1 - X[i] * expRT * cndd2) + putResult[i] = (X[i] * expRT * (1.0 - cndd2) - S[i] * (1.0 - cndd1)) + + +def randfloat(rand_var, low, high): + return (1.0 - rand_var) * low + rand_var * high + + +class TestBlackScholes(TestCase): + def test_array_expr(self): + OPT_N = 400 + + stockPrice = randfloat(self.random.random_sample(OPT_N), 5.0, 30.0) + optionStrike = randfloat(self.random.random_sample(OPT_N), 1.0, 100.0) + optionYears = randfloat(self.random.random_sample(OPT_N), 0.25, 10.0) + + args = stockPrice, optionStrike, optionYears, RISKFREE, VOLATILITY + + callResultGold, putResultGold = blackscholes_arrayexpr.py_func(*args) + callResultNumba, putResultNumba = blackscholes_arrayexpr(*args) + + delta = np.abs(callResultGold - callResultNumba) + self.assertAlmostEqual(delta.max(), 0) + + def test_scalar(self): + OPT_N = 400 + + callResultGold = np.zeros(OPT_N) + putResultGold = np.zeros(OPT_N) + + callResultNumba = np.zeros(OPT_N) + putResultNumba = np.zeros(OPT_N) + + stockPrice = randfloat(self.random.random_sample(OPT_N), 5.0, 30.0) + optionStrike = randfloat(self.random.random_sample(OPT_N), 1.0, 100.0) + optionYears = randfloat(self.random.random_sample(OPT_N), 0.25, 10.0) + + args = stockPrice, optionStrike, optionYears, RISKFREE, VOLATILITY + + blackscholes_scalar.py_func(callResultGold, putResultGold, *args) + blackscholes_scalar(callResultNumba, putResultNumba, *args) + + delta = np.abs(callResultGold - callResultNumba) + self.assertAlmostEqual(delta.max(), 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_cfunc.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_cfunc.py new file mode 100644 index 0000000000000000000000000000000000000000..1920b2e22e9fb8bff06ae5209618ad0d17aa29f8 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_cfunc.py @@ -0,0 +1,408 @@ +""" +Tests for @cfunc and friends. +""" + + +import ctypes +import os +import subprocess +import sys +from collections import namedtuple + +import numpy as np + +from numba import cfunc, carray, farray, njit +from numba.core import types, typing, utils +import numba.core.typing.cffi_utils as cffi_support +from numba.tests.support import (TestCase, skip_unless_cffi, tag, + captured_stderr) +import unittest +from numba.np import numpy_support + + +def add_usecase(a, b): + return a + b + +def div_usecase(a, b): + c = a / b + return c + +def square_usecase(a): + return a ** 2 + +add_sig = "float64(float64, float64)" + +div_sig = "float64(int64, int64)" + +square_sig = "float64(float64)" + +def objmode_usecase(a, b): + object() + return a + b + +# Test functions for carray() and farray() + +CARRAY_USECASE_OUT_LEN = 8 + +def make_cfarray_usecase(func): + + def cfarray_usecase(in_ptr, out_ptr, m, n): + # Tuple shape + in_ = func(in_ptr, (m, n)) + # Integer shape + out = func(out_ptr, CARRAY_USECASE_OUT_LEN) + out[0] = in_.ndim + out[1:3] = in_.shape + out[3:5] = in_.strides + out[5] = in_.flags.c_contiguous + out[6] = in_.flags.f_contiguous + s = 0 + for i, j in np.ndindex(m, n): + s += in_[i, j] * (i - j) + out[7] = s + + return cfarray_usecase + +carray_usecase = make_cfarray_usecase(carray) +farray_usecase = make_cfarray_usecase(farray) + + +def make_cfarray_dtype_usecase(func): + # Same as make_cfarray_usecase(), but with explicit dtype. + + def cfarray_usecase(in_ptr, out_ptr, m, n): + # Tuple shape + in_ = func(in_ptr, (m, n), dtype=np.float32) + # Integer shape + out = func(out_ptr, CARRAY_USECASE_OUT_LEN, np.float32) + out[0] = in_.ndim + out[1:3] = in_.shape + out[3:5] = in_.strides + out[5] = in_.flags.c_contiguous + out[6] = in_.flags.f_contiguous + s = 0 + for i, j in np.ndindex(m, n): + s += in_[i, j] * (i - j) + out[7] = s + + return cfarray_usecase + +carray_dtype_usecase = make_cfarray_dtype_usecase(carray) +farray_dtype_usecase = make_cfarray_dtype_usecase(farray) + +carray_float32_usecase_sig = types.void(types.CPointer(types.float32), + types.CPointer(types.float32), + types.intp, types.intp) + +carray_float64_usecase_sig = types.void(types.CPointer(types.float64), + types.CPointer(types.float64), + types.intp, types.intp) + +carray_voidptr_usecase_sig = types.void(types.voidptr, types.voidptr, + types.intp, types.intp) + + +class TestCFunc(TestCase): + + def test_basic(self): + """ + Basic usage and properties of a cfunc. + """ + f = cfunc(add_sig)(add_usecase) + + self.assertEqual(f.__name__, "add_usecase") + self.assertEqual(f.__qualname__, "add_usecase") + self.assertIs(f.__wrapped__, add_usecase) + + symbol = f.native_name + self.assertIsInstance(symbol, str) + self.assertIn("add_usecase", symbol) + + addr = f.address + self.assertIsInstance(addr, int) + + ct = f.ctypes + self.assertEqual(ctypes.cast(ct, ctypes.c_void_p).value, addr) + + self.assertPreciseEqual(ct(2.0, 3.5), 5.5) + + @skip_unless_cffi + def test_cffi(self): + from numba.tests import cffi_usecases + ffi, lib = cffi_usecases.load_inline_module() + + f = cfunc(square_sig)(square_usecase) + + res = lib._numba_test_funcptr(f.cffi) + self.assertPreciseEqual(res, 2.25) # 1.5 ** 2 + + def test_locals(self): + # By forcing the intermediate result into an integer, we + # truncate the ultimate function result + f = cfunc(div_sig, locals={'c': types.int64})(div_usecase) + self.assertPreciseEqual(f.ctypes(8, 3), 2.0) + + def test_errors(self): + f = cfunc(div_sig)(div_usecase) + + with captured_stderr() as err: + self.assertPreciseEqual(f.ctypes(5, 2), 2.5) + self.assertEqual(err.getvalue(), "") + + with captured_stderr() as err: + res = f.ctypes(5, 0) + # This is just a side effect of Numba zero-initializing + # stack variables, and could change in the future. + self.assertPreciseEqual(res, 0.0) + err = err.getvalue() + self.assertIn("ZeroDivisionError:", err) + self.assertIn("Exception ignored", err) + + def test_llvm_ir(self): + f = cfunc(add_sig)(add_usecase) + ir = f.inspect_llvm() + self.assertIn(f.native_name, ir) + self.assertIn("fadd double", ir) + + def test_object_mode(self): + """ + Object mode is currently unsupported. + """ + with self.assertRaises(NotImplementedError): + cfunc(add_sig, forceobj=True)(add_usecase) + with self.assertTypingError() as raises: + cfunc(add_sig)(objmode_usecase) + self.assertIn("Untyped global name 'object'", str(raises.exception)) + + +class TestCArray(TestCase): + """ + Tests for carray() and farray(). + """ + + def run_carray_usecase(self, pointer_factory, func): + a = np.arange(10, 16).reshape((2, 3)).astype(np.float32) + out = np.empty(CARRAY_USECASE_OUT_LEN, dtype=np.float32) + func(pointer_factory(a), pointer_factory(out), *a.shape) + return out + + def check_carray_usecase(self, pointer_factory, pyfunc, cfunc): + expected = self.run_carray_usecase(pointer_factory, pyfunc) + got = self.run_carray_usecase(pointer_factory, cfunc) + self.assertPreciseEqual(expected, got) + + def make_voidptr(self, arr): + return arr.ctypes.data_as(ctypes.c_void_p) + + def make_float32_pointer(self, arr): + return arr.ctypes.data_as(ctypes.POINTER(ctypes.c_float)) + + def make_float64_pointer(self, arr): + return arr.ctypes.data_as(ctypes.POINTER(ctypes.c_double)) + + def check_carray_farray(self, func, order): + def eq(got, expected): + # Same layout, dtype, shape, etc. + self.assertPreciseEqual(got, expected) + # Same underlying data + self.assertEqual(got.ctypes.data, expected.ctypes.data) + + base = np.arange(6).reshape((2, 3)).astype(np.float32).copy(order=order) + + # With typed pointer and implied dtype + a = func(self.make_float32_pointer(base), base.shape) + eq(a, base) + # Integer shape + a = func(self.make_float32_pointer(base), base.size) + eq(a, base.ravel('K')) + + # With typed pointer and explicit dtype + a = func(self.make_float32_pointer(base), base.shape, base.dtype) + eq(a, base) + a = func(self.make_float32_pointer(base), base.shape, np.float32) + eq(a, base) + + # With voidptr and explicit dtype + a = func(self.make_voidptr(base), base.shape, base.dtype) + eq(a, base) + a = func(self.make_voidptr(base), base.shape, np.int32) + eq(a, base.view(np.int32)) + + # voidptr without dtype + with self.assertRaises(TypeError): + func(self.make_voidptr(base), base.shape) + # Invalid pointer type + with self.assertRaises(TypeError): + func(base.ctypes.data, base.shape) + # Mismatching dtype + with self.assertRaises(TypeError) as raises: + func(self.make_float32_pointer(base), base.shape, np.int32) + self.assertIn("mismatching dtype 'int32' for pointer", + str(raises.exception)) + + def test_carray(self): + """ + Test pure Python carray(). + """ + self.check_carray_farray(carray, 'C') + + def test_farray(self): + """ + Test pure Python farray(). + """ + self.check_carray_farray(farray, 'F') + + def make_carray_sigs(self, formal_sig): + """ + Generate a bunch of concrete signatures by varying the width + and signedness of size arguments (see issue #1923). + """ + for actual_size in (types.intp, types.int32, types.intc, + types.uintp, types.uint32, types.uintc): + args = tuple(actual_size if a == types.intp else a + for a in formal_sig.args) + yield formal_sig.return_type(*args) + + def check_numba_carray_farray(self, usecase, dtype_usecase): + # With typed pointers and implicit dtype + pyfunc = usecase + for sig in self.make_carray_sigs(carray_float32_usecase_sig): + f = cfunc(sig)(pyfunc) + self.check_carray_usecase(self.make_float32_pointer, pyfunc, f.ctypes) + + # With typed pointers and explicit (matching) dtype + pyfunc = dtype_usecase + for sig in self.make_carray_sigs(carray_float32_usecase_sig): + f = cfunc(sig)(pyfunc) + self.check_carray_usecase(self.make_float32_pointer, pyfunc, f.ctypes) + # With typed pointers and mismatching dtype + with self.assertTypingError() as raises: + f = cfunc(carray_float64_usecase_sig)(pyfunc) + self.assertIn("mismatching dtype 'float32' for pointer type 'float64*'", + str(raises.exception)) + + # With voidptr + pyfunc = dtype_usecase + for sig in self.make_carray_sigs(carray_voidptr_usecase_sig): + f = cfunc(sig)(pyfunc) + self.check_carray_usecase(self.make_float32_pointer, pyfunc, f.ctypes) + + def test_numba_carray(self): + """ + Test Numba-compiled carray() against pure Python carray() + """ + self.check_numba_carray_farray(carray_usecase, carray_dtype_usecase) + + def test_numba_farray(self): + """ + Test Numba-compiled farray() against pure Python farray() + """ + self.check_numba_carray_farray(farray_usecase, farray_dtype_usecase) + + +@skip_unless_cffi +class TestCffiStruct(TestCase): + c_source = """ +typedef struct _big_struct { + int i1; + float f2; + double d3; + float af4[9]; +} big_struct; + +typedef struct _error { + int bits:4; +} error; + +typedef double (*myfunc)(big_struct*, size_t); +""" + + def get_ffi(self, src=c_source): + from cffi import FFI + + ffi = FFI() + ffi.cdef(src) + return ffi + + def test_type_parsing(self): + ffi = self.get_ffi() + # Check struct typedef + big_struct = ffi.typeof('big_struct') + nbtype = cffi_support.map_type(big_struct, use_record_dtype=True) + self.assertIsInstance(nbtype, types.Record) + self.assertEqual(len(nbtype), 4) + self.assertEqual(nbtype.typeof('i1'), types.int32) + self.assertEqual(nbtype.typeof('f2'), types.float32) + self.assertEqual(nbtype.typeof('d3'), types.float64) + self.assertEqual( + nbtype.typeof('af4'), + types.NestedArray(dtype=types.float32, shape=(9,)), + ) + + # Check function typedef + myfunc = ffi.typeof('myfunc') + sig = cffi_support.map_type(myfunc, use_record_dtype=True) + self.assertIsInstance(sig, typing.Signature) + self.assertEqual(sig.args[0], types.CPointer(nbtype)) + self.assertEqual(sig.args[1], types.uintp) + self.assertEqual(sig.return_type, types.float64) + + def test_cfunc_callback(self): + ffi = self.get_ffi() + big_struct = ffi.typeof('big_struct') + nb_big_struct = cffi_support.map_type(big_struct, use_record_dtype=True) + sig = cffi_support.map_type(ffi.typeof('myfunc'), use_record_dtype=True) + + @njit + def calc(base): + tmp = 0 + for i in range(base.size): + elem = base[i] + tmp += elem.i1 * elem.f2 / elem.d3 + tmp += base[i].af4.sum() + return tmp + + @cfunc(sig) + def foo(ptr, n): + base = carray(ptr, n) + return calc(base) + + # Make data + mydata = ffi.new('big_struct[3]') + ptr = ffi.cast('big_struct*', mydata) + for i in range(3): + ptr[i].i1 = i * 123 + ptr[i].f2 = i * 213 + ptr[i].d3 = (1 + i) * 213 + for j in range(9): + ptr[i].af4[j] = i * 10 + j + + # Address of my data + addr = int(ffi.cast('size_t', ptr)) + got = foo.ctypes(addr, 3) + + # Make numpy array from the cffi buffer + array = np.ndarray( + buffer=ffi.buffer(mydata), + dtype=numpy_support.as_dtype(nb_big_struct), + shape=3, + ) + expect = calc(array) + self.assertEqual(got, expect) + + def test_unsupport_bitsize(self): + ffi = self.get_ffi() + with self.assertRaises(ValueError) as raises: + cffi_support.map_type( + ffi.typeof('error'), + use_record_dtype=True, + ) + # When bitsize is provided, bitshift defaults to 0. + self.assertEqual( + "field 'bits' has bitshift, this is not supported", + str(raises.exception) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_chrome_trace.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_chrome_trace.py new file mode 100644 index 0000000000000000000000000000000000000000..613a6d8d28f25b7e4afc9b6cbc147bc3414468d2 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_chrome_trace.py @@ -0,0 +1,51 @@ +import os +import json +import unittest +from textwrap import dedent +from tempfile import TemporaryDirectory + +from numba.tests.support import TestCase, run_in_subprocess + + +class TestChromeTraceModule(TestCase): + """ + Test chrome tracing generated file(s). + """ + + def test_trace_output(self): + code = """ + from numba import njit + import numpy as np + + x = np.arange(100).reshape(10, 10) + + @njit + def go_fast(a): + trace = 0.0 + for i in range(a.shape[0]): + trace += np.tanh(a[i, i]) + return a + trace + + go_fast(x) + """ + + src = dedent(code) + with TemporaryDirectory() as tmpdir: + path = os.path.join(tmpdir, "test_trace.json") + env = os.environ.copy() + env['NUMBA_CHROME_TRACE'] = path + run_in_subprocess(src, env=env) + with open(path) as file: + events = json.load(file) + self.assertIsInstance(events, list) + for ev in events: + self.assertIsInstance(ev, dict) + # check that each record has the right fields. + self.assertEqual( + set(ev.keys()), + {"cat", "pid", "tid", "ph", "name", "args", "ts"}, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_compiler_flags.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_compiler_flags.py new file mode 100644 index 0000000000000000000000000000000000000000..fe31e5452070c84de426caa2da6b8d4dd9285675 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_compiler_flags.py @@ -0,0 +1,119 @@ +import re + +from numba import njit +from numba.core.extending import overload +from numba.core.targetconfig import ConfigStack +from numba.core.compiler import Flags, DEFAULT_FLAGS +from numba.core import types +from numba.core.funcdesc import default_mangler + +from numba.tests.support import TestCase, unittest + + +class TestCompilerFlags(TestCase): + def test_setting_invalid_attribute(self): + flags = Flags() + msg = "'Flags' object has no attribute 'this_really_does_not_exist'" + with self.assertRaisesRegex(AttributeError, msg): + flags.this_really_does_not_exist = True + + +class TestCompilerFlagCachedOverload(TestCase): + def test_fastmath_in_overload(self): + def fastmath_status(): + pass + + @overload(fastmath_status) + def ov_fastmath_status(): + flags = ConfigStack().top() + val = "Has fastmath" if flags.fastmath else "No fastmath" + + def codegen(): + return val + + return codegen + + @njit(fastmath=True) + def set_fastmath(): + return fastmath_status() + + @njit() + def foo(): + a = fastmath_status() + b = set_fastmath() + return (a, b) + + a, b = foo() + self.assertEqual(a, "No fastmath") + self.assertEqual(b, "Has fastmath") + + +class TestFlagMangling(TestCase): + + def test_demangle(self): + + def check(flags): + mangled = flags.get_mangle_string() + out = flags.demangle(mangled) + # Demangle result MUST match summary() + self.assertEqual(out, flags.summary()) + + # test empty flags + flags = Flags() + check(flags) + + # test default + check(DEFAULT_FLAGS) + + # test other + flags = Flags() + flags.no_cpython_wrapper = True + flags.nrt = True + flags.fastmath = True + check(flags) + + def test_mangled_flags_is_shorter(self): + # at least for these control cases + flags = Flags() + flags.nrt = True + flags.auto_parallel = True + self.assertLess(len(flags.get_mangle_string()), len(flags.summary())) + + def test_mangled_flags_with_fastmath_parfors_inline(self): + # at least for these control cases + flags = Flags() + flags.nrt = True + flags.auto_parallel = True + flags.fastmath = True + flags.inline = "always" + self.assertLess(len(flags.get_mangle_string()), len(flags.summary())) + demangled = flags.demangle(flags.get_mangle_string()) + # There should be no pointer value in the demangled string. + self.assertNotIn("0x", demangled) + + def test_demangling_from_mangled_symbols(self): + """Test demangling of flags from mangled symbol""" + # Use default mangler to mangle the string + fname = 'foo' + argtypes = types.int32, + flags = Flags() + flags.nrt = True + flags.inline = "always" + name = default_mangler( + fname, argtypes, abi_tags=[flags.get_mangle_string()], + ) + # Find the ABI-tag. Starts with "B" + prefix = "_Z3fooB" + # Find the length of the ABI-tag + m = re.match("[0-9]+", name[len(prefix):]) + size = m.group(0) + # Extract the ABI tag + base = len(prefix) + len(size) + abi_mangled = name[base:base + int(size)] + # Demangle and check + demangled = Flags.demangle(abi_mangled) + self.assertEqual(demangled, flags.summary()) + + +if __name__ == "__main__": + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_copy_propagate.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_copy_propagate.py new file mode 100644 index 0000000000000000000000000000000000000000..ca410fedaf4c8f40f26bee8143457f5e596c3f14 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_copy_propagate.py @@ -0,0 +1,169 @@ +# +# Copyright (c) 2017 Intel Corporation +# SPDX-License-Identifier: BSD-2-Clause +# + +from numba import jit, njit +from numba.core import types, ir, config, compiler +from numba.core.registry import cpu_target +from numba.core.annotations import type_annotations +from numba.core.ir_utils import (copy_propagate, apply_copy_propagate, + get_name_var_table) +from numba.core.typed_passes import type_inference_stage +from numba.tests.support import IRPreservingTestPipeline +import numpy as np +import unittest + + +def test_will_propagate(b, z, w): + x = 3 + x1 = x + if b > 0: + y = z + w + else: + y = 0 + a = 2 * x1 + return a < b + + +def test_wont_propagate(b, z, w): + x = 3 + if b > 0: + y = z + w + x = 1 + else: + y = 0 + a = 2 * x + return a < b + + +def null_func(a,b,c,d): + False + + +def inListVar(list_var, var): + for i in list_var: + if i.name == var: + return True + return False + + +def findAssign(func_ir, var): + for label, block in func_ir.blocks.items(): + for i, inst in enumerate(block.body): + if isinstance(inst, ir.Assign) and inst.target.name!=var: + all_var = inst.list_vars() + if inListVar(all_var, var): + return True + + return False + + +class TestCopyPropagate(unittest.TestCase): + def test1(self): + typingctx = cpu_target.typing_context + targetctx = cpu_target.target_context + test_ir = compiler.run_frontend(test_will_propagate) + typingctx.refresh() + targetctx.refresh() + args = (types.int64, types.int64, types.int64) + typemap, return_type, calltypes, _ = type_inference_stage(typingctx, + targetctx, + test_ir, + args, + None) + type_annotation = type_annotations.TypeAnnotation( + func_ir=test_ir, + typemap=typemap, + calltypes=calltypes, + lifted=(), + lifted_from=None, + args=args, + return_type=return_type, + html_output=config.HTML) + in_cps, out_cps = copy_propagate(test_ir.blocks, typemap) + apply_copy_propagate(test_ir.blocks, in_cps, + get_name_var_table(test_ir.blocks), typemap, + calltypes) + + self.assertFalse(findAssign(test_ir, "x1")) + + def test2(self): + typingctx = cpu_target.typing_context + targetctx = cpu_target.target_context + test_ir = compiler.run_frontend(test_wont_propagate) + typingctx.refresh() + targetctx.refresh() + args = (types.int64, types.int64, types.int64) + typemap, return_type, calltypes, _ = type_inference_stage(typingctx, + targetctx, + test_ir, + args, + None) + type_annotation = type_annotations.TypeAnnotation( + func_ir=test_ir, + typemap=typemap, + calltypes=calltypes, + lifted=(), + lifted_from=None, + args=args, + return_type=return_type, + html_output=config.HTML) + in_cps, out_cps = copy_propagate(test_ir.blocks, typemap) + apply_copy_propagate(test_ir.blocks, in_cps, get_name_var_table(test_ir.blocks), typemap, calltypes) + + self.assertTrue(findAssign(test_ir, "x")) + + def test_input_ir_extra_copies(self): + """make sure Interpreter._remove_unused_temporaries() has removed extra copies + in the IR in simple cases so copy propagation is faster + """ + def test_impl(a): + b = a + 3 + return b + + j_func = njit(pipeline_class=IRPreservingTestPipeline)(test_impl) + self.assertEqual(test_impl(5), j_func(5)) + + # make sure b is the target of the expression assignment, not a temporary + fir = j_func.overloads[j_func.signatures[0]].metadata['preserved_ir'] + self.assertTrue(len(fir.blocks) == 1) + block = next(iter(fir.blocks.values())) + b_found = False + for stmt in block.body: + if isinstance(stmt, ir.Assign) and stmt.target.name == "b": + b_found = True + self.assertTrue(isinstance(stmt.value, ir.Expr) + and stmt.value.op == "binop" and stmt.value.lhs.name == "a") + + self.assertTrue(b_found) + + def test_input_ir_copy_remove_transform(self): + """make sure Interpreter._remove_unused_temporaries() does not generate + invalid code for rare chained assignment cases + """ + # regular chained assignment + def impl1(a): + b = c = a + 1 + return (b, c) + + # chained assignment with setitem + def impl2(A, i, a): + b = A[i] = a + 1 + return b, A[i] + 2 + + # chained assignment with setattr + def impl3(A, a): + b = A.a = a + 1 + return b, A.a + 2 + + class C: + pass + + self.assertEqual(impl1(5), njit(impl1)(5)) + self.assertEqual(impl2(np.ones(3), 0, 5), njit(impl2)(np.ones(3), 0, 5)) + self.assertEqual(impl3(C(), 5), jit(forceobj=True)(impl3)(C(), 5)) + + +if __name__ == "__main__": + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_datamodel.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_datamodel.py new file mode 100644 index 0000000000000000000000000000000000000000..03a0179fa74ca84e673b72ca28bfc36499d1cfe5 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_datamodel.py @@ -0,0 +1,257 @@ +from llvmlite import ir, binding as ll + +from numba.core import types, datamodel +from numba.core.datamodel.testing import test_factory +from numba.core.datamodel.manager import DataModelManager +from numba.core.datamodel.models import OpaqueModel +import unittest + + +class TestBool(test_factory()): + fe_type = types.boolean + + +class TestPyObject(test_factory()): + fe_type = types.pyobject + + +class TestInt8(test_factory()): + fe_type = types.int8 + + +class TestInt16(test_factory()): + fe_type = types.int16 + + +class TestInt32(test_factory()): + fe_type = types.int32 + + +class TestInt64(test_factory()): + fe_type = types.int64 + + +class TestUInt8(test_factory()): + fe_type = types.uint8 + + +class TestUInt16(test_factory()): + fe_type = types.uint16 + + +class TestUInt32(test_factory()): + fe_type = types.uint32 + + +class TestUInt64(test_factory()): + fe_type = types.uint64 + + +class TestFloat(test_factory()): + fe_type = types.float32 + + +class TestDouble(test_factory()): + fe_type = types.float64 + + +class TestComplex(test_factory()): + fe_type = types.complex64 + + +class TestDoubleComplex(test_factory()): + fe_type = types.complex128 + + +class TestPointerOfInt32(test_factory()): + fe_type = types.CPointer(types.int32) + + +class TestUniTupleOf2xInt32(test_factory()): + fe_type = types.UniTuple(types.int32, 2) + + +class TestUniTupleEmpty(test_factory()): + fe_type = types.UniTuple(types.int32, 0) + + +class TestTupleInt32Float32(test_factory()): + fe_type = types.Tuple([types.int32, types.float32]) + + +class TestTupleEmpty(test_factory()): + fe_type = types.Tuple([]) + + +class Test1DArrayOfInt32(test_factory()): + fe_type = types.Array(types.int32, 1, 'C') + + +class Test2DArrayOfComplex128(test_factory()): + fe_type = types.Array(types.complex128, 2, 'C') + + +class Test0DArrayOfInt32(test_factory()): + fe_type = types.Array(types.int32, 0, 'C') + + +class TestArgInfo(unittest.TestCase): + + def _test_as_arguments(self, fe_args): + """ + Test round-tripping types *fe_args* through the default data model's + argument conversion and unpacking logic. + """ + dmm = datamodel.default_manager + fi = datamodel.ArgPacker(dmm, fe_args) + + module = ir.Module() + fnty = ir.FunctionType(ir.VoidType(), []) + function = ir.Function(module, fnty, name="test_arguments") + builder = ir.IRBuilder() + builder.position_at_end(function.append_basic_block()) + + args = [ir.Constant(dmm.lookup(t).get_value_type(), None) + for t in fe_args] + + # Roundtrip + values = fi.as_arguments(builder, args) + asargs = fi.from_arguments(builder, values) + + self.assertEqual(len(asargs), len(fe_args)) + valtys = tuple([v.type for v in values]) + self.assertEqual(valtys, fi.argument_types) + + expect_types = [a.type for a in args] + got_types = [a.type for a in asargs] + + self.assertEqual(expect_types, got_types) + + # Assign names (check this doesn't raise) + fi.assign_names(values, ["arg%i" for i in range(len(fe_args))]) + + builder.ret_void() + + ll.parse_assembly(str(module)) + + def test_int32_array_complex(self): + fe_args = [types.int32, + types.Array(types.int32, 1, 'C'), + types.complex64] + self._test_as_arguments(fe_args) + + def test_two_arrays(self): + fe_args = [types.Array(types.int32, 1, 'C')] * 2 + self._test_as_arguments(fe_args) + + def test_two_0d_arrays(self): + fe_args = [types.Array(types.int32, 0, 'C')] * 2 + self._test_as_arguments(fe_args) + + def test_tuples(self): + fe_args = [types.UniTuple(types.int32, 2), + types.UniTuple(types.int32, 3)] + self._test_as_arguments(fe_args) + # Tuple of struct-likes + arrty = types.Array(types.int32, 1, 'C') + fe_args = [types.UniTuple(arrty, 2), + types.UniTuple(arrty, 3)] + self._test_as_arguments(fe_args) + # Nested tuple + fe_args = [types.UniTuple(types.UniTuple(types.int32, 2), 3)] + self._test_as_arguments(fe_args) + + def test_empty_tuples(self): + # Empty tuple + fe_args = [types.UniTuple(types.int16, 0), + types.Tuple(()), + types.int32] + self._test_as_arguments(fe_args) + + def test_nested_empty_tuples(self): + fe_args = [types.int32, + types.UniTuple(types.Tuple(()), 2), + types.int64] + self._test_as_arguments(fe_args) + + +class TestMemInfo(unittest.TestCase): + def setUp(self): + self.dmm = datamodel.default_manager + + def test_number(self): + ty = types.int32 + dm = self.dmm[ty] + self.assertFalse(dm.contains_nrt_meminfo()) + + def test_array(self): + ty = types.int32[:] + dm = self.dmm[ty] + self.assertTrue(dm.contains_nrt_meminfo()) + + def test_tuple_of_number(self): + ty = types.UniTuple(dtype=types.int32, count=2) + dm = self.dmm[ty] + self.assertFalse(dm.contains_nrt_meminfo()) + + def test_tuple_of_array(self): + ty = types.UniTuple(dtype=types.int32[:], count=2) + dm = self.dmm[ty] + self.assertTrue(dm.contains_nrt_meminfo()) + + +class TestMisc(unittest.TestCase): + + def test_issue2921(self): + import numpy as np + from numba import njit + + @njit + def copy(a, b): + for i in range(a.shape[0]): + a[i] = b[i] + + b = np.arange(5, dtype=np.uint8).view(np.bool_) + a = np.zeros_like(b) + copy(a, b) + np.testing.assert_equal(a, np.array((False,) + (True,) * 4)) + + +class TestDMMChaining(unittest.TestCase): + def test_basic(self): + dmm = DataModelManager() + + class int_handler(OpaqueModel): + pass + + class float_handler(OpaqueModel): + pass + + dmm.register(types.Integer, int_handler) + dmm.register(types.Float, float_handler) + + inter_dmm = DataModelManager() + + class new_int_handler(OpaqueModel): + pass + + inter_dmm.register(types.Integer, new_int_handler) + chained_dmm = inter_dmm.chain(dmm) + + # Check that the chained DMM has the new handler + self.assertIsInstance(chained_dmm.lookup(types.intp), new_int_handler) + # and not the old handler + self.assertNotIsInstance(chained_dmm.lookup(types.intp), int_handler) + # Check that the base DMM has the old handler + self.assertIsInstance(dmm.lookup(types.intp), int_handler) + # Check that float goes to the float_handler + self.assertIsInstance(chained_dmm.lookup(types.float32), float_handler) + self.assertIsInstance(dmm.lookup(types.float32), float_handler) + # Check the intermediate DMM + self.assertIsInstance(inter_dmm.lookup(types.intp), new_int_handler) + with self.assertRaises(KeyError): + inter_dmm.lookup(types.float32) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_dictimpl.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_dictimpl.py new file mode 100644 index 0000000000000000000000000000000000000000..4814e843610a7d53c9d6edf6598f19e3bd43113d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_dictimpl.py @@ -0,0 +1,656 @@ +""" +Testing C implementation of the numba dictionary +""" + +import ctypes +import random + +from numba.tests.support import TestCase +from numba import _helperlib, jit, typed, types +from numba.core.config import IS_32BITS +from numba.core.datamodel.models import UniTupleModel +from numba.extending import register_model, typeof_impl, unbox, overload + + +DKIX_EMPTY = -1 + + +ALIGN = 4 if IS_32BITS else 8 + + +class Dict(object): + """A wrapper around the C-API to provide a minimal dictionary object for + testing. + """ + def __init__(self, tc, keysize, valsize): + """ + Parameters + ---------- + tc : TestCase instance + keysize : int + byte size for the key + valsize : int + byte size for the value + """ + self.tc = tc + self.keysize = keysize + self.valsize = valsize + self.dp = self.dict_new_minsize(keysize, valsize) + + def __del__(self): + self.tc.numba_dict_free(self.dp) + + def __len__(self): + return self.dict_length() + + def __setitem__(self, k, v): + bk = bytes(k.encode()) + bv = bytes(v.encode()) + self.tc.assertEqual(len(bk), self.keysize) + self.tc.assertEqual(len(bv), self.valsize) + self.dict_insert(bk, bv) + + def __getitem__(self, k): + bk = bytes(k.encode()) + self.tc.assertEqual(len(bk), self.keysize) + ix, old = self.dict_lookup(bk) + if ix == DKIX_EMPTY: + raise KeyError + else: + return old.decode() + + def __delitem__(self, k): + bk = bytes(k.encode()) + self.tc.assertEqual(len(bk), self.keysize) + if not self.dict_delitem(bk): + raise KeyError(k) + + def get(self, k): + try: + return self[k] + except KeyError: + return + + def items(self): + return DictIter(self) + + def popitem(self): + k, v = self.dict_popitem() + return k.decode(), v.decode() + + # + # The methods below are higher-level wrappers for the C-API + # + + def dict_new_minsize(self, key_size, val_size): + dp = ctypes.c_void_p() + status = self.tc.numba_dict_new_sized( + ctypes.byref(dp), 0, key_size, val_size, + ) + self.tc.assertEqual(status, 0) + return dp + + def dict_length(self): + return self.tc.numba_dict_length(self.dp) + + def dict_insert(self, key_bytes, val_bytes): + hashval = hash(key_bytes) + status = self.tc.numba_dict_insert_ez( + self.dp, key_bytes, hashval, val_bytes, + ) + self.tc.assertGreaterEqual(status, 0) + + def dict_lookup(self, key_bytes): + hashval = hash(key_bytes) + oldval_bytes = ctypes.create_string_buffer(self.valsize) + ix = self.tc.numba_dict_lookup( + self.dp, key_bytes, hashval, oldval_bytes, + ) + self.tc.assertGreaterEqual(ix, DKIX_EMPTY) + return ix, oldval_bytes.value + + def dict_delitem(self, key_bytes): + ix, oldval = self.dict_lookup(key_bytes) + if ix == DKIX_EMPTY: + return False + hashval = hash(key_bytes) + status = self.tc.numba_dict_delitem(self.dp, hashval, ix) + self.tc.assertEqual(status, 0) + return True + + def dict_popitem(self): + key_bytes = ctypes.create_string_buffer(self.keysize) + val_bytes = ctypes.create_string_buffer(self.valsize) + status = self.tc.numba_dict_popitem(self.dp, key_bytes, val_bytes) + if status != 0: + if status == -4: + raise KeyError('popitem(): dictionary is empty') + else: + self.tc._fail('Unknown') + return key_bytes.value, val_bytes.value + + def dict_iter(self, itptr): + self.tc.numba_dict_iter(itptr, self.dp) + + def dict_iter_next(self, itptr): + bk = ctypes.c_void_p(0) + bv = ctypes.c_void_p(0) + status = self.tc.numba_dict_iter_next( + itptr, ctypes.byref(bk), ctypes.byref(bv), + ) + if status == -2: + raise ValueError('dictionary mutated') + elif status == -3: + return + else: + self.tc.assertGreaterEqual(status, 0) + + # Check the alignment of the key-value in the entries. + # We know we are getting the pointers to data in the entries. + + self.tc.assertEqual(bk.value % ALIGN, 0, msg='key not aligned') + self.tc.assertEqual(bv.value % ALIGN, 0, msg='val not aligned') + + key = (ctypes.c_char * self.keysize).from_address(bk.value) + val = (ctypes.c_char * self.valsize).from_address(bv.value) + return key.value, val.value + + +class DictIter(object): + """A iterator for the `Dict.items()`. + + Only the `.items()` is needed. `.keys` and `.values` can be trivially + implemented on the `.items` iterator. + """ + def __init__(self, parent): + self.parent = parent + itsize = self.parent.tc.numba_dict_iter_sizeof() + self.it_state_buf = (ctypes.c_char_p * itsize)(0) + self.it = ctypes.cast(self.it_state_buf, ctypes.c_void_p) + self.parent.dict_iter(self.it) + + def __iter__(self): + return self + + def __next__(self): + out = self.parent.dict_iter_next(self.it) + if out is None: + raise StopIteration + else: + k, v = out + return k.decode(), v.decode() + + next = __next__ # needed for py2 only + + +class Parametrized(tuple): + """supporting type for TestDictImpl.test_parametrized_types + needs to be global to be cacheable""" + def __init__(self, tup): + assert all(isinstance(v, str) for v in tup) + + +class ParametrizedType(types.Type): + """this is essentially UniTuple(unicode_type, n) + BUT type name is the same for all n""" + + def __init__(self, value): + super(ParametrizedType, self).__init__('ParametrizedType') + self.dtype = types.unicode_type + self.n = len(value) + + @property + def key(self): + return self.n + + def __len__(self): + return self.n + + +class TestDictImpl(TestCase): + def setUp(self): + """Bind to the c_helper library and provide the ctypes wrapper. + """ + dict_t = ctypes.c_void_p + iter_t = ctypes.c_void_p + hash_t = ctypes.c_ssize_t + + def wrap(name, restype, argtypes=()): + proto = ctypes.CFUNCTYPE(restype, *argtypes) + return proto(_helperlib.c_helpers[name]) + + # numba_test_dict() + self.numba_test_dict = wrap( + 'test_dict', + ctypes.c_int, + ) + # numba_dict_new_sized( + # NB_Dict **out, + # Py_ssize_t n_keys, + # Py_ssize_t key_size, + # Py_ssize_t val_size + # ) + self.numba_dict_new_sized = wrap( + 'dict_new_sized', + ctypes.c_int, + [ + ctypes.POINTER(dict_t), # out + ctypes.c_ssize_t, # n_keys + ctypes.c_ssize_t, # key_size + ctypes.c_ssize_t, # val_size + ], + ) + # numba_dict_free(NB_Dict *d) + self.numba_dict_free = wrap( + 'dict_free', + None, + [dict_t], + ) + # numba_dict_length(NB_Dict *d) + self.numba_dict_length = wrap( + 'dict_length', + ctypes.c_ssize_t, + [dict_t], + ) + # numba_dict_insert_ez( + # NB_Dict *d, + # const char *key_bytes, + # Py_hash_t hash, + # const char *val_bytes, + # ) + self.numba_dict_insert_ez = wrap( + 'dict_insert_ez', + ctypes.c_int, + [ + dict_t, # d + ctypes.c_char_p, # key_bytes + hash_t, # hash + ctypes.c_char_p, # val_bytes + ], + ) + # numba_dict_lookup( + # NB_Dict *d, + # const char *key_bytes, + # Py_hash_t hash, + # char *oldval_bytes + # ) + self.numba_dict_lookup = wrap( + 'dict_lookup', + ctypes.c_ssize_t, + [ + dict_t, # d + ctypes.c_char_p, # key_bytes + hash_t, # hash + ctypes.c_char_p, # oldval_bytes + ], + ) + # numba_dict_delitem( + # NB_Dict *d, + # Py_hash_t hash, + # Py_ssize_t ix + # ) + self.numba_dict_delitem = wrap( + 'dict_delitem', + ctypes.c_int, + [ + dict_t, # d + hash_t, # hash + ctypes.c_ssize_t, # ix + ], + ) + # numba_dict_popitem( + # NB_Dict *d, + # char *key_bytes, + # char *val_bytes + # ) + self.numba_dict_popitem = wrap( + 'dict_popitem', + ctypes.c_int, + [ + dict_t, # d + ctypes.c_char_p, # key_bytes + ctypes.c_char_p, # val_bytes + ], + ) + # numba_dict_iter_sizeof() + self.numba_dict_iter_sizeof = wrap( + 'dict_iter_sizeof', + ctypes.c_size_t, + ) + # numba_dict_iter( + # NB_DictIter *it, + # NB_Dict *d + # ) + self.numba_dict_iter = wrap( + 'dict_iter', + None, + [ + iter_t, + dict_t, + ], + ) + # numba_dict_iter_next( + # NB_DictIter *it, + # const char **key_ptr, + # const char **val_ptr + # ) + self.numba_dict_iter_next = wrap( + 'dict_iter_next', + ctypes.c_int, + [ + iter_t, # it + ctypes.POINTER(ctypes.c_void_p), # key_ptr + ctypes.POINTER(ctypes.c_void_p), # val_ptr + ], + ) + + def test_simple_c_test(self): + # Runs the basic test in C. + ret = self.numba_test_dict() + self.assertEqual(ret, 0) + + def test_insertion_small(self): + # Tests insertion and lookup for a small dict. + d = Dict(self, 4, 8) + self.assertEqual(len(d), 0) + self.assertIsNone(d.get('abcd')) + + # First key + d['abcd'] = 'beefcafe' + self.assertEqual(len(d), 1) + self.assertIsNotNone(d.get('abcd')) + self.assertEqual(d['abcd'], 'beefcafe') + + # Duplicated key replaces + d['abcd'] = 'cafe0000' + self.assertEqual(len(d), 1) + self.assertEqual(d['abcd'], 'cafe0000') + + # Second key + d['abce'] = 'cafe0001' + self.assertEqual(len(d), 2) + self.assertEqual(d['abcd'], 'cafe0000') + self.assertEqual(d['abce'], 'cafe0001') + + # Third key + d['abcf'] = 'cafe0002' + self.assertEqual(len(d), 3) + self.assertEqual(d['abcd'], 'cafe0000') + self.assertEqual(d['abce'], 'cafe0001') + self.assertEqual(d['abcf'], 'cafe0002') + + def check_insertion_many(self, nmax): + # Helper to test insertion/lookup/resize + d = Dict(self, 8, 8) + + def make_key(v): + return "key_{:04}".format(v) + + def make_val(v): + return "val_{:04}".format(v) + + # Check insert + for i in range(nmax): + d[make_key(i)] = make_val(i) + self.assertEqual(len(d), i + 1) + + # Check lookup + for i in range(nmax): + self.assertEqual(d[make_key(i)], make_val(i)) + + def test_insertion_many(self): + # Test insertion for differently sized dict + # Around minsize + self.check_insertion_many(nmax=7) + self.check_insertion_many(nmax=8) + self.check_insertion_many(nmax=9) + # Around nmax = 32 + self.check_insertion_many(nmax=31) + self.check_insertion_many(nmax=32) + self.check_insertion_many(nmax=33) + # Around nmax = 1024 + self.check_insertion_many(nmax=1023) + self.check_insertion_many(nmax=1024) + self.check_insertion_many(nmax=1025) + # Around nmax = 4096 + self.check_insertion_many(nmax=4095) + self.check_insertion_many(nmax=4096) + self.check_insertion_many(nmax=4097) + + def test_deletion_small(self): + # Test deletion + d = Dict(self, 4, 8) + self.assertEqual(len(d), 0) + self.assertIsNone(d.get('abcd')) + + d['abcd'] = 'cafe0000' + d['abce'] = 'cafe0001' + d['abcf'] = 'cafe0002' + + self.assertEqual(len(d), 3) + self.assertEqual(d['abcd'], 'cafe0000') + self.assertEqual(d['abce'], 'cafe0001') + self.assertEqual(d['abcf'], 'cafe0002') + self.assertEqual(len(d), 3) + + # Delete first item + del d['abcd'] + self.assertIsNone(d.get('abcd')) + self.assertEqual(d['abce'], 'cafe0001') + self.assertEqual(d['abcf'], 'cafe0002') + self.assertEqual(len(d), 2) + + # Delete first item again + with self.assertRaises(KeyError): + del d['abcd'] + + # Delete third + del d['abcf'] + self.assertIsNone(d.get('abcd')) + self.assertEqual(d['abce'], 'cafe0001') + self.assertIsNone(d.get('abcf')) + self.assertEqual(len(d), 1) + + # Delete second + del d['abce'] + self.assertIsNone(d.get('abcd')) + self.assertIsNone(d.get('abce')) + self.assertIsNone(d.get('abcf')) + self.assertEqual(len(d), 0) + + def check_delete_randomly(self, nmax, ndrop, nrefill, seed=0): + # Helper to test deletion + random.seed(seed) + + d = Dict(self, 8, 8) + keys = {} + + def make_key(v): + return "k_{:06x}".format(v) + + def make_val(v): + return "v_{:06x}".format(v) + + for i in range(nmax): + d[make_key(i)] = make_val(i) + + # Fill to nmax + for i in range(nmax): + k = make_key(i) + v = make_val(i) + keys[k] = v + self.assertEqual(d[k], v) + + self.assertEqual(len(d), nmax) + + # Randomly drop + droplist = random.sample(list(keys), ndrop) + remain = keys.copy() + for i, k in enumerate(droplist, start=1): + del d[k] + del remain[k] + self.assertEqual(len(d), nmax - i) + self.assertEqual(len(d), nmax - ndrop) + + # Make sure everything dropped is gone + for k in droplist: + self.assertIsNone(d.get(k)) + + # Make sure everything else is still here + for k in remain: + self.assertEqual(d[k], remain[k]) + + # Refill + for i in range(nrefill): + k = make_key(nmax + i) + v = make_val(nmax + i) + remain[k] = v + d[k] = v + + self.assertEqual(len(remain), len(d)) + + # Make sure everything is here + for k in remain: + self.assertEqual(d[k], remain[k]) + + def test_delete_randomly(self): + # Test deletion for differently sized dict + self.check_delete_randomly(nmax=8, ndrop=2, nrefill=2) + self.check_delete_randomly(nmax=13, ndrop=10, nrefill=31) + self.check_delete_randomly(nmax=100, ndrop=50, nrefill=200) + self.check_delete_randomly(nmax=100, ndrop=99, nrefill=100) + self.check_delete_randomly(nmax=100, ndrop=100, nrefill=100) + self.check_delete_randomly(nmax=1024, ndrop=999, nrefill=1) + self.check_delete_randomly(nmax=1024, ndrop=999, nrefill=2048) + + def test_delete_randomly_large(self): + # Go beyond 2^16 to exercise large indices. + # Internally, size of index changes as the hashtable size changes. + # Size of index can be 8, 16, 32 or 64 bytes (on 64-bit). + # We are not inserting >2^32 elements because of limitation of time. + self.check_delete_randomly(nmax=2**17, ndrop=2**16, nrefill=2**10) + + def test_popitem(self): + nmax = 10 + d = Dict(self, 8, 8) + + def make_key(v): + return "k_{:06x}".format(v) + + def make_val(v): + return "v_{:06x}".format(v) + + for i in range(nmax): + d[make_key(i)] = make_val(i) + + self.assertEqual(len(d), nmax) + k, v = d.popitem() + self.assertEqual(len(d), nmax - 1) + self.assertEqual(k, make_key(len(d))) + self.assertEqual(v, make_val(len(d))) + + while len(d): + n = len(d) + k, v = d.popitem() + self.assertEqual(len(d), n - 1) + self.assertEqual(k, make_key(len(d))) + self.assertEqual(v, make_val(len(d))) + + self.assertEqual(len(d), 0) + with self.assertRaises(KeyError) as raises: + d.popitem() + self.assertIn( + 'popitem(): dictionary is empty', + str(raises.exception), + ) + + def test_iter_items(self): + # Test .items iteration + d = Dict(self, 4, 4) + nmax = 1000 + + def make_key(v): + return "{:04}".format(v) + + def make_val(v): + return "{:04}".format(v + nmax) + + for i in range(nmax): + d[make_key(i)] = make_val(i) + + # Check that the everything is ordered + for i, (k, v) in enumerate(d.items()): + self.assertEqual(make_key(i), k) + self.assertEqual(make_val(i), v) + + def check_sizing(self, key_size, val_size, nmax): + # Helper to verify different key/value sizes. + d = Dict(self, key_size, val_size) + + def make_key(v): + return "{:0{}}".format(v, key_size)[:key_size] + + def make_val(v): + return "{:0{}}".format(nmax - v - 1, val_size)[:val_size] + + for i in range(nmax): + d[make_key(i)] = make_val(i) + + # Check that the everything is ordered + for i, (k, v) in enumerate(d.items()): + self.assertEqual(make_key(i), k) + self.assertEqual(make_val(i), v) + + def test_sizing(self): + # Check different sizes of the key & value. + for i in range(1, 8): + self.check_sizing(key_size=i, val_size=i, nmax=2**i) + + def test_parameterized_types(self): + """https://github.com/numba/numba/issues/6401""" + + register_model(ParametrizedType)(UniTupleModel) + + @typeof_impl.register(Parametrized) + def typeof_unit(val, c): + return ParametrizedType(val) + + @unbox(ParametrizedType) + def unbox_parametrized(typ, obj, context): + return context.unbox(types.UniTuple(typ.dtype, len(typ)), obj) + + def dict_vs_cache_vs_parametrized(v): + assert 0 + + @overload(dict_vs_cache_vs_parametrized) + def ol_dict_vs_cache_vs_parametrized(v): + typ = v + + def objmode_vs_cache_vs_parametrized_impl(v): + # typed.List shows same behaviour after fix for #6397 + d = typed.Dict.empty(types.unicode_type, typ) + d['data'] = v + + return objmode_vs_cache_vs_parametrized_impl + + @jit(nopython=True, cache=True) + def set_parametrized_data(x, y): + # Has had a tendency to segfault when the compiled function + # was loaded from cache in a different process than the one + # it was originally compiled in. + # The new process is simulated below by resetting the dispatchers + # and the target context + dict_vs_cache_vs_parametrized(x) + dict_vs_cache_vs_parametrized(y) + + x, y = Parametrized(('a', 'b')), Parametrized(('a',)) + set_parametrized_data(x, y) + + # reset dispatchers and targetctx to force re-load from cache as if a + # new process would jit the function + set_parametrized_data._make_finalizer()() + set_parametrized_data._reset_overloads() + set_parametrized_data.targetctx.init() + + for ii in range(50): # <- sometimes works a few times + self.assertIsNone(set_parametrized_data(x, y)) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_dictobject.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_dictobject.py new file mode 100644 index 0000000000000000000000000000000000000000..9e04af997bf9e2a61405a51e8de1b763ad2c25ce --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_dictobject.py @@ -0,0 +1,2561 @@ +""" +Testing numba implementation of the numba dictionary. + +The tests here only check that the numba typing and codegen are working +correctly. Detailed testing of the underlying dictionary operations is done +in test_dictimpl.py. +""" + +import sys +import warnings + +import numpy as np + +from numba import njit, literally +from numba import int32, int64, float32, float64 +from numba import typeof +from numba.typed import Dict, dictobject, List +from numba.typed.typedobjectutils import _sentry_safe_cast +from numba.core.errors import TypingError +from numba.core import types +from numba.tests.support import (TestCase, MemoryLeakMixin, unittest, + override_config, forbid_codegen) +from numba.experimental import jitclass +from numba.extending import overload + + +class TestDictObject(MemoryLeakMixin, TestCase): + def test_dict_bool(self): + """ + Exercise bool(dict) + """ + @njit + def foo(n): + d = dictobject.new_dict(int32, float32) + for i in range(n): + d[i] = i + 1 + return bool(d) + + # Insert nothing + self.assertEqual(foo(n=0), False) + # Insert 1 entry + self.assertEqual(foo(n=1), True) + # Insert 2 entries + self.assertEqual(foo(n=2), True) + # Insert 100 entries + self.assertEqual(foo(n=100), True) + + def test_dict_create(self): + """ + Exercise dictionary creation, insertion and len + """ + @njit + def foo(n): + d = dictobject.new_dict(int32, float32) + for i in range(n): + d[i] = i + 1 + return len(d) + + # Insert nothing + self.assertEqual(foo(n=0), 0) + # Insert 1 entry + self.assertEqual(foo(n=1), 1) + # Insert 2 entries + self.assertEqual(foo(n=2), 2) + # Insert 100 entries + self.assertEqual(foo(n=100), 100) + + def test_dict_get(self): + """ + Exercise dictionary creation, insertion and get + """ + @njit + def foo(n, targets): + d = dictobject.new_dict(int32, float64) + # insertion loop + for i in range(n): + d[i] = i + # retrieval loop + output = [] + for t in targets: + output.append(d.get(t)) + return output + + self.assertEqual(foo(5, [0, 1, 9]), [0, 1, None]) + self.assertEqual(foo(10, [0, 1, 9]), [0, 1, 9]) + self.assertEqual(foo(10, [-1, 9, 1]), [None, 9, 1]) + + def test_dict_get_with_default(self): + """ + Exercise dict.get(k, d) where d is set + """ + @njit + def foo(n, target, default): + d = dictobject.new_dict(int32, float64) + # insertion loop + for i in range(n): + d[i] = i + # retrieval loop + return d.get(target, default) + + self.assertEqual(foo(5, 3, -1), 3) + self.assertEqual(foo(5, 5, -1), -1) + + def test_dict_getitem(self): + """ + Exercise dictionary __getitem__ + """ + @njit + def foo(keys, vals, target): + d = dictobject.new_dict(int32, float64) + # insertion + for k, v in zip(keys, vals): + d[k] = v + + # lookup + return d[target] + + keys = [1, 2, 3] + vals = [0.1, 0.2, 0.3] + self.assertEqual(foo(keys, vals, 1), 0.1) + self.assertEqual(foo(keys, vals, 2), 0.2) + self.assertEqual(foo(keys, vals, 3), 0.3) + # check no leak so far + self.assert_no_memory_leak() + # disable leak check for exception test + self.disable_leak_check() + with self.assertRaisesRegex(KeyError, "0"): + foo(keys, vals, 0) + with self.assertRaisesRegex(KeyError, "4"): + foo(keys, vals, 4) + + def test_dict_popitem(self): + """ + Exercise dictionary .popitem + """ + @njit + def foo(keys, vals): + d = dictobject.new_dict(int32, float64) + # insertion + for k, v in zip(keys, vals): + d[k] = v + + # popitem + return d.popitem() + + keys = [1, 2, 3] + vals = [0.1, 0.2, 0.3] + for i in range(1, len(keys)): + self.assertEqual( + foo(keys[:i], vals[:i]), + (keys[i - 1], vals[i - 1]), + ) + + def test_dict_popitem_many(self): + """ + Exercise dictionary .popitem + """ + + @njit + def core(d, npop): + # popitem + keysum, valsum = 0, 0 + for _ in range(npop): + k, v = d.popitem() + keysum += k + valsum -= v + return keysum, valsum + + @njit + def foo(keys, vals, npop): + d = dictobject.new_dict(int32, int32) + # insertion + for k, v in zip(keys, vals): + d[k] = v + + return core(d, npop) + + keys = [1, 2, 3] + vals = [10, 20, 30] + + for i in range(len(keys)): + self.assertEqual( + foo(keys, vals, npop=3), + core.py_func(dict(zip(keys, vals)), npop=3), + ) + + # check no leak so far + self.assert_no_memory_leak() + # disable leak check for exception test + self.disable_leak_check() + + with self.assertRaises(KeyError): + foo(keys, vals, npop=4) + + def test_dict_pop(self): + """ + Exercise dictionary .pop + """ + @njit + def foo(keys, vals, target): + d = dictobject.new_dict(int32, float64) + # insertion + for k, v in zip(keys, vals): + d[k] = v + + # popitem + return d.pop(target, None), len(d) + + keys = [1, 2, 3] + vals = [0.1, 0.2, 0.3] + + self.assertEqual(foo(keys, vals, 1), (0.1, 2)) + self.assertEqual(foo(keys, vals, 2), (0.2, 2)) + self.assertEqual(foo(keys, vals, 3), (0.3, 2)) + self.assertEqual(foo(keys, vals, 0), (None, 3)) + + # check no leak so far + self.assert_no_memory_leak() + # disable leak check for exception test + self.disable_leak_check() + + @njit + def foo(): + d = dictobject.new_dict(int32, float64) + # popitem + return d.pop(0) + + with self.assertRaises(KeyError): + foo() + + def test_dict_pop_many(self): + """ + Exercise dictionary .pop + """ + + @njit + def core(d, pops): + total = 0 + for k in pops: + total += k + d.pop(k, 0.123) + len(d) + total *= 2 + return total + + @njit + def foo(keys, vals, pops): + d = dictobject.new_dict(int32, float64) + # insertion + for k, v in zip(keys, vals): + d[k] = v + # popitem + return core(d, pops) + + keys = [1, 2, 3] + vals = [0.1, 0.2, 0.3] + pops = [2, 3, 3, 1, 0, 2, 1, 0, -1] + + self.assertEqual( + foo(keys, vals, pops), + core.py_func(dict(zip(keys, vals)), pops), + ) + + def test_dict_delitem(self): + @njit + def foo(keys, vals, target): + d = dictobject.new_dict(int32, float64) + # insertion + for k, v in zip(keys, vals): + d[k] = v + del d[target] + return len(d), d.get(target) + + keys = [1, 2, 3] + vals = [0.1, 0.2, 0.3] + self.assertEqual(foo(keys, vals, 1), (2, None)) + self.assertEqual(foo(keys, vals, 2), (2, None)) + self.assertEqual(foo(keys, vals, 3), (2, None)) + # check no leak so far + self.assert_no_memory_leak() + # disable leak check for exception test + self.disable_leak_check() + with self.assertRaises(KeyError): + foo(keys, vals, 0) + + def test_dict_clear(self): + """ + Exercise dict.clear + """ + @njit + def foo(keys, vals): + d = dictobject.new_dict(int32, float64) + # insertion + for k, v in zip(keys, vals): + d[k] = v + b4 = len(d) + # clear + d.clear() + return b4, len(d) + + keys = [1, 2, 3] + vals = [0.1, 0.2, 0.3] + self.assertEqual(foo(keys, vals), (3, 0)) + + def test_dict_items(self): + """ + Exercise dict.items + """ + @njit + def foo(keys, vals): + d = dictobject.new_dict(int32, float64) + # insertion + for k, v in zip(keys, vals): + d[k] = v + out = [] + for kv in d.items(): + out.append(kv) + return out + + keys = [1, 2, 3] + vals = [0.1, 0.2, 0.3] + + self.assertEqual( + foo(keys, vals), + list(zip(keys, vals)), + ) + + # Test .items() on empty dict + @njit + def foo(): + d = dictobject.new_dict(int32, float64) + out = [] + for kv in d.items(): + out.append(kv) + return out + + self.assertEqual(foo(), []) + + def test_dict_keys(self): + """ + Exercise dict.keys + """ + @njit + def foo(keys, vals): + d = dictobject.new_dict(int32, float64) + # insertion + for k, v in zip(keys, vals): + d[k] = v + out = [] + for k in d.keys(): + out.append(k) + return out + + keys = [1, 2, 3] + vals = [0.1, 0.2, 0.3] + + self.assertEqual( + foo(keys, vals), + keys, + ) + + def test_dict_keys_len(self): + """ + Exercise len(dict.keys()) + """ + @njit + def foo(keys, vals): + d = dictobject.new_dict(int32, float64) + # insertion + for k, v in zip(keys, vals): + d[k] = v + return len(d.keys()) + + keys = [1, 2, 3] + vals = [0.1, 0.2, 0.3] + + self.assertEqual( + foo(keys, vals), + len(keys), + ) + + def test_dict_values(self): + """ + Exercise dict.values + """ + @njit + def foo(keys, vals): + d = dictobject.new_dict(int32, float64) + # insertion + for k, v in zip(keys, vals): + d[k] = v + out = [] + for v in d.values(): + out.append(v) + return out + + keys = [1, 2, 3] + vals = [0.1, 0.2, 0.3] + + self.assertEqual( + foo(keys, vals), + vals, + ) + + def test_dict_values_len(self): + """ + Exercise len(dict.values()) + """ + @njit + def foo(keys, vals): + d = dictobject.new_dict(int32, float64) + # insertion + for k, v in zip(keys, vals): + d[k] = v + return len(d.values()) + + keys = [1, 2, 3] + vals = [0.1, 0.2, 0.3] + + self.assertEqual( + foo(keys, vals), + len(vals), + ) + + def test_dict_items_len(self): + """ + Exercise len(dict.items()) + """ + @njit + def foo(keys, vals): + d = dictobject.new_dict(int32, float64) + # insertion + for k, v in zip(keys, vals): + d[k] = v + return len(d.items()) + + keys = [1, 2, 3] + vals = [0.1, 0.2, 0.3] + self.assertPreciseEqual( + foo(keys, vals), + len(vals), + ) + + def test_dict_iter(self): + """ + Exercise iter(dict) + """ + @njit + def foo(keys, vals): + d = dictobject.new_dict(int32, float64) + # insertion + for k, v in zip(keys, vals): + d[k] = v + out = [] + for k in d: + out.append(k) + return out + + keys = [1, 2, 3] + vals = [0.1, 0.2, 0.3] + + self.assertEqual( + foo(keys, vals), + [1, 2, 3] + ) + + def test_dict_contains(self): + """ + Exercise operator.contains + """ + @njit + def foo(keys, vals, checklist): + d = dictobject.new_dict(int32, float64) + # insertion + for k, v in zip(keys, vals): + d[k] = v + out = [] + for k in checklist: + out.append(k in d) + return out + + keys = [1, 2, 3] + vals = [0.1, 0.2, 0.3] + + self.assertEqual( + foo(keys, vals, [2, 3, 4, 1, 0]), + [True, True, False, True, False], + ) + + def test_dict_copy(self): + """ + Exercise dict.copy + """ + @njit + def foo(keys, vals): + d = dictobject.new_dict(int32, float64) + # insertion + for k, v in zip(keys, vals): + d[k] = v + return list(d.copy().items()) + + keys = list(range(20)) + vals = [x + i / 100 for i, x in enumerate(keys)] + out = foo(keys, vals) + self.assertEqual(out, list(zip(keys, vals))) + + def test_dict_setdefault(self): + """ + Exercise dict.setdefault + """ + @njit + def foo(): + d = dictobject.new_dict(int32, float64) + d.setdefault(1, 1.2) # used because key is not in + a = d.get(1) + d[1] = 2.3 + b = d.get(1) + d[2] = 3.4 + d.setdefault(2, 4.5) # not used because key is in + c = d.get(2) + return a, b, c + + self.assertEqual(foo(), (1.2, 2.3, 3.4)) + + def test_dict_equality(self): + """ + Exercise dict.__eq__ and .__ne__ + """ + @njit + def foo(na, nb, fa, fb): + da = dictobject.new_dict(int32, float64) + db = dictobject.new_dict(int32, float64) + for i in range(na): + da[i] = i * fa + for i in range(nb): + db[i] = i * fb + return da == db, da != db + + # Same keys and values + self.assertEqual(foo(10, 10, 3, 3), (True, False)) + # Same keys and diff values + self.assertEqual(foo(10, 10, 3, 3.1), (False, True)) + # LHS has more keys + self.assertEqual(foo(11, 10, 3, 3), (False, True)) + # RHS has more keys + self.assertEqual(foo(10, 11, 3, 3), (False, True)) + + def test_dict_equality_more(self): + """ + Exercise dict.__eq__ + """ + @njit + def foo(ak, av, bk, bv): + # The key-value types are different in the two dictionaries + da = dictobject.new_dict(int32, float64) + db = dictobject.new_dict(int64, float32) + for i in range(len(ak)): + da[ak[i]] = av[i] + for i in range(len(bk)): + db[bk[i]] = bv[i] + return da == db + + # Simple equal case + ak = [1, 2, 3] + av = [2, 3, 4] + bk = [1, 2, 3] + bv = [2, 3, 4] + self.assertTrue(foo(ak, av, bk, bv)) + + # Equal with replacement + ak = [1, 2, 3] + av = [2, 3, 4] + bk = [1, 2, 2, 3] + bv = [2, 1, 3, 4] + self.assertTrue(foo(ak, av, bk, bv)) + + # Diff values + ak = [1, 2, 3] + av = [2, 3, 4] + bk = [1, 2, 3] + bv = [2, 1, 4] + self.assertFalse(foo(ak, av, bk, bv)) + + # Diff keys + ak = [0, 2, 3] + av = [2, 3, 4] + bk = [1, 2, 3] + bv = [2, 3, 4] + self.assertFalse(foo(ak, av, bk, bv)) + + def test_dict_equality_diff_type(self): + """ + Exercise dict.__eq__ + """ + @njit + def foo(na, b): + da = dictobject.new_dict(int32, float64) + for i in range(na): + da[i] = i + return da == b + + # dict != int + self.assertFalse(foo(10, 1)) + # dict != tuple[int] + self.assertFalse(foo(10, (1,))) + + def test_dict_to_from_meminfo(self): + """ + Exercise dictobject.{_as_meminfo, _from_meminfo} + """ + @njit + def make_content(nelem): + for i in range(nelem): + yield i, i + (i + 1) / 100 + + @njit + def boxer(nelem): + d = dictobject.new_dict(int32, float64) + for k, v in make_content(nelem): + d[k] = v + return dictobject._as_meminfo(d) + + dcttype = types.DictType(int32, float64) + + @njit + def unboxer(mi): + d = dictobject._from_meminfo(mi, dcttype) + return list(d.items()) + + mi = boxer(10) + self.assertEqual(mi.refcount, 1) + + got = unboxer(mi) + expected = list(make_content.py_func(10)) + self.assertEqual(got, expected) + + def test_001_cannot_downcast_key(self): + @njit + def foo(n): + d = dictobject.new_dict(int32, float64) + for i in range(n): + d[i] = i + 1 + # bad key type + z = d.get(1j) + return z + + with self.assertRaises(TypingError) as raises: + foo(10) + self.assertIn( + 'cannot safely cast complex128 to int32', + str(raises.exception), + ) + + def test_002_cannot_downcast_default(self): + @njit + def foo(n): + d = dictobject.new_dict(int32, float64) + for i in range(n): + d[i] = i + 1 + # bad default type + z = d.get(2 * n, 1j) + return z + + with self.assertRaises(TypingError) as raises: + foo(10) + self.assertIn( + 'cannot safely cast complex128 to float64', + str(raises.exception), + ) + + def test_003_cannot_downcast_key(self): + @njit + def foo(n): + d = dictobject.new_dict(int32, float64) + for i in range(n): + d[i] = i + 1 + # bad cast!? + z = d.get(2.4) + return z + + # should raise + with self.assertRaises(TypingError) as raises: + foo(10) + self.assertIn( + 'cannot safely cast float64 to int32', + str(raises.exception), + ) + + def test_004_cannot_downcast_key(self): + @njit + def foo(): + d = dictobject.new_dict(int32, float64) + # should raise TypingError + d[1j] = 7. + + with self.assertRaises(TypingError) as raises: + foo() + self.assertIn( + 'cannot safely cast complex128 to int32', + str(raises.exception), + ) + + def test_005_cannot_downcast_value(self): + @njit + def foo(): + d = dictobject.new_dict(int32, float64) + # should raise TypingError + d[1] = 1j + + with self.assertRaises(TypingError) as raises: + foo() + self.assertIn( + 'cannot safely cast complex128 to float64', + str(raises.exception), + ) + + def test_006_cannot_downcast_key(self): + @njit + def foo(): + d = dictobject.new_dict(int32, float64) + # raise TypingError + d[11.5] + + with self.assertRaises(TypingError) as raises: + foo() + self.assertIn( + 'cannot safely cast float64 to int32', + str(raises.exception), + ) + + @unittest.skipUnless(sys.maxsize > 2 ** 32, "64 bit test only") + def test_007_collision_checks(self): + # this checks collisions in real life for 64bit systems + @njit + def foo(v1, v2): + d = dictobject.new_dict(int64, float64) + c1 = np.uint64(2 ** 61 - 1) + c2 = np.uint64(0) + assert hash(c1) == hash(c2) + d[c1] = v1 + d[c2] = v2 + return (d[c1], d[c2]) + + a, b = 10., 20. + x, y = foo(a, b) + self.assertEqual(x, a) + self.assertEqual(y, b) + + def test_008_lifo_popitem(self): + # check that (keys, vals) are LIFO .popitem() + @njit + def foo(n): + d = dictobject.new_dict(int32, float64) + for i in range(n): + d[i] = i + 1 + keys = [] + vals = [] + for i in range(n): + tmp = d.popitem() + keys.append(tmp[0]) + vals.append(tmp[1]) + return keys, vals + + z = 10 + gk, gv = foo(z) + + self.assertEqual(gk, [x for x in reversed(range(z))]) + self.assertEqual(gv, [x + 1 for x in reversed(range(z))]) + + def test_010_cannot_downcast_default(self): + @njit + def foo(): + d = dictobject.new_dict(int32, float64) + d[0] = 6. + d[1] = 7. + # pop'd default must have same type as value + d.pop(11, 12j) + + with self.assertRaises(TypingError) as raises: + foo() + self.assertIn( + "cannot safely cast complex128 to float64", + str(raises.exception), + ) + + def test_011_cannot_downcast_key(self): + @njit + def foo(): + d = dictobject.new_dict(int32, float64) + d[0] = 6. + d[1] = 7. + # pop'd key must have same type as key + d.pop(11j) + + with self.assertRaises(TypingError) as raises: + foo() + self.assertIn( + "cannot safely cast complex128 to int32", + str(raises.exception), + ) + + def test_012_cannot_downcast_key(self): + @njit + def foo(): + d = dictobject.new_dict(int32, float64) + d[0] = 6. + # invalid key type + return 1j in d + + with self.assertRaises(TypingError) as raises: + foo() + self.assertIn( + "cannot safely cast complex128 to int32", + str(raises.exception), + ) + + def test_013_contains_empty_dict(self): + @njit + def foo(): + d = dictobject.new_dict(int32, float64) + # contains on empty dict + return 1 in d + + self.assertFalse(foo()) + + def test_014_not_contains_empty_dict(self): + @njit + def foo(): + d = dictobject.new_dict(int32, float64) + # not contains empty dict + return 1 not in d + + self.assertTrue(foo()) + + def test_015_dict_clear(self): + @njit + def foo(n): + d = dictobject.new_dict(int32, float64) + for i in range(n): + d[i] = i + 1 + x = len(d) + d.clear() + y = len(d) + return x, y + + m = 10 + self.assertEqual(foo(m), (m, 0)) + + def test_016_cannot_downcast_key(self): + @njit + def foo(): + d = dictobject.new_dict(int32, float64) + # key is wrong type + d.setdefault(1j, 12.) + + with self.assertRaises(TypingError) as raises: + foo() + self.assertIn( + "cannot safely cast complex128 to int32", + str(raises.exception), + ) + + def test_017_cannot_downcast_default(self): + @njit + def foo(): + d = dictobject.new_dict(int32, float64) + # default value is wrong type + d.setdefault(1, 12.j) + + with self.assertRaises(TypingError) as raises: + foo() + self.assertIn( + "cannot safely cast complex128 to float64", + str(raises.exception), + ) + + def test_018_keys_iter_are_views(self): + # this is broken somewhere in llvmlite, intent of test is to check if + # keys behaves like a view or not + @njit + def foo(): + d = dictobject.new_dict(int32, float64) + d[11] = 12. + k1 = d.keys() + d[22] = 9. + k2 = d.keys() + rk1 = [x for x in k1] + rk2 = [x for x in k2] + return rk1, rk2 + + a, b = foo() + self.assertEqual(a, b) + self.assertEqual(a, [11, 22]) + + # Not implemented yet + @unittest.expectedFailure + def test_019(self): + # should keys/vals be set-like? + @njit + def foo(): + d = dictobject.new_dict(int32, float64) + d[11] = 12. + d[22] = 9. + k2 = d.keys() & {12, } + return k2 + + print(foo()) + + def test_020_string_key(self): + @njit + def foo(): + d = dictobject.new_dict(types.unicode_type, float64) + d['a'] = 1. + d['b'] = 2. + d['c'] = 3. + d['d'] = 4. + out = [] + for x in d.items(): + out.append(x) + return out, d['a'] + + items, da = foo() + self.assertEqual(items, [('a', 1.), ('b', 2.), ('c', 3.), ('d', 4)]) + self.assertEqual(da, 1.) + + def test_021_long_str_key(self): + @njit + def foo(): + d = dictobject.new_dict(types.unicode_type, float64) + tmp = [] + for i in range(10000): + tmp.append('a') + s = ''.join(tmp) + d[s] = 1. + out = list(d.items()) + return out + self.assertEqual(foo(), [('a' * 10000, 1)]) + + def test_022_references_juggle(self): + @njit + def foo(): + d = dictobject.new_dict(int32, float64) + e = d + d[1] = 12. + e[2] = 14. + e = dictobject.new_dict(int32, float64) + e[1] = 100. + e[2] = 1000. + f = d + d = e + + k1 = [x for x in d.items()] + k2 = [x for x in e.items()] + k3 = [x for x in f.items()] + + return k1, k2, k3 + + k1, k2, k3 = foo() + self.assertEqual(k1, [(1, 100.0), (2, 1000.0)]) + self.assertEqual(k2, [(1, 100.0), (2, 1000.0)]) + self.assertEqual(k3, [(1, 12), (2, 14)]) + + def test_023_closure(self): + @njit + def foo(): + d = dictobject.new_dict(int32, float64) + + def bar(): + d[1] = 12. + d[2] = 14. + bar() + return [x for x in d.keys()] + + self.assertEqual(foo(), [1, 2]) + + def test_024_unicode_getitem_keys(self): + # See issue #6135 + @njit + def foo(): + s = 'a\u1234' + d = {s[0] : 1} + return d['a'] + + self.assertEqual(foo(), foo.py_func()) + + @njit + def foo(): + s = 'abc\u1234' + d = {s[:1] : 1} + return d['a'] + + self.assertEqual(foo(), foo.py_func()) + + def test_issue6570_alignment_padding(self): + # Create a key type that is 12-bytes long on a 8-byte aligned system + # so that the a 4-byte padding is needed. + # If the 4-byte padding is not zero-filled, it will have garbage data + # that affects key matching in the lookup. + keyty = types.Tuple([types.uint64, types.float32]) + + @njit + def foo(): + d = dictobject.new_dict(keyty, float64) + t1 = np.array([3], dtype=np.uint64) + t2 = np.array([5.67], dtype=np.float32) + v1 = np.array([10.23], dtype=np.float32) + d[(t1[0], t2[0])] = v1[0] + return (t1[0], t2[0]) in d + + self.assertTrue(foo()) + + def test_dict_update(self): + """ + Tests dict.update works with various dictionaries. + """ + n = 10 + + def f1(n): + """ + Test update with a regular dictionary. + """ + d1 = {i: i + 1 for i in range(n)} + d2 = {3 * i: i for i in range(n)} + d1.update(d2) + return d1 + + py_func = f1 + cfunc = njit()(f1) + a = py_func(n) + b = cfunc(n) + self.assertEqual(a, b) + + def f2(n): + """ + Test update where one of the dictionaries + is created as a Python literal. + """ + d1 = { + 1: 2, + 3: 4, + 5: 6 + } + d2 = {3 * i: i for i in range(n)} + d1.update(d2) + return d1 + + py_func = f2 + cfunc = njit()(f2) + a = py_func(n) + b = cfunc(n) + self.assertEqual(a, b) + + +class TestDictTypeCasting(TestCase): + def check_good(self, fromty, toty): + _sentry_safe_cast(fromty, toty) + + def check_bad(self, fromty, toty): + with self.assertRaises(TypingError) as raises: + _sentry_safe_cast(fromty, toty) + self.assertIn( + 'cannot safely cast {fromty} to {toty}'.format(**locals()), + str(raises.exception), + ) + + def test_cast_int_to(self): + self.check_good(types.int32, types.float32) + self.check_good(types.int32, types.float64) + self.check_good(types.int32, types.complex128) + self.check_good(types.int64, types.complex128) + self.check_bad(types.int32, types.complex64) + self.check_good(types.int8, types.complex64) + + def test_cast_float_to(self): + self.check_good(types.float32, types.float64) + self.check_good(types.float32, types.complex64) + self.check_good(types.float64, types.complex128) + + def test_cast_bool_to(self): + self.check_good(types.boolean, types.int32) + self.check_good(types.boolean, types.float64) + self.check_good(types.boolean, types.complex128) + + +class TestTypedDict(MemoryLeakMixin, TestCase): + def test_basic(self): + d = Dict.empty(int32, float32) + # len + self.assertEqual(len(d), 0) + # setitems + d[1] = 1 + d[2] = 2.3 + d[3] = 3.4 + self.assertEqual(len(d), 3) + # keys + self.assertEqual(list(d.keys()), [1, 2, 3]) + # values + for x, y in zip(list(d.values()), [1, 2.3, 3.4]): + self.assertAlmostEqual(x, y, places=4) + # getitem + self.assertAlmostEqual(d[1], 1) + self.assertAlmostEqual(d[2], 2.3, places=4) + self.assertAlmostEqual(d[3], 3.4, places=4) + # deltiem + del d[2] + self.assertEqual(len(d), 2) + # get + self.assertIsNone(d.get(2)) + # setdefault + d.setdefault(2, 100) + d.setdefault(3, 200) + self.assertEqual(d[2], 100) + self.assertAlmostEqual(d[3], 3.4, places=4) + # update + d.update({4: 5, 5: 6}) + self.assertAlmostEqual(d[4], 5) + self.assertAlmostEqual(d[5], 6) + # contains + self.assertTrue(4 in d) + # items + pyd = dict(d.items()) + self.assertEqual(len(pyd), len(d)) + # pop + self.assertAlmostEqual(d.pop(4), 5) + # popitem + nelem = len(d) + k, v = d.popitem() + self.assertEqual(len(d), nelem - 1) + self.assertTrue(k not in d) + # __eq__ & copy + copied = d.copy() + self.assertEqual(copied, d) + self.assertEqual(list(copied.items()), list(d.items())) + + def test_copy_from_dict(self): + expect = {k: float(v) for k, v in zip(range(10), range(10, 20))} + nbd = Dict.empty(int32, float64) + for k, v in expect.items(): + nbd[k] = v + got = dict(nbd) + self.assertEqual(got, expect) + + def test_compiled(self): + @njit + def producer(): + d = Dict.empty(int32, float64) + d[1] = 1.23 + return d + + @njit + def consumer(d): + return d[1] + + d = producer() + val = consumer(d) + self.assertEqual(val, 1.23) + + def test_gh7908(self): + d = Dict.empty( + key_type=types.Tuple([types.uint32, + types.uint32]), + value_type=int64) + + d[(1, 1)] = 12345 + self.assertEqual(d[(1, 1)], d.get((1, 1))) + + def check_stringify(self, strfn, prefix=False): + nbd = Dict.empty(int32, int32) + d = {} + nbd[1] = 2 + d[1] = 2 + checker = self.assertIn if prefix else self.assertEqual + checker(strfn(d), strfn(nbd)) + nbd[2] = 3 + d[2] = 3 + checker(strfn(d), strfn(nbd)) + for i in range(10, 20): + nbd[i] = i + 1 + d[i] = i + 1 + checker(strfn(d), strfn(nbd)) + if prefix: + self.assertTrue(strfn(nbd).startswith('DictType')) + + def test_repr(self): + self.check_stringify(repr, prefix=True) + + def test_str(self): + self.check_stringify(str) + + +class DictIterableCtor: + + def test_iterable_type_constructor(self): + # https://docs.python.org/3/library/stdtypes.html#dict + @njit + def func1(a, b): + d = Dict(zip(a, b)) + return d + + @njit + def func2(a_, b): + a = range(3) + return Dict(zip(a, b)) + + @njit + def func3(a_, b): + a = [0, 1, 2] + return Dict(zip(a, b)) + + @njit + def func4(a, b): + c = zip(a, b) + return Dict(zip(a, zip(c, a))) + + @njit + def func5(a, b): + return Dict(zip(zip(a, b), b)) + + @njit + def func6(items): + return Dict(items) + + @njit + def func7(k, v): + return Dict({k: v}) # mapping - not supported + + @njit + def func8(k, v): + d = Dict() + d[k] = v + return d + + def _get_dict(py_dict): + d = Dict() + for k, v in py_dict.items(): + d[k] = v + return d + + vals = ( + (func1, [(0, 1, 2), 'abc'], _get_dict({0: 'a', 1: 'b', 2: 'c'})), + (func2, [(0, 1, 2), 'abc'], _get_dict({0: 'a', 1: 'b', 2: 'c'})), + (func3, [(0, 1, 2), 'abc'], _get_dict({0: 'a', 1: 'b', 2: 'c'})), + (func4, [(0, 1, 2), 'abc'], _get_dict( + {0: ((0, 'a'), 0), 1: ((1, 'b'), 1), 2: ((2, 'c'), 2)})), + (func5, [(0, 1, 2), 'abc'], _get_dict( + {(0, 'a'): 'a', (1, 'b'): 'b', (2, 'c'): 'c'})), + # (func6, [(),], Dict({})), + (func6, [((1, 'a'), (3, 'b')),], _get_dict({1: 'a', 3: 'b'})), + (func1, ['key', _get_dict({1: 'abc'})], _get_dict({'k': 1})), + (func8, ['key', _get_dict({1: 'abc'})], _get_dict( + {'key': _get_dict({1: 'abc'})})), + (func8, ['key', List([1, 2, 3])], _get_dict( + {'key': List([1, 2, 3])})), + ) + + for func, args, expected in vals: + if self.jit_enabled: + got = func(*args) + else: + got = func.py_func(*args) + self.assertPreciseEqual(expected, got) + + +class TestDictIterableCtorJit(TestCase, DictIterableCtor): + + def setUp(self): + self.jit_enabled = True + + def test_exception_no_iterable_arg(self): + @njit + def ctor(): + return Dict(3) + + msg = ".*No implementation of function.*" + with self.assertRaisesRegex(TypingError, msg): + ctor() + + def test_exception_dict_mapping(self): + @njit + def ctor(): + return Dict({1: 2, 3: 4}) + + msg = ".*No implementation of function.*" + with self.assertRaisesRegex(TypingError, msg): + ctor() + + def test_exception_setitem(self): + @njit + def ctor(): + return Dict(((1, 'a'), (2, 'b', 3))) + + msg = ".*No implementation of function.*" + with self.assertRaisesRegex(TypingError, msg): + ctor() + + +class TestDictIterableCtorNoJit(TestCase, DictIterableCtor): + + def setUp(self): + self.jit_enabled = False + + def test_exception_nargs(self): + msg = 'Dict expect at most 1 argument, got 2' + with self.assertRaisesRegex(TypingError, msg): + Dict(1, 2) + + def test_exception_mapping_ctor(self): + msg = r'.*dict\(mapping\) is not supported.*' # noqa: W605 + with self.assertRaisesRegex(TypingError, msg): + Dict({1: 2}) + + def test_exception_non_iterable_arg(self): + msg = '.*object is not iterable.*' + with self.assertRaisesRegex(TypingError, msg): + Dict(3) + + def test_exception_setitem(self): + msg = ".*dictionary update sequence element #1 has length 3.*" + with self.assertRaisesRegex(ValueError, msg): + Dict(((1, 'a'), (2, 'b', 3))) + + +class TestDictRefctTypes(MemoryLeakMixin, TestCase): + + def test_str_key(self): + @njit + def foo(): + d = Dict.empty( + key_type=types.unicode_type, + value_type=types.int32, + ) + d["123"] = 123 + d["321"] = 321 + return d + + d = foo() + self.assertEqual(d['123'], 123) + self.assertEqual(d['321'], 321) + expect = {'123': 123, '321': 321} + self.assertEqual(dict(d), expect) + # Test insert replacement + d['123'] = 231 + expect['123'] = 231 + self.assertEqual(d['123'], 231) + self.assertEqual(dict(d), expect) + # Test dictionary growth + nelem = 100 + for i in range(nelem): + d[str(i)] = i + expect[str(i)] = i + for i in range(nelem): + self.assertEqual(d[str(i)], i) + self.assertEqual(dict(d), expect) + + def test_str_val(self): + @njit + def foo(): + d = Dict.empty( + key_type=types.int32, + value_type=types.unicode_type, + ) + d[123] = "123" + d[321] = "321" + return d + + d = foo() + self.assertEqual(d[123], '123') + self.assertEqual(d[321], '321') + expect = {123: '123', 321: '321'} + self.assertEqual(dict(d), expect) + # Test insert replacement + d[123] = "231" + expect[123] = "231" + self.assertEqual(dict(d), expect) + # Test dictionary growth + nelem = 1 + for i in range(nelem): + d[i] = str(i) + expect[i] = str(i) + for i in range(nelem): + self.assertEqual(d[i], str(i)) + self.assertEqual(dict(d), expect) + + def test_str_key_array_value(self): + np.random.seed(123) + d = Dict.empty( + key_type=types.unicode_type, + value_type=types.float64[:], + ) + expect = [] + expect.append(np.random.random(10)) + d['mass'] = expect[-1] + expect.append(np.random.random(20)) + d['velocity'] = expect[-1] + for i in range(100): + expect.append(np.random.random(i)) + d[str(i)] = expect[-1] + self.assertEqual(len(d), len(expect)) + self.assertPreciseEqual(d['mass'], expect[0]) + self.assertPreciseEqual(d['velocity'], expect[1]) + # Ordering is kept + for got, exp in zip(d.values(), expect): + self.assertPreciseEqual(got, exp) + + # Try deleting + self.assertTrue('mass' in d) + self.assertTrue('velocity' in d) + del d['mass'] + self.assertFalse('mass' in d) + del d['velocity'] + self.assertFalse('velocity' in d) + del expect[0:2] + + for i in range(90): + k, v = d.popitem() + w = expect.pop() + self.assertPreciseEqual(v, w) + + # Trigger a resize + expect.append(np.random.random(10)) + d["last"] = expect[-1] + + # Ordering is kept + for got, exp in zip(d.values(), expect): + self.assertPreciseEqual(got, exp) + + def test_dict_of_dict_int_keyval(self): + def inner_numba_dict(): + d = Dict.empty( + key_type=types.intp, + value_type=types.intp, + ) + return d + + d = Dict.empty( + key_type=types.intp, + value_type=types.DictType(types.intp, types.intp), + ) + + def usecase(d, make_inner_dict): + for i in range(100): + mid = make_inner_dict() + for j in range(i + 1): + mid[j] = j * 10000 + d[i] = mid + return d + + got = usecase(d, inner_numba_dict) + expect = usecase({}, dict) + + self.assertIsInstance(expect, dict) + + self.assertEqual(dict(got), expect) + + # Delete items + for where in [12, 3, 6, 8, 10]: + del got[where] + del expect[where] + self.assertEqual(dict(got), expect) + + def test_dict_of_dict_npm(self): + inner_dict_ty = types.DictType(types.intp, types.intp) + + @njit + def inner_numba_dict(): + d = Dict.empty( + key_type=types.intp, + value_type=types.intp, + ) + return d + + @njit + def foo(count): + d = Dict.empty( + key_type=types.intp, + value_type=inner_dict_ty, + ) + for i in range(count): + d[i] = inner_numba_dict() + for j in range(i + 1): + d[i][j] = j + + return d + + d = foo(100) + ct = 0 + for k, dd in d.items(): + ct += 1 + self.assertEqual(len(dd), k + 1) + for kk, vv in dd.items(): + self.assertEqual(kk, vv) + + self.assertEqual(ct, 100) + + def test_delitem(self): + d = Dict.empty(types.int64, types.unicode_type) + d[1] = 'apple' + + @njit + def foo(x, k): + del x[1] + + foo(d, 1) + self.assertEqual(len(d), 0) + self.assertFalse(d) + + def test_getitem_return_type(self): + # Dict.__getitem__ must return non-optional type. + d = Dict.empty(types.int64, types.int64[:]) + d[1] = np.arange(10, dtype=np.int64) + + @njit + def foo(d): + d[1] += 100 + return d[1] + + foo(d) + # Return type is an array, not optional + retty = foo.nopython_signatures[0].return_type + self.assertIsInstance(retty, types.Array) + self.assertNotIsInstance(retty, types.Optional) + # Value is correctly updated + self.assertPreciseEqual(d[1], np.arange(10, dtype=np.int64) + 100) + + def test_storage_model_mismatch(self): + # https://github.com/numba/numba/issues/4520 + # check for storage model mismatch in refcount ops generation + dct = Dict() + ref = [ + ("a", True, "a"), + ("b", False, "b"), + ("c", False, "c"), + ] + # populate + for x in ref: + dct[x] = x + # test + for i, x in enumerate(ref): + self.assertEqual(dct[x], x) + + +class TestDictForbiddenTypes(TestCase): + def assert_disallow(self, expect, callable): + with self.assertRaises(TypingError) as raises: + callable() + msg = str(raises.exception) + self.assertIn(expect, msg) + + def assert_disallow_key(self, ty): + msg = '{} as key is forbidden'.format(ty) + self.assert_disallow(msg, lambda: Dict.empty(ty, types.intp)) + + @njit + def foo(): + Dict.empty(ty, types.intp) + self.assert_disallow(msg, foo) + + def assert_disallow_value(self, ty): + msg = '{} as value is forbidden'.format(ty) + self.assert_disallow(msg, lambda: Dict.empty(types.intp, ty)) + + @njit + def foo(): + Dict.empty(types.intp, ty) + self.assert_disallow(msg, foo) + + def test_disallow_list(self): + self.assert_disallow_key(types.List(types.intp)) + self.assert_disallow_value(types.List(types.intp)) + + def test_disallow_set(self): + self.assert_disallow_key(types.Set(types.intp)) + self.assert_disallow_value(types.Set(types.intp)) + + +class TestDictInferred(TestCase): + def test_simple_literal(self): + @njit + def foo(): + d = Dict() + d[123] = 321 + return d + + k, v = 123, 321 + d = foo() + self.assertEqual(dict(d), {k: v}) + self.assertEqual(typeof(d).key_type, typeof(k)) + self.assertEqual(typeof(d).value_type, typeof(v)) + + def test_simple_args(self): + @njit + def foo(k, v): + d = Dict() + d[k] = v + return d + + k, v = 123, 321 + d = foo(k, v) + self.assertEqual(dict(d), {k: v}) + self.assertEqual(typeof(d).key_type, typeof(k)) + self.assertEqual(typeof(d).value_type, typeof(v)) + + def test_simple_upcast(self): + @njit + def foo(k, v, w): + d = Dict() + d[k] = v + d[k] = w + return d + + k, v, w = 123, 32.1, 321 + d = foo(k, v, w) + self.assertEqual(dict(d), {k: w}) + self.assertEqual(typeof(d).key_type, typeof(k)) + self.assertEqual(typeof(d).value_type, typeof(v)) + + def test_conflicting_value_type(self): + @njit + def foo(k, v, w): + d = Dict() + d[k] = v + d[k] = w + return d + + k, v, w = 123, 321, 32.1 + with self.assertRaises(TypingError) as raises: + foo(k, v, w) + self.assertIn( + 'cannot safely cast float64 to {}'.format(typeof(v)), + str(raises.exception), + ) + + def test_conflicting_key_type(self): + @njit + def foo(k, h, v): + d = Dict() + d[k] = v + d[h] = v + return d + + k, h, v = 123, 123.1, 321 + with self.assertRaises(TypingError) as raises: + foo(k, h, v) + self.assertIn( + 'cannot safely cast float64 to {}'.format(typeof(v)), + str(raises.exception), + ) + + def test_conflict_key_type_non_number(self): + # Allow non-number types to cast unsafely + @njit + def foo(k1, v1, k2): + d = Dict() + d[k1] = v1 + return d, d[k2] + + # k2 will unsafely downcast typeof(k1) + k1 = (np.int8(1), np.int8(2)) + k2 = (np.int32(1), np.int32(2)) + v1 = np.intp(123) + + with warnings.catch_warnings(record=True) as w: + d, dk2 = foo(k1, v1, k2) + self.assertEqual(len(w), 1) + # Make sure the warning is about unsafe cast + msg = 'unsafe cast from UniTuple(int32 x 2) to UniTuple(int8 x 2)' + self.assertIn(msg, str(w[0])) + + keys = list(d.keys()) + self.assertEqual(keys[0], (1, 2)) + self.assertEqual(dk2, d[(np.int32(1), np.int32(2))]) + + def test_ifelse_filled_both_branches(self): + @njit + def foo(k, v): + d = Dict() + if k: + d[k] = v + else: + d[0xdead] = v + 1 + + return d + + k, v = 123, 321 + d = foo(k, v) + self.assertEqual(dict(d), {k: v}) + k, v = 0, 0 + d = foo(k, v) + self.assertEqual(dict(d), {0xdead: v + 1}) + + def test_ifelse_empty_one_branch(self): + @njit + def foo(k, v): + d = Dict() + if k: + d[k] = v + + return d + + k, v = 123, 321 + d = foo(k, v) + self.assertEqual(dict(d), {k: v}) + k, v = 0, 0 + d = foo(k, v) + self.assertEqual(dict(d), {}) + self.assertEqual(typeof(d).key_type, typeof(k)) + self.assertEqual(typeof(d).value_type, typeof(v)) + + def test_loop(self): + @njit + def foo(ks, vs): + d = Dict() + for k, v in zip(ks, vs): + d[k] = v + return d + + vs = list(range(4)) + ks = list(map(lambda x : x + 100, vs)) + d = foo(ks, vs) + self.assertEqual(dict(d), dict(zip(ks, vs))) + + def test_unused(self): + @njit + def foo(): + d = Dict() + return d + + with self.assertRaises(TypingError) as raises: + foo() + self.assertIn( + "imprecise type", + str(raises.exception) + ) + + def test_define_after_use(self): + @njit + def foo(define): + d = Dict() + ct = len(d) + for k, v in d.items(): + ct += v + + if define: + # This will set the type + d[1] = 2 + return ct, d, len(d) + + ct, d, n = foo(True) + self.assertEqual(ct, 0) + self.assertEqual(n, 1) + self.assertEqual(dict(d), {1: 2}) + + ct, d, n = foo(False) + self.assertEqual(ct, 0) + self.assertEqual(dict(d), {}) + self.assertEqual(n, 0) + + def test_dict_of_dict(self): + @njit + def foo(k1, k2, v): + d = Dict() + z1 = Dict() + z1[k1 + 1] = v + k1 + z2 = Dict() + z2[k2 + 2] = v + k2 + d[k1] = z1 + d[k2] = z2 + return d + + k1, k2, v = 100, 200, 321 + d = foo(k1, k2, v) + self.assertEqual( + dict(d), + { + k1: {k1 + 1: k1 + v}, + k2: {k2 + 2: k2 + v}, + }, + ) + + def test_comprehension_basic(self): + @njit + def foo(): + return {i: 2 * i for i in range(10)} + + self.assertEqual(foo(), foo.py_func()) + + def test_comprehension_basic_mixed_type(self): + @njit + def foo(): + return {i: float(j) for i, j in zip(range(10), range(10, 0, -1))} + + self.assertEqual(foo(), foo.py_func()) + + def test_comprehension_involved(self): + @njit + def foo(): + a = {0: 'A', 1: 'B', 2: 'C'} + return {3 + i: a[i] for i in range(3)} + + self.assertEqual(foo(), foo.py_func()) + + def test_comprehension_fail_mixed_type(self): + @njit + def foo(): + a = {0: 'A', 1: 'B', 2: 1j} + return {3 + i: a[i] for i in range(3)} + + with self.assertRaises(TypingError) as e: + foo() + + excstr = str(e.exception) + self.assertIn("Cannot cast complex128 to unicode_type", excstr) + + +class TestNonCompiledInfer(TestCase): + def test_check_untyped_dict_ops(self): + # Check operation on untyped dictionary + d = Dict() + self.assertFalse(d._typed) + self.assertEqual(len(d), 0) + self.assertEqual(str(d), str({})) + self.assertEqual(list(iter(d)), []) + # Test __getitem__ + with self.assertRaises(KeyError) as raises: + d[1] + self.assertEqual(str(raises.exception), str(KeyError(1))) + # Test __delitem__ + with self.assertRaises(KeyError) as raises: + del d[1] + self.assertEqual(str(raises.exception), str(KeyError(1))) + # Test .pop + with self.assertRaises(KeyError): + d.pop(1) + self.assertEqual(str(raises.exception), str(KeyError(1))) + # Test .pop + self.assertIs(d.pop(1, None), None) + # Test .get + self.assertIs(d.get(1), None) + # Test .popitem + with self.assertRaises(KeyError) as raises: + d.popitem() + self.assertEqual(str(raises.exception), + str(KeyError('dictionary is empty'))) + # Test setdefault(k) + with self.assertRaises(TypeError) as raises: + d.setdefault(1) + self.assertEqual( + str(raises.exception), + str(TypeError('invalid operation on untyped dictionary')), + ) + # Test __contains__ + self.assertFalse(1 in d) + # It's untyped + self.assertFalse(d._typed) + + def test_getitem(self): + # Test __getitem__ + d = Dict() + d[1] = 2 + # It's typed now + self.assertTrue(d._typed) + self.assertEqual(d[1], 2) + + def test_setdefault(self): + # Test setdefault(k, d) + d = Dict() + d.setdefault(1, 2) + # It's typed now + self.assertTrue(d._typed) + self.assertEqual(d[1], 2) + + +@jitclass(spec=[('a', types.intp)]) +class Bag(object): + def __init__(self, a): + self.a = a + + def __hash__(self): + return hash(self.a) + + +class TestDictWithJitclass(TestCase): + def test_jitclass_as_value(self): + @njit + def foo(x): + d = Dict() + d[0] = x + d[1] = Bag(101) + return d + + d = foo(Bag(a=100)) + self.assertEqual(d[0].a, 100) + self.assertEqual(d[1].a, 101) + + +class TestNoJit(TestCase): + """Exercise dictionary creation with JIT disabled. """ + + def test_dict_create_no_jit_using_new_dict(self): + with override_config('DISABLE_JIT', True): + with forbid_codegen(): + d = dictobject.new_dict(int32, float32) + self.assertEqual(type(d), dict) + + def test_dict_create_no_jit_using_Dict(self): + with override_config('DISABLE_JIT', True): + with forbid_codegen(): + d = Dict() + self.assertEqual(type(d), dict) + + def test_dict_create_no_jit_using_empty(self): + with override_config('DISABLE_JIT', True): + with forbid_codegen(): + d = Dict.empty(types.int32, types.float32) + self.assertEqual(type(d), dict) + + +class TestDictIterator(TestCase): + def test_dict_iterator(self): + @njit + def fun1(): + dd = Dict.empty(key_type=types.intp, + value_type=types.intp) + dd[0] = 10 + dd[1] = 20 + dd[2] = 30 + + return list(dd.keys()), list(dd.values()) + + @njit + def fun2(): + dd = Dict.empty(key_type=types.intp, + value_type=types.intp) + dd[4] = 77 + dd[5] = 88 + dd[6] = 99 + + return list(dd.keys()), list(dd.values()) + res1 = fun1() + res2 = fun2() + + self.assertEqual([0,1,2], res1[0]) + self.assertEqual([10,20,30], res1[1]) + self.assertEqual([4,5,6], res2[0]) + self.assertEqual([77,88,99], res2[1]) + + +class TestTypedDictInitialValues(MemoryLeakMixin, TestCase): + """Tests that typed dictionaries carry their initial value if present""" + + def test_homogeneous_and_literal(self): + def bar(d): + ... + + @overload(bar) + def ol_bar(d): + if d.initial_value is None: + return lambda d: literally(d) + self.assertTrue(isinstance(d, types.DictType)) + self.assertEqual(d.initial_value, {'a': 1, 'b': 2, 'c': 3}) + self.assertEqual(hasattr(d, 'literal_value'), False) + return lambda d: d + + @njit + def foo(): + # keys and values all have literal representation + x = {'a': 1, 'b': 2, 'c': 3} + bar(x) + + foo() + + def test_heterogeneous_but_castable_to_homogeneous(self): + def bar(d): + ... + + @overload(bar) + def ol_bar(d): + self.assertTrue(isinstance(d, types.DictType)) + self.assertEqual(d.initial_value, None) + self.assertEqual(hasattr(d, 'literal_value'), False) + return lambda d: d + + @njit + def foo(): + # This dictionary will be typed based on 1j, i.e. complex128 + # as the values are not all literals, there's no "initial_value" + # available irrespective of whether it's possible to rip this + # information out of the bytecode. + x = {'a': 1j, 'b': 2, 'c': 3} + bar(x) + + foo() + + def test_heterogeneous_but_not_castable_to_homogeneous(self): + def bar(d): + ... + + @overload(bar) + def ol_bar(d): + a = {'a': 1, 'b': 2j, 'c': 3} + + def specific_ty(z): + return types.literal(z) if types.maybe_literal(z) else typeof(z) + expected = {types.literal(x): specific_ty(y) for x, y in a.items()} + self.assertTrue(isinstance(d, types.LiteralStrKeyDict)) + self.assertEqual(d.literal_value, expected) + self.assertEqual(hasattr(d, 'initial_value'), False) + return lambda d: d + + @njit + def foo(): + # This dictionary will be typed based on 1, i.e. intp, as the values + # cannot all be cast to this type, but the keys are literal strings + # this is a LiteralStrKey[Dict], there's no initial_value but there + # is a literal_value. + x = {'a': 1, 'b': 2j, 'c': 3} + bar(x) + + foo() + + def test_mutation_not_carried(self): + def bar(d): + ... + + @overload(bar) + def ol_bar(d): + if d.initial_value is None: + return lambda d: literally(d) + self.assertTrue(isinstance(d, types.DictType)) + self.assertEqual(d.initial_value, {'a': 1, 'b': 2, 'c': 3}) + return lambda d: d + + @njit + def foo(): + # This dictionary is mutated, check the initial_value carries + # correctly and is not mutated + x = {'a': 1, 'b': 2, 'c': 3} + x['d'] = 4 + bar(x) + + foo() + + def test_mutation_not_carried_single_function(self): + # this is another pattern for using literally + + @njit + def nop(*args): + pass + + for fn, iv in (nop, None), (literally, {'a': 1, 'b': 2, 'c': 3}): + @njit + def baz(x): + pass + + def bar(z): + pass + + @overload(bar) + def ol_bar(z): + def impl(z): + fn(z) + baz(z) + return impl + + @njit + def foo(): + x = {'a': 1, 'b': 2, 'c': 3} + bar(x) + x['d'] = 4 + return x + + foo() + # baz should be specialised based on literally being invoked and + # the literal/unliteral arriving at the call site + larg = baz.signatures[0][0] + self.assertEqual(larg.initial_value, iv) + + def test_unify_across_function_call(self): + + @njit + def bar(x): + o = {1: 2} + if x: + o = {2: 3} + return o + + @njit + def foo(x): + if x: + d = {3: 4} + else: + d = bar(x) + return d + + e1 = Dict() + e1[3] = 4 + e2 = Dict() + e2[1] = 2 + self.assertEqual(foo(True), e1) + self.assertEqual(foo(False), e2) + + +class TestLiteralStrKeyDict(MemoryLeakMixin, TestCase): + """ Tests for dictionaries with string keys that can map to anything!""" + + def test_basic_const_lowering_boxing(self): + @njit + def foo(): + ld = {'a': 1, 'b': 2j, 'c': 'd'} + return (ld['a'], ld['b'], ld['c']) + + self.assertEqual(foo(), (1, 2j, 'd')) + + def test_basic_nonconst_in_scope(self): + @njit + def foo(x): + y = x + 5 + e = True if y > 2 else False + ld = {'a': 1, 'b': 2j, 'c': 'd', 'non_const': e} + return ld['non_const'] + + # Recall that key non_const has a value of a known type, bool, and it's + # value is stuffed in at run time, this is permitted as the dictionary + # is immutable in type + self.assertTrue(foo(34)) + self.assertFalse(foo(-100)) + + def test_basic_nonconst_freevar(self): + e = 5 + + def bar(x): + pass + + @overload(bar) + def ol_bar(x): + self.assertEqual(x.literal_value, + {types.literal('a'): types.literal(1), + types.literal('b'): typeof(2j), + types.literal('c'): types.literal('d'), + types.literal('d'): types.literal(5)}) + + def impl(x): + pass + return impl + + @njit + def foo(): + ld = {'a': 1, 'b': 2j, 'c': 'd', 'd': e} + bar(ld) + + foo() + + def test_literal_value(self): + + def bar(x): + pass + + @overload(bar) + def ol_bar(x): + self.assertEqual(x.literal_value, + {types.literal('a'): types.literal(1), + types.literal('b'): typeof(2j), + types.literal('c'): types.literal('d')}) + + def impl(x): + pass + return impl + + @njit + def foo(): + ld = {'a': 1, 'b': 2j, 'c': 'd'} + bar(ld) + + foo() + + def test_list_and_array_as_value(self): + + def bar(x): + pass + + @overload(bar) + def ol_bar(x): + self.assertEqual(x.literal_value, + {types.literal('a'): types.literal(1), + types.literal('b'): + types.List(types.intp, initial_value=[1,2,3]), + types.literal('c'): typeof(np.zeros(5))}) + + def impl(x): + pass + return impl + + @njit + def foo(): + b = [1, 2, 3] + ld = {'a': 1, 'b': b, 'c': np.zeros(5)} + bar(ld) + + foo() + + def test_repeated_key_literal_value(self): + + def bar(x): + pass + + @overload(bar) + def ol_bar(x): + # order is important, 'a' was seen first, but updated later + self.assertEqual(x.literal_value, + {types.literal('a'): types.literal('aaaa'), + types.literal('b'): typeof(2j), + types.literal('c'): types.literal('d')}) + + def impl(x): + pass + return impl + + @njit + def foo(): + ld = {'a': 1, 'a': 10, 'b': 2j, 'c': 'd', 'a': 'aaaa'} # noqa #F601 + bar(ld) + + foo() + + def test_read_only(self): + + def _len(): + ld = {'a': 1, 'b': 2j, 'c': 'd'} + return len(ld) + + def static_getitem(): + ld = {'a': 1, 'b': 2j, 'c': 'd'} + return ld['b'] + + def contains(): + ld = {'a': 1, 'b': 2j, 'c': 'd'} + return 'b' in ld, 'f' in ld + + def copy(): + ld = {'a': 1, 'b': 2j, 'c': 'd'} + new = ld.copy() + return ld == new + + rdonlys = (_len, static_getitem, contains, copy) + + for test in rdonlys: + with self.subTest(test.__name__): + self.assertPreciseEqual(njit(test)(), test()) + + def test_mutation_failure(self): + + def setitem(): + ld = {'a': 1, 'b': 2j, 'c': 'd'} + ld['a'] = 12 + + def delitem(): + ld = {'a': 1, 'b': 2j, 'c': 'd'} + del ld['a'] + + def popitem(): + ld = {'a': 1, 'b': 2j, 'c': 'd'} + ld.popitem() + + def pop(): + ld = {'a': 1, 'b': 2j, 'c': 'd'} + ld.pop() + + def clear(): + ld = {'a': 1, 'b': 2j, 'c': 'd'} + ld.clear() + + def setdefault(): + ld = {'a': 1, 'b': 2j, 'c': 'd'} + ld.setdefault('f', 1) + + illegals = (setitem, delitem, popitem, pop, clear, setdefault) + + for test in illegals: + with self.subTest(test.__name__): + with self.assertRaises(TypingError) as raises: + njit(test)() + expect = "Cannot mutate a literal dictionary" + self.assertIn(expect, str(raises.exception)) + + def test_get(self): + + @njit + def get(x): + ld = {'a': 2j, 'c': 'd'} + return ld.get(x) + + @njit + def getitem(x): + ld = {'a': 2j, 'c': 'd'} + return ld[x] + + for test in (get, getitem): + with self.subTest(test.__name__): + with self.assertRaises(TypingError) as raises: + test('a') + expect = "Cannot get{item}() on a literal dictionary" + self.assertIn(expect, str(raises.exception)) + + def test_dict_keys(self): + + @njit + def foo(): + ld = {'a': 2j, 'c': 'd'} + return [x for x in ld.keys()] + + self.assertEqual(foo(), ['a', 'c']) + + def test_dict_values(self): + + @njit + def foo(): + ld = {'a': 2j, 'c': 'd'} + return ld.values() + + self.assertEqual(foo(), (2j, 'd')) + + def test_dict_items(self): + @njit + def foo(): + ld = {'a': 2j, 'c': 'd', 'f': np.zeros((5))} + return ld.items() + + self.assertPreciseEqual(foo(), + (('a', 2j), ('c', 'd'), ('f', np.zeros((5))))) + + def test_dict_return(self): + + @njit + def foo(): + ld = {'a': 2j, 'c': 'd'} + return ld + + # escaping heterogeneous dictionary is not supported + with self.assertRaises(TypeError) as raises: + foo() + + excstr = str(raises.exception) + self.assertIn("cannot convert native LiteralStrKey", excstr) + + def test_dict_unify(self): + @njit + def foo(x): + if x + 7 > 4: + a = {'a': 2j, 'c': 'd', 'e': np.zeros(4)} + else: + # Note the use of a different literal str for key 'c' + a = {'a': 5j, 'c': 'CAT', 'e': np.zeros((5,))} + return a['c'] + + self.assertEqual(foo(100), 'd') + self.assertEqual(foo(-100), 'CAT') + self.assertEqual(foo(100), foo.py_func(100)) + self.assertEqual(foo(-100), foo.py_func(-100)) + + def test_dict_not_unify(self): + + @njit + def key_mismatch(x): + if x + 7 > 4: + a = {'BAD_KEY': 2j, 'c': 'd', 'e': np.zeros(4)} + else: + a = {'a': 5j, 'c': 'CAT', 'e': np.zeros((5,))} + # prevents inline of return on py310 + py310_defeat1 = 1 # noqa + py310_defeat2 = 2 # noqa + py310_defeat3 = 3 # noqa + py310_defeat4 = 4 # noqa + return a['a'] + + with self.assertRaises(TypingError) as raises: + key_mismatch(100) + + self.assertIn("Cannot unify LiteralStrKey", str(raises.exception)) + + @njit + def value_type_mismatch(x): + if x + 7 > 4: + a = {'a': 2j, 'c': 'd', 'e': np.zeros((4, 3))} + else: + a = {'a': 5j, 'c': 'CAT', 'e': np.zeros((5,))} + # prevents inline of return on py310 + py310_defeat1 = 1 # noqa + py310_defeat2 = 2 # noqa + py310_defeat3 = 3 # noqa + py310_defeat4 = 4 # noqa + return a['a'] + + with self.assertRaises(TypingError) as raises: + value_type_mismatch(100) + + self.assertIn("Cannot unify LiteralStrKey", str(raises.exception)) + + def test_dict_value_coercion(self): + # checks that things coerce or not! + + p = {# safe and no conversion: TypedDict + (np.int32, np.int32): types.DictType, + # safe and convertible: TypedDict + (np.int32, np.int8): types.DictType, + # safe convertible: TypedDict + (np.complex128, np.int32): types.DictType, + # unsafe not convertible: LiteralStrKey + (np.int32, np.complex128): types.LiteralStrKeyDict, + # unsafe not convertible: LiteralStrKey + (np.int32, np.array): types.LiteralStrKeyDict, + # unsafe not convertible: LiteralStrKey + (np.array, np.int32): types.LiteralStrKeyDict, + # unsafe not convertible: LiteralStrKey + (np.int8, np.int32): types.LiteralStrKeyDict, + # unsafe not convertible: LiteralStrKey (issue #6420 case) + (np.int64, np.float64): types.LiteralStrKeyDict,} + + def bar(x): + pass + + for dts, container in p.items(): + @overload(bar) + def ol_bar(x): + self.assertTrue(isinstance(x, container)) + + def impl(x): + pass + return impl + + ty1, ty2 = dts + + @njit + def foo(): + d = {'a': ty1(1), 'b': ty2(2)} + bar(d) + + foo() + + def test_build_map_op_code(self): + # tests building dictionaries via `build_map`, which, for statically + # determinable str key->things cases is just a single key:value + # any other build_map would either end up as being non-const str keys + # or keys of some non-string type and therefore not considered. + def bar(x): + pass + + @overload(bar) + def ol_bar(x): + def impl(x): + pass + return impl + + @njit + def foo(): + a = {'a': {'b1': 10, 'b2': 'string'}} + bar(a) + + foo() + + def test_dict_as_arg(self): + @njit + def bar(fake_kwargs=None): + if fake_kwargs is not None: + # Add 10 to array in key 'd' + fake_kwargs['d'][:] += 10 + + @njit + def foo(): + a = 1 + b = 2j + c = 'string' + d = np.zeros(3) + e = {'a': a, 'b': b, 'c': c, 'd': d} + bar(fake_kwargs=e) + return e['d'] + + np.testing.assert_allclose(foo(), np.ones(3) * 10) + + def test_dict_with_single_literallist_value(self): + #see issue #6094 + @njit + def foo(): + z = {"A": [lambda a: 2 * a, "B"]} + return z["A"][0](5) + + self.assertPreciseEqual(foo(), foo.py_func()) + + def test_tuple_not_in_mro(self): + # Related to #6094, make sure that LiteralStrKey does not inherit from + # types.BaseTuple as this breaks isinstance checks. + def bar(x): + pass + + @overload(bar) + def ol_bar(x): + self.assertFalse(isinstance(x, types.BaseTuple)) + self.assertTrue(isinstance(x, types.LiteralStrKeyDict)) + return lambda x: ... + + @njit + def foo(): + d = {'a': 1, 'b': 'c'} + bar(d) + + foo() + + def test_const_key_not_in_dict(self): + + @njit + def foo(): + a = {'not_a': 2j, 'c': 'd', 'e': np.zeros(4)} + return a['a'] + + with self.assertRaises(TypingError) as raises: + foo() + + self.assertIn("Key 'a' is not in dict.", str(raises.exception)) + + def test_uncommon_identifiers(self): + # Tests uncommon identifiers like numerical values and operators in + # the key fields. See #6518 and #7416. + + # Numerical values in keys + @njit + def foo(): + d = {'0': np.ones(5), '1': 4} + return len(d) + + self.assertPreciseEqual(foo(), foo.py_func()) + + # operators in keys + @njit + def bar(): + d = {'+': np.ones(5), 'x--': 4} + return len(d) + + self.assertPreciseEqual(bar(), bar.py_func()) + + def test_update_error(self): + # Tests that dict.update produces a reasonable + # error with a LiteralStrKeyDict input. + @njit + def foo(): + + d1 = { + 'a': 2, + 'b': 4, + 'c': 'a' + } + d1.update({'x': 3}) + return d1 + + with self.assertRaises(TypingError) as raises: + foo() + + self.assertIn( + "Cannot mutate a literal dictionary", + str(raises.exception) + ) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_extending.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_extending.py new file mode 100644 index 0000000000000000000000000000000000000000..f8608a6e6d98a072fdb770b723e910a0bce0cec0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_extending.py @@ -0,0 +1,2248 @@ +import inspect +import math +import operator +import sys +import pickle +import multiprocessing +import ctypes +import warnings +import re + +import numpy as np +from llvmlite import ir + +import numba +from numba import njit, jit, vectorize, guvectorize, objmode +from numba.core import types, errors, typing, compiler, cgutils +from numba.core.typed_passes import type_inference_stage +from numba.core.registry import cpu_target +from numba.core.imputils import lower_constant +from numba.tests.support import ( + TestCase, + captured_stdout, + temp_directory, + override_config, + run_in_new_process_in_cache_dir, + skip_if_typeguard, +) +from numba.core.errors import LoweringError +import unittest + +from numba.extending import ( + typeof_impl, + type_callable, + lower_builtin, + lower_cast, + overload, + overload_attribute, + overload_method, + models, + register_model, + box, + unbox, + NativeValue, + intrinsic, + _Intrinsic, + register_jitable, + get_cython_function_address, + is_jitted, + overload_classmethod, +) +from numba.core.typing.templates import ( + ConcreteTemplate, + signature, + infer, + infer_global, + AbstractTemplate, +) + + +# Pandas-like API implementation +from .pdlike_usecase import Index, Series + + +try: + import scipy.special.cython_special as sc +except ImportError: + sc = None + + +# ----------------------------------------------------------------------- +# Define a custom type and an implicit cast on it + + +class MyDummy(object): + pass + + +class MyDummyType(types.Opaque): + def can_convert_to(self, context, toty): + if isinstance(toty, types.Number): + from numba.core.typeconv import Conversion + + return Conversion.safe + + +mydummy_type = MyDummyType("mydummy") +mydummy = MyDummy() + + +@typeof_impl.register(MyDummy) +def typeof_mydummy(val, c): + return mydummy_type + + +@lower_cast(MyDummyType, types.Number) +def mydummy_to_number(context, builder, fromty, toty, val): + """ + Implicit conversion from MyDummy to int. + """ + return context.get_constant(toty, 42) + + +def get_dummy(): + return mydummy + + +register_model(MyDummyType)(models.OpaqueModel) + + +@unbox(MyDummyType) +def unbox_index(typ, obj, c): + return NativeValue(c.context.get_dummy_value()) + + +# ----------------------------------------------------------------------- +# Define a second custom type but w/o implicit cast to Number + + +def base_dummy_type_factory(name): + class DynType(object): + pass + + class DynTypeType(types.Opaque): + pass + + dyn_type_type = DynTypeType(name) + + @typeof_impl.register(DynType) + def typeof_mydummy(val, c): + return dyn_type_type + + register_model(DynTypeType)(models.OpaqueModel) + return DynTypeType, DynType, dyn_type_type + + +MyDummyType2, MyDummy2, mydummy_type_2 = base_dummy_type_factory("mydummy2") + + +@unbox(MyDummyType2) +def unbox_index2(typ, obj, c): + return NativeValue(c.context.get_dummy_value()) + + +# ----------------------------------------------------------------------- +# Define a function's typing and implementation using the classical +# two-step API + + +def func1(x=None): + raise NotImplementedError + + +def type_func1_(context): + def typer(x=None): + if x in (None, types.none): + # 0-arg or 1-arg with None + return types.int32 + elif isinstance(x, types.Float): + # 1-arg with float + return x + + return typer + + +type_func1 = type_callable(func1)(type_func1_) + + +@lower_builtin(func1) +@lower_builtin(func1, types.none) +def func1_nullary(context, builder, sig, args): + return context.get_constant(sig.return_type, 42) + + +@lower_builtin(func1, types.Float) +def func1_unary(context, builder, sig, args): + def func1_impl(x): + return math.sqrt(2 * x) + + return context.compile_internal(builder, func1_impl, sig, args) + + +# We can do the same for a known internal operation, here "print_item" +# which we extend to support MyDummyType. + + +@infer +class PrintDummy(ConcreteTemplate): + key = "print_item" + cases = [signature(types.none, mydummy_type)] + + +@lower_builtin("print_item", MyDummyType) +def print_dummy(context, builder, sig, args): + [x] = args + pyapi = context.get_python_api(builder) + strobj = pyapi.unserialize(pyapi.serialize_object("hello!")) + pyapi.print_object(strobj) + pyapi.decref(strobj) + return context.get_dummy_value() + + +# ----------------------------------------------------------------------- +# Define an overloaded function (combined API) + + +def where(cond, x, y): + raise NotImplementedError + + +def np_where(cond, x, y): + """ + Wrap np.where() to allow for keyword arguments + """ + return np.where(cond, x, y) + + +def call_where(cond, x, y): + return where(cond, y=y, x=x) + + +@overload(where) +def overload_where_arrays(cond, x, y): + """ + Implement where() for arrays. + """ + # Choose implementation based on argument types. + if isinstance(cond, types.Array): + if x.dtype != y.dtype: + raise errors.TypingError("x and y should have the same dtype") + + # Array where() => return an array of the same shape + if all(ty.layout == "C" for ty in (cond, x, y)): + + def where_impl(cond, x, y): + """ + Fast implementation for C-contiguous arrays + """ + shape = cond.shape + if x.shape != shape or y.shape != shape: + raise ValueError("all inputs should have the same shape") + res = np.empty_like(x) + cf = cond.flat + xf = x.flat + yf = y.flat + rf = res.flat + for i in range(cond.size): + rf[i] = xf[i] if cf[i] else yf[i] + return res + + else: + + def where_impl(cond, x, y): + """ + Generic implementation for other arrays + """ + shape = cond.shape + if x.shape != shape or y.shape != shape: + raise ValueError("all inputs should have the same shape") + res = np.empty_like(x) + for idx, c in np.ndenumerate(cond): + res[idx] = x[idx] if c else y[idx] + return res + + return where_impl + + +# We can define another overload function for the same function, they +# will be tried in turn until one succeeds. + + +@overload(where) +def overload_where_scalars(cond, x, y): + """ + Implement where() for scalars. + """ + if not isinstance(cond, types.Array): + if x != y: + raise errors.TypingError("x and y should have the same type") + + def where_impl(cond, x, y): + """ + Scalar where() => return a 0-dim array + """ + scal = x if cond else y + # Can't use full_like() on Numpy < 1.8 + arr = np.empty_like(scal) + arr[()] = scal + return arr + + return where_impl + + +# ----------------------------------------------------------------------- +# Overload an already defined built-in function, extending it for new types. + + +@overload(len) +def overload_len_dummy(arg): + if isinstance(arg, MyDummyType): + + def len_impl(arg): + return 13 + + return len_impl + + +@overload(operator.add) +def overload_add_dummy(arg1, arg2): + if isinstance(arg1, (MyDummyType, MyDummyType2)) and isinstance( + arg2, (MyDummyType, MyDummyType2) + ): + + def dummy_add_impl(arg1, arg2): + return 42 + + return dummy_add_impl + + +@overload(operator.delitem) +def overload_dummy_delitem(obj, idx): + if isinstance(obj, MyDummyType) and isinstance(idx, types.Integer): + + def dummy_delitem_impl(obj, idx): + print("del", obj, idx) + + return dummy_delitem_impl + + +@overload(operator.getitem) +def overload_dummy_getitem(obj, idx): + if isinstance(obj, MyDummyType) and isinstance(idx, types.Integer): + + def dummy_getitem_impl(obj, idx): + return idx + 123 + + return dummy_getitem_impl + + +@overload(operator.setitem) +def overload_dummy_setitem(obj, idx, val): + if all( + [ + isinstance(obj, MyDummyType), + isinstance(idx, types.Integer), + isinstance(val, types.Integer), + ] + ): + + def dummy_setitem_impl(obj, idx, val): + print(idx, val) + + return dummy_setitem_impl + + +def call_add_operator(arg1, arg2): + return operator.add(arg1, arg2) + + +def call_add_binop(arg1, arg2): + return arg1 + arg2 + + +@overload(operator.iadd) +def overload_iadd_dummy(arg1, arg2): + if isinstance(arg1, (MyDummyType, MyDummyType2)) and isinstance( + arg2, (MyDummyType, MyDummyType2) + ): + + def dummy_iadd_impl(arg1, arg2): + return 42 + + return dummy_iadd_impl + + +def call_iadd_operator(arg1, arg2): + return operator.add(arg1, arg2) + + +def call_iadd_binop(arg1, arg2): + arg1 += arg2 + + return arg1 + + +def call_delitem(obj, idx): + del obj[idx] + + +def call_getitem(obj, idx): + return obj[idx] + + +def call_setitem(obj, idx, val): + obj[idx] = val + + +@overload_method(MyDummyType, "length") +def overload_method_length(arg): + def imp(arg): + return len(arg) + + return imp + + +def cache_overload_method_usecase(x): + return x.length() + + +def call_func1_nullary(): + return func1() + + +def call_func1_unary(x): + return func1(x) + + +def len_usecase(x): + return len(x) + + +def print_usecase(x): + print(x) + + +def getitem_usecase(x, key): + return x[key] + + +def npyufunc_usecase(x): + return np.cos(np.sin(x)) + + +def get_data_usecase(x): + return x._data + + +def get_index_usecase(x): + return x._index + + +def is_monotonic_usecase(x): + return x.is_monotonic_increasing + + +def make_series_usecase(data, index): + return Series(data, index) + + +def clip_usecase(x, lo, hi): + return x.clip(lo, hi) + + +# ----------------------------------------------------------------------- + + +def return_non_boxable(): + return np + + +@overload(return_non_boxable) +def overload_return_non_boxable(): + def imp(): + return np + + return imp + + +def non_boxable_ok_usecase(sz): + mod = return_non_boxable() + return mod.arange(sz) + + +def non_boxable_bad_usecase(): + return return_non_boxable() + + +def mk_func_input(f): + pass + + +@infer_global(mk_func_input) +class MkFuncTyping(AbstractTemplate): + def generic(self, args, kws): + assert isinstance(args[0], types.MakeFunctionLiteral) + return signature(types.none, *args) + + +def mk_func_test_impl(): + mk_func_input(lambda a: a) + + +# ----------------------------------------------------------------------- +# Define a types derived from types.Callable and overloads for them + + +class MyClass(object): + pass + + +class CallableTypeRef(types.Callable): + + def __init__(self, instance_type): + self.instance_type = instance_type + self.sig_to_impl_key = {} + self.compiled_templates = [] + super(CallableTypeRef, self).__init__('callable_type_ref' + '[{}]'.format(self.instance_type)) + + def get_call_type(self, context, args, kws): + + res_sig = None + for template in context._functions[type(self)]: + try: + res_sig = template.apply(args, kws) + except Exception: + pass # for simplicity assume args must match exactly + else: + compiled_ovlds = getattr(template, '_compiled_overloads', {}) + if args in compiled_ovlds: + self.sig_to_impl_key[res_sig] = compiled_ovlds[args] + self.compiled_templates.append(template) + break + + return res_sig + + def get_call_signatures(self): + sigs = list(self.sig_to_impl_key.keys()) + return sigs, True + + def get_impl_key(self, sig): + return self.sig_to_impl_key[sig] + + +@register_model(CallableTypeRef) +class CallableTypeModel(models.OpaqueModel): + + def __init__(self, dmm, fe_type): + + models.OpaqueModel.__init__(self, dmm, fe_type) + + +infer_global(MyClass, CallableTypeRef(MyClass)) + + +@lower_constant(CallableTypeRef) +def constant_callable_typeref(context, builder, ty, pyval): + return context.get_dummy_value() + + +# ----------------------------------------------------------------------- + + +@overload(np.exp) +def overload_np_exp(obj): + if isinstance(obj, MyDummyType): + + def imp(obj): + # Returns a constant if a MyDummyType is seen + return 0xDEADBEEF + + return imp + + +class TestLowLevelExtending(TestCase): + """ + Test the low-level two-tier extension API. + """ + + # Check with `@jit` from within the test process and also in a new test + # process so as to check the registration mechanism. + + def test_func1(self): + pyfunc = call_func1_nullary + cfunc = jit(nopython=True)(pyfunc) + self.assertPreciseEqual(cfunc(), 42) + pyfunc = call_func1_unary + cfunc = jit(nopython=True)(pyfunc) + self.assertPreciseEqual(cfunc(None), 42) + self.assertPreciseEqual(cfunc(18.0), 6.0) + + @TestCase.run_test_in_subprocess + def test_func1_isolated(self): + self.test_func1() + + def test_type_callable_keeps_function(self): + self.assertIs(type_func1, type_func1_) + self.assertIsNotNone(type_func1) + + @TestCase.run_test_in_subprocess + def test_cast_mydummy(self): + pyfunc = get_dummy + cfunc = njit(types.float64(),)(pyfunc) + self.assertPreciseEqual(cfunc(), 42.0) + + def test_mk_func_literal(self): + """make sure make_function is passed to typer class as a literal + """ + test_ir = compiler.run_frontend(mk_func_test_impl) + typingctx = cpu_target.typing_context + targetctx = cpu_target.target_context + typingctx.refresh() + targetctx.refresh() + typing_res = type_inference_stage(typingctx, targetctx, test_ir, (), + None) + self.assertTrue( + any( + isinstance(a, types.MakeFunctionLiteral) + for a in typing_res.typemap.values() + ) + ) + + +class TestPandasLike(TestCase): + """ + Test implementing a pandas-like Index object. + Also stresses most of the high-level API. + """ + + def test_index_len(self): + i = Index(np.arange(3)) + cfunc = jit(nopython=True)(len_usecase) + self.assertPreciseEqual(cfunc(i), 3) + + def test_index_getitem(self): + i = Index(np.int32([42, 8, -5])) + cfunc = jit(nopython=True)(getitem_usecase) + self.assertPreciseEqual(cfunc(i, 1), 8) + ii = cfunc(i, slice(1, None)) + self.assertIsInstance(ii, Index) + self.assertEqual(list(ii), [8, -5]) + + def test_index_ufunc(self): + """ + Check Numpy ufunc on an Index object. + """ + i = Index(np.int32([42, 8, -5])) + cfunc = jit(nopython=True)(npyufunc_usecase) + ii = cfunc(i) + self.assertIsInstance(ii, Index) + self.assertPreciseEqual(ii._data, np.cos(np.sin(i._data))) + + def test_index_get_data(self): + # The _data attribute is exposed with make_attribute_wrapper() + i = Index(np.int32([42, 8, -5])) + cfunc = jit(nopython=True)(get_data_usecase) + data = cfunc(i) + self.assertIs(data, i._data) + + def test_index_is_monotonic(self): + # The is_monotonic_increasing attribute is exposed with + # overload_attribute() + cfunc = jit(nopython=True)(is_monotonic_usecase) + for values, expected in [ + ([8, 42, 5], False), + ([5, 8, 42], True), + ([], True), + ]: + i = Index(np.int32(values)) + got = cfunc(i) + self.assertEqual(got, expected) + + def test_series_len(self): + i = Index(np.int32([2, 4, 3])) + s = Series(np.float64([1.5, 4.0, 2.5]), i) + cfunc = jit(nopython=True)(len_usecase) + self.assertPreciseEqual(cfunc(s), 3) + + def test_series_get_index(self): + i = Index(np.int32([2, 4, 3])) + s = Series(np.float64([1.5, 4.0, 2.5]), i) + cfunc = jit(nopython=True)(get_index_usecase) + got = cfunc(s) + self.assertIsInstance(got, Index) + self.assertIs(got._data, i._data) + + def test_series_ufunc(self): + """ + Check Numpy ufunc on an Series object. + """ + i = Index(np.int32([42, 8, -5])) + s = Series(np.int64([1, 2, 3]), i) + cfunc = jit(nopython=True)(npyufunc_usecase) + ss = cfunc(s) + self.assertIsInstance(ss, Series) + self.assertIsInstance(ss._index, Index) + self.assertIs(ss._index._data, i._data) + self.assertPreciseEqual(ss._values, np.cos(np.sin(s._values))) + + def test_series_constructor(self): + i = Index(np.int32([42, 8, -5])) + d = np.float64([1.5, 4.0, 2.5]) + cfunc = jit(nopython=True)(make_series_usecase) + got = cfunc(d, i) + self.assertIsInstance(got, Series) + self.assertIsInstance(got._index, Index) + self.assertIs(got._index._data, i._data) + self.assertIs(got._values, d) + + def test_series_clip(self): + i = Index(np.int32([42, 8, -5])) + s = Series(np.float64([1.5, 4.0, 2.5]), i) + cfunc = jit(nopython=True)(clip_usecase) + ss = cfunc(s, 1.6, 3.0) + self.assertIsInstance(ss, Series) + self.assertIsInstance(ss._index, Index) + self.assertIs(ss._index._data, i._data) + self.assertPreciseEqual(ss._values, np.float64([1.6, 3.0, 2.5])) + + +class TestHighLevelExtending(TestCase): + """ + Test the high-level combined API. + """ + + def test_where(self): + """ + Test implementing a function with @overload. + """ + pyfunc = call_where + cfunc = jit(nopython=True)(pyfunc) + + def check(*args, **kwargs): + expected = np_where(*args, **kwargs) + got = cfunc(*args, **kwargs) + self.assertPreciseEqual(expected, got) + + check(x=3, cond=True, y=8) + check(True, 3, 8) + check( + np.bool_([True, False, True]), + np.int32([1, 2, 3]), + np.int32([4, 5, 5]), + ) + + # The typing error is propagated + with self.assertRaises(errors.TypingError) as raises: + cfunc(np.bool_([]), np.int32([]), np.int64([])) + self.assertIn( + "x and y should have the same dtype", str(raises.exception) + ) + + def test_len(self): + """ + Test re-implementing len() for a custom type with @overload. + """ + cfunc = jit(nopython=True)(len_usecase) + self.assertPreciseEqual(cfunc(MyDummy()), 13) + self.assertPreciseEqual(cfunc([4, 5]), 2) + + def test_print(self): + """ + Test re-implementing print() for a custom type with @overload. + """ + cfunc = jit(nopython=True)(print_usecase) + with captured_stdout(): + cfunc(MyDummy()) + self.assertEqual(sys.stdout.getvalue(), "hello!\n") + + def test_add_operator(self): + """ + Test re-implementing operator.add() for a custom type with @overload. + """ + pyfunc = call_add_operator + cfunc = jit(nopython=True)(pyfunc) + + self.assertPreciseEqual(cfunc(1, 2), 3) + self.assertPreciseEqual(cfunc(MyDummy2(), MyDummy2()), 42) + + # this will call add(Number, Number) as MyDummy implicitly casts to + # Number + self.assertPreciseEqual(cfunc(MyDummy(), MyDummy()), 84) + + def test_add_binop(self): + """ + Test re-implementing '+' for a custom type via @overload(operator.add). + """ + pyfunc = call_add_binop + cfunc = jit(nopython=True)(pyfunc) + + self.assertPreciseEqual(cfunc(1, 2), 3) + self.assertPreciseEqual(cfunc(MyDummy2(), MyDummy2()), 42) + + # this will call add(Number, Number) as MyDummy implicitly casts to + # Number + self.assertPreciseEqual(cfunc(MyDummy(), MyDummy()), 84) + + def test_iadd_operator(self): + """ + Test re-implementing operator.add() for a custom type with @overload. + """ + pyfunc = call_iadd_operator + cfunc = jit(nopython=True)(pyfunc) + + self.assertPreciseEqual(cfunc(1, 2), 3) + self.assertPreciseEqual(cfunc(MyDummy2(), MyDummy2()), 42) + + # this will call add(Number, Number) as MyDummy implicitly casts to + # Number + self.assertPreciseEqual(cfunc(MyDummy(), MyDummy()), 84) + + def test_iadd_binop(self): + """ + Test re-implementing '+' for a custom type via @overload(operator.add). + """ + pyfunc = call_iadd_binop + cfunc = jit(nopython=True)(pyfunc) + + self.assertPreciseEqual(cfunc(1, 2), 3) + self.assertPreciseEqual(cfunc(MyDummy2(), MyDummy2()), 42) + + # this will call add(Number, Number) as MyDummy implicitly casts to + # Number + self.assertPreciseEqual(cfunc(MyDummy(), MyDummy()), 84) + + def test_delitem(self): + pyfunc = call_delitem + cfunc = jit(nopython=True)(pyfunc) + obj = MyDummy() + e = None + + with captured_stdout() as out: + try: + cfunc(obj, 321) + except Exception as exc: + e = exc + + if e is not None: + raise e + self.assertEqual(out.getvalue(), "del hello! 321\n") + + def test_getitem(self): + pyfunc = call_getitem + cfunc = jit(nopython=True)(pyfunc) + self.assertPreciseEqual(cfunc(MyDummy(), 321), 321 + 123) + + def test_setitem(self): + pyfunc = call_setitem + cfunc = jit(nopython=True)(pyfunc) + obj = MyDummy() + e = None + + with captured_stdout() as out: + try: + cfunc(obj, 321, 123) + except Exception as exc: + e = exc + + if e is not None: + raise e + self.assertEqual(out.getvalue(), "321 123\n") + + def test_no_cpython_wrapper(self): + """ + Test overloading whose return value cannot be represented in CPython. + """ + # Test passing Module type from a @overload implementation to ensure + # that the *no_cpython_wrapper* flag works + ok_cfunc = jit(nopython=True)(non_boxable_ok_usecase) + n = 10 + got = ok_cfunc(n) + expect = non_boxable_ok_usecase(n) + np.testing.assert_equal(expect, got) + # Verify that the Module type cannot be returned to CPython + bad_cfunc = jit(nopython=True)(non_boxable_bad_usecase) + with self.assertRaises(TypeError) as raises: + bad_cfunc() + errmsg = str(raises.exception) + expectmsg = "cannot convert native Module" + self.assertIn(expectmsg, errmsg) + + def test_typing_vs_impl_signature_mismatch_handling(self): + """ + Tests that an overload which has a differing typing and implementing + signature raises an exception. + """ + + def gen_ol(impl=None): + def myoverload(a, b, c, kw=None): + pass + + @overload(myoverload) + def _myoverload_impl(a, b, c, kw=None): + return impl + + @jit(nopython=True) + def foo(a, b, c, d): + myoverload(a, b, c, kw=d) + + return foo + + sentinel = "Typing and implementation arguments differ in" + + # kwarg value is different + def impl1(a, b, c, kw=12): + if a > 10: + return 1 + else: + return -1 + + with self.assertRaises(errors.TypingError) as e: + gen_ol(impl1)(1, 2, 3, 4) + msg = str(e.exception) + self.assertIn(sentinel, msg) + self.assertIn("keyword argument default values", msg) + self.assertIn('', msg) + self.assertIn('', msg) + + # kwarg name is different + def impl2(a, b, c, kwarg=None): + if a > 10: + return 1 + else: + return -1 + + with self.assertRaises(errors.TypingError) as e: + gen_ol(impl2)(1, 2, 3, 4) + msg = str(e.exception) + self.assertIn(sentinel, msg) + self.assertIn("keyword argument names", msg) + self.assertIn('', msg) + self.assertIn('', msg) + + # arg name is different + def impl3(z, b, c, kw=None): + if a > 10: # noqa: F821 + return 1 + else: + return -1 + + with self.assertRaises(errors.TypingError) as e: + gen_ol(impl3)(1, 2, 3, 4) + msg = str(e.exception) + self.assertIn(sentinel, msg) + self.assertIn("argument names", msg) + self.assertFalse("keyword" in msg) + self.assertIn('', msg) + self.assertIn('', msg) + + from .overload_usecases import impl4, impl5 + + with self.assertRaises(errors.TypingError) as e: + gen_ol(impl4)(1, 2, 3, 4) + msg = str(e.exception) + self.assertIn(sentinel, msg) + self.assertIn("argument names", msg) + self.assertFalse("keyword" in msg) + self.assertIn("First difference: 'z'", msg) + + with self.assertRaises(errors.TypingError) as e: + gen_ol(impl5)(1, 2, 3, 4) + msg = str(e.exception) + self.assertIn(sentinel, msg) + self.assertIn("argument names", msg) + self.assertFalse("keyword" in msg) + self.assertIn('', msg) + self.assertIn('', msg) + + # too many args + def impl6(a, b, c, d, e, kw=None): + if a > 10: + return 1 + else: + return -1 + + with self.assertRaises(errors.TypingError) as e: + gen_ol(impl6)(1, 2, 3, 4) + msg = str(e.exception) + self.assertIn(sentinel, msg) + self.assertIn("argument names", msg) + self.assertFalse("keyword" in msg) + self.assertIn('', msg) + self.assertIn('', msg) + + # too few args + def impl7(a, b, kw=None): + if a > 10: + return 1 + else: + return -1 + + with self.assertRaises(errors.TypingError) as e: + gen_ol(impl7)(1, 2, 3, 4) + msg = str(e.exception) + self.assertIn(sentinel, msg) + self.assertIn("argument names", msg) + self.assertFalse("keyword" in msg) + self.assertIn('', msg) + + # too many kwargs + def impl8(a, b, c, kw=None, extra_kwarg=None): + if a > 10: + return 1 + else: + return -1 + + with self.assertRaises(errors.TypingError) as e: + gen_ol(impl8)(1, 2, 3, 4) + msg = str(e.exception) + self.assertIn(sentinel, msg) + self.assertIn("keyword argument names", msg) + self.assertIn('', msg) + + # too few kwargs + def impl9(a, b, c): + if a > 10: + return 1 + else: + return -1 + + with self.assertRaises(errors.TypingError) as e: + gen_ol(impl9)(1, 2, 3, 4) + msg = str(e.exception) + self.assertIn(sentinel, msg) + self.assertIn("keyword argument names", msg) + self.assertIn('', msg) + + def test_typing_vs_impl_signature_mismatch_handling_var_positional(self): + """ + Tests that an overload which has a differing typing and implementing + signature raises an exception and uses VAR_POSITIONAL (*args) in typing + """ + + def myoverload(a, kw=None): + pass + + from .overload_usecases import var_positional_impl + + overload(myoverload)(var_positional_impl) + + @jit(nopython=True) + def foo(a, b): + return myoverload(a, b, 9, kw=11) + + with self.assertRaises(errors.TypingError) as e: + foo(1, 5) + msg = str(e.exception) + self.assertIn("VAR_POSITIONAL (e.g. *args) argument kind", msg) + self.assertIn("offending argument name is '*star_args_token'", msg) + + def test_typing_vs_impl_signature_mismatch_handling_var_keyword(self): + """ + Tests that an overload which uses **kwargs (VAR_KEYWORD) + """ + + def gen_ol(impl, strict=True): + def myoverload(a, kw=None): + pass + + overload(myoverload, strict=strict)(impl) + + @jit(nopython=True) + def foo(a, b): + return myoverload(a, kw=11) + + return foo + + # **kwargs in typing + def ol1(a, **kws): + def impl(a, kw=10): + return a + + return impl + + gen_ol(ol1, False)(1, 2) # no error if strictness not enforced + with self.assertRaises(errors.TypingError) as e: + gen_ol(ol1)(1, 2) + msg = str(e.exception) + self.assertIn("use of VAR_KEYWORD (e.g. **kwargs) is unsupported", msg) + self.assertIn("offending argument name is '**kws'", msg) + + # **kwargs in implementation + def ol2(a, kw=0): + def impl(a, **kws): + return a + + return impl + + with self.assertRaises(errors.TypingError) as e: + gen_ol(ol2)(1, 2) + msg = str(e.exception) + self.assertIn("use of VAR_KEYWORD (e.g. **kwargs) is unsupported", msg) + self.assertIn("offending argument name is '**kws'", msg) + + def test_overload_method_kwargs(self): + # Issue #3489 + @overload_method(types.Array, "foo") + def fooimpl(arr, a_kwarg=10): + def impl(arr, a_kwarg=10): + return a_kwarg + + return impl + + @njit + def bar(A): + return A.foo(), A.foo(20), A.foo(a_kwarg=30) + + Z = np.arange(5) + + self.assertEqual(bar(Z), (10, 20, 30)) + + def test_overload_method_literal_unpack(self): + # Issue #3683 + @overload_method(types.Array, "litfoo") + def litfoo(arr, val): + # Must be an integer + if isinstance(val, types.Integer): + # Must not be literal + if not isinstance(val, types.Literal): + + def impl(arr, val): + return val + + return impl + + @njit + def bar(A): + return A.litfoo(0xCAFE) + + A = np.zeros(1) + bar(A) + self.assertEqual(bar(A), 0xCAFE) + + def test_overload_ufunc(self): + # Issue #4133. + # Use an extended type (MyDummyType) to use with a customized + # ufunc (np.exp). + @njit + def test(): + return np.exp(mydummy) + + self.assertEqual(test(), 0xDEADBEEF) + + def test_overload_method_stararg(self): + @overload_method(MyDummyType, "method_stararg") + def _ov_method_stararg(obj, val, val2, *args): + def get(obj, val, val2, *args): + return (val, val2, args) + + return get + + @njit + def foo(obj, *args): + # Test with expanding stararg + return obj.method_stararg(*args) + + obj = MyDummy() + self.assertEqual(foo(obj, 1, 2), (1, 2, ())) + self.assertEqual(foo(obj, 1, 2, 3), (1, 2, (3,))) + self.assertEqual(foo(obj, 1, 2, 3, 4), (1, 2, (3, 4))) + + @njit + def bar(obj): + # Test with explicit argument + return ( + obj.method_stararg(1, 2), + obj.method_stararg(1, 2, 3), + obj.method_stararg(1, 2, 3, 4), + ) + + self.assertEqual( + bar(obj), ((1, 2, ()), (1, 2, (3,)), (1, 2, (3, 4))), + ) + + # Check cases that put tuple type into stararg + # NOTE: the expected result has an extra tuple because of stararg. + self.assertEqual( + foo(obj, 1, 2, (3,)), (1, 2, ((3,),)), + ) + self.assertEqual( + foo(obj, 1, 2, (3, 4)), (1, 2, ((3, 4),)), + ) + self.assertEqual( + foo(obj, 1, 2, (3, (4, 5))), (1, 2, ((3, (4, 5)),)), + ) + + def test_overload_classmethod(self): + # Add classmethod to a subclass of Array + class MyArray(types.Array): + pass + + @overload_classmethod(MyArray, "array_alloc") + def ol_array_alloc(cls, nitems): + def impl(cls, nitems): + arr = np.arange(nitems) + return arr + return impl + + @njit + def foo(nitems): + return MyArray.array_alloc(nitems) + + nitems = 13 + self.assertPreciseEqual(foo(nitems), np.arange(nitems)) + + # Check that the base type doesn't get the classmethod + + @njit + def no_classmethod_in_base(nitems): + return types.Array.array_alloc(nitems) + + with self.assertRaises(errors.TypingError) as raises: + no_classmethod_in_base(nitems) + self.assertIn( + "Unknown attribute 'array_alloc' of", + str(raises.exception), + ) + + def test_overload_callable_typeref(self): + + @overload(CallableTypeRef) + def callable_type_call_ovld1(x): + if isinstance(x, types.Integer): + def impl(x): + return 42.5 + x + return impl + + @overload(CallableTypeRef) + def callable_type_call_ovld2(x): + if isinstance(x, types.UnicodeType): + def impl(x): + return '42.5' + x + + return impl + + @njit + def foo(a, b): + return MyClass(a), MyClass(b) + + args = (4, '4') + expected = (42.5 + args[0], '42.5' + args[1]) + self.assertPreciseEqual(foo(*args), expected) + + +def _assert_cache_stats(cfunc, expect_hit, expect_misses): + hit = cfunc._cache_hits[cfunc.signatures[0]] + if hit != expect_hit: + raise AssertionError("cache not used") + miss = cfunc._cache_misses[cfunc.signatures[0]] + if miss != expect_misses: + raise AssertionError("cache not used") + + +@skip_if_typeguard +class TestOverloadMethodCaching(TestCase): + # Nested multiprocessing.Pool raises AssertionError: + # "daemonic processes are not allowed to have children" + _numba_parallel_test_ = False + + def test_caching_overload_method(self): + self._cache_dir = temp_directory(self.__class__.__name__) + with override_config("CACHE_DIR", self._cache_dir): + self.run_caching_overload_method() + + def run_caching_overload_method(self): + cfunc = jit(nopython=True, cache=True)(cache_overload_method_usecase) + self.assertPreciseEqual(cfunc(MyDummy()), 13) + _assert_cache_stats(cfunc, 0, 1) + llvmir = cfunc.inspect_llvm((mydummy_type,)) + # Ensure the inner method is not a declaration + decls = [ + ln + for ln in llvmir.splitlines() + if ln.startswith("declare") and "overload_method_length" in ln + ] + self.assertEqual(len(decls), 0) + # Test in a separate process + try: + ctx = multiprocessing.get_context("spawn") + except AttributeError: + ctx = multiprocessing + q = ctx.Queue() + p = ctx.Process( + target=run_caching_overload_method, args=(q, self._cache_dir) + ) + p.start() + q.put(MyDummy()) + p.join() + # Ensure subprocess exited normally + self.assertEqual(p.exitcode, 0) + res = q.get(timeout=1) + self.assertEqual(res, 13) + + +def run_caching_overload_method(q, cache_dir): + """ + Used by TestOverloadMethodCaching.test_caching_overload_method + """ + with override_config("CACHE_DIR", cache_dir): + arg = q.get() + cfunc = jit(nopython=True, cache=True)(cache_overload_method_usecase) + res = cfunc(arg) + q.put(res) + # Check cache stat + _assert_cache_stats(cfunc, 1, 0) + + +class TestIntrinsic(TestCase): + def test_void_return(self): + """ + Verify that returning a None from codegen function is handled + automatically for void functions, otherwise raise exception. + """ + + @intrinsic + def void_func(typingctx, a): + sig = types.void(types.int32) + + def codegen(context, builder, signature, args): + pass # do nothing, return None, should be turned into + # dummy value + + return sig, codegen + + @intrinsic + def non_void_func(typingctx, a): + sig = types.int32(types.int32) + + def codegen(context, builder, signature, args): + pass # oops, should be returning a value here, raise exception + + return sig, codegen + + @jit(nopython=True) + def call_void_func(): + void_func(1) + return 0 + + @jit(nopython=True) + def call_non_void_func(): + non_void_func(1) + return 0 + + # void func should work + self.assertEqual(call_void_func(), 0) + # not void function should raise exception + with self.assertRaises(LoweringError) as e: + call_non_void_func() + self.assertIn("non-void function returns None", e.exception.msg) + + def test_ll_pointer_cast(self): + """ + Usecase test: custom reinterpret cast to turn int values to pointers + """ + from ctypes import CFUNCTYPE, POINTER, c_float, c_int + + # Use intrinsic to make a reinterpret_cast operation + def unsafe_caster(result_type): + assert isinstance(result_type, types.CPointer) + + @intrinsic + def unsafe_cast(typingctx, src): + self.assertIsInstance(typingctx, typing.Context) + if isinstance(src, types.Integer): + sig = result_type(types.uintp) + + # defines the custom code generation + def codegen(context, builder, signature, args): + [src] = args + rtype = signature.return_type + llrtype = context.get_value_type(rtype) + return builder.inttoptr(src, llrtype) + + return sig, codegen + + return unsafe_cast + + # make a nopython function to use our cast op. + # this is not usable from cpython due to the returning of a pointer. + def unsafe_get_ctypes_pointer(src): + raise NotImplementedError("not callable from python") + + @overload(unsafe_get_ctypes_pointer, strict=False) + def array_impl_unsafe_get_ctypes_pointer(arrtype): + if isinstance(arrtype, types.Array): + unsafe_cast = unsafe_caster(types.CPointer(arrtype.dtype)) + + def array_impl(arr): + return unsafe_cast(src=arr.ctypes.data) + + return array_impl + + # the ctype wrapped function for use in nopython mode + def my_c_fun_raw(ptr, n): + for i in range(n): + print(ptr[i]) + + prototype = CFUNCTYPE(None, POINTER(c_float), c_int) + my_c_fun = prototype(my_c_fun_raw) + + # Call our pointer-cast in a @jit compiled function and use + # the pointer in a ctypes function + @jit(nopython=True) + def foo(arr): + ptr = unsafe_get_ctypes_pointer(arr) + my_c_fun(ptr, arr.size) + + # Test + arr = np.arange(10, dtype=np.float32) + with captured_stdout() as buf: + foo(arr) + got = buf.getvalue().splitlines() + buf.close() + expect = list(map(str, arr)) + self.assertEqual(expect, got) + + def test_serialization(self): + """ + Test serialization of intrinsic objects + """ + # define a intrinsic + @intrinsic + def identity(context, x): + def codegen(context, builder, signature, args): + return args[0] + + sig = x(x) + return sig, codegen + + # use in a jit function + @jit(nopython=True) + def foo(x): + return identity(x) + + self.assertEqual(foo(1), 1) + + # get serialization memo + memo = _Intrinsic._memo + memo_size = len(memo) + + # pickle foo and check memo size + serialized_foo = pickle.dumps(foo) + # increases the memo size + memo_size += 1 + self.assertEqual(memo_size, len(memo)) + # unpickle + foo_rebuilt = pickle.loads(serialized_foo) + self.assertEqual(memo_size, len(memo)) + # check rebuilt foo + self.assertEqual(foo(1), foo_rebuilt(1)) + + # pickle identity directly + serialized_identity = pickle.dumps(identity) + # memo size unchanged + self.assertEqual(memo_size, len(memo)) + # unpickle + identity_rebuilt = pickle.loads(serialized_identity) + # must be the same object + self.assertIs(identity, identity_rebuilt) + # memo size unchanged + self.assertEqual(memo_size, len(memo)) + + def test_deserialization(self): + """ + Test deserialization of intrinsic + """ + + def defn(context, x): + def codegen(context, builder, signature, args): + return args[0] + + return x(x), codegen + + memo = _Intrinsic._memo + memo_size = len(memo) + # invoke _Intrinsic indirectly to avoid registration which keeps an + # internal reference inside the compiler + original = _Intrinsic("foo", defn) + self.assertIs(original._defn, defn) + pickled = pickle.dumps(original) + # by pickling, a new memo entry is created + memo_size += 1 + self.assertEqual(memo_size, len(memo)) + del original # remove original before unpickling + + # by deleting, the memo entry is NOT removed due to recent + # function queue + self.assertEqual(memo_size, len(memo)) + + # Manually force clear of _recent queue + _Intrinsic._recent.clear() + memo_size -= 1 + self.assertEqual(memo_size, len(memo)) + + rebuilt = pickle.loads(pickled) + # verify that the rebuilt object is different + self.assertIsNot(rebuilt._defn, defn) + + # the second rebuilt object is the same as the first + second = pickle.loads(pickled) + self.assertIs(rebuilt._defn, second._defn) + + def test_docstring(self): + + @intrinsic + def void_func(typingctx, a: int): + """void_func docstring""" + sig = types.void(types.int32) + + def codegen(context, builder, signature, args): + pass # do nothing, return None, should be turned into + # dummy value + + return sig, codegen + + self.assertEqual("numba.tests.test_extending", void_func.__module__) + self.assertEqual("void_func", void_func.__name__) + self.assertEqual("TestIntrinsic.test_docstring..void_func", + void_func.__qualname__) + self.assertDictEqual({'a': int}, inspect.get_annotations(void_func)) + self.assertEqual("void_func docstring", void_func.__doc__) + + +class TestRegisterJitable(unittest.TestCase): + def test_no_flags(self): + @register_jitable + def foo(x, y): + return x + y + + def bar(x, y): + return foo(x, y) + + cbar = jit(nopython=True)(bar) + + expect = bar(1, 2) + got = cbar(1, 2) + self.assertEqual(expect, got) + + def test_flags_no_nrt(self): + @register_jitable(_nrt=False) + def foo(n): + return np.arange(n) + + def bar(n): + return foo(n) + + self.assertEqual(bar(3).tolist(), [0, 1, 2]) + + cbar = jit(nopython=True)(bar) + with self.assertRaises(errors.TypingError) as raises: + cbar(2) + msg = ( + "Only accept returning of array passed into the function as " + "argument" + ) + self.assertIn(msg, str(raises.exception)) + + +class TestImportCythonFunction(unittest.TestCase): + @unittest.skipIf(sc is None, "Only run if SciPy >= 0.19 is installed") + def test_getting_function(self): + addr = get_cython_function_address( + "scipy.special.cython_special", "j0" + ) + functype = ctypes.CFUNCTYPE(ctypes.c_double, ctypes.c_double) + _j0 = functype(addr) + j0 = jit(nopython=True)(lambda x: _j0(x)) + self.assertEqual(j0(0), 1) + + def test_missing_module(self): + with self.assertRaises(ImportError) as raises: + get_cython_function_address("fakemodule", "fakefunction") + # The quotes are not there in Python 2 + msg = "No module named '?fakemodule'?" + match = re.match(msg, str(raises.exception)) + self.assertIsNotNone(match) + + @unittest.skipIf(sc is None, "Only run if SciPy >= 0.19 is installed") + def test_missing_function(self): + with self.assertRaises(ValueError) as raises: + get_cython_function_address( + "scipy.special.cython_special", "foo" + ) + msg = ( + "No function 'foo' found in __pyx_capi__ of " + "'scipy.special.cython_special'" + ) + self.assertEqual(msg, str(raises.exception)) + + +@overload_method( + MyDummyType, "method_jit_option_check_nrt", jit_options={"_nrt": True} +) +def ov_method_jit_option_check_nrt(obj): + def imp(obj): + return np.arange(10) + + return imp + + +@overload_method( + MyDummyType, "method_jit_option_check_no_nrt", jit_options={"_nrt": False} +) +def ov_method_jit_option_check_no_nrt(obj): + def imp(obj): + return np.arange(10) + + return imp + + +@overload_attribute( + MyDummyType, "attr_jit_option_check_nrt", jit_options={"_nrt": True} +) +def ov_attr_jit_option_check_nrt(obj): + def imp(obj): + return np.arange(10) + + return imp + + +@overload_attribute( + MyDummyType, "attr_jit_option_check_no_nrt", jit_options={"_nrt": False} +) +def ov_attr_jit_option_check_no_nrt(obj): + def imp(obj): + return np.arange(10) + + return imp + + +class TestJitOptionsNoNRT(TestCase): + # Test overload*(jit_options={...}) by turning off _nrt + + def check_error_no_nrt(self, func, *args, **kwargs): + # Check that the compilation fails with a complaint about dynamic array + msg = ( + "Only accept returning of array passed into " + "the function as argument" + ) + with self.assertRaises(errors.TypingError) as raises: + func(*args, **kwargs) + self.assertIn(msg, str(raises.exception)) + + def no_nrt_overload_check(self, flag): + def dummy(): + return np.arange(10) + + @overload(dummy, jit_options={"_nrt": flag}) + def ov_dummy(): + def dummy(): + return np.arange(10) + + return dummy + + @njit + def foo(): + return dummy() + + if flag: + self.assertPreciseEqual(foo(), np.arange(10)) + else: + self.check_error_no_nrt(foo) + + def test_overload_no_nrt(self): + self.no_nrt_overload_check(True) + self.no_nrt_overload_check(False) + + def test_overload_method_no_nrt(self): + @njit + def udt(x): + return x.method_jit_option_check_nrt() + + self.assertPreciseEqual(udt(mydummy), np.arange(10)) + + @njit + def udt(x): + return x.method_jit_option_check_no_nrt() + + self.check_error_no_nrt(udt, mydummy) + + def test_overload_attribute_no_nrt(self): + @njit + def udt(x): + return x.attr_jit_option_check_nrt + + self.assertPreciseEqual(udt(mydummy), np.arange(10)) + + @njit + def udt(x): + return x.attr_jit_option_check_no_nrt + + self.check_error_no_nrt(udt, mydummy) + + +class TestBoxingCallingJIT(TestCase): + def setUp(self): + super().setUp() + many = base_dummy_type_factory("mydummy2") + self.DynTypeType, self.DynType, self.dyn_type_type = many + self.dyn_type = self.DynType() + + def test_unboxer_basic(self): + # Implements an unboxer on DynType that calls an intrinsic into the + # unboxer code. + magic_token = 0xCAFE + magic_offset = 123 + + @intrinsic + def my_intrinsic(typingctx, val): + # An intrinsic that returns `val + magic_offset` + def impl(context, builder, sig, args): + [val] = args + return builder.add(val, val.type(magic_offset)) + + sig = signature(val, val) + return sig, impl + + @unbox(self.DynTypeType) + def unboxer(typ, obj, c): + # The unboxer that calls some jitcode + def bridge(x): + # proof that this is a jit'ed context by calling jit only + # intrinsic + return my_intrinsic(x) + + args = [c.context.get_constant(types.intp, magic_token)] + sig = signature(types.voidptr, types.intp) + is_error, res = c.pyapi.call_jit_code(bridge, sig, args) + return NativeValue(res, is_error=is_error) + + @box(self.DynTypeType) + def boxer(typ, val, c): + # The boxer that returns an integer representation + res = c.builder.ptrtoint(val, cgutils.intp_t) + return c.pyapi.long_from_ssize_t(res) + + @njit + def passthru(x): + return x + + out = passthru(self.dyn_type) + self.assertEqual(out, magic_token + magic_offset) + + def test_unboxer_raise(self): + # Testing exception raising in jitcode called from unboxing. + @unbox(self.DynTypeType) + def unboxer(typ, obj, c): + # The unboxer that calls some jitcode + def bridge(x): + if x > 0: + raise ValueError("cannot be x > 0") + return x + + args = [c.context.get_constant(types.intp, 1)] + sig = signature(types.voidptr, types.intp) + is_error, res = c.pyapi.call_jit_code(bridge, sig, args) + return NativeValue(res, is_error=is_error) + + @box(self.DynTypeType) + def boxer(typ, val, c): + # The boxer that returns an integer representation + res = c.builder.ptrtoint(val, cgutils.intp_t) + return c.pyapi.long_from_ssize_t(res) + + @njit + def passthru(x): + return x + + with self.assertRaises(ValueError) as raises: + passthru(self.dyn_type) + self.assertIn( + "cannot be x > 0", str(raises.exception), + ) + + def test_boxer(self): + # Call jitcode inside the boxer + magic_token = 0xCAFE + magic_offset = 312 + + @intrinsic + def my_intrinsic(typingctx, val): + # An intrinsic that returns `val + magic_offset` + def impl(context, builder, sig, args): + [val] = args + return builder.add(val, val.type(magic_offset)) + + sig = signature(val, val) + return sig, impl + + @unbox(self.DynTypeType) + def unboxer(typ, obj, c): + return NativeValue(c.context.get_dummy_value()) + + @box(self.DynTypeType) + def boxer(typ, val, c): + # Note: this doesn't do proper error handling + def bridge(x): + return my_intrinsic(x) + + args = [c.context.get_constant(types.intp, magic_token)] + sig = signature(types.intp, types.intp) + is_error, res = c.pyapi.call_jit_code(bridge, sig, args) + return c.pyapi.long_from_ssize_t(res) + + @njit + def passthru(x): + return x + + r = passthru(self.dyn_type) + self.assertEqual(r, magic_token + magic_offset) + + def test_boxer_raise(self): + # Call jitcode inside the boxer + @unbox(self.DynTypeType) + def unboxer(typ, obj, c): + return NativeValue(c.context.get_dummy_value()) + + @box(self.DynTypeType) + def boxer(typ, val, c): + def bridge(x): + if x > 0: + raise ValueError("cannot do x > 0") + return x + + args = [c.context.get_constant(types.intp, 1)] + sig = signature(types.intp, types.intp) + is_error, res = c.pyapi.call_jit_code(bridge, sig, args) + # The error handling + retval = cgutils.alloca_once(c.builder, c.pyapi.pyobj, zfill=True) + with c.builder.if_then(c.builder.not_(is_error)): + obj = c.pyapi.long_from_ssize_t(res) + c.builder.store(obj, retval) + return c.builder.load(retval) + + @njit + def passthru(x): + return x + + with self.assertRaises(ValueError) as raises: + passthru(self.dyn_type) + self.assertIn( + "cannot do x > 0", str(raises.exception), + ) + + +def with_objmode_cache_ov_example(x): + # This is the function stub for overloading inside + # TestCachingOverloadObjmode.test_caching_overload_objmode + pass + + +@skip_if_typeguard +class TestCachingOverloadObjmode(TestCase): + """Test caching of the use of overload implementations that use + `with objmode` + """ + _numba_parallel_test_ = False + + def setUp(self): + warnings.simplefilter("error", errors.NumbaWarning) + + def tearDown(self): + warnings.resetwarnings() + + def test_caching_overload_objmode(self): + cache_dir = temp_directory(self.__class__.__name__) + with override_config("CACHE_DIR", cache_dir): + + def realwork(x): + # uses numpy code + arr = np.arange(x) / x + return np.linalg.norm(arr) + + def python_code(x): + # create indirections + return realwork(x) + + @overload(with_objmode_cache_ov_example) + def _ov_with_objmode_cache_ov_example(x): + def impl(x): + with objmode(y="float64"): + y = python_code(x) + return y + + return impl + + @njit(cache=True) + def testcase(x): + return with_objmode_cache_ov_example(x) + + expect = realwork(123) + got = testcase(123) + self.assertEqual(got, expect) + + testcase_cached = njit(cache=True)(testcase.py_func) + got = testcase_cached(123) + self.assertEqual(got, expect) + + @classmethod + def check_objmode_cache_ndarray(cls): + def do_this(a, b): + return np.sum(a + b) + + def do_something(a, b): + return np.sum(a + b) + + @overload(do_something) + def overload_do_something(a, b): + def _do_something_impl(a, b): + with objmode(y='float64'): + y = do_this(a, b) + return y + return _do_something_impl + + @njit(cache=True) + def test_caching(): + a = np.arange(20) + b = np.arange(20) + return do_something(a, b) + + got = test_caching() + expect = test_caching.py_func() + + # Check result + if got != expect: + raise AssertionError("incorrect result") + return test_caching + + @classmethod + def populate_objmode_cache_ndarray_check_cache(cls): + cls.check_objmode_cache_ndarray() + + @classmethod + def check_objmode_cache_ndarray_check_cache(cls): + disp = cls.check_objmode_cache_ndarray() + if len(disp.stats.cache_misses) != 0: + raise AssertionError('unexpected cache miss') + if len(disp.stats.cache_hits) <= 0: + raise AssertionError("unexpected missing cache hit") + + def test_check_objmode_cache_ndarray(self): + # See issue #6130. + # Env is missing after cache load. + cache_dir = temp_directory(self.__class__.__name__) + with override_config("CACHE_DIR", cache_dir): + # Run in new process to populate the cache + run_in_new_process_in_cache_dir( + self.populate_objmode_cache_ndarray_check_cache, cache_dir + ) + # Run in new process to use the cache in a fresh process. + res = run_in_new_process_in_cache_dir( + self.check_objmode_cache_ndarray_check_cache, cache_dir + ) + self.assertEqual(res['exitcode'], 0) + + +class TestMisc(TestCase): + def test_is_jitted(self): + def foo(x): + pass + + self.assertFalse(is_jitted(foo)) + self.assertTrue(is_jitted(njit(foo))) + self.assertFalse(is_jitted(vectorize(foo))) + self.assertFalse(is_jitted(vectorize(parallel=True)(foo))) + self.assertFalse( + is_jitted(guvectorize("void(float64[:])", "(m)")(foo)) + ) + + def test_overload_arg_binding(self): + # See issue #7982, checks that calling a function with named args works + # correctly irrespective of the order in which the names are supplied. + @njit + def standard_order(): + return np.full(shape=123, fill_value=456).shape + + @njit + def reversed_order(): + return np.full(fill_value=456, shape=123).shape + + self.assertPreciseEqual(standard_order(), standard_order.py_func()) + self.assertPreciseEqual(reversed_order(), reversed_order.py_func()) + + +class TestOverloadPreferLiteral(TestCase): + def test_overload(self): + def prefer_lit(x): + pass + + def non_lit(x): + pass + + def ov(x): + if isinstance(x, types.IntegerLiteral): + # With prefer_literal=False, this branch will not be reached. + if x.literal_value == 1: + def impl(x): + return 0xcafe + return impl + else: + raise errors.TypingError('literal value') + else: + def impl(x): + return x * 100 + return impl + + overload(prefer_lit, prefer_literal=True)(ov) + overload(non_lit)(ov) + + @njit + def check_prefer_lit(x): + return prefer_lit(1), prefer_lit(2), prefer_lit(x) + + a, b, c = check_prefer_lit(3) + self.assertEqual(a, 0xcafe) + self.assertEqual(b, 200) + self.assertEqual(c, 300) + + @njit + def check_non_lit(x): + return non_lit(1), non_lit(2), non_lit(x) + + a, b, c = check_non_lit(3) + self.assertEqual(a, 100) + self.assertEqual(b, 200) + self.assertEqual(c, 300) + + def test_overload_method(self): + def ov(self, x): + if isinstance(x, types.IntegerLiteral): + # With prefer_literal=False, this branch will not be reached. + if x.literal_value == 1: + def impl(self, x): + return 0xcafe + return impl + else: + raise errors.TypingError('literal value') + else: + def impl(self, x): + return x * 100 + return impl + + overload_method( + MyDummyType, "method_prefer_literal", + prefer_literal=True, + )(ov) + + overload_method( + MyDummyType, "method_non_literal", + prefer_literal=False, + )(ov) + + @njit + def check_prefer_lit(dummy, x): + return ( + dummy.method_prefer_literal(1), + dummy.method_prefer_literal(2), + dummy.method_prefer_literal(x), + ) + + a, b, c = check_prefer_lit(MyDummy(), 3) + self.assertEqual(a, 0xcafe) + self.assertEqual(b, 200) + self.assertEqual(c, 300) + + @njit + def check_non_lit(dummy, x): + return ( + dummy.method_non_literal(1), + dummy.method_non_literal(2), + dummy.method_non_literal(x), + ) + + a, b, c = check_non_lit(MyDummy(), 3) + self.assertEqual(a, 100) + self.assertEqual(b, 200) + self.assertEqual(c, 300) + + +class TestIntrinsicPreferLiteral(TestCase): + def test_intrinsic(self): + def intrin(context, x): + # This intrinsic will return 0xcafe if `x` is a literal `1`. + sig = signature(types.intp, x) + if isinstance(x, types.IntegerLiteral): + # With prefer_literal=False, this branch will not be reached + if x.literal_value == 1: + def codegen(context, builder, signature, args): + atype = signature.args[0] + llrtype = context.get_value_type(atype) + return ir.Constant(llrtype, 0xcafe) + return sig, codegen + else: + raise errors.TypingError('literal value') + else: + def codegen(context, builder, signature, args): + atype = signature.return_type + llrtype = context.get_value_type(atype) + int_100 = ir.Constant(llrtype, 100) + return builder.mul(args[0], int_100) + return sig, codegen + + prefer_lit = intrinsic(prefer_literal=True)(intrin) + non_lit = intrinsic(prefer_literal=False)(intrin) + + @njit + def check_prefer_lit(x): + return prefer_lit(1), prefer_lit(2), prefer_lit(x) + + a, b, c = check_prefer_lit(3) + self.assertEqual(a, 0xcafe) + self.assertEqual(b, 200) + self.assertEqual(c, 300) + + @njit + def check_non_lit(x): + return non_lit(1), non_lit(2), non_lit(x) + + a, b, c = check_non_lit(3) + self.assertEqual(a, 100) + self.assertEqual(b, 200) + self.assertEqual(c, 300) + + +class TestNumbaInternalOverloads(TestCase): + + def test_signatures_match_overloaded_api(self): + # This is a "best-effort" test to try and ensure that Numba's internal + # overload declarations have signatures with argument names that match + # the API they are overloading. The purpose of ensuring there is a + # match is so that users can use call-by-name for positional arguments. + + # Set this to: + # 0 to make violations raise a ValueError (default). + # 1 to get violations reported to STDOUT + # 2 to get a verbose output of everything that was checked and its state + # reported to STDOUT. + DEBUG = 0 + + # np.random.* does not have a signature exposed to `inspect`... so + # custom parse the docstrings. + def sig_from_np_random(x): + if not x.startswith('_'): + thing = getattr(np.random, x) + if inspect.isbuiltin(thing): + docstr = thing.__doc__.splitlines() + for l in docstr: + if l: + sl = l.strip() + if sl.startswith(x): # its the signature + # special case np.random.seed, it has `self` in + # the signature whereas all the other functions + # do not!? + if x == "seed": + sl = "seed(seed)" + + fake_impl = f"def {sl}:\n\tpass" + l = {} + try: + exec(fake_impl, {}, l) + except SyntaxError: + # likely elipsis, e.g. rand(d0, d1, ..., dn) + if DEBUG == 2: + print("... skipped as cannot parse " + "signature") + return None + else: + fn = l.get(x) + return inspect.signature(fn) + + def checker(func, overload_func): + if DEBUG == 2: + print(f"Checking: {func}") + + def create_message(func, overload_func, func_sig, ol_sig): + msg = [] + s = (f"{func} from module '{getattr(func, '__module__')}' " + "has mismatched sig.") + msg.append(s) + msg.append(f" - expected: {func_sig}") + msg.append(f" - got: {ol_sig}") + lineno = inspect.getsourcelines(overload_func)[1] + tmpsrcfile = inspect.getfile(overload_func) + srcfile = tmpsrcfile.replace(numba.__path__[0], '') + msg.append(f"from {srcfile}:{lineno}") + msgstr = '\n' + '\n'.join(msg) + return msgstr + + func_sig = None + try: + func_sig = inspect.signature(func) + except ValueError: + # probably a built-in/C code, see if it's a np.random function + if fname := getattr(func, '__name__', False): + if maybe_func := getattr(np.random, fname, False): + if maybe_func == func: + # it's a built-in from np.random + func_sig = sig_from_np_random(fname) + + if func_sig is not None: + ol_sig = inspect.signature(overload_func) + x = list(func_sig.parameters.keys()) + y = list(ol_sig.parameters.keys()) + for a, b in zip(x[:len(y)], y): + if a != b: + p = func_sig.parameters[a] + if p.kind == p.POSITIONAL_ONLY: + # probably a built-in/C code + if DEBUG == 2: + print("... skipped as positional only " + "arguments found") + break + elif '*' in str(p): # probably *args or similar + if DEBUG == 2: + print("... skipped as contains *args") + break + else: + # Only error/report on functions that have a module + # or are from somewhere other than Numba. + if (not func.__module__ or + not func.__module__.startswith("numba")): + msgstr = create_message(func, overload_func, + func_sig, ol_sig) + if DEBUG != 0: + if DEBUG == 2: + print("... INVALID") + if msgstr: + print(msgstr) + break + else: + raise ValueError(msgstr) + else: + if DEBUG == 2: + if not func.__module__: + print("... skipped as no __module__ " + "present") + else: + print("... skipped as Numba internal") + break + else: + if DEBUG == 2: + print("... OK") + + # Compile something to make sure that the typing context registries + # are populated with everything from the CPU target. + njit(lambda : None).compile(()) + tyctx = numba.core.typing.context.Context() + tyctx.refresh() + + # Walk the registries and check each function that is an overload + regs = tyctx._registries + for k, v in regs.items(): + for item in k.functions: + if getattr(item, '_overload_func', False): + checker(item.key, item._overload_func) + + +if __name__ == "__main__": + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_extending_types.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_extending_types.py new file mode 100644 index 0000000000000000000000000000000000000000..540472e37a01d799f7a7e318c63ed69be167ea54 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_extending_types.py @@ -0,0 +1,170 @@ +""" +Test extending types via the numba.extending.* API. +""" +import operator + +from numba import njit, literally +from numba.core import types, cgutils +from numba.core.errors import TypingError, NumbaTypeError +from numba.core.extending import lower_builtin +from numba.core.extending import models, register_model +from numba.core.extending import make_attribute_wrapper +from numba.core.extending import type_callable +from numba.core.extending import overload +from numba.core.extending import typeof_impl + +import unittest + + +def gen_mock_float(): + # Stub to overload, pretending to be `float`. The real `float` function is + # not used as multiple registrations can collide. + def mock_float(x): + pass + return mock_float + + +class TestExtTypDummy(unittest.TestCase): + + def setUp(self): + class Dummy(object): + def __init__(self, value): + self.value = value + + class DummyType(types.Type): + def __init__(self): + super(DummyType, self).__init__(name='Dummy') + + dummy_type = DummyType() + + @register_model(DummyType) + class DummyModel(models.StructModel): + def __init__(self, dmm, fe_type): + members = [ + ('value', types.intp), + ] + models.StructModel.__init__(self, dmm, fe_type, members) + + make_attribute_wrapper(DummyType, 'value', 'value') + + @type_callable(Dummy) + def type_dummy(context): + def typer(value): + return dummy_type + return typer + + @lower_builtin(Dummy, types.intp) + def impl_dummy(context, builder, sig, args): + typ = sig.return_type + [value] = args + dummy = cgutils.create_struct_proxy(typ)(context, builder) + dummy.value = value + return dummy._getvalue() + + @typeof_impl.register(Dummy) + def typeof_dummy(val, c): + return DummyType() + + # Store attributes + self.Dummy = Dummy + self.DummyType = DummyType + + def _add_float_overload(self, mock_float_inst): + @overload(mock_float_inst) + def dummy_to_float(x): + if isinstance(x, self.DummyType): + def codegen(x): + return float(x.value) + return codegen + else: + raise NumbaTypeError('cannot type float({})'.format(x)) + + def test_overload_float(self): + mock_float = gen_mock_float() + self._add_float_overload(mock_float) + Dummy = self.Dummy + + @njit + def foo(x): + return mock_float(Dummy(x)) + + self.assertEqual(foo(123), float(123)) + + def test_overload_float_error_msg(self): + mock_float = gen_mock_float() + self._add_float_overload(mock_float) + + @njit + def foo(x): + return mock_float(x) + + with self.assertRaises(TypingError) as raises: + foo(1j) + + self.assertIn("cannot type float(complex128)", + str(raises.exception)) + + def test_unboxing(self): + """A test for the unboxing logic on unknown type + """ + Dummy = self.Dummy + + @njit + def foo(x): + # pass a dummy object into another function + bar(Dummy(x)) + + # make sure a cpython wrapper is created + @njit(no_cpython_wrapper=False) + def bar(dummy_obj): + pass + + foo(123) + with self.assertRaises(TypeError) as raises: + bar(Dummy(123)) + self.assertIn("can't unbox Dummy type", str(raises.exception)) + + def test_boxing(self): + """A test for the boxing logic on unknown type + """ + Dummy = self.Dummy + + @njit + def foo(x): + return Dummy(x) + + with self.assertRaises(TypeError) as raises: + foo(123) + self.assertIn("cannot convert native Dummy to Python object", + str(raises.exception)) + + def test_issue5565_literal_getitem(self): + # the following test is adapted from + # https://github.com/numba/numba/issues/5565 + Dummy, DummyType = self.Dummy, self.DummyType + + MAGIC_NUMBER = 12321 + + @overload(operator.getitem) + def dummy_getitem_ovld(self, idx): + if not isinstance(self, DummyType): + return None + # suppose we can only support idx as literal argument + if isinstance(idx, types.StringLiteral): + def dummy_getitem_impl(self, idx): + return MAGIC_NUMBER + return dummy_getitem_impl + + if isinstance(idx, types.UnicodeType): + def dummy_getitem_impl(self, idx): + return literally(idx) + return dummy_getitem_impl + + return None + + @njit + def test_impl(x, y): + return Dummy(x)[y] + + var = 'abc' + self.assertEqual(test_impl(1, var), MAGIC_NUMBER) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_fastmath.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_fastmath.py new file mode 100644 index 0000000000000000000000000000000000000000..528adf494e9dfcf5fde0ff8d1c958a2ea71eed4c --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_fastmath.py @@ -0,0 +1,123 @@ +import math +import numpy as np + +from numba.tests.support import captured_stdout, override_config +from numba import njit, vectorize, guvectorize +import unittest + + +class TestFastMath(unittest.TestCase): + def test_jit(self): + def foo(x): + return x + math.sin(x) + fastfoo = njit(fastmath=True)(foo) + slowfoo = njit(foo) + self.assertEqual(fastfoo(0.5), slowfoo(0.5)) + fastllvm = fastfoo.inspect_llvm(fastfoo.signatures[0]) + slowllvm = slowfoo.inspect_llvm(slowfoo.signatures[0]) + # Ensure fast attribute in fast version only + self.assertIn('fadd fast', fastllvm) + self.assertIn('call fast', fastllvm) + self.assertNotIn('fadd fast', slowllvm) + self.assertNotIn('call fast', slowllvm) + + def test_jit_subset_behaviour(self): + def foo(x, y): + return (x - y) + y + fastfoo = njit(fastmath={'reassoc', 'nsz'})(foo) + slowfoo = njit(fastmath={'reassoc'})(foo) + self.assertEqual(fastfoo(0.5, np.inf), 0.5) + self.assertTrue(np.isnan(slowfoo(0.5, np.inf))) + + def test_jit_subset_code(self): + def foo(x): + return x + math.sin(x) + fastfoo = njit(fastmath={'reassoc', 'nsz'})(foo) + slowfoo = njit()(foo) + self.assertEqual(fastfoo(0.5), slowfoo(0.5)) + fastllvm = fastfoo.inspect_llvm(fastfoo.signatures[0]) + slowllvm = slowfoo.inspect_llvm(slowfoo.signatures[0]) + # Ensure fast attributes in fast version only + self.assertNotIn('fadd fast', slowllvm) + self.assertNotIn('call fast', slowllvm) + self.assertNotIn('fadd reassoc nsz', slowllvm) + self.assertNotIn('call reassoc nsz', slowllvm) + self.assertNotIn('fadd nsz reassoc', slowllvm) + self.assertNotIn('call nsz reassoc', slowllvm) + self.assertTrue( + ('fadd nsz reassoc' in fastllvm) or + ('fadd reassoc nsz' in fastllvm), + fastllvm + ) + self.assertTrue( + ('call nsz reassoc' in fastllvm) or + ('call reassoc nsz' in fastllvm), + fastllvm + ) + + def test_jit_subset_errors(self): + with self.assertRaises(ValueError) as raises: + njit(fastmath={'spqr'})(lambda x: x + 1)(1) + self.assertIn( + "Unrecognized fastmath flags:", + str(raises.exception), + ) + + with self.assertRaises(ValueError) as raises: + njit(fastmath={'spqr': False})(lambda x: x + 1)(1) + self.assertIn( + 'Unrecognized fastmath flags:', + str(raises.exception), + ) + + with self.assertRaises(ValueError) as raises: + njit(fastmath=1337)(lambda x: x + 1)(1) + self.assertIn( + 'Expected fastmath option(s) to be', + str(raises.exception), + ) + + def test_vectorize(self): + def foo(x): + return x + math.sin(x) + fastfoo = vectorize(fastmath=True)(foo) + slowfoo = vectorize(foo) + x = np.random.random(8).astype(np.float32) + # capture the optimized llvm to check for fast flag + with override_config('DUMP_OPTIMIZED', True): + with captured_stdout() as slow_cap: + expect = slowfoo(x) + slowllvm = slow_cap.getvalue() + with captured_stdout() as fast_cap: + got = fastfoo(x) + fastllvm = fast_cap.getvalue() + np.testing.assert_almost_equal(expect, got) + self.assertIn('fadd fast', fastllvm) + self.assertIn('call fast', fastllvm) + self.assertNotIn('fadd fast', slowllvm) + self.assertNotIn('call fast', slowllvm) + + def test_guvectorize(self): + def foo(x, out): + out[0] = x + math.sin(x) + x = np.random.random(8).astype(np.float32) + with override_config('DUMP_OPTIMIZED', True): + types = ['(float32, float32[:])'] + sig = '()->()' + with captured_stdout() as fast_cap: + fastfoo = guvectorize(types, sig, fastmath=True)(foo) + fastllvm = fast_cap.getvalue() + with captured_stdout() as slow_cap: + slowfoo = guvectorize(types, sig)(foo) + slowllvm = slow_cap.getvalue() + expect = slowfoo(x) + got = fastfoo(x) + np.testing.assert_almost_equal(expect, got) + self.assertIn('fadd fast', fastllvm) + self.assertIn('call fast', fastllvm) + self.assertNotIn('fadd fast', slowllvm) + self.assertNotIn('call fast', slowllvm) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_findlib.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_findlib.py new file mode 100644 index 0000000000000000000000000000000000000000..6d42734ebeb04a1947ce48e78359e2660c727d4f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_findlib.py @@ -0,0 +1,12 @@ +from numba.tests.support import TestCase, unittest +from numba.misc import findlib + + +class TestFindlib(TestCase): + def test_find_file_nonexistent_path(self): + candidates = findlib.find_file('libirrelevant.so', 'NONEXISTENT') + self.assertEqual(candidates, []) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_gdb_dwarf.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_gdb_dwarf.py new file mode 100644 index 0000000000000000000000000000000000000000..07aecbf40e368db8b2df96128d19955337300cc2 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_gdb_dwarf.py @@ -0,0 +1,261 @@ +"""Tests for gdb interacting with the DWARF numba generates""" +from numba.tests.support import TestCase, linux_only +from numba.tests.gdb_support import needs_gdb, skip_unless_pexpect, GdbMIDriver +from unittest.mock import patch, Mock +from numba.core import datamodel +import numpy as np +from numba import typeof +import ctypes as ct +import unittest + + +@linux_only +@needs_gdb +@skip_unless_pexpect +class TestGDBDwarf(TestCase): + # This runs the tests in numba.tests.gdb, each submodule must contain one + # test class called "Test" and it must contain one test called "test". + # Variation is provided by the module name. The reason this convention exits + # is because gdb tests tend to be line number sensitive (breakpoints etc + # care about this) and doing this prevents constant churn and permits the + # reuse of the existing subprocess_test_runner harness. + _NUMBA_OPT_0_ENV = {'NUMBA_OPT': '0'} + + def _gdb_has_numpy(self): + """Returns True if gdb has NumPy support, False otherwise""" + driver = GdbMIDriver(__file__, debug=False,) + has_numpy = driver.supports_numpy() + driver.quit() + return has_numpy + + def _subprocess_test_runner(self, test_mod): + themod = f'numba.tests.gdb.{test_mod}' + self.subprocess_test_runner(test_module=themod, + test_class='Test', + test_name='test', + envvars=self._NUMBA_OPT_0_ENV) + + def test_basic(self): + self._subprocess_test_runner('test_basic') + + def test_array_arg(self): + self._subprocess_test_runner('test_array_arg') + + def test_conditional_breakpoint(self): + self._subprocess_test_runner('test_conditional_breakpoint') + + def test_break_on_symbol(self): + self._subprocess_test_runner('test_break_on_symbol') + + def test_break_on_symbol_version(self): + self._subprocess_test_runner('test_break_on_symbol_version') + + def test_pretty_print(self): + if not self._gdb_has_numpy(): + _msg = "Cannot find gdb with NumPy support" + self.skipTest(_msg) + + self._subprocess_test_runner('test_pretty_print') + + +class TestGDBPrettyPrinterLogic(TestCase): + # Tests the logic in numba.misc.gdb_print_extension.NumbaArrayPrinter + # it's quite involved and susceptible to changes to the string + # representation of Numba array and dtypes as it parses these + # representations and recreates NumPy array/dtypes based on them! + + def setUp(self): + # Patch sys.modules with mock gdb modules such that the + # numba.misc.gdb_print_extension can import ok, the rest of the gdb + # classes etc are implemented later + + mock_modules = {'gdb': Mock(), + 'gdb.printing': Mock()} + self.patched_sys = patch.dict('sys.modules', mock_modules) + self.patched_sys.start() + + # Now sys.modules has a gdb in it, patch the gdb.selected_inferior. + # This function should return a process wrapping object that has a + # read_memory method that can read a memory region from a given address + # in the process' address space. + + import gdb + + class SelectedInferior(): + + def read_memory(self, data, extent): + buf = (ct.c_char * extent).from_address(data) + return buf.raw # this is bytes + + si = SelectedInferior() + gdb.configure_mock(**{'selected_inferior': lambda :si}) + + def tearDown(self): + # drop the sys.modules patch + self.patched_sys.stop() + + def get_gdb_repr(self, array): + # Returns the gdb repr of an array as reconstructed via the + # gdb_print_extension (should be the same as NumPy!). + + # This is the module being tested, it uses gdb and gdb.printing, both + # of which are mocked in self.setUp() + from numba.misc import gdb_print_extension + + # The following classes are ducks for the gdb classes (which are not + # easily/guaranteed importable from the test suite). They implement the + # absolute bare minimum necessary to test the gdb_print_extension. + + class DISubrange(): + def __init__(self, lo, hi): + self._lo = lo + self._hi = hi + + @property + def type(self): + return self + + def range(self): + return self._lo, self._hi + + class DW_TAG_array_type(): + def __init__(self, lo, hi): + self._lo, self._hi = lo, hi + + def fields(self): + return [DISubrange(self._lo, self._hi),] + + class DIDerivedType_tuple(): + def __init__(self, the_tuple): + self._type = DW_TAG_array_type(0, len(the_tuple) - 1) + self._tuple = the_tuple + + @property + def type(self): + return self._type + + def __getitem__(self, item): + return self._tuple[item] + + class DICompositeType_Array(): + def __init__(self, arr, type_str): + self._arr = arr + self._type_str = type_str + + def __getitem__(self, item): + return getattr(self, item) + + @property + def data(self): + return self._arr.ctypes.data + + @property + def itemsize(self): + return self._arr.itemsize + + @property + def shape(self): + return DIDerivedType_tuple(self._arr.shape) + + @property + def strides(self): + return DIDerivedType_tuple(self._arr.strides) + + @property + def type(self): + return self._type_str + + # The type string encoded into the DWARF is the string repr of the Numba + # type followed by the LLVM repr of the data model in brackets. + dmm = datamodel.default_manager + array_model = datamodel.models.ArrayModel(dmm, typeof(array)) + data_type = array_model.get_data_type() + type_str = f"{typeof(array)} ({data_type.structure_repr()})" + fake_gdb_arr = DICompositeType_Array(array, type_str) + + printer = gdb_print_extension.NumbaArrayPrinter(fake_gdb_arr) + + return printer.to_string().strip() # strip, there's new lines + + def check(self, array): + gdb_printed = self.get_gdb_repr(array) + self.assertEqual(str(gdb_printed), str(array)) + + def test_np_array_printer_simple_numeric_types(self): + # Tests printer over a selection of basic types + n = 4 + m = 3 + + for dt in (np.int8, np.uint16, np.int64, np.float32, np.complex128): + arr = np.arange(m * n, dtype=dt).reshape(m, n) + self.check(arr) + + def test_np_array_printer_simple_numeric_types_strided(self): + # Tests printer over randomized strided arrays + n_tests = 30 + np.random.seed(0) + + for _ in range(n_tests): + + shape = np.random.randint(1, high=12, size=np.random.randint(1, 5)) + tmp = np.arange(np.prod(shape)).reshape(shape) + + slices = [] + for x in shape: + start = np.random.randint(0, x) + # x + 3 is to ensure that sometimes the stop is beyond the + # end of the size in a given dimension + stop = np.random.randint(start + 1, max(start + 1, x + 3)) + step = np.random.randint(1, 3) # step as 1, 2 + strd = slice(start, stop, step) + slices.append(strd) + + arr = tmp[tuple(slices)] + self.check(arr) + + def test_np_array_printer_simple_structured_dtype(self): + # Tests printer over a selection of basic types + n = 4 + m = 3 + + aligned = np.dtype([("x", np.int16), ("y", np.float64)], align=True) + unaligned = np.dtype([("x", np.int16), ("y", np.float64)], align=False) + + for dt in (aligned, unaligned): + arr = np.empty(m * n, dtype=dt).reshape(m, n) + arr['x'] = np.arange(m * n, dtype=dt['x']).reshape(m, n) + arr['y'] = 100 * np.arange(m * n, dtype=dt['y']).reshape(m, n) + self.check(arr) + + def test_np_array_printer_chr_array(self): + # Test unichr array + arr = np.array(['abcde']) + self.check(arr) + + def test_np_array_printer_unichr_structured_dtype(self): + # Not supported yet + n = 4 + m = 3 + + dt = np.dtype([("x", ' C order + noncontig, # 1d non-contig -> A order + (noncontig, contig), # 2d C order + (contig, noncontig), # 2d F order + (noncontig, noncontig), # 2d A order + (noncontig, noncontig, contig), # 3d C order + (contig, noncontig, noncontig), # 3d F order + (noncontig, noncontig, noncontig), # 3d A order + ) + + for ty, idx in product(tys, indexes): + compilable = njit(gen(ty, idx)) + # check the type of the typed list returned matches the type + # as constructed in the interpreter + expected = ty[idx] + # check execution + self.assertEqual(compilable()._dtype, expected) + got = compilable.nopython_signatures[0].return_type.dtype + # check sig + self.assertEqual(got, expected) + + def test_shorthand_syntax(self): + # tests a couple of shorthand syntax examples + # (test_static_getitem_on_type is a more extensive test of the + # functionality but it uses slices directly). + + @njit + def foo1(): + ty = types.float32[::1, :] # 2d F order + return typed.List.empty_list(ty) + + self.assertEqual(foo1()._dtype, types.float32[::1, :]) + + @njit + def foo2(): + ty = types.complex64[:, :, :] # 3d A order + return typed.List.empty_list(ty) + + self.assertEqual(foo2()._dtype, types.complex64[:, :, :]) + + def test_static_getitem_on_invalid_type(self): + # check that an unsupported type cannot be instantiated in njit code + + # check this executes in the interpreter: + types.void[:] + + # check the same fails in compilation as it's not supported + # it'll fall back to a generic getitem + with self.assertRaises(errors.TypingError) as raises: + @njit + def foo(): + types.void[:] + + foo() + + msg = ("No implementation", + "getitem(typeref[none], slice)") + + excstr = str(raises.exception) + for m in msg: + self.assertIn(m, excstr) + + def test_standard_getitem_on_type(self): + # not supported at present, should be doable if the slice is a literal + # though. + + # check using a non-static arg to the getitem raises + with self.assertRaises(errors.TypingError) as raises: + @njit + def foo(not_static): + types.float64[not_static] + + foo(slice(None, None, 1)) + + msg = ("No implementation", + "getitem(class(float64), slice)") + + excstr = str(raises.exception) + for m in msg: + self.assertIn(m, excstr) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_gil.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_gil.py new file mode 100644 index 0000000000000000000000000000000000000000..1f91dbb6810c032794626e2f5b3d2550035aa4ad --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_gil.py @@ -0,0 +1,184 @@ +import ctypes +import ctypes.util +import os +import sys +import threading +import warnings + +import numpy as np + +import unittest +from numba import jit +from numba.core import errors +from numba.tests.support import TestCase, tag, skip_if_freethreading + + +# This CPython API function is a portable way to get the current thread id. +PyThread_get_thread_ident = ctypes.pythonapi.PyThread_get_thread_ident +PyThread_get_thread_ident.restype = ctypes.c_long +PyThread_get_thread_ident.argtypes = [] + +# A way of sleeping from nopython code +if os.name == 'nt': + sleep = ctypes.windll.kernel32.Sleep + sleep.argtypes = [ctypes.c_uint] + sleep.restype = None + sleep_factor = 1 # milliseconds +else: + sleep = ctypes.CDLL(ctypes.util.find_library("c")).usleep + sleep.argtypes = [ctypes.c_uint] + sleep.restype = ctypes.c_int + sleep_factor = 1000 # microseconds + + +def f(a, indices): + # If run from one thread at a time, the function will always fill the + # array with identical values. + # If run from several threads at a time, the function will probably + # fill the array with differing values. + for idx in indices: + # Let another thread run + sleep(10 * sleep_factor) + a[idx] = PyThread_get_thread_ident() + +f_sig = "void(int64[:], intp[:])" + +def lifted_f(a, indices): + """ + Same as f(), but inside a lifted loop + """ + object() # Force object mode + for idx in indices: + # Let another thread run + sleep(10 * sleep_factor) + a[idx] = PyThread_get_thread_ident() + +def object_f(a, indices): + """ + Same as f(), but in object mode + """ + for idx in indices: + # Let another thread run + sleep(10 * sleep_factor) + object() # Force object mode + a[idx] = PyThread_get_thread_ident() + + +class TestGILRelease(TestCase): + + def make_test_array(self, n_members): + return np.arange(n_members, dtype=np.int64) + + def run_in_threads(self, func, n_threads): + # Run the function in parallel over an array and collect results. + threads = [] + # Warm up compilation, since we don't want that to interfere with + # the test proper. + func(self.make_test_array(1), np.arange(1, dtype=np.intp)) + arr = self.make_test_array(50) + for i in range(n_threads): + # Ensure different threads write into the array in different + # orders. + indices = np.arange(arr.size, dtype=np.intp) + np.random.shuffle(indices) + t = threading.Thread(target=func, args=(arr, indices)) + threads.append(t) + for t in threads: + t.start() + for t in threads: + t.join() + return arr + + def check_gil_held(self, func): + arr = self.run_in_threads(func, n_threads=4) + distinct = set(arr) + self.assertEqual(len(distinct), 1, distinct) + + def check_gil_released(self, func): + for n_threads in (4, 12, 32): + # Try harder each time. On an empty machine 4 threads seems + # sufficient, but in some contexts (e.g. Travis CI) we need more. + arr = self.run_in_threads(func, n_threads) + distinct = set(arr) + try: + self.assertGreater(len(distinct), 1, distinct) + except AssertionError as e: + failure = e + else: + return + raise failure + + @skip_if_freethreading + def test_gil_held(self): + """ + Test the GIL is held by default, by checking serialized runs + produce deterministic results. + """ + cfunc = jit(f_sig, nopython=True)(f) + self.check_gil_held(cfunc) + + def test_gil_released(self): + """ + Test releasing the GIL, by checking parallel runs produce + unpredictable results. + """ + cfunc = jit(f_sig, nopython=True, nogil=True)(f) + self.check_gil_released(cfunc) + + def test_gil_released_inside_lifted_loop(self): + """ + Test the GIL can by released by a lifted loop even though the + surrounding code uses object mode. + """ + cfunc = jit(f_sig, forceobj=True, nogil=True)(lifted_f) + self.check_gil_released(cfunc) + + def test_gil_released_by_caller(self): + """ + Releasing the GIL in the caller is sufficient to have it + released in a callee. + """ + compiled_f = jit(f_sig, nopython=True)(f) + @jit(f_sig, nopython=True, nogil=True) + def caller(a, i): + compiled_f(a, i) + self.check_gil_released(caller) + + def test_gil_released_by_caller_and_callee(self): + """ + Same, but with both caller and callee asking to release the GIL. + """ + compiled_f = jit(f_sig, nopython=True, nogil=True)(f) + @jit(f_sig, nopython=True, nogil=True) + def caller(a, i): + compiled_f(a, i) + self.check_gil_released(caller) + + @skip_if_freethreading + def test_gil_ignored_by_callee(self): + """ + When only the callee asks to release the GIL, it gets ignored. + """ + compiled_f = jit(f_sig, nopython=True, nogil=True)(f) + @jit(f_sig, nopython=True) + def caller(a, i): + compiled_f(a, i) + self.check_gil_held(caller) + + def test_object_mode(self): + """ + When the function is compiled in object mode, a warning is + printed out. + """ + with warnings.catch_warnings(record=True) as wlist: + warnings.simplefilter('always', errors.NumbaWarning) + cfunc = jit(f_sig, forceobj=True, nogil=True)(object_f) + self.assertTrue(any(w.category is errors.NumbaWarning + and "Code running in object mode won't allow parallel execution" in str(w.message) + for w in wlist), wlist) + # Just check it doesn't crash. + self.run_in_threads(cfunc, 2) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_literal_dispatch.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_literal_dispatch.py new file mode 100644 index 0000000000000000000000000000000000000000..6d759f06e70c66ac50b3e5359dc9c9d7013f75c5 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_literal_dispatch.py @@ -0,0 +1,400 @@ +import numpy as np + +import numba +import unittest +from numba.tests.support import TestCase +from numba import njit +from numba.core import types, errors, cgutils +from numba.core.typing import signature +from numba.core.datamodel import models +from numba.core.extending import ( + overload, SentryLiteralArgs, overload_method, register_model, intrinsic, +) +from numba.misc.special import literally + + +class TestLiteralDispatch(TestCase): + def check_literal_basic(self, literal_args): + @njit + def foo(x): + return literally(x) + + # Test with int + for lit in literal_args: + self.assertEqual(foo(lit), lit) + + for lit, sig in zip(literal_args, foo.signatures): + self.assertEqual(sig[0].literal_value, lit) + + def test_literal_basic(self): + self.check_literal_basic([123, 321]) + self.check_literal_basic(["abc", "cb123"]) + + def test_literal_nested(self): + @njit + def foo(x): + return literally(x) * 2 + + @njit + def bar(y, x): + return foo(y) + x + + y, x = 3, 7 + self.assertEqual(bar(y, x), y * 2 + x) + [foo_sig] = foo.signatures + self.assertEqual(foo_sig[0], types.literal(y)) + [bar_sig] = bar.signatures + self.assertEqual(bar_sig[0], types.literal(y)) + self.assertNotIsInstance(bar_sig[1], types.Literal) + + def test_literally_freevar(self): + # Try referring to numba.literally not in the globals + import numba + + @njit + def foo(x): + return numba.literally(x) + + self.assertEqual(foo(123), 123) + self.assertEqual(foo.signatures[0][0], types.literal(123)) + + def test_mutual_recursion_literal(self): + def get_functions(decor): + @decor + def outer_fac(n, value): + if n < 1: + return value + return n * inner_fac(n - 1, value) + + @decor + def inner_fac(n, value): + if n < 1: + return literally(value) + return n * outer_fac(n - 1, value) + + return outer_fac, inner_fac + + ref_outer_fac, ref_inner_fac = get_functions(lambda x: x) + outer_fac, inner_fac = get_functions(njit) + + self.assertEqual(outer_fac(10, 12), ref_outer_fac(10, 12)) + self.assertEqual(outer_fac.signatures[0][1].literal_value, 12) + self.assertEqual(inner_fac.signatures[0][1].literal_value, 12) + + self.assertEqual(inner_fac(11, 13), ref_inner_fac(11, 13)) + self.assertEqual(outer_fac.signatures[1][1].literal_value, 13) + self.assertEqual(inner_fac.signatures[1][1].literal_value, 13) + + def test_literal_nested_multi_arg(self): + @njit + def foo(a, b, c): + return inner(a, c) + + @njit + def inner(x, y): + return x + literally(y) + + kwargs = dict(a=1, b=2, c=3) + got = foo(**kwargs) + expect = (lambda a, b, c: a + c)(**kwargs) + self.assertEqual(got, expect) + [foo_sig] = foo.signatures + self.assertEqual(foo_sig[2], types.literal(3)) + + def test_unsupported_literal_type(self): + @njit + def foo(a, b, c): + return inner(a, c) + + @njit + def inner(x, y): + return x + literally(y) + + arr = np.arange(10) + with self.assertRaises(errors.LiteralTypingError) as raises: + foo(a=1, b=2, c=arr) + self.assertIn("numpy.ndarray", str(raises.exception)) + + def test_biliteral(self): + # Test usecase with more than one literal call + @njit + def foo(a, b, c): + return inner(a, b) + inner(b, c) + + @njit + def inner(x, y): + return x + literally(y) + + kwargs = dict(a=1, b=2, c=3) + got = foo(**kwargs) + expect = (lambda a, b, c: a + b + b + c)(**kwargs) + self.assertEqual(got, expect) + [(type_a, type_b, type_c)] = foo.signatures + self.assertNotIsInstance(type_a, types.Literal) + self.assertIsInstance(type_b, types.Literal) + self.assertEqual(type_b.literal_value, 2) + self.assertIsInstance(type_c, types.Literal) + self.assertEqual(type_c.literal_value, 3) + + def test_literally_varargs(self): + @njit + def foo(a, *args): + return literally(args) + + with self.assertRaises(errors.LiteralTypingError): + foo(1, 2, 3) + + @njit + def bar(a, b): + foo(a, b) + + with self.assertRaises(errors.TypingError) as raises: + bar(1, 2) + self.assertIn( + "Cannot request literal type", + str(raises.exception), + ) + + @unittest.expectedFailure + def test_literally_defaults(self): + # Problem with OmittedArg + @njit + def foo(a, b=1): + return (a, literally(b)) + foo(a=1) + + @unittest.expectedFailure + def test_literally_defaults_inner(self): + # Problem with Omitted + @njit + def foo(a, b=1): + return (a, literally(b)) + + @njit + def bar(a): + return foo(a) + 1 + + bar(1) + + def test_literally_from_module(self): + # Problem with Omitted + @njit + def foo(x): + return numba.literally(x) + + got = foo(123) + self.assertEqual(got, foo.py_func(123)) + self.assertIsInstance(foo.signatures[0][0], types.Literal) + + def test_non_literal(self): + @njit + def foo(a, b): + return literally(1 + a) + + with self.assertRaises(errors.TypingError) as raises: + foo(1, 2) + self.assertIn( + "Invalid use of non-Literal type", + str(raises.exception), + ) + + def test_inlined_literal(self): + # Check that literally accepts inlined literal + @njit + def foo(a, b): + v = 1000 + return a + literally(v) + literally(b) + + got = foo(1, 2) + self.assertEqual(got, foo.py_func(1, 2)) + + @njit + def bar(): + a = 100 + b = 9 + return foo(a=b, b=a) + + got = bar() + self.assertEqual(got, bar.py_func()) + + def test_aliased_variable(self): + @njit + def foo(a, b, c): + def closure(d): + return literally(d) + 10 * inner(a, b) + # The inlining of the closure will create an alias to c + return closure(c) + + @njit + def inner(x, y): + return x + literally(y) + + kwargs = dict(a=1, b=2, c=3) + got = foo(**kwargs) + expect = (lambda a, b, c: c + 10 * (a + b))(**kwargs) + self.assertEqual(got, expect) + [(type_a, type_b, type_c)] = foo.signatures + self.assertNotIsInstance(type_a, types.Literal) + self.assertIsInstance(type_b, types.Literal) + self.assertEqual(type_b.literal_value, 2) + self.assertIsInstance(type_c, types.Literal) + self.assertEqual(type_c.literal_value, 3) + + def test_overload_explicit(self): + # This test represents a more controlled usage with ensuring literal + # typing for an argument. + def do_this(x, y): + return x + y + + @overload(do_this) + def ov_do_this(x, y): + SentryLiteralArgs(['x']).for_function(ov_do_this).bind(x, y) + return lambda x, y: x + y + + @njit + def foo(a, b): + return do_this(a, b) + + a = 123 + b = 321 + r = foo(a, b) + self.assertEqual(r, a + b) + [type_a, type_b] = foo.signatures[0] + self.assertIsInstance(type_a, types.Literal) + self.assertEqual(type_a.literal_value, a) + self.assertNotIsInstance(type_b, types.Literal) + + def test_overload_implicit(self): + # This test represents the preferred usage style for using literally + # in overload. Here, literally() is used inside the "implementation" + # function of the overload. + def do_this(x, y): + return x + y + + @njit + def hidden(x, y): + return literally(x) + y + + @overload(do_this) + def ov_do_this(x, y): + if isinstance(x, types.Integer): + # At this point, `x` can be a literal or not + return lambda x, y: hidden(x, y) + + @njit + def foo(a, b): + return do_this(a, b) + + a = 123 + b = 321 + r = foo(a, b) + self.assertEqual(r, a + b) + [type_a, type_b] = foo.signatures[0] + self.assertIsInstance(type_a, types.Literal) + self.assertEqual(type_a.literal_value, a) + self.assertNotIsInstance(type_b, types.Literal) + + def test_overload_error_loop(self): + # Test a case where a infinite compiling loop is caused because a + # literal type is requested but an error would raise for the + # literal-ized code path. This causes the overload resolution to + # retry by "de-literal-izing" the values. + def do_this(x, y): + return x + y + + @njit + def hidden(x, y): + return literally(x) + y + + @overload(do_this) + def ov_do_this(x, y): + if isinstance(y, types.IntegerLiteral): + # This error is however suppressed because a non-literal + # version is valid. + raise errors.NumbaValueError("oops") + else: + def impl(x, y): + return hidden(x, y) + return impl + + @njit + def foo(a, b): + return do_this(a, literally(b)) + + # Expect raising CompilerError to stop re-compiling with duplicated + # literal typing request. + with self.assertRaises(errors.CompilerError) as raises: + foo(a=123, b=321) + self.assertIn("Repeated literal typing request", + str(raises.exception)) + + +class TestLiteralDispatchWithCustomType(TestCase): + def make_dummy_type(self): + class Dummy(object): + def lit(self, a): + return a + + class DummyType(types.Type): + def __init__(self): + super(DummyType, self).__init__(name="dummy") + + @register_model(DummyType) + class DummyTypeModel(models.StructModel): + def __init__(self, dmm, fe_type): + members = [] + super(DummyTypeModel, self).__init__(dmm, fe_type, members) + + @intrinsic + def init_dummy(typingctx): + def codegen(context, builder, signature, args): + dummy = cgutils.create_struct_proxy( + signature.return_type)(context, builder) + + return dummy._getvalue() + + sig = signature(DummyType()) + return sig, codegen + + @overload(Dummy) + def dummy_overload(): + def ctor(): + return init_dummy() + + return ctor + + return (DummyType, Dummy) + + def test_overload_method(self): + # from issue #5011 + DummyType, Dummy = self.make_dummy_type() + + @overload_method(DummyType, 'lit') + def lit_overload(self, a): + def impl(self, a): + return literally(a) # <-- using literally here + + return impl + + @njit + def test_impl(a): + d = Dummy() + + return d.lit(a) + + # Successful case + self.assertEqual(test_impl(5), 5) + + # Failing case + @njit + def inside(a): + return test_impl(a + 1) + + with self.assertRaises(errors.TypingError) as raises: + inside(4) + + self.assertIn("Cannot request literal type.", str(raises.exception)) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_llvm_pass_timings.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_llvm_pass_timings.py new file mode 100644 index 0000000000000000000000000000000000000000..cdb128fb303ee70ff83fb835e5c135b62b4cb4fe --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_llvm_pass_timings.py @@ -0,0 +1,124 @@ +import unittest + +from numba import njit +from numba.tests.support import TestCase, override_config +from numba.misc import llvm_pass_timings as lpt + + +timings_raw1 = """ +===-------------------------------------------------------------------------=== + ... Pass execution timing report ... +===-------------------------------------------------------------------------=== + Total Execution Time: 0.0001 seconds (0.0001 wall clock) + + ---User Time--- --System Time-- --User+System-- ---Wall Time--- --- Name --- + 0.0001 ( 90.1%) 0.0001 ( 90.1%) 0.0001 ( 90.1%) 0.0001 ( 90.1%) A1 + 0.0000 ( 9.9%) 0.0000 ( 9.9%) 0.0000 ( 9.9%) 0.0000 ( 9.9%) A2 + 0.0001 (100.0%) 0.0001 (100.0%) 0.0001 (100.0%) 0.0001 (100.0%) Total + +""" # noqa: E501 + +timings_raw2 = """ +===-------------------------------------------------------------------------=== + ... Pass execution timing report ... +===-------------------------------------------------------------------------=== + Total Execution Time: 0.0001 seconds (0.0001 wall clock) + + ---User Time--- --System Time-- --User+System-- ---Wall Time--- --- Name --- + 0.0001 ( 90.1%) ----- 0.0001 ( 90.1%) 0.0001 ( 90.1%) A1 + 0.0000 ( 9.9%) ----- 0.0000 ( 9.9%) 0.0000 ( 9.9%) A2 + 0.0001 (100.0%) ----- 0.0001 (100.0%) 0.0001 (100.0%) Total + +""" # noqa: E501 + + +class TestLLVMPassTimings(TestCase): + + def test_usage(self): + @njit + def foo(n): + c = 0 + for i in range(n): + c += i + return c + + with override_config('LLVM_PASS_TIMINGS', True): + foo(10) + + md = foo.get_metadata(foo.signatures[0]) + timings = md['llvm_pass_timings'] + # Check: timing is of correct type + self.assertIsInstance(timings, lpt.PassTimingsCollection) + # Check: basic for __str__ + text = str(timings) + self.assertIn("Module passes (full optimization)", text) + # Check: there must be more than one record + self.assertGreater(len(timings), 0) + # Check: __getitem__ + last = timings[-1] + self.assertIsInstance(last, lpt.NamedTimings) + # Check: NamedTimings + self.assertIsInstance(last.name, str) + self.assertIsInstance(last.timings, lpt.ProcessedPassTimings) + + def test_analyze(self): + @njit + def foo(n): + c = 0 + for i in range(n): + for j in range(i): + c += j + return c + + with override_config('LLVM_PASS_TIMINGS', True): + foo(10) + + md = foo.get_metadata(foo.signatures[0]) + timings_collection = md['llvm_pass_timings'] + # Check: get_total_time() + self.assertIsInstance(timings_collection.get_total_time(), float) + # Check: summary() + self.assertIsInstance(timings_collection.summary(), str) + # Check: list_longest_first() ordering + longest_first = timings_collection.list_longest_first() + self.assertEqual(len(longest_first), len(timings_collection)) + last = longest_first[0].timings.get_total_time() + for rec in longest_first[1:]: + cur = rec.timings.get_total_time() + self.assertGreaterEqual(last, cur) + cur = last + + def test_parse_raw(self): + timings1 = lpt.ProcessedPassTimings(timings_raw1) + self.assertAlmostEqual(timings1.get_total_time(), 0.0001) + self.assertIsInstance(timings1.summary(), str) + + timings2 = lpt.ProcessedPassTimings(timings_raw2) + self.assertAlmostEqual(timings2.get_total_time(), 0.0001) + self.assertIsInstance(timings2.summary(), str) + + +class TestLLVMPassTimingsDisabled(TestCase): + def test_disabled_behavior(self): + @njit + def foo(n): + c = 0 + for i in range(n): + c += i + return c + + with override_config('LLVM_PASS_TIMINGS', False): + foo(10) + + md = foo.get_metadata(foo.signatures[0]) + timings = md['llvm_pass_timings'] + # Check that the right message is returned + self.assertEqual(timings.summary(), "No pass timings were recorded") + # Check that None is returned + self.assertIsNone(timings.get_total_time()) + # Check that empty list is returned + self.assertEqual(timings.list_longest_first(), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_mandelbrot.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_mandelbrot.py new file mode 100644 index 0000000000000000000000000000000000000000..7a9fc2dd1411e6f52c77654e9dd51e87a612b0a0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_mandelbrot.py @@ -0,0 +1,28 @@ +import unittest +from numba import njit +from numba.core import types + + +def is_in_mandelbrot(c): + i = 0 + z = 0.0j + for i in range(100): + z = z ** 2 + c + if (z.real * z.real + z.imag * z.imag) >= 4: + return False + return True + + +class TestMandelbrot(unittest.TestCase): + + def test_mandelbrot(self): + pyfunc = is_in_mandelbrot + cfunc = njit((types.complex64,))(pyfunc) + + points = [0+0j, 1+0j, 0+1j, 1+1j, 0.1+0.1j] + for p in points: + self.assertEqual(cfunc(p), pyfunc(p)) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_nan.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_nan.py new file mode 100644 index 0000000000000000000000000000000000000000..a38a486c1a635b20ff3e2ead149ce8b2f9786b12 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_nan.py @@ -0,0 +1,37 @@ +import unittest +from numba import jit +from numba.core import types + +enable_pyobj_flags = {'forceobj': True} +no_pyobj_flags = {'nopython': True} + + +def isnan(x): + return x != x + + +def isequal(x): + return x == x + + +class TestNaN(unittest.TestCase): + + def test_nans(self, flags=enable_pyobj_flags): + pyfunc = isnan + cfunc = jit((types.float64,), **flags)(pyfunc) + + self.assertTrue(cfunc(float('nan'))) + self.assertFalse(cfunc(1.0)) + + pyfunc = isequal + cfunc = jit((types.float64,), **flags)(pyfunc) + + self.assertFalse(cfunc(float('nan'))) + self.assertTrue(cfunc(1.0)) + + def test_nans_npm(self): + self.test_nans(flags=no_pyobj_flags) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_ndarray_subclasses.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_ndarray_subclasses.py new file mode 100644 index 0000000000000000000000000000000000000000..944d314e7112024ff7bb22022d040847a1162c2f --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_ndarray_subclasses.py @@ -0,0 +1,346 @@ +""" +Test NumPy Subclassing features +""" + +import builtins +import unittest +from numbers import Number +from functools import wraps + +import numpy as np +from llvmlite import ir + +import numba +from numba import njit, typeof, objmode +from numba.core import cgutils, types, typing +from numba.core.pythonapi import box +from numba.core.errors import TypingError +from numba.core.registry import cpu_target +from numba.extending import (intrinsic, lower_builtin, overload_classmethod, + register_model, type_callable, typeof_impl, + register_jitable) +from numba.np import numpy_support + +from numba.tests.support import TestCase, MemoryLeakMixin + +# A quick util to allow logging within jit code + +_logger = None + + +def _do_log(*args): + if _logger is not None: + _logger.append(args) + + +@register_jitable +def log(*args): + with objmode(): + _do_log(*args) + + +def use_logger(fn): + @wraps(fn) + def core(*args, **kwargs): + global _logger + _logger = [] + return fn(*args, **kwargs) + return core + + +class MyArray(np.ndarray): + # Tell Numba to not seamlessly treat this type as a regular ndarray. + __numba_array_subtype_dispatch__ = True + + # __array__ is not needed given that this is a ndarray subclass + # + # def __array__(self, dtype=None): + # return self + + # Interoperate with NumPy outside of Numba. + def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): + if method == "__call__": + N = None + scalars = [] + for inp in inputs: + if isinstance(inp, Number): + scalars.append(inp) + elif isinstance(inp, (type(self), np.ndarray)): + if isinstance(inp, type(self)): + scalars.append(np.ndarray(inp.shape, inp.dtype, inp)) + else: + scalars.append(inp) + if N is not None: + if N != inp.shape: + raise TypeError("inconsistent sizes") + else: + N = inp.shape + else: + return NotImplemented + ret = ufunc(*scalars, **kwargs) + return self.__class__(ret.shape, ret.dtype, ret) + else: + return NotImplemented + + +class MyArrayType(types.Array): + def __init__(self, dtype, ndim, layout, readonly=False, aligned=True): + name = f"MyArray({ndim}, {dtype}, {layout})" + super().__init__(dtype, ndim, layout, readonly=readonly, + aligned=aligned, name=name) + + def copy(self, *args, **kwargs): + # This is here to future-proof. + # The test here never uses this. + raise NotImplementedError + + # Tell Numba typing how to combine MyArrayType with other ndarray types. + def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): + if method == "__call__": + for inp in inputs: + if not isinstance(inp, (types.Array, types.Number)): + return NotImplemented + # Ban if all arguments are MyArrayType + if all(isinstance(inp, MyArrayType) for inp in inputs): + return NotImplemented + return MyArrayType + else: + return NotImplemented + + @property + def box_type(self): + return MyArray + + +@typeof_impl.register(MyArray) +def typeof_ta_ndarray(val, c): + try: + dtype = numpy_support.from_dtype(val.dtype) + except NotImplementedError: + raise ValueError("Unsupported array dtype: %s" % (val.dtype,)) + layout = numpy_support.map_layout(val) + readonly = not val.flags.writeable + return MyArrayType(dtype, val.ndim, layout, readonly=readonly) + + +@register_model(MyArrayType) +class MyArrayTypeModel(numba.core.datamodel.models.StructModel): + def __init__(self, dmm, fe_type): + ndim = fe_type.ndim + members = [ + ('meminfo', types.MemInfoPointer(fe_type.dtype)), + ('parent', types.pyobject), + ('nitems', types.intp), + ('itemsize', types.intp), + ('data', types.CPointer(fe_type.dtype)), + ('shape', types.UniTuple(types.intp, ndim)), + ('strides', types.UniTuple(types.intp, ndim)), + ('extra_field', types.intp), + ] + super(MyArrayTypeModel, self).__init__(dmm, fe_type, members) + + +@type_callable(MyArray) +def type_myarray(context): + def typer(shape, dtype, buf): + out = MyArrayType( + dtype=buf.dtype, ndim=len(shape), layout=buf.layout + ) + return out + + return typer + + +@lower_builtin(MyArray, types.UniTuple, types.DType, types.Array) +def impl_myarray(context, builder, sig, args): + from numba.np.arrayobj import make_array, populate_array + + srcaryty = sig.args[-1] + shape, dtype, buf = args + + srcary = make_array(srcaryty)(context, builder, value=buf) + # Copy source array and remove the parent field to avoid boxer re-using + # the original ndarray instance. + retary = make_array(sig.return_type)(context, builder) + populate_array(retary, + data=srcary.data, + shape=srcary.shape, + strides=srcary.strides, + itemsize=srcary.itemsize, + meminfo=srcary.meminfo) + + ret = retary._getvalue() + context.nrt.incref(builder, sig.return_type, ret) + return ret + + +@box(MyArrayType) +def box_array(typ, val, c): + assert c.context.enable_nrt + np_dtype = numpy_support.as_dtype(typ.dtype) + dtypeptr = c.env_manager.read_const(c.env_manager.add_const(np_dtype)) + newary = c.pyapi.nrt_adapt_ndarray_to_python(typ, val, dtypeptr) + # Steals NRT ref + c.context.nrt.decref(c.builder, typ, val) + return newary + + +@overload_classmethod(MyArrayType, "_allocate") +def _ol_array_allocate(cls, allocsize, align): + """Implements a Numba-only classmethod on the array type. + """ + def impl(cls, allocsize, align): + log("LOG _ol_array_allocate", allocsize, align) + return allocator_MyArray(allocsize, align) + + return impl + + +@intrinsic +def allocator_MyArray(typingctx, allocsize, align): + def impl(context, builder, sig, args): + context.nrt._require_nrt() + size, align = args + + mod = builder.module + u32 = ir.IntType(32) + voidptr = cgutils.voidptr_t + + get_alloc_fnty = ir.FunctionType(voidptr, ()) + get_alloc_fn = cgutils.get_or_insert_function( + mod, get_alloc_fnty, name="_nrt_get_sample_external_allocator" + ) + ext_alloc = builder.call(get_alloc_fn, ()) + + fnty = ir.FunctionType(voidptr, [cgutils.intp_t, u32, voidptr]) + fn = cgutils.get_or_insert_function( + mod, fnty, name="NRT_MemInfo_alloc_safe_aligned_external" + ) + fn.return_value.add_attribute("noalias") + if isinstance(align, builtins.int): + align = context.get_constant(types.uint32, align) + else: + assert align.type == u32, "align must be a uint32" + call = builder.call(fn, [size, align, ext_alloc]) + call.name = "allocate_MyArray" + return call + + mip = types.MemInfoPointer(types.voidptr) # return untyped pointer + sig = typing.signature(mip, allocsize, align) + return sig, impl + + +class TestNdarraySubclasses(MemoryLeakMixin, TestCase): + + def test_myarray_return(self): + """This tests the path to `MyArrayType.box_type` + """ + @njit + def foo(a): + return a + 1 + + buf = np.arange(4) + a = MyArray(buf.shape, buf.dtype, buf) + expected = foo.py_func(a) + got = foo(a) + self.assertIsInstance(got, MyArray) + self.assertIs(type(expected), type(got)) + self.assertPreciseEqual(expected, got) + + def test_myarray_passthru(self): + @njit + def foo(a): + return a + + buf = np.arange(4) + a = MyArray(buf.shape, buf.dtype, buf) + expected = foo.py_func(a) + got = foo(a) + self.assertIsInstance(got, MyArray) + self.assertIs(type(expected), type(got)) + self.assertPreciseEqual(expected, got) + + def test_myarray_convert(self): + @njit + def foo(buf): + return MyArray(buf.shape, buf.dtype, buf) + + buf = np.arange(4) + expected = foo.py_func(buf) + got = foo(buf) + self.assertIsInstance(got, MyArray) + self.assertIs(type(expected), type(got)) + self.assertPreciseEqual(expected, got) + + def test_myarray_asarray_non_jit(self): + def foo(buf): + converted = MyArray(buf.shape, buf.dtype, buf) + return np.asarray(converted) + buf + + buf = np.arange(4) + got = foo(buf) + self.assertIs(type(got), np.ndarray) + self.assertPreciseEqual(got, buf + buf) + + @unittest.expectedFailure + def test_myarray_asarray(self): + self.disable_leak_check() + + @njit + def foo(buf): + converted = MyArray(buf.shape, buf.dtype, buf) + return np.asarray(converted) + + buf = np.arange(4) + got = foo(buf) + # the following fails because our np.asarray is returning the source + # array type + self.assertIs(type(got), np.ndarray) + + def test_myarray_ufunc_unsupported(self): + @njit + def foo(buf): + converted = MyArray(buf.shape, buf.dtype, buf) + return converted + converted + + buf = np.arange(4, dtype=np.float32) + with self.assertRaises(TypingError) as raises: + foo(buf) + + msg = ("No implementation of function", + "add(MyArray(1, float32, C), MyArray(1, float32, C))") + for m in msg: + self.assertIn(m, str(raises.exception)) + + @use_logger + def test_myarray_allocator_override(self): + """ + Checks that our custom allocator is used + """ + @njit + def foo(a): + b = a + np.arange(a.size, dtype=np.float64) + c = a + 1j + return b, c + + buf = np.arange(4, dtype=np.float64) + a = MyArray(buf.shape, buf.dtype, buf) + + expected = foo.py_func(a) + got = foo(a) + + self.assertPreciseEqual(got, expected) + + logged_lines = _logger + + targetctx = cpu_target.target_context + nb_dtype = typeof(buf.dtype) + align = targetctx.get_preferred_array_alignment(nb_dtype) + self.assertEqual(logged_lines, [ + ("LOG _ol_array_allocate", expected[0].nbytes, align), + ("LOG _ol_array_allocate", expected[1].nbytes, align), + ]) + + +if __name__ == "__main__": + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_numberctor.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_numberctor.py new file mode 100644 index 0000000000000000000000000000000000000000..fd074bef5f7b4436589f0b9262f8c4fabf290c55 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_numberctor.py @@ -0,0 +1,241 @@ +import numpy as np + +from numba import jit, njit +from numba.core import types + +from numba.tests.support import TestCase, tag +import unittest + + +def dobool(a): + return bool(a) + + +def doint(a): + return int(a) + + +def dofloat(a): + return float(a) + + +def docomplex(a): + return complex(a) + + +def docomplex2(a, b): + return complex(a, b) + + +def complex_calc(a): + z = complex(a) + return z.real ** 2 + z.imag ** 2 + + +def complex_calc2(a, b): + z = complex(a, b) + return z.real ** 2 + z.imag ** 2 + + +def converter(tp): + def f(a): + return tp(a) + return f + + +def real_np_types(): + for tp_name in ('int8', 'int16', 'int32', 'int64', + 'uint8', 'uint16', 'uint32', 'uint64', + 'intc', 'uintc', 'intp', 'uintp', + 'float32', 'float64', 'bool_'): + yield tp_name + +def complex_np_types(): + for tp_name in ('complex64', 'complex128'): + yield tp_name + + +class TestScalarNumberCtor(TestCase): + """ + Test (some scalar) + """ + + def check_int_constructor(self, pyfunc): + x_types = [ + types.boolean, types.int32, types.int64, types.float32, types.float64 + ] + x_values = [1, 0, 1000, 12.2, 23.4] + + for ty, x in zip(x_types, x_values): + cfunc = njit((ty,))(pyfunc) + self.assertPreciseEqual(pyfunc(x), cfunc(x)) + + def test_bool(self): + self.check_int_constructor(dobool) + + def test_int(self): + self.check_int_constructor(doint) + + def test_float(self): + pyfunc = dofloat + + x_types = [ + types.int32, types.int64, types.float32, types.float64 + ] + x_values = [1, 1000, 12.2, 23.4] + + for ty, x in zip(x_types, x_values): + cfunc = njit((ty,))(pyfunc) + self.assertPreciseEqual(pyfunc(x), cfunc(x), + prec='single' if ty is types.float32 else 'exact') + + def test_complex(self): + pyfunc = docomplex + + x_types = [ + types.int32, types.int64, types.float32, types.float64, + types.complex64, types.complex128, + ] + x_values = [1, 1000, 12.2, 23.4, 1.5-5j, 1-4.75j] + + for ty, x in zip(x_types, x_values): + cfunc = njit((ty,))(pyfunc) + got = cfunc(x) + expected = pyfunc(x) + self.assertPreciseEqual(pyfunc(x), cfunc(x), + prec='single' if ty is types.float32 else 'exact') + + # Check that complex(float32) really creates a complex64, + # by checking the accuracy of computations. + pyfunc = complex_calc + x = 1.0 + 2**-50 + cfunc = njit((types.float32,))(pyfunc) + self.assertPreciseEqual(cfunc(x), 1.0) + # Control (complex128) + cfunc = njit((types.float64,))(pyfunc) + self.assertGreater(cfunc(x), 1.0) + + def test_complex2(self): + pyfunc = docomplex2 + + x_types = [ + types.int32, types.int64, types.float32, types.float64 + ] + x_values = [1, 1000, 12.2, 23.4] + y_values = [x - 3 for x in x_values] + + for ty, x, y in zip(x_types, x_values, y_values): + cfunc = njit((ty, ty))(pyfunc) + self.assertPreciseEqual(pyfunc(x, y), cfunc(x, y), + prec='single' if ty is types.float32 else 'exact') + + # Check that complex(float32, float32) really creates a complex64, + # by checking the accuracy of computations. + pyfunc = complex_calc2 + x = 1.0 + 2**-50 + cfunc = njit((types.float32, types.float32))(pyfunc) + self.assertPreciseEqual(cfunc(x, x), 2.0) + # Control (complex128) + cfunc = njit((types.float64, types.float32))(pyfunc) + self.assertGreater(cfunc(x, x), 2.0) + + def check_type_converter(self, tp, np_type, values): + pyfunc = converter(tp) + cfunc = jit(nopython=True)(pyfunc) + if issubclass(np_type, np.integer): + # Converting from a Python int to a small Numpy int on 32-bit + # builds can raise "OverflowError: Python int too large to + # convert to C long". Work around by going through a large + # Numpy int first. + np_converter = lambda x: np_type(np.int64(x)) + else: + np_converter = np_type + dtype = np.dtype(np_type) + for val in values: + if dtype.kind == 'u' and isinstance(val, float) and val < 0.0: + # Converting negative float to unsigned int yields undefined + # behaviour (and concretely different on ARM vs. x86) + continue + expected = np_converter(val) + got = cfunc(val) + self.assertPreciseEqual(got, expected, + msg="for type %s with arg %s" % (np_type, val)) + + def check_number_types(self, tp_factory): + values = [0, 1, -1, 100003, 10000000000007, -100003, -10000000000007, + 1.5, -3.5] + for tp_name in real_np_types(): + np_type = getattr(np, tp_name) + tp = tp_factory(tp_name) + self.check_type_converter(tp, np_type, values) + values.append(1.5+3j) + for tp_name in complex_np_types(): + np_type = getattr(np, tp_name) + tp = tp_factory(tp_name) + self.check_type_converter(tp, np_type, values) + + def test_numba_types(self): + """ + Test explicit casting to Numba number types. + """ + def tp_factory(tp_name): + return getattr(types, tp_name) + self.check_number_types(tp_factory) + + def test_numpy_types(self): + """ + Test explicit casting to Numpy number types. + """ + def tp_factory(tp_name): + return getattr(np, tp_name) + self.check_number_types(tp_factory) + + +class TestArrayNumberCtor(TestCase): + """ + Test (some sequence) + """ + + def check_type_constructor(self, np_type, values): + pyfunc = converter(np_type) + cfunc = jit(nopython=True)(pyfunc) + for val in values: + expected = np_type(val) + got = cfunc(val) + self.assertPreciseEqual(got, expected) + + def test_1d(self): + values = [ + (1.0, 2.5), + (1, 2.5), + [1.0, 2.5], + (), + ] + for tp_name in real_np_types(): + np_type = getattr(np, tp_name) + self.check_type_constructor(np_type, values) + values = [ + (1j, 2.5), + [1.0, 2.5], + ] + for tp_name in complex_np_types(): + np_type = getattr(np, tp_name) + self.check_type_constructor(np_type, values) + + def test_2d(self): + values = [ + ((1.0, 2.5), (3.5, 4)), + [(1.0, 2.5), (3.5, 4.0)], + ([1.0, 2.5], [3.5, 4.0]), + [(), ()], + ] + for tp_name in real_np_types(): + np_type = getattr(np, tp_name) + self.check_type_constructor(np_type, values) + for tp_name in complex_np_types(): + np_type = getattr(np, tp_name) + self.check_type_constructor(np_type, values) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_objects.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..a47f9ca00877ec2dcfc203e7df25b4ddd5da3003 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_objects.py @@ -0,0 +1,57 @@ +""" +Test generic manipulation of objects. +""" + + +import unittest +from numba import jit +from numba.core import types +from numba.tests.support import TestCase + + +class C(object): + pass + + +def setattr_usecase(o, v): + o.x = v + + +def delattr_usecase(o): + del o.x + + +class TestAttributes(TestCase): + def test_setattr(self): + pyfunc = setattr_usecase + cfunc = jit((types.pyobject, types.int32), forceobj=True)(pyfunc) + c = C() + cfunc(c, 123) + self.assertEqual(c.x, 123) + + def test_setattr_attribute_error(self): + pyfunc = setattr_usecase + cfunc = jit((types.pyobject, types.int32), forceobj=True)(pyfunc) + # Can't set undeclared slot + with self.assertRaises(AttributeError): + cfunc(object(), 123) + + def test_delattr(self): + pyfunc = delattr_usecase + cfunc = jit((types.pyobject,), forceobj=True)(pyfunc) + c = C() + c.x = 123 + cfunc(c) + with self.assertRaises(AttributeError): + c.x + + def test_delattr_attribute_error(self): + pyfunc = delattr_usecase + cfunc = jit((types.pyobject,), forceobj=True)(pyfunc) + # Can't delete non-existing attribute + with self.assertRaises(AttributeError): + cfunc(C()) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_optimisation_pipelines.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_optimisation_pipelines.py new file mode 100644 index 0000000000000000000000000000000000000000..a11e6632442d907c3a4dc9c3588a40cc2b518c34 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_optimisation_pipelines.py @@ -0,0 +1,58 @@ +import unittest + +from numba.tests.support import (TestCase, override_config) +from numba import njit +from numba.core import types +import llvmlite.binding as llvm + + +class TestPassManagerOptimization(TestCase): + """ Tests that pass manager is not overriding the intended + optimization level. + """ + + def _get_llvmir(self, fn, sig): + with override_config('OPT', 0): + fn.compile(sig) + return fn.inspect_llvm(sig) + + def test_override_config(self): + @njit(debug=True, error_model='numpy') + def foo(a): + b = a + 1.23 + c = b * 2.34 + d = b / c + print(d) + return d + + sig = (types.float64,) + full_ir = self._get_llvmir(foo, sig=sig) + + module = llvm.parse_assembly(full_ir) + + name = foo.overloads[foo.signatures[0]].fndesc.mangled_name + funcs = [x for x in module.functions if x.name == name] + self.assertEqual(len(funcs), 1) + func = funcs[0] + blocks = [x for x in func.blocks] + self.assertGreater(len(blocks), 1) + block = blocks[0] + + # Find sequence with non-debug instructions + instrs = [x for x in block.instructions if x.opcode != 'call'] + op_expect = {'fadd', 'fmul', 'fdiv'} + started = False + for x in instrs: + if x.opcode in op_expect: + op_expect.remove(x.opcode) + if not started: + started = True + elif op_expect and started: + break + + self.assertGreater(len(op_expect), 0, + "Function was optimized unexpectedly") + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_polynomial.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_polynomial.py new file mode 100644 index 0000000000000000000000000000000000000000..ecc8291f0502df6893a7216aede5195fec503f16 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_polynomial.py @@ -0,0 +1,577 @@ +import gc +from itertools import product + +import numpy as np +from numpy.polynomial import polynomial as poly +from numpy.polynomial import polyutils as pu + +from numba import jit, njit +from numba.tests.support import (TestCase, needs_lapack, + EnableNRTStatsMixin, MemoryLeakMixin) +from numba.core.errors import TypingError + + +def roots_fn(p): + return np.roots(p) + + +def polyadd(c1,c2): + return poly.polyadd(c1,c2) + + +def polysub(c1,c2): + return poly.polysub(c1,c2) + + +def polymul(c1,c2): + return poly.polymul(c1,c2) + + +def trimseq(seq): + return pu.trimseq(seq) + + +def polyasseries1(a): + res = pu.as_series(a) + return res + + +def polyasseries2(a, trim): + res = pu.as_series(a, trim) + return res + + +def polydiv(c1, c2): + res = poly.polydiv(c1, c2) + return res + + +def polyval2(x, c): + res = poly.polyval(x, c) + return res + + +def polyval3T(x, c): + res = poly.polyval(x, c, True) + return res + + +def polyval3F(x, c): + res = poly.polyval(x, c, False) + return res + + +def polyint(c, m=1): + res = poly.polyint(c, m) + return res + + +class TestPolynomialBase(EnableNRTStatsMixin, TestCase): + """ + Provides setUp and common data/error modes for testing polynomial functions. + """ + + # supported dtypes + dtypes = (np.float64, np.float32, np.complex128, np.complex64) + + def setUp(self): + # Collect leftovers from previous test cases before checking for leaks + gc.collect() + super(TestPolynomialBase, self).setUp() + + def assert_error(self, cfunc, args, msg, err=ValueError): + with self.assertRaises(err) as raises: + cfunc(*args) + self.assertIn(msg, str(raises.exception)) + + def assert_1d_input(self, cfunc, args): + msg = "Input must be a 1d array." + self.assert_error(cfunc, args, msg) + + +class TestPoly1D(TestPolynomialBase): + + def assert_no_domain_change(self, name, cfunc, args): + msg = name + "() argument must not cause a domain change." + self.assert_error(cfunc, args, msg) + + @needs_lapack + def test_roots(self): + + cfunc = jit(nopython=True)(roots_fn) + + default_resolution = np.finfo(np.float64).resolution + + def check(a, **kwargs): + expected = roots_fn(a, **kwargs) + got = cfunc(a, **kwargs) + + # eigen decomposition used so type specific impl + # will be used in numba whereas a wide type impl + # will be used in numpy, so compare using a more + # fuzzy comparator + + if a.dtype in self.dtypes: + resolution = np.finfo(a.dtype).resolution + else: + # this is for integer types when roots() will cast to float64 + resolution = default_resolution + + np.testing.assert_allclose( + expected, + got, + rtol=10 * resolution, + atol=100 * resolution # zeros tend to be fuzzy + ) + + # Ensure proper resource management + with self.assertNoNRTLeak(): + cfunc(a, **kwargs) + + # test vectors in real space + # contrived examples to trip branches + r_vectors = ( + np.array([1]), + np.array([1, 3, 2]), + np.array([0, 0, 0]), + np.array([1, 6, 11, 6]), + np.array([0, 0, 0, 1, 3, 2]), + np.array([1, 1, 0, 0, 0]), + np.array([0, 0, 1, 0, 0, 0]) + ) + + # test loop real space + for v, dtype in \ + product(r_vectors, [np.int32, np.int64] + list(self.dtypes)): + a = v.astype(dtype) + check(a) + + c_vectors = ( + np.array([1 + 1j]), + np.array([1, 3 + 1j, 2]), + np.array([0, 0 + 0j, 0]), + np.array([1, 6 + 1j, 11, 6]), + np.array([0, 0, 0, 1 + 1j, 3, 2]), + np.array([1 + 1j, 1, 0, 0, 0]), + np.array([0, 0, 1 + 1j, 0, 0, 0]) + ) + + # test loop complex space + for v, dtype in product(c_vectors, self.dtypes[2:]): + a = v.astype(dtype) + check(a) + + # check input with dimension > 1 raises + self.assert_1d_input(cfunc, (np.arange(4.).reshape(2, 2),)) + + # check real input with complex roots raises + x = np.array([7., 2., 0., 1.]) + self.assert_no_domain_change("eigvals", cfunc, (x,)) + # but works fine if type conv to complex first + cfunc(x.astype(np.complex128)) + + +class TestPolynomial(MemoryLeakMixin, TestCase): + + # + # tests for Polyutils functions + # + + def test_trimseq_basic(self): + pyfunc = trimseq + cfunc = njit(trimseq) + + def inputs(): + for i in range(5): + yield np.array([1] + [0] * i) + + for coefs in inputs(): + self.assertPreciseEqual(pyfunc(coefs), cfunc(coefs)) + + def test_trimseq_exception(self): + cfunc = njit(trimseq) + + self.disable_leak_check() + + with self.assertRaises(TypingError) as raises: + cfunc("abc") + self.assertIn('The argument "seq" must be array-like', + str(raises.exception)) + + with self.assertRaises(TypingError) as e: + cfunc(np.arange(10).reshape(5, 2)) + self.assertIn('Coefficient array is not 1-d', + str(e.exception)) + + with self.assertRaises(TypingError) as e: + cfunc((1, 2, 3, 0)) + self.assertIn('Unsupported type UniTuple(int64, 4) for argument "seq"', + str(e.exception)) + + def test_pu_as_series_basic(self): + pyfunc1 = polyasseries1 + cfunc1 = njit(polyasseries1) + pyfunc2 = polyasseries2 + cfunc2 = njit(polyasseries2) + + def inputs(): + yield np.arange(4) + yield np.arange(6).reshape((2,3)) + yield (1, np.arange(3), np.arange(2, dtype=np.float32)) + yield ([1, 2, 3, 4, 0], [1, 2, 3]) + yield ((0, 0, 1e-3, 0, 1e-5, 0, 0), (1, 2, 3, 4, 5, 6, 7)) + yield ((0, 0, 1e-3, 0, 1e-5, 0, 0), (1j, 2, 3j, 4j, 5, 6j, 7)) + yield (2, [1.1, 0.]) + yield ([1, 2, 3, 0], ) + yield ((1, 2, 3, 0), ) + yield (np.array([1, 2, 3, 0]), ) + yield [np.array([1, 2, 3, 0]), np.array([1, 2, 3, 0])] + yield [np.array([1,2,3]), ] + + for input in inputs(): + self.assertPreciseEqual(pyfunc1(input), cfunc1(input)) + self.assertPreciseEqual(pyfunc2(input, False), cfunc2(input, False)) + self.assertPreciseEqual(pyfunc2(input, True), cfunc2(input, True)) + + def test_pu_as_series_exception(self): + cfunc1 = njit(polyasseries1) + cfunc2 = njit(polyasseries2) + + self.disable_leak_check() + + with self.assertRaises(TypingError) as raises: + cfunc1("abc") + self.assertIn('The argument "alist" must be array-like', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc2("abc", True) + self.assertIn('The argument "alist" must be array-like', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc2(np.arange(4), "abc") + self.assertIn('The argument "trim" must be boolean', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc1(([1, 2, 3], np.arange(16).reshape(4,4))) + self.assertIn('Coefficient array is not 1-d', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc1(np.arange(8).reshape((2, 2, 2))) + self.assertIn('Coefficient array is not 1-d', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc1([np.array([[1,2,3],[1,2,3]]), ]) + self.assertIn('Coefficient array is not 1-d', + str(raises.exception)) + + with self.assertRaises(ValueError) as raises: + cfunc1(np.array([[]], dtype=np.float64)) + self.assertIn('Coefficient array is empty', + str(raises.exception)) + + with self.assertRaises(ValueError) as raises: + cfunc1(([1, 2, 3], np.array([], dtype=np.float64), + np.array([1,2,1]))) + self.assertIn('Coefficient array is empty', + str(raises.exception)) + + def _test_polyarithm_basic(self, pyfunc, ignore_sign_on_zero=False): + # test suite containing tests for polyadd, polysub, polymul, polydiv + cfunc = njit(pyfunc) + + def inputs(): + # basic, taken from https://github.com/numpy/numpy/blob/48a8277855849be094a5979c48d9f5f1778ee4de/numpy/polynomial/tests/test_polynomial.py#L58-L123 # noqa: E501 + for i in range(5): + for j in range(5): + p1 = np.array([0] * i + [1]) + p2 = np.array([0] * j + [1]) + yield p1, p2 + # test lists, tuples, scalars + yield [1, 2, 3], [1, 2, 3] + yield [1, 2, 3], (1, 2, 3) + yield (1, 2, 3), [1, 2, 3] + yield [1, 2, 3], 3 + yield 3, (1, 2, 3) + # test different dtypes + yield np.array([1, 2, 3]), np.array([1.0, 2.0, 3.0]) + yield np.array([1j, 2j, 3j]), np.array([1.0, 2.0, 3.0]) + yield np.array([1, 2, 3]), np.array([1j, 2j, 3j]) + yield (1, 2, 3), 3.0 + yield (1, 2, 3), 3j + yield (1, 1e-3, 3), (1, 2, 3) + + for p1, p2 in inputs(): + self.assertPreciseEqual(pyfunc(p1,p2), cfunc(p1,p2), + ignore_sign_on_zero=ignore_sign_on_zero) + + def _test_polyarithm_exception(self, pyfunc): + # test suite containing tests for polyadd, polysub, polymul, polydiv + cfunc = njit(pyfunc) + + self.disable_leak_check() + + with self.assertRaises(TypingError) as raises: + cfunc("abc", np.array([1,2,3])) + self.assertIn('The argument "c1" must be array-like', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc(np.array([1,2,3]), "abc") + self.assertIn('The argument "c2" must be array-like', + str(raises.exception)) + + with self.assertRaises(TypingError) as e: + cfunc(np.arange(10).reshape(5, 2), np.array([1, 2, 3])) + self.assertIn('Coefficient array is not 1-d', + str(e.exception)) + + with self.assertRaises(TypingError) as e: + cfunc(np.array([1, 2, 3]), np.arange(10).reshape(5, 2)) + self.assertIn('Coefficient array is not 1-d', + str(e.exception)) + + def test_polyadd_basic(self): + self._test_polyarithm_basic(polyadd) + + def test_polyadd_exception(self): + self._test_polyarithm_exception(polyadd) + + def test_polysub_basic(self): + self._test_polyarithm_basic(polysub, ignore_sign_on_zero=True) + + def test_polysub_exception(self): + self._test_polyarithm_exception(polysub) + + def test_polymul_basic(self): + self._test_polyarithm_basic(polymul) + + def test_polymul_exception(self): + self._test_polyarithm_exception(polymul) + + def test_poly_polydiv_basic(self): + pyfunc = polydiv + cfunc = njit(polydiv) + self._test_polyarithm_basic(polydiv) + + def inputs(): + # Based on https://github.com/numpy/numpy/blob/160c16f055d4d2fce072004e286d8075b31955cd/numpy/polynomial/tests/test_polynomial.py#L99-L114 # noqa: E501 + # check scalar division + yield [2], [2] + yield [2, 2], [2] + # check rest. + for i in range(5): + for j in range(5): + ci = [0] * i + [1, 2] + cj = [0] * j + [1, 2] + tgt = poly.polyadd(ci, cj) + yield tgt, ci + yield np.array([1,0,0,0,0,0,-1]), np.array([1,0,0,-1]) + + for c1, c2 in inputs(): + self.assertPreciseEqual(pyfunc(c1, c2), cfunc(c1, c2)) + + def test_poly_polydiv_exception(self): + self._test_polyarithm_exception(polydiv) + cfunc = njit(polydiv) + # Based on https://github.com/numpy/numpy/blob/160c16f055d4d2fce072004e286d8075b31955cd/numpy/polynomial/tests/test_polynomial.py#L97 # noqa: E501 + # check zero division + with self.assertRaises(ZeroDivisionError) as _: + cfunc([1], [0]) + + def test_poly_polyval_basic(self): + pyfunc2 = polyval2 + cfunc2 = njit(polyval2) + pyfunc3T = polyval3T + cfunc3T = njit(polyval3T) + pyfunc3F = polyval3F + cfunc3F = njit(polyval3F) + + def inputs(): + # Based on https://github.com/numpy/numpy/blob/160c16f055d4d2fce072004e286d8075b31955cd/numpy/polynomial/tests/test_polynomial.py#L137-L157 # noqa: E501 + # check empty input + yield np.array([], dtype=np.float64), [1] + yield 1, [1,2,3] + yield np.arange(4).reshape(2,2), [1,2,3] + # check normal input + for i in range(5): + yield np.linspace(-1, 1), [0] * i + [1] + yield np.linspace(-1, 1), [0, -1, 0, 1] + # check that shape is preserved + for i in range(3): + dims = [2] * i + x = np.zeros(dims) + yield x, [1] + yield x, [1, 0] + yield x, [1, 0, 0] + # Check that behaviour corresponds to tensor = False + yield np.array([1, 2]), np.arange(4).reshape(2,2) + yield [1, 2], np.arange(4).reshape(2,2) + + for x, c in inputs(): + self.assertPreciseEqual(pyfunc2(x, c), cfunc2(x, c)) + # test tensor argument + self.assertPreciseEqual(pyfunc3T(x, c), cfunc3T(x, c)) + self.assertPreciseEqual(pyfunc3F(x, c), cfunc3F(x, c)) + + def test_poly_polyval_exception(self): + cfunc2 = njit(polyval2) + cfunc3T = njit(polyval3T) + cfunc3F = njit(polyval3F) + + self.disable_leak_check() + + with self.assertRaises(TypingError) as raises: + cfunc2(3, "abc") + self.assertIn('The argument "c" must be array-like', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc2("abc", 3) + self.assertIn('The argument "x" must be array-like', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc2("abc", "def") + self.assertIn('The argument "x" must be array-like', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc3T(3, "abc") + self.assertIn('The argument "c" must be array-like', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc3T("abc", 3) + self.assertIn('The argument "x" must be array-like', + str(raises.exception)) + + @njit + def polyval3(x, c, tensor): + res = poly.polyval(x, c, tensor) + return res + with self.assertRaises(TypingError) as raises: + polyval3(3, 3, "abc") + self.assertIn('The argument "tensor" must be boolean', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc3F("abc", "def") + self.assertIn('The argument "x" must be array-like', + str(raises.exception)) + + def test_poly_polyint_basic(self): + pyfunc = polyint + cfunc = njit(polyint) + # basic + self.assertPreciseEqual(pyfunc([1,2,3]), cfunc([1,2,3])) + # Based on https://github.com/numpy/numpy/blob/160c16f055d4d2fce072004e286d8075b31955cd/numpy/polynomial/tests/test_polynomial.py#L314-L381 # noqa: E501 + # test integration of zero polynomial + for i in range(2, 5): + self.assertPreciseEqual(pyfunc([0], m=i), cfunc([0], m=i)) + + # check single integration with integration constant + for i in range(5): + pol = [0] * i + [1] + self.assertPreciseEqual(pyfunc(pol, m=1), pyfunc(pol, m=1)) + + # check multiple integrations with default k + for i in range(5): + for j in range(2, 5): + pol = [0] * i + [1] + self.assertPreciseEqual(pyfunc(pol, m=j), cfunc(pol, m=j)) + + # test multidimensional arrays + c2 = np.array([[0,1], [0,2]]) + self.assertPreciseEqual(pyfunc(c2), cfunc(c2)) + c3 = np.arange(8).reshape((2,2,2)) + self.assertPreciseEqual(pyfunc(c3), cfunc(c3)) + + def test_poly_polyint_exception(self): + cfunc = njit(polyint) + + self.disable_leak_check() + + with self.assertRaises(TypingError) as raises: + cfunc("abc") + self.assertIn('The argument "c" must be array-like', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc(np.array([1,2,3]), "abc") + self.assertIn('The argument "m" must be an integer', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc(['a', 'b', 'c'], 1) + self.assertIn('Input dtype must be scalar.', + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc(('a', 'b', 'c'), 1) + self.assertIn('Input dtype must be scalar.', + str(raises.exception)) + + # + # tests for Polynomial class + # + + def test_Polynomial_constructor(self): + + def pyfunc3(c, dom, win): + p = poly.Polynomial(c, dom, win) + return p + cfunc3 = njit(pyfunc3) + + def pyfunc1(c): + p = poly.Polynomial(c) + return p + cfunc1 = njit(pyfunc1) + list1 = (np.array([0, 1]), np.array([0., 1.])) + list2 = (np.array([0, 1]), np.array([0., 1.])) + list3 = (np.array([0, 1]), np.array([0., 1.])) + for c in list1: + for dom in list2: + for win in list3: + p1 = pyfunc3(c, dom, win) + p2 = cfunc3(c, dom, win) + q1 = pyfunc1(c) + q2 = cfunc1(c) + self.assertPreciseEqual(p1, p2) + self.assertPreciseEqual(p1.coef, p2.coef) + self.assertPreciseEqual(p1.domain, p2.domain) + self.assertPreciseEqual(p1.window, p2.window) + self.assertPreciseEqual(q1.coef, q2.coef) + self.assertPreciseEqual(q1.domain, q2.domain) + self.assertPreciseEqual(q1.window, q2.window) + + def test_Polynomial_exeption(self): + def pyfunc3(c, dom, win): + p = poly.Polynomial(c, dom, win) + return p + cfunc3 = njit(pyfunc3) + + self.disable_leak_check() + + input2 = np.array([1, 2]) + input3 = np.array([1, 2, 3]) + input2D = np.arange(4).reshape((2, 2)) + + with self.assertRaises(ValueError) as raises: + cfunc3(input2, input3, input2) + self.assertIn("Domain has wrong number of elements.", + str(raises.exception)) + + with self.assertRaises(ValueError) as raises: + cfunc3(input2, input2, input3) + self.assertIn("Window has wrong number of elements.", + str(raises.exception)) + + with self.assertRaises(TypingError) as raises: + cfunc3(input2D, input2, input2) + self.assertIn("Coefficient array is not 1-d", + str(raises.exception)) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_print.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_print.py new file mode 100644 index 0000000000000000000000000000000000000000..01b51145bc0dcc17b6d1f9728c837288d4076af3 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_print.py @@ -0,0 +1,189 @@ +import sys + +import numpy as np + +import unittest +from numba import jit, njit +from numba.core import types, errors, utils +from numba.tests.support import (captured_stdout, TestCase, EnableNRTStatsMixin) + + +def print_value(x): + print(x) + +def print_array_item(arr, i): + print(arr[i].x) + +def print_values(a, b, c): + print(a, b, c) + +def print_empty(): + print() + +def print_string(x): + print(x, "hop!", 3.5) + +def print_vararg(a, b, c): + print(a, b, *c) + +def print_string_vararg(a, b, c): + print(a, "hop!", b, *c) + +def make_print_closure(x): + def print_closure(): + return x + return jit(nopython=True)(x) + + +class TestPrint(EnableNRTStatsMixin, TestCase): + + def check_values(self, typ, values): + cfunc = njit((typ,))(print_value) + for val in values: + with captured_stdout(): + cfunc(val) + self.assertEqual(sys.stdout.getvalue(), str(val) + '\n') + + def test_print_values(self): + """ + Test printing a single argument value. + """ + # Various scalars + self.check_values(types.int32, (1, -234)) + self.check_values(types.int64, (1, -234, + 123456789876543210, + -123456789876543210)) + self.check_values(types.uint64, (1, 234, + 123456789876543210, 2**63 + 123)) + self.check_values(types.boolean, (True, False)) + self.check_values(types.float64, (1.5, 100.0**10.0, float('nan'))) + self.check_values(types.complex64, (1+1j,)) + self.check_values(types.NPTimedelta('ms'), (np.timedelta64(100, 'ms'),)) + + cfunc = njit((types.float32,))(print_value) + with captured_stdout(): + cfunc(1.1) + # Float32 will lose precision + got = sys.stdout.getvalue() + expect = '1.10000002384' + self.assertTrue(got.startswith(expect)) + self.assertTrue(got.endswith('\n')) + + # Test array + arraytype = types.Array(types.int32, 1, 'C') + cfunc = njit((arraytype,))(print_value) + with captured_stdout(): + cfunc(np.arange(10, dtype=np.int32)) + self.assertEqual(sys.stdout.getvalue(), + '[0 1 2 3 4 5 6 7 8 9]\n') + + @unittest.skip("Issue with intermittent NRT leak, see #9355.") + def test_print_nrt_type(self): + # NOTE: this check is extracted from the above as it started + # intermittently leaking since the merge of #9330 (compile_isolated + # removal patch). It's not clear why this happens, see #9355 for + # thoughts/details. This test is skipped until it is resolved. + + # NRT-enabled type + with self.assertNoNRTLeak(): + x = [1, 3, 5, 7] + with self.assertRefCount(x): + self.check_values(types.List(types.intp, reflected=True), (x,)) + + def test_print_array_item(self): + """ + Test printing a Numpy character sequence + """ + dtype = np.dtype([('x', 'S4')]) + arr = np.frombuffer(bytearray(range(1, 9)), dtype=dtype) + + pyfunc = print_array_item + cfunc = jit(nopython=True)(pyfunc) + for i in range(len(arr)): + with captured_stdout(): + cfunc(arr, i) + self.assertEqual(sys.stdout.getvalue(), str(arr[i]['x']) + '\n') + + def test_print_multiple_values(self): + pyfunc = print_values + cfunc = njit((types.intp,) * 3)(pyfunc) + with captured_stdout(): + cfunc(1, 2, 3) + self.assertEqual(sys.stdout.getvalue(), '1 2 3\n') + + def test_print_nogil(self): + pyfunc = print_values + cfunc = jit(nopython=True, nogil=True)(pyfunc) + with captured_stdout(): + cfunc(1, 2, 3) + self.assertEqual(sys.stdout.getvalue(), '1 2 3\n') + + def test_print_empty(self): + pyfunc = print_empty + cfunc = njit((),)(pyfunc) + with captured_stdout(): + cfunc() + self.assertEqual(sys.stdout.getvalue(), '\n') + + def test_print_strings(self): + pyfunc = print_string + cfunc = njit((types.intp,))(pyfunc) + with captured_stdout(): + cfunc(1) + self.assertEqual(sys.stdout.getvalue(), '1 hop! 3.5\n') + + def test_print_vararg(self): + # Test *args support for print(). This is desired since + # print() can use a dedicated IR node. + pyfunc = print_vararg + cfunc = jit(nopython=True)(pyfunc) + with captured_stdout(): + cfunc(1, (2, 3), (4, 5j)) + self.assertEqual(sys.stdout.getvalue(), '1 (2, 3) 4 5j\n') + + pyfunc = print_string_vararg + cfunc = jit(nopython=True)(pyfunc) + with captured_stdout(): + cfunc(1, (2, 3), (4, 5j)) + self.assertEqual(sys.stdout.getvalue(), '1 hop! (2, 3) 4 5j\n') + + def test_inner_fn_print(self): + @jit(nopython=True) + def foo(x): + print(x) + + @jit(nopython=True) + def bar(x): + foo(x) + foo('hello') + + # Printing an array requires the Env. + # We need to make sure the inner function can obtain the Env. + x = np.arange(5) + with captured_stdout(): + bar(x) + self.assertEqual(sys.stdout.getvalue(), '[0 1 2 3 4]\nhello\n') + + def test_print_w_kwarg_raises(self): + @jit(nopython=True) + def print_kwarg(): + print('x', flush=True) + + with self.assertRaises(errors.UnsupportedError) as raises: + print_kwarg() + expected = ("Numba's print() function implementation does not support " + "keyword arguments.") + self.assertIn(raises.exception.msg, expected) + + def test_print_no_truncation(self): + ''' See: https://github.com/numba/numba/issues/3811 + ''' + @jit(nopython=True) + def foo(): + print(''.join(['a'] * 10000)) + with captured_stdout(): + foo() + self.assertEqual(sys.stdout.getvalue(), ''.join(['a'] * 10000) + '\n') + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_profiler.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_profiler.py new file mode 100644 index 0000000000000000000000000000000000000000..11dd80f7e04225f4a33fd68c546aa35705c19ec0 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_profiler.py @@ -0,0 +1,144 @@ +import cProfile as profiler +import os +import pstats +import subprocess +import sys + +import numpy as np + +from numba import jit, types +from numba.tests.support import needs_blas, skip_if_sysmon_unsupported +import unittest + + +def generate_standard_dot_case(): + + @jit((types.float32[::1], types.float32[::1],)) + def dot(a, b): + sum = 0 + for i in range(len(a)): + sum += a[i]*b[i] + return sum + + dot._enable_sysmon = True + return dot, dot + + +def generate_raising_dot_case(): + + @jit((types.float32[::1], types.float32[::1],)) + def raising_dot(a, b): + # this is like dot above, it does all the work, but the raises + sum = 0 + for i in range(len(a)): + sum += a[i]*b[i] + raise ValueError("problem with dot") + + raising_dot._enable_sysmon = True + + def call_raising_dot(a, b): + try: + raising_dot(a, b) + except ValueError: + pass + + return raising_dot, call_raising_dot + + +def np_dot(a, b): + return np.dot(a, b) + + +class TestProfiler(unittest.TestCase): + + def check_profiler_dot(self, caller, cfunc): + """ + Make sure the jit-compiled function shows up in the profile stats + as a regular Python function. + """ + a = np.arange(16, dtype=np.float32) + b = np.arange(16, dtype=np.float32) + n_calls = 123 + p = profiler.Profile() + p.enable() + try: + for _ in range(n_calls): + caller(a, b) + finally: + p.disable() + stats = pstats.Stats(p).strip_dirs() + + def check_stats_for_key(stats, code, n_calls): + expected_key = (os.path.basename(code.co_filename), + code.co_firstlineno, + code.co_name, + ) + # check the key is in the stats + self.assertIn(expected_key, stats.stats) + # check that call for the key has been made `n_calls` times. + func_stats = stats.stats[expected_key] + self.assertEqual(func_stats[:2], (n_calls, n_calls)) + + # check the JIT compiled function + check_stats_for_key(stats, cfunc.py_func.__code__, n_calls) + + # check the caller if it's not the same as the cfunc + if caller is not cfunc: + check_stats_for_key(stats, caller.__code__, n_calls) + + @skip_if_sysmon_unsupported + def test_profiler(self): + dot, _ = generate_standard_dot_case() + self.check_profiler_dot(dot, dot) + + @skip_if_sysmon_unsupported + def test_profiler_for_raising_function(self): + raising_dot, call_raising_dot = generate_raising_dot_case() + self.check_profiler_dot(call_raising_dot, raising_dot) + + @needs_blas + def test_profiler_np_dot(self): + # Issue #1786: initializing BLAS would crash when profiling + code = """if 1: + import cProfile as profiler + + import numpy as np + + from numba import jit + from numba.tests.test_profiler import np_dot + + cfunc = jit(nopython=True)(np_dot) + + a = np.arange(16, dtype=np.float32) + b = np.arange(16, dtype=np.float32) + + p = profiler.Profile() + p.enable() + cfunc(a, b) + cfunc(a, b) + p.disable() + """ + subprocess.check_call([sys.executable, "-c", code]) + + def test_issue_3229(self): + # Issue #3229: Seemingly random segfaults when profiling due to + # frame injection. + # numba.tests.npyufunc.test_dufunc.TestDUFunc.test_npm_call is the + # first test case crashing when profiling. Fingers crossed fixing + # this is sufficient proof for the general case. + + code = """if 1: + import cProfile as profiler + p = profiler.Profile() + p.enable() + + from numba.tests.npyufunc.test_dufunc import TestDUFunc + t = TestDUFunc('test_npm_call') + t.test_npm_call() + + p.disable() + """ + subprocess.check_call([sys.executable, "-c", code]) + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_range.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_range.py new file mode 100644 index 0000000000000000000000000000000000000000..91079cdd8e6abd70c386fac1986907f27126baf7 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_range.py @@ -0,0 +1,201 @@ +import unittest + +import numpy as np + +from numba import jit, njit +from numba.core import types +from numba.tests.support import TestCase + +from numba.core.inline_closurecall import length_of_iterator + +def loop1(n): + s = 0 + for i in range(n): + s += i + return s + + +def loop2(a, b): + s = 0 + for i in range(a, b): + s += i + return s + + +def loop3(a, b, c): + s = 0 + for i in range(a, b, c): + s += i + return s + + +def range_len1(n): + return len(range(n)) + +def range_len2(a, b): + return len(range(a, b)) + +def range_len3(a, b, c): + return len(range(a, b, c)) +def range_iter_len1(a): + return length_of_iterator(iter(range(a))) + +def range_iter_len2(a): + return length_of_iterator(iter(a)) + +def range_attrs(start, stop, step): + r1 = range(start) + r2 = range(start, stop) + r3 = range(start, stop, step) + tmp = [] + for r in (r1, r2, r3): + tmp.append((r.start, r.stop, r.step)) + return tmp + +def range_contains(val, start, stop, step): + r1 = range(start) + r2 = range(start, stop) + r3 = range(start, stop, step) + return [val in r for r in (r1, r2, r3)] + + +class TestRange(unittest.TestCase): + + def test_loop1_int16(self): + pyfunc = loop1 + cfunc = njit((types.int16,))(pyfunc) + self.assertTrue(cfunc(5), pyfunc(5)) + + def test_loop2_int16(self): + pyfunc = loop2 + cfunc = njit((types.int16, types.int16))(pyfunc) + self.assertTrue(cfunc(1, 6), pyfunc(1, 6)) + + def test_loop3_int32(self): + pyfunc = loop3 + cfunc = njit((types.int32, types.int32, types.int32))(pyfunc) + arglist = [ + (1, 2, 1), + (2, 8, 3), + (-10, -11, -10), + (-10, -10, -2), + ] + for args in arglist: + self.assertEqual(cfunc(*args), pyfunc(*args)) + + def test_range_len1(self): + pyfunc = range_len1 + typelist = [types.int16, types.int32, types.int64] + arglist = [5, 0, -5] + for typ in typelist: + cfunc = njit((typ,))(pyfunc) + for arg in arglist: + self.assertEqual(cfunc(typ(arg)), pyfunc(typ(arg))) + + def test_range_len2(self): + pyfunc = range_len2 + typelist = [types.int16, types.int32, types.int64] + arglist = [(1,6), (6,1), (-5, -1)] + for typ in typelist: + cfunc = njit((typ, typ))(pyfunc) + for args in arglist: + args_ = tuple(typ(x) for x in args) + self.assertEqual(cfunc(*args_), pyfunc(*args_)) + + def test_range_len3(self): + pyfunc = range_len3 + typelist = [types.int16, types.int32, types.int64] + arglist = [ + (1, 2, 1), + (2, 8, 3), + (-10, -11, -10), + (-10, -10, -2), + ] + for typ in typelist: + cfunc = njit((typ, typ, typ))(pyfunc) + for args in arglist: + args_ = tuple(typ(x) for x in args) + self.assertEqual(cfunc(*args_), pyfunc(*args_)) + + def test_range_iter_len1(self): + range_func = range_len1 + range_iter_func = range_iter_len1 + typelist = [types.int16, types.int32, types.int64] + arglist = [5, 0, -5] + for typ in typelist: + cfunc = njit((typ,))(range_iter_func) + for arg in arglist: + self.assertEqual(cfunc(typ(arg)), range_func(typ(arg))) + + def test_range_iter_list(self): + range_iter_func = range_iter_len2 + cfunc = njit((types.List(types.intp, reflected=True),))(range_iter_func) + arglist = [1, 2, 3, 4, 5] + self.assertEqual(cfunc(arglist), len(arglist)) + + def test_range_attrs(self): + pyfunc = range_attrs + arglist = [(0, 0, 1), + (0, -1, 1), + (-1, 1, 1), + (-1, 4, 1), + (-1, 4, 10), + (5, -5, -2),] + + cfunc = njit((types.int64, types.int64, types.int64),)(pyfunc) + for arg in arglist: + self.assertEqual(cfunc(*arg), pyfunc(*arg)) + + def test_range_contains(self): + pyfunc = range_contains + arglist = [(0, 0, 1), + (-1, 0, 1), + (1, 0, -1), + (0, -1, 1), + (0, 1, -1), + (-1, 1, 1), + (-1, 4, 1), + (-1, 4, 10), + (5, -5, -2),] + + bool_vals = [True, False] + int_vals = [-10, -6, -5, -4, -2, -1, 0, + 1, 2, 4, 5, 6, 10] + float_vals = [-1.1, -1.0, 0.0, 1.0, 1.1] + complex_vals = [1 + 0j, 1 + 1j, 1.1 + 0j, 1.0 + 1.1j] + + vallist = (bool_vals + int_vals + float_vals + + complex_vals) + + cfunc = njit(pyfunc) + for arg in arglist: + for val in vallist: + self.assertEqual(cfunc(val, *arg), pyfunc(val, *arg)) + + non_numeric_vals = [{'a': 1}, [1, ], 'abc', (1,)] + + cfunc_obj = jit(pyfunc, forceobj=True) + for arg in arglist: + for val in non_numeric_vals: + self.assertEqual(cfunc_obj(val, *arg), pyfunc(val, *arg)) + + +@njit +def my_arange(start, stop, step): + x = np.zeros(len(range(start, stop, step)), dtype=np.uint64) + i = 0 + for v in range(start, stop, step): + x[i] = v + i += 1 + return x + + +class TestRangeNumpy(TestCase): + def test_range_safe_cast_mixed(self): + """Test that mixing `uint64` and `int64` works.""" + a = my_arange(np.uint64(6), np.uint64(0), np.int64(-1)) + self.assertPreciseEqual(a, np.arange(6, 0, -1, dtype=np.uint64)) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_remove_dead.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_remove_dead.py new file mode 100644 index 0000000000000000000000000000000000000000..b1ab55ce2d5e38d36bfffcf05fceb07be1567efc --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_remove_dead.py @@ -0,0 +1,436 @@ +# +# Copyright (c) 2017 Intel Corporation +# SPDX-License-Identifier: BSD-2-Clause +# + +import numba +import numba.parfors.parfor +from numba import njit, jit +from numba.core import ir_utils +from numba.core import types, ir, compiler +from numba.core.registry import cpu_target +from numba.core.ir_utils import (copy_propagate, apply_copy_propagate, + get_name_var_table, remove_dels, remove_dead, + remove_call_handlers, alias_func_extensions) +from numba.core.typed_passes import type_inference_stage +from numba.core.compiler_machinery import FunctionPass, register_pass, PassManager +from numba.core.untyped_passes import (ExtractByteCode, TranslateByteCode, FixupArgs, + IRProcessing, DeadBranchPrune, + RewriteSemanticConstants, GenericRewrites, + WithLifting, PreserveIR, InlineClosureLikes) + +from numba.core.typed_passes import (NopythonTypeInference, AnnotateTypes, + NopythonRewrites, PreParforPass, ParforPass, + DumpParforDiagnostics, NativeLowering, + IRLegalization, NoPythonBackend, NativeLowering) +import numpy as np +from numba.tests.support import skip_parfors_unsupported, needs_blas, TestCase +import unittest + + +def test_will_propagate(b, z, w): + x1 = 3 + x = x1 + if b > 0: + y = z + w + else: + y = 0 + a = 2 * x + return a < b + +def null_func(a,b,c,d): + False + +@numba.njit +def dummy_aliased_func(A): + return A + +def alias_ext_dummy_func(lhs_name, args, alias_map, arg_aliases): + ir_utils._add_alias(lhs_name, args[0].name, alias_map, arg_aliases) + +def findLhsAssign(func_ir, var): + for label, block in func_ir.blocks.items(): + for i, inst in enumerate(block.body): + if isinstance(inst, ir.Assign) and inst.target.name==var: + return True + + return False + +class TestRemoveDead(TestCase): + + _numba_parallel_test_ = False + + def compile_parallel(self, func, arg_types): + return njit(arg_types, parallel=True, fastmath=True)(func) + + def test1(self): + typingctx = cpu_target.typing_context + targetctx = cpu_target.target_context + test_ir = compiler.run_frontend(test_will_propagate) + + typingctx.refresh() + targetctx.refresh() + args = (types.int64, types.int64, types.int64) + typemap, _, calltypes, _ = type_inference_stage(typingctx, targetctx, test_ir, args, None) + remove_dels(test_ir.blocks) + in_cps, out_cps = copy_propagate(test_ir.blocks, typemap) + apply_copy_propagate(test_ir.blocks, in_cps, get_name_var_table(test_ir.blocks), typemap, calltypes) + + remove_dead(test_ir.blocks, test_ir.arg_names, test_ir) + self.assertFalse(findLhsAssign(test_ir, "x")) + + def test2(self): + def call_np_random_seed(): + np.random.seed(2) + + def seed_call_exists(func_ir): + for inst in func_ir.blocks[0].body: + if (isinstance(inst, ir.Assign) and + isinstance(inst.value, ir.Expr) and + inst.value.op == 'call' and + func_ir.get_definition(inst.value.func).attr == 'seed'): + return True + return False + + test_ir = compiler.run_frontend(call_np_random_seed) + remove_dead(test_ir.blocks, test_ir.arg_names, test_ir) + self.assertTrue(seed_call_exists(test_ir)) + + def run_array_index_test(self, func): + A1 = np.arange(6).reshape(2,3) + A2 = A1.copy() + i = 0 + pfunc = self.compile_parallel(func, (numba.typeof(A1), numba.typeof(i))) + + func(A1, i) + pfunc(A2, i) + np.testing.assert_array_equal(A1, A2) + + def test_alias_ravel(self): + def func(A, i): + B = A.ravel() + B[i] = 3 + + self.run_array_index_test(func) + + def test_alias_flat(self): + def func(A, i): + B = A.flat + B[i] = 3 + + self.run_array_index_test(func) + + def test_alias_transpose1(self): + def func(A, i): + B = A.T + B[i,0] = 3 + + self.run_array_index_test(func) + + def test_alias_transpose2(self): + def func(A, i): + B = A.transpose() + B[i,0] = 3 + + self.run_array_index_test(func) + + def test_alias_transpose3(self): + def func(A, i): + B = np.transpose(A) + B[i,0] = 3 + + self.run_array_index_test(func) + + @skip_parfors_unsupported + @needs_blas + def test_alias_ctypes(self): + # use xxnrm2 to test call a C function with ctypes + from numba.np.linalg import _BLAS + xxnrm2 = _BLAS().numba_xxnrm2(types.float64) + + def remove_dead_xxnrm2(rhs, lives, call_list): + if call_list == [xxnrm2]: + return rhs.args[4].name not in lives + return False + + # adding this handler has no-op effect since this function won't match + # anything else but it's a bit cleaner to save the state and recover + old_remove_handlers = remove_call_handlers[:] + remove_call_handlers.append(remove_dead_xxnrm2) + + def func(ret): + a = np.ones(4) + xxnrm2(100, 4, a.ctypes, 1, ret.ctypes) + + A1 = np.zeros(1) + A2 = A1.copy() + + try: + pfunc = self.compile_parallel(func, (numba.typeof(A1),)) + numba.njit(func)(A1) + pfunc(A2) + finally: + # recover global state + remove_call_handlers[:] = old_remove_handlers + + self.assertEqual(A1[0], A2[0]) + + def test_alias_reshape1(self): + def func(A, i): + B = np.reshape(A, (3,2)) + B[i,0] = 3 + + self.run_array_index_test(func) + + def test_alias_reshape2(self): + def func(A, i): + B = A.reshape(3,2) + B[i,0] = 3 + + self.run_array_index_test(func) + + def test_alias_func_ext(self): + def func(A, i): + B = dummy_aliased_func(A) + B[i, 0] = 3 + + # save global state + old_ext_handlers = alias_func_extensions.copy() + try: + alias_func_extensions[('dummy_aliased_func', + 'numba.tests.test_remove_dead')] = alias_ext_dummy_func + self.run_array_index_test(func) + finally: + # recover global state + ir_utils.alias_func_extensions = old_ext_handlers + + def test_rm_dead_rhs_vars(self): + """make sure lhs variable of assignment is considered live if used in + rhs (test for #6715). + """ + def func(): + for i in range(3): + a = (lambda j: j)(i) + a = np.array(a) + return a + + self.assertEqual(func(), numba.njit(func)()) + + @skip_parfors_unsupported + def test_alias_parfor_extension(self): + """Make sure aliases are considered in remove dead extension for + parfors. + """ + def func(): + n = 11 + numba.parfors.parfor.init_prange() + A = np.empty(n) + B = A # create alias to A + for i in numba.prange(n): + A[i] = i + + return B + + @register_pass(analysis_only=False, mutates_CFG=True) + class LimitedParfor(FunctionPass): + _name = "limited_parfor" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + parfor_pass = numba.parfors.parfor.ParforPass( + state.func_ir, + state.typemap, + state.calltypes, + state.return_type, + state.typingctx, + state.flags.auto_parallel, + state.flags, + state.metadata, + state.parfor_diagnostics + ) + remove_dels(state.func_ir.blocks) + parfor_pass.array_analysis.run(state.func_ir.blocks) + parfor_pass._convert_loop(state.func_ir.blocks) + remove_dead(state.func_ir.blocks, + state.func_ir.arg_names, + state.func_ir, + state.typemap) + numba.parfors.parfor.get_parfor_params(state.func_ir.blocks, + parfor_pass.options.fusion, + parfor_pass.nested_fusion_info) + return True + + class TestPipeline(compiler.Compiler): + """Test pipeline that just converts prange() to parfor and calls + remove_dead(). Copy propagation can replace B in the example code + which this pipeline avoids. + """ + def define_pipelines(self): + name = 'test parfor aliasing' + pm = PassManager(name) + pm.add_pass(TranslateByteCode, "analyzing bytecode") + pm.add_pass(FixupArgs, "fix up args") + pm.add_pass(IRProcessing, "processing IR") + pm.add_pass(WithLifting, "Handle with contexts") + # pre typing + if not self.state.flags.no_rewrites: + pm.add_pass(GenericRewrites, "nopython rewrites") + pm.add_pass(RewriteSemanticConstants, "rewrite semantic constants") + pm.add_pass(DeadBranchPrune, "dead branch pruning") + pm.add_pass(InlineClosureLikes, + "inline calls to locally defined closures") + # typing + pm.add_pass(NopythonTypeInference, "nopython frontend") + + # lower + pm.add_pass(NativeLowering, "native lowering") + pm.add_pass(NoPythonBackend, "nopython mode backend") + pm.finalize() + return [pm] + + test_res = numba.jit(pipeline_class=TestPipeline)(func)() + py_res = func() + np.testing.assert_array_equal(test_res, py_res) + + +class TestSSADeadBranchPrune(TestCase): + """ + Test issues that required dead-branch-prune on SSA IR + """ + def test_issue_9706(self): + @njit + def foo(x, y=None): + if y is not None: + return x + y + else: + y = x + return x + y + + @njit + def foo_manual_ssa(x, y=None): + if y is not None: + return x + y + else: + # avoid changing type of `y` + y_ = x + return x + y_ + + self.assertEqual(foo(3, None), foo_manual_ssa(3, None)) + self.assertEqual(foo(3, 10), foo_manual_ssa(3, 10)) + + def test_issue_6541(self): + @njit + def f(xs, out=None): + N, = xs.shape + if out is None: + out = np.arange(N) + else: + assert np.all((0 <= out) & (out < N)) + out[:] = N + return out + + expected = f(np.array([3, 1, 2])) + out = np.arange(3, dtype='i8') + got = f(np.array([3, 1, 2]), out=out) + self.assertIs(got, out) + self.assertPreciseEqual(got, expected) + out = None + got = f(np.array([3, 1, 2]), out=out) + self.assertPreciseEqual(got, expected) + + def test_issue_7482(self): + @njit + def compute(smth, weights, default=0.0): + if weights is None: + return None + + if len(weights) == 0: + return default + + idx = smth > weights + weights = weights[idx] + + return default * weights + + self.assertIsNone(compute(smth=1, weights=None)) + kwargs = dict(smth=1, weights=np.arange(5), default=np.zeros(1)) + self.assertEqual(compute(**kwargs), + compute.py_func(**kwargs)) + + def test_issue_5661(self): + @njit + def foo(a, b=None): + if b is None: + b = 1 + elif b < a: + b += 1 + + return a + b + + args_list = [ + (1, 2), + (2, 1), + (1,), + ] + for args in args_list: + self.assertEqual(foo(*args), foo.py_func(*args)) + + # Variation + # https://github.com/numba/numba/issues/5661#issuecomment-697902475 + def make(decor=njit): + @decor + def inner(state): + if state is None: + state = 0 + else: + state += 1 + return state + + @decor + def fn(): + state = None + for i in range(10): + state = inner(state) + return state + + return fn() + + self.assertEqual(make(), make(lambda x: x)) + + def test_issue_9742(self): + CONST = 32 + + @jit + def foo(): + # This is a prune by value case, conditional is a compile time + # evaluatable constant. + conditional = CONST // 2 + collect = [] + while conditional: + collect.append(conditional) + conditional //= 2 + + return collect + + self.assertEqual(foo(), foo.py_func()) + + def test_issue_9742_variant(self): + CONST = 32 + + @jit + def foo(): + collect = [] + # This is a prune by value case, conditional is a compile time + # evaluatable constant. + x = CONST + 1 + if x: + collect.append(x) + return collect + + self.assertEqual(foo(), foo.py_func()) + + +if __name__ == "__main__": + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_struct_ref.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_struct_ref.py new file mode 100644 index 0000000000000000000000000000000000000000..2b259416c3fb731d41ab8df2d64d4b6e4136280b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_struct_ref.py @@ -0,0 +1,454 @@ +""" +Test mutable struct, aka, structref +""" +import warnings + +import numpy as np + +from numba import typed, njit, errors, typeof +from numba.core import types +from numba.experimental import structref +from numba.extending import overload_method, overload_attribute +from numba.tests.support import ( + MemoryLeakMixin, TestCase, temp_directory, override_config, +) + + +@structref.register +class MySimplerStructType(types.StructRef): + """ + Test associated with this type represent the lowest level uses of structref. + """ + pass + + +my_struct_ty = MySimplerStructType( + fields=[("values", types.intp[:]), ("counter", types.intp)] +) + +structref.define_boxing(MySimplerStructType, structref.StructRefProxy) + + +class MyStruct(structref.StructRefProxy): + + def __new__(cls, values, counter): + # Define this method to customize the constructor. + # The default takes `*args`. Customizing allow the use of keyword-arg. + # The impl of the method calls `StructRefProxy.__new__` + return structref.StructRefProxy.__new__(cls, values, counter) + + # The below defines wrappers for attributes and methods manually + + @property + def values(self): + return get_values(self) + + @values.setter + def values(self, val): + return set_values(self, val) + + @property + def counter(self): + return get_counter(self) + + def testme(self, arg): + return self.values * arg + self.counter + + @property + def prop(self): + return self.values, self.counter + + def __hash__(self): + return compute_fields(self) + + +@structref.register +class MyStructType(types.StructRef): + """Test associated with this type represent the higher-level uses of + structef. + """ + pass + + +# Call to define_proxy is needed to register the use of `MyStruct` as a +# PyObject proxy for creating a Numba-allocated structref. +# The `MyStruct` class can then be used in both jit-code and interpreted-code. +structref.define_proxy( + MyStruct, + MyStructType, + ['values', 'counter'], +) + + +@njit +def my_struct(values, counter): + st = structref.new(my_struct_ty) + my_struct_init(st, values, counter) + return st + + +@njit +def my_struct_init(self, values, counter): + self.values = values + self.counter = counter + + +@njit +def ctor_by_intrinsic(vs, ctr): + st = my_struct(vs, counter=ctr) + st.values += st.values + st.counter *= ctr + return st + + +@njit +def ctor_by_class(vs, ctr): + return MyStruct(values=vs, counter=ctr) + + +@njit +def get_values(st): + return st.values + + +@njit +def set_values(st, val): + st.values = val + + +@njit +def get_counter(st): + return st.counter + + +@njit +def compute_fields(st): + return st.values + st.counter + + +@njit +def test_structref_is(): + c = MyStruct(3, 4) + d = MyStruct(3, 4) + return (c is c, c is d) + + +class TestStructRefIs(TestCase): + def test_is_identity(self): + res = test_structref_is() + self.assertTrue(res[0]) + self.assertFalse(res[1]) + + +class TestStructRefBasic(MemoryLeakMixin, TestCase): + def test_structref_type(self): + sr = types.StructRef([('a', types.int64)]) + self.assertEqual(sr.field_dict['a'], types.int64) + sr = types.StructRef([('a', types.int64), ('b', types.float64)]) + self.assertEqual(sr.field_dict['a'], types.int64) + self.assertEqual(sr.field_dict['b'], types.float64) + # bad case + with self.assertRaisesRegex(ValueError, + "expecting a str for field name"): + types.StructRef([(1, types.int64)]) + with self.assertRaisesRegex(ValueError, + "expecting a Numba Type for field type"): + types.StructRef([('a', 123)]) + + def test_invalid_uses(self): + with self.assertRaisesRegex(ValueError, "cannot register"): + structref.register(types.StructRef) + with self.assertRaisesRegex(ValueError, "cannot register"): + structref.define_boxing(types.StructRef, MyStruct) + + def test_MySimplerStructType(self): + vs = np.arange(10, dtype=np.intp) + ctr = 13 + + first_expected = vs + vs + first_got = ctor_by_intrinsic(vs, ctr) + # the returned instance is a structref.StructRefProxy + # but not a MyStruct + self.assertNotIsInstance(first_got, MyStruct) + self.assertPreciseEqual(first_expected, get_values(first_got)) + + second_expected = first_expected + (ctr * ctr) + second_got = compute_fields(first_got) + self.assertPreciseEqual(second_expected, second_got) + + def test_MySimplerStructType_wrapper_has_no_attrs(self): + vs = np.arange(10, dtype=np.intp) + ctr = 13 + wrapper = ctor_by_intrinsic(vs, ctr) + self.assertIsInstance(wrapper, structref.StructRefProxy) + with self.assertRaisesRegex(AttributeError, 'values'): + wrapper.values + with self.assertRaisesRegex(AttributeError, 'counter'): + wrapper.counter + + def test_MyStructType(self): + vs = np.arange(10, dtype=np.float64) + ctr = 11 + + first_expected_arr = vs.copy() + first_got = ctor_by_class(vs, ctr) + self.assertIsInstance(first_got, MyStruct) + self.assertPreciseEqual(first_expected_arr, first_got.values) + + second_expected = first_expected_arr + ctr + second_got = compute_fields(first_got) + self.assertPreciseEqual(second_expected, second_got) + self.assertEqual(first_got.counter, ctr) + + def test_MyStructType_mixed_types(self): + # structref constructor is generic + @njit + def mixed_type(x, y, m, n): + return MyStruct(x, y), MyStruct(m, n) + + a, b = mixed_type(1, 2.3, 3.4j, (4,)) + self.assertEqual(a.values, 1) + self.assertEqual(a.counter, 2.3) + self.assertEqual(b.values, 3.4j) + self.assertEqual(b.counter, (4,)) + + def test_MyStructType_in_dict(self): + td = typed.Dict() + td['a'] = MyStruct(1, 2.3) + self.assertEqual(td['a'].values, 1) + self.assertEqual(td['a'].counter, 2.3) + # overwrite + td['a'] = MyStruct(2, 3.3) + self.assertEqual(td['a'].values, 2) + self.assertEqual(td['a'].counter, 3.3) + # mutate + td['a'].values += 10 + self.assertEqual(td['a'].values, 12) # changed + self.assertEqual(td['a'].counter, 3.3) # unchanged + # insert + td['b'] = MyStruct(4, 5.6) + + def test_MyStructType_in_dict_mixed_type_error(self): + self.disable_leak_check() + + td = typed.Dict() + td['a'] = MyStruct(1, 2.3) + self.assertEqual(td['a'].values, 1) + self.assertEqual(td['a'].counter, 2.3) + + # ERROR: store different types + with self.assertRaisesRegex(errors.TypingError, + r"Cannot cast numba.MyStructType"): + # because first field is not a float; + # the second field is now an integer. + td['b'] = MyStruct(2.3, 1) + + def test_MyStructType_hash_no_typeof_recursion(self): + # Tests that __hash__ is not called prematurely in typeof + # causing infinite recursion (see #8241). + st = MyStruct(1, 2) + typeof(st) + + self.assertEqual(hash(st), 3) + + +@overload_method(MyStructType, "testme") +def _ol_mystructtype_testme(self, arg): + def impl(self, arg): + return self.values * arg + self.counter + return impl + + +@overload_attribute(MyStructType, "prop") +def _ol_mystructtype_prop(self): + def get(self): + return self.values, self.counter + return get + + +class TestStructRefExtending(MemoryLeakMixin, TestCase): + def test_overload_method(self): + @njit + def check(x): + vs = np.arange(10, dtype=np.float64) + ctr = 11 + obj = MyStruct(vs, ctr) + return obj.testme(x) + + x = 3 + got = check(x) + expect = check.py_func(x) + self.assertPreciseEqual(got, expect) + + def test_overload_attribute(self): + @njit + def check(): + vs = np.arange(10, dtype=np.float64) + ctr = 11 + obj = MyStruct(vs, ctr) + return obj.prop + + got = check() + expect = check.py_func() + self.assertPreciseEqual(got, expect) + + +def caching_test_make(x, y): + struct = MyStruct(values=x, counter=y) + return struct + + +def caching_test_use(struct, z): + return struct.testme(z) + + +class TestStructRefCaching(MemoryLeakMixin, TestCase): + def setUp(self): + self._cache_dir = temp_directory(TestStructRefCaching.__name__) + self._cache_override = override_config('CACHE_DIR', self._cache_dir) + self._cache_override.__enter__() + warnings.simplefilter("error") + warnings.filterwarnings(action="ignore", module="typeguard") + + def tearDown(self): + self._cache_override.__exit__(None, None, None) + warnings.resetwarnings() + + def test_structref_caching(self): + def assert_cached(stats): + self.assertEqual(len(stats.cache_hits), 1) + self.assertEqual(len(stats.cache_misses), 0) + + def assert_not_cached(stats): + self.assertEqual(len(stats.cache_hits), 0) + self.assertEqual(len(stats.cache_misses), 1) + + def check(cached): + check_make = njit(cache=True)(caching_test_make) + check_use = njit(cache=True)(caching_test_use) + vs = np.random.random(3) + ctr = 17 + factor = 3 + st = check_make(vs, ctr) + got = check_use(st, factor) + expect = vs * factor + ctr + self.assertPreciseEqual(got, expect) + + if cached: + assert_cached(check_make.stats) + assert_cached(check_use.stats) + else: + assert_not_cached(check_make.stats) + assert_not_cached(check_use.stats) + + check(cached=False) + check(cached=True) + + +@structref.register +class PolygonStructType(types.StructRef): + + def preprocess_fields(self, fields): + # temp name to allow Optional instantiation + self.name = f"numba.PolygonStructType#{id(self)}" + fields = tuple([ + ('value', types.Optional(types.int64)), + ('parent', types.Optional(self)), + ]) + + return fields + + +polygon_struct_type = PolygonStructType(fields=( + ('value', types.Any), + ('parent', types.Any) +)) + + +class PolygonStruct(structref.StructRefProxy): + def __new__(cls, value, parent): + return structref.StructRefProxy.__new__(cls, value, parent) + + @property + def value(self): + return PolygonStruct_get_value(self) + + @property + def parent(self): + return PolygonStruct_get_parent(self) + + +@njit +def PolygonStruct_get_value(self): + return self.value + + +@njit +def PolygonStruct_get_parent(self): + return self.parent + + +structref.define_proxy( + PolygonStruct, + PolygonStructType, + ["value", "parent"] +) + + +@overload_method(PolygonStructType, "flip") +def _ol_polygon_struct_flip(self): + def impl(self): + if self.value is not None: + self.value = -self.value + return impl + + +@overload_attribute(PolygonStructType, "prop") +def _ol_polygon_struct_prop(self): + def get(self): + return self.value, self.parent + return get + + +class TestStructRefForwardTyping(MemoryLeakMixin, TestCase): + def test_same_type_assignment(self): + @njit + def check(x): + poly = PolygonStruct(None, None) + p_poly = PolygonStruct(None, None) + poly.value = x + poly.parent = p_poly + p_poly.value = x + return poly.parent.value + + x = 11 + got = check(x) + expect = x + self.assertPreciseEqual(got, expect) + + def test_overload_method(self): + @njit + def check(x): + poly = PolygonStruct(None, None) + p_poly = PolygonStruct(None, None) + poly.value = x + poly.parent = p_poly + p_poly.value = x + poly.flip() + poly.parent.flip() + return poly.parent.value + + x = 3 + got = check(x) + expect = -x + self.assertPreciseEqual(got, expect) + + def test_overload_attribute(self): + @njit + def check(): + obj = PolygonStruct(5, None) + return obj.prop[0] + + got = check() + expect = 5 + self.assertPreciseEqual(got, expect) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_support.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_support.py new file mode 100644 index 0000000000000000000000000000000000000000..80f2e9c46e4c58dcb33f428cfc5cb5277ca45257 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_support.py @@ -0,0 +1,347 @@ +import itertools + +import numpy as np + +from numba import jit +from numba.core import utils +from numba.tests.support import TestCase, forbid_codegen + +from .enum_usecases import * +import unittest + +DBL_EPSILON = 2**-52 +FLT_EPSILON = 2**-23 + +INF = float('inf') +NAN = float('nan') + + +class TestAssertPreciseEqual(TestCase): + """ + Tests for TestCase.assertPreciseEqual(). + """ + + int_types = [int] + np_float_types = [np.float32, np.float64] + float_types = [float] + np_float_types + np_complex_types = [np.complex64, np.complex128] + complex_types = [complex] + np_complex_types + bool_types = [bool, np.bool_] + + def eq(self, left, right, **kwargs): + def assert_succeed(left, right): + self.assertPreciseEqual(left, right, **kwargs) + self.assertPreciseEqual(right, left, **kwargs) + assert_succeed(left, right) + assert_succeed((left, left), (right, right)) + assert_succeed([left, left], [right, right]) + + def ne(self, left, right, **kwargs): + def assert_fail(left, right): + try: + self.assertPreciseEqual(left, right, **kwargs) + except AssertionError: + pass + else: + self.fail("%s and %s unexpectedly considered equal" % (left, right)) + assert_fail(left, right) + assert_fail(right, left) + assert_fail((left, left), (right, right)) + assert_fail((right, right), (left, left)) + assert_fail([left, left], [right, right]) + assert_fail([right, right], [left, left]) + + def test_types(self): + # assertPreciseEqual() should test for type compatibility + # int-like, float-like, complex-like are not compatible + for i, f, c in itertools.product(self.int_types, self.float_types, + self.complex_types): + self.ne(i(1), f(1)) + self.ne(f(1), c(1)) + self.ne(i(1), c(1)) + # int and long are compatible between each other + for u, v in itertools.product(self.int_types, self.int_types): + self.eq(u(1), v(1)) + # int and bool are not compatible between each other + for u, v in itertools.product(self.int_types, self.bool_types): + self.ne(u(1), v(1)) + # NumPy float types are not compatible between each other + for u, v in itertools.product(self.np_float_types, self.np_float_types): + if u is v: + self.eq(u(1), v(1)) + else: + self.ne(u(1), v(1)) + # NumPy complex types are not compatible between each other + for u, v in itertools.product(self.np_complex_types, self.np_complex_types): + if u is v: + self.eq(u(1), v(1)) + else: + self.ne(u(1), v(1)) + + def test_int_values(self): + for tp in self.int_types: + for prec in ['exact', 'single', 'double']: + self.eq(tp(0), tp(0), prec=prec) + self.ne(tp(0), tp(1), prec=prec) + self.ne(tp(-1), tp(1), prec=prec) + self.ne(tp(2**80), tp(1+2**80), prec=prec) + + def test_bool_values(self): + for tpa, tpb in itertools.product(self.bool_types, self.bool_types): + self.eq(tpa(True), tpb(True)) + self.eq(tpa(False), tpb(False)) + self.ne(tpa(True), tpb(False)) + + def test_abs_tol_parse(self): + # check invalid values in abs_tol kwarg raises + with self.assertRaises(ValueError): + self.eq(np.float64(1e-17), np.float64(1e-17), abs_tol="invalid") + with self.assertRaises(ValueError): + self.eq(np.float64(1), np.float64(2), abs_tol=int(7)) + + def test_float_values(self): + for tp in self.float_types: + for prec in ['exact', 'single', 'double']: + self.eq(tp(1.5), tp(1.5), prec=prec) + # Signed zeros + self.eq(tp(0.0), tp(0.0), prec=prec) + self.eq(tp(-0.0), tp(-0.0), prec=prec) + self.ne(tp(0.0), tp(-0.0), prec=prec) + self.eq(tp(0.0), tp(-0.0), prec=prec, ignore_sign_on_zero=True) + # Infinities + self.eq(tp(INF), tp(INF), prec=prec) + self.ne(tp(INF), tp(1e38), prec=prec) + self.eq(tp(-INF), tp(-INF), prec=prec) + self.ne(tp(INF), tp(-INF), prec=prec) + # NaNs + self.eq(tp(NAN), tp(NAN), prec=prec) + self.ne(tp(NAN), tp(0), prec=prec) + self.ne(tp(NAN), tp(INF), prec=prec) + self.ne(tp(NAN), tp(-INF), prec=prec) + + def test_float64_values(self): + for tp in [float, np.float64]: + self.ne(tp(1.0 + DBL_EPSILON), tp(1.0)) + + def test_float32_values(self): + tp = np.float32 + self.ne(tp(1.0 + FLT_EPSILON), tp(1.0)) + + def test_float64_values_inexact(self): + for tp in [float, np.float64]: + for scale in [1.0, -2**3, 2**-4, -2**-20]: + a = scale * 1.0 + b = scale * (1.0 + DBL_EPSILON) + c = scale * (1.0 + DBL_EPSILON * 2) + d = scale * (1.0 + DBL_EPSILON * 4) + self.ne(tp(a), tp(b)) + self.ne(tp(a), tp(b), prec='exact') + self.eq(tp(a), tp(b), prec='double') + self.eq(tp(a), tp(b), prec='double', ulps=1) + self.ne(tp(a), tp(c), prec='double') + self.eq(tp(a), tp(c), prec='double', ulps=2) + self.ne(tp(a), tp(d), prec='double', ulps=2) + self.eq(tp(a), tp(c), prec='double', ulps=3) + self.eq(tp(a), tp(d), prec='double', ulps=3) + # test absolute tolerance based on eps + self.eq(tp(1e-16), tp(3e-16), prec='double', abs_tol="eps") + self.ne(tp(1e-16), tp(4e-16), prec='double', abs_tol="eps") + # test absolute tolerance based on value + self.eq(tp(1e-17), tp(1e-18), prec='double', abs_tol=1e-17) + self.ne(tp(1e-17), tp(3e-17), prec='double', abs_tol=1e-17) + + def test_float32_values_inexact(self): + tp = np.float32 + for scale in [1.0, -2**3, 2**-4, -2**-20]: + # About the choice of 0.9: there seem to be issues when + # converting + a = scale * 1.0 + b = scale * (1.0 + FLT_EPSILON) + c = scale * (1.0 + FLT_EPSILON * 2) + d = scale * (1.0 + FLT_EPSILON * 4) + self.ne(tp(a), tp(b)) + self.ne(tp(a), tp(b), prec='exact') + self.ne(tp(a), tp(b), prec='double') + self.eq(tp(a), tp(b), prec='single') + self.ne(tp(a), tp(c), prec='single') + self.eq(tp(a), tp(c), prec='single', ulps=2) + self.ne(tp(a), tp(d), prec='single', ulps=2) + self.eq(tp(a), tp(c), prec='single', ulps=3) + self.eq(tp(a), tp(d), prec='single', ulps=3) + # test absolute tolerance based on eps + self.eq(tp(1e-7), tp(2e-7), prec='single', abs_tol="eps") + self.ne(tp(1e-7), tp(3e-7), prec='single', abs_tol="eps") + # test absolute tolerance based on value + self.eq(tp(1e-7), tp(1e-8), prec='single', abs_tol=1e-7) + self.ne(tp(1e-7), tp(3e-7), prec='single', abs_tol=1e-7) + + def test_complex_values(self): + # Complex literals with signed zeros are confusing, better use + # the explicit constructor. + c_pp, c_pn, c_np, c_nn = [complex(0.0, 0.0), complex(0.0, -0.0), + complex(-0.0, 0.0), complex(-0.0, -0.0)] + for tp in self.complex_types: + for prec in ['exact', 'single', 'double']: + self.eq(tp(1 + 2j), tp(1 + 2j), prec=prec) + self.ne(tp(1 + 1j), tp(1 + 2j), prec=prec) + self.ne(tp(2 + 2j), tp(1 + 2j), prec=prec) + # Signed zeros + self.eq(tp(c_pp), tp(c_pp), prec=prec) + self.eq(tp(c_np), tp(c_np), prec=prec) + self.eq(tp(c_nn), tp(c_nn), prec=prec) + self.ne(tp(c_pp), tp(c_pn), prec=prec) + self.ne(tp(c_pn), tp(c_nn), prec=prec) + # Infinities + self.eq(tp(complex(INF, INF)), tp(complex(INF, INF)), prec=prec) + self.eq(tp(complex(INF, -INF)), tp(complex(INF, -INF)), prec=prec) + self.eq(tp(complex(-INF, -INF)), tp(complex(-INF, -INF)), prec=prec) + self.ne(tp(complex(INF, INF)), tp(complex(INF, -INF)), prec=prec) + self.ne(tp(complex(INF, INF)), tp(complex(-INF, INF)), prec=prec) + self.eq(tp(complex(INF, 0)), tp(complex(INF, 0)), prec=prec) + # NaNs + self.eq(tp(complex(NAN, 0)), tp(complex(NAN, 0)), prec=prec) + self.eq(tp(complex(0, NAN)), tp(complex(0, NAN)), prec=prec) + self.eq(tp(complex(NAN, NAN)), tp(complex(NAN, NAN)), prec=prec) + self.eq(tp(complex(INF, NAN)), tp(complex(INF, NAN)), prec=prec) + self.eq(tp(complex(NAN, -INF)), tp(complex(NAN, -INF)), prec=prec) + # FIXME + #self.ne(tp(complex(NAN, INF)), tp(complex(NAN, -INF))) + #self.ne(tp(complex(NAN, 0)), tp(complex(NAN, 1))) + #self.ne(tp(complex(INF, NAN)), tp(complex(-INF, NAN))) + #self.ne(tp(complex(0, NAN)), tp(complex(1, NAN))) + #self.ne(tp(complex(NAN, 0)), tp(complex(0, NAN))) + # XXX should work with other precisions as well? + self.ne(tp(complex(INF, 0)), tp(complex(INF, 1)), prec='exact') + + def test_complex128_values_inexact(self): + for tp in [complex, np.complex128]: + for scale in [1.0, -2**3, 2**-4, -2**-20]: + a = scale * 1.0 + b = scale * (1.0 + DBL_EPSILON) + c = scale * (1.0 + DBL_EPSILON * 2) + aa = tp(complex(a, a)) + ab = tp(complex(a, b)) + bb = tp(complex(b, b)) + self.ne(tp(aa), tp(ab)) + self.eq(tp(aa), tp(ab), prec='double') + self.eq(tp(ab), tp(bb), prec='double') + self.eq(tp(aa), tp(bb), prec='double') + ac = tp(complex(a, c)) + cc = tp(complex(c, c)) + self.ne(tp(aa), tp(ac), prec='double') + self.ne(tp(ac), tp(cc), prec='double') + self.eq(tp(aa), tp(ac), prec='double', ulps=2) + self.eq(tp(ac), tp(cc), prec='double', ulps=2) + self.eq(tp(aa), tp(cc), prec='double', ulps=2) + self.eq(tp(aa), tp(cc), prec='single') + + def test_complex64_values_inexact(self): + tp = np.complex64 + for scale in [1.0, -2**3, 2**-4, -2**-20]: + a = scale * 1.0 + b = scale * (1.0 + FLT_EPSILON) + c = scale * (1.0 + FLT_EPSILON * 2) + aa = tp(complex(a, a)) + ab = tp(complex(a, b)) + bb = tp(complex(b, b)) + self.ne(tp(aa), tp(ab)) + self.ne(tp(aa), tp(ab), prec='double') + self.eq(tp(aa), tp(ab), prec='single') + self.eq(tp(ab), tp(bb), prec='single') + self.eq(tp(aa), tp(bb), prec='single') + ac = tp(complex(a, c)) + cc = tp(complex(c, c)) + self.ne(tp(aa), tp(ac), prec='single') + self.ne(tp(ac), tp(cc), prec='single') + self.eq(tp(aa), tp(ac), prec='single', ulps=2) + self.eq(tp(ac), tp(cc), prec='single', ulps=2) + self.eq(tp(aa), tp(cc), prec='single', ulps=2) + + def test_enums(self): + values = [Color.red, Color.green, Color.blue, Shake.mint, + Shape.circle, Shape.square, Planet.EARTH, Planet.MERCURY] + for val in values: + self.eq(val, val) + self.ne(val, val.value) + for a, b in itertools.combinations(values, 2): + self.ne(a, b) + + def test_arrays(self): + a = np.arange(1, 7, dtype=np.int16).reshape((2, 3)) + b = a.copy() + self.eq(a, b) + # Different values + self.ne(a, b + 1) + self.ne(a, b[:-1]) + self.ne(a, b.T) + # Different dtypes + self.ne(a, b.astype(np.int32)) + # Different layout + self.ne(a, b.T.copy().T) + # Different ndim + self.ne(a, b.flatten()) + # Different writeability + b.flags.writeable = False + self.ne(a, b) + # Precision + a = np.arange(1, 3, dtype=np.float64) + b = a * (1.0 + DBL_EPSILON) + c = a * (1.0 + DBL_EPSILON * 2) + self.ne(a, b) + self.eq(a, b, prec='double') + self.ne(a, c, prec='double') + + def test_npdatetime(self): + a = np.datetime64('1900', 'Y') + b = np.datetime64('1900', 'Y') + c = np.datetime64('1900-01-01', 'D') + d = np.datetime64('1901', 'Y') + self.eq(a, b) + # Different unit + self.ne(a, c) + # Different value + self.ne(a, d) + + def test_nptimedelta(self): + a = np.timedelta64(1, 'h') + b = np.timedelta64(1, 'h') + c = np.timedelta64(60, 'm') + d = np.timedelta64(2, 'h') + self.eq(a, b) + # Different unit + self.ne(a, c) + # Different value + self.ne(a, d) + + +class TestMisc(TestCase): + + def test_assertRefCount(self): + # Use objects to avoid interning + x = object() + y = object() + l = [] + with self.assertRefCount(x, y): + pass + with self.assertRaises(AssertionError) as cm: + # y gains a reference + with self.assertRefCount(x, y): + l.append(y) + self.assertIn(str(y), str(cm.exception)) + + def test_forbid_codegen(self): + """ + Test that forbid_codegen() prevents code generation using the @jit + decorator. + """ + def f(): + return 1 + with forbid_codegen(): + with self.assertRaises(RuntimeError) as raises: + cfunc = jit(nopython=True)(f) + cfunc() + self.assertIn("codegen forbidden by test case", str(raises.exception)) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_target_extension.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_target_extension.py new file mode 100644 index 0000000000000000000000000000000000000000..a78b234b81ef1fdfa258f7b4a32b0afdd01b7ba9 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_target_extension.py @@ -0,0 +1,851 @@ +"""This tests the target extension API to ensure that rudimentary expected +behaviours are present and correct. It uses a piece of fake hardware as a +target, the Dummy Processing Unit (DPU), to do this. The DPU borrows a lot from +the CPU but is part of the GPU class of target. The DPU target has deliberately +strange implementations of fundamental operations so as to make it identifiable +in testing.""" + +import unittest +from numba.tests.support import TestCase +import ctypes +import operator +from functools import cached_property +import numpy as np +from numba import njit, types +from numba.extending import (overload, overload_attribute, + overload_classmethod, intrinsic) +from numba.core.target_extension import ( + JitDecorator, + target_registry, + dispatcher_registry, + jit_registry, + target_override, + GPU, + resolve_dispatcher_from_str, +) +from numba.core import utils, fastmathpass, errors +from numba.core.dispatcher import Dispatcher +from numba.core.descriptors import TargetDescriptor +from numba.core import cpu, typing, cgutils +from numba.core.base import BaseContext +from numba.core.compiler_lock import global_compiler_lock +from numba.core import callconv +from numba.core.codegen import CPUCodegen, JITCodeLibrary +from numba.core.callwrapper import PyCallWrapper +from numba.core.imputils import RegistryLoader, Registry +from numba.core.typing.typeof import typeof +from numba import _dynfunc +import llvmlite.binding as ll +from llvmlite import ir as llir +from numba.core.runtime import rtsys + +from numba.core import compiler +from numba.core.compiler import CompilerBase, DefaultPassBuilder +from numba.core.compiler_machinery import FunctionPass, register_pass +from numba.core.typed_passes import PreLowerStripPhis + +# Define a new target, this target extends GPU, this places the DPU in the +# target hierarchy as a type of GPU. + + +class DPU(GPU): + ... + + +# register the dpu target hierarchy token in the target registry, this +# permits lookup and reference in userspace by the string "dpu" +target_registry["dpu"] = DPU + +# Create a JIT DPU codegen for the DPU target + + +class JITDPUCodegen(CPUCodegen): + # This largely rips off the CPU for ease + + _library_class = JITCodeLibrary + + def _customize_tm_options(self, options): + # Customize the target machine options. + options["cpu"] = self._get_host_cpu_name() + arch = ll.Target.from_default_triple().name + if arch.startswith("x86"): + reloc_model = "static" + elif arch.startswith("ppc"): + reloc_model = "pic" + else: + reloc_model = "default" + options["reloc"] = reloc_model + options["codemodel"] = "jitdefault" + + # Set feature attributes (such as ISA extensions) + # This overrides default feature selection by CPU model above + options["features"] = self._tm_features + + # Deal with optional argument to ll.Target.create_target_machine + sig = utils.pysignature(ll.Target.create_target_machine) + if "jit" in sig.parameters: + # Mark that this is making a JIT engine + options["jit"] = True + + def _customize_tm_features(self): + # For JIT target, we will use LLVM to get the feature map + return self._get_host_cpu_features() + + def _add_module(self, module): + self._engine.add_module(module) + + def set_env(self, env_name, env): + """Set the environment address. + + Update the GlobalVariable named *env_name* to the address of *env*. + """ + gvaddr = self._engine.get_global_value_address(env_name) + envptr = (ctypes.c_void_p * 1).from_address(gvaddr) + envptr[0] = ctypes.c_void_p(id(env)) + + +# This is the function registry for the dpu, it just has one registry, this one! +dpu_function_registry = Registry() + +# Implement a new context for the DPU target + + +class DPUContext(BaseContext): + allow_dynamic_globals = True + + # Overrides + def create_module(self, name): + return self._internal_codegen._create_empty_module(name) + + @global_compiler_lock + def init(self): + self._internal_codegen = JITDPUCodegen("numba.exec") + # Initialize NRT runtime + rtsys.initialize(self) + self.refresh() + + def refresh(self): + registry = dpu_function_registry + try: + loader = self._registries[registry] + except KeyError: + loader = RegistryLoader(registry) + self._registries[registry] = loader + self.install_registry(registry) + # Also refresh typing context, since @overload declarations can + # affect it. + self.typing_context.refresh() + + @property + def target_data(self): + return self._internal_codegen.target_data + + def codegen(self): + return self._internal_codegen + + # Borrow the CPU call conv + @cached_property + def call_conv(self): + return callconv.CPUCallConv(self) + + def get_env_body(self, builder, envptr): + """ + From the given *envptr* (a pointer to a _dynfunc.Environment object), + get a EnvBody allowing structured access to environment fields. + """ + body_ptr = cgutils.pointer_add( + builder, envptr, _dynfunc._impl_info["offsetof_env_body"] + ) + return cpu.EnvBody(self, builder, ref=body_ptr, cast_ref=True) + + def get_env_manager(self, builder): + envgv = self.declare_env_global( + builder.module, self.get_env_name(self.fndesc) + ) + envarg = builder.load(envgv) + pyapi = self.get_python_api(builder) + pyapi.emit_environment_sentry( + envarg, debug_msg=self.fndesc.env_name, + ) + env_body = self.get_env_body(builder, envarg) + return pyapi.get_env_manager(self.environment, env_body, envarg) + + def get_generator_state(self, builder, genptr, return_type): + """ + From the given *genptr* (a pointer to a _dynfunc.Generator object), + get a pointer to its state area. + """ + return cgutils.pointer_add( + builder, + genptr, + _dynfunc._impl_info["offsetof_generator_state"], + return_type=return_type, + ) + + def post_lowering(self, mod, library): + if self.fastmath: + fastmathpass.rewrite_module(mod, self.fastmath) + + library.add_linking_library(rtsys.library) + + def create_cpython_wrapper( + self, library, fndesc, env, call_helper, release_gil=False + ): + wrapper_module = self.create_module("wrapper") + fnty = self.call_conv.get_function_type(fndesc.restype, fndesc.argtypes) + wrapper_callee = llir.Function( + wrapper_module, fnty, fndesc.llvm_func_name + ) + builder = PyCallWrapper( + self, + wrapper_module, + wrapper_callee, + fndesc, + env, + call_helper=call_helper, + release_gil=release_gil, + ) + builder.build() + library.add_ir_module(wrapper_module) + + def create_cfunc_wrapper(self, library, fndesc, env, call_helper): + # There's no cfunc wrapper on the dpu + pass + + def get_executable(self, library, fndesc, env): + """ + Returns + ------- + (cfunc, fnptr) + + - cfunc + callable function (Can be None) + - fnptr + callable function address + - env + an execution environment (from _dynfunc) + """ + # Code generation + fnptr = library.get_pointer_to_function( + fndesc.llvm_cpython_wrapper_name + ) + + # Note: we avoid reusing the original docstring to avoid encoding + # issues on Python 2, see issue #1908 + doc = "compiled wrapper for %r" % (fndesc.qualname,) + cfunc = _dynfunc.make_function( + fndesc.lookup_module(), + fndesc.qualname.split(".")[-1], + doc, + fnptr, + env, + # objects to keepalive with the function + (library,), + ) + library.codegen.set_env(self.get_env_name(fndesc), env) + return cfunc + + +# Implement a DPU TargetDescriptor, this one borrows bits from the CPU +class DPUTarget(TargetDescriptor): + options = cpu.CPUTargetOptions + + @cached_property + def _toplevel_target_context(self): + # Lazily-initialized top-level target context, for all threads + return DPUContext(self.typing_context, self._target_name) + + @cached_property + def _toplevel_typing_context(self): + # Lazily-initialized top-level typing context, for all threads + return typing.Context() + + @property + def target_context(self): + """ + The target context for DPU targets. + """ + return self._toplevel_target_context + + @property + def typing_context(self): + """ + The typing context for CPU targets. + """ + return self._toplevel_typing_context + + +# Create a DPU target instance +dpu_target = DPUTarget("dpu") + + +# Declare a dispatcher for the DPU target +class DPUDispatcher(Dispatcher): + targetdescr = dpu_target + + def compile(self, sig): + with target_override('dpu'): + return super().compile(sig) + + +# Register a dispatcher for the DPU target, a lot of the code uses this +# internally to work out what to do RE compilation +dispatcher_registry[target_registry["dpu"]] = DPUDispatcher + +# Implement a dispatcher for the DPU target + + +class djit(JitDecorator): + def __init__(self, *args, **kwargs): + self._args = args + self._kwargs = kwargs + + def __call__(self, *args): + assert len(args) < 2 + if args: + func = args[0] + else: + func = self._args[0] + self.py_func = func + # wrap in dispatcher + return self.dispatcher_wrapper() + + def get_dispatcher(self): + """ + Returns the dispatcher + """ + return dispatcher_registry[target_registry["dpu"]] + + def dispatcher_wrapper(self): + disp = self.get_dispatcher() + # Parse self._kwargs here + topt = {} + if "nopython" in self._kwargs: + topt["nopython"] = True + + # It would be easy to specialise the default compilation pipeline for + # this target here. + pipeline_class = compiler.Compiler + if "pipeline_class" in self._kwargs: + pipeline_class = self._kwargs["pipeline_class"] + return disp( + py_func=self.py_func, + targetoptions=topt, + pipeline_class=pipeline_class, + ) + + +# add it to the decorator registry, this is so e.g. @overload can look up a +# JIT function to do the compilation work. +jit_registry[target_registry["dpu"]] = djit + +# The DPU target "knows" nothing, add in some primitives for basic things... + +# need to register how to lower dummy for @intrinsic + + +@dpu_function_registry.lower_constant(types.Dummy) +def constant_dummy(context, builder, ty, pyval): + return context.get_dummy_value() + + +# and how to deal with IntegerLiteral to Integer casts +@dpu_function_registry.lower_cast(types.IntegerLiteral, types.Integer) +def literal_int_to_number(context, builder, fromty, toty, val): + lit = context.get_constant_generic( + builder, fromty.literal_type, fromty.literal_value, + ) + return context.cast(builder, lit, fromty.literal_type, toty) + + +# and how to lower an Int constant +@dpu_function_registry.lower_constant(types.Integer) +def const_int(context, builder, ty, pyval): + lty = context.get_value_type(ty) + return lty(pyval) + + +# and tell the DPU how to lower a float constant +@dpu_function_registry.lower_constant(types.Float) +def const_float(context, builder, ty, pyval): + lty = context.get_value_type(ty) + return lty(pyval) + + +# The DPU actually subtracts when it's asked to 'add'! +@intrinsic(target="dpu") +def intrin_add(tyctx, x, y): + sig = x(x, y) + + def codegen(cgctx, builder, tyargs, llargs): + return builder.sub(*llargs) + + return sig, codegen + + +# Use extending.overload API to register 'add', call the dpu specific intrinsic +@overload(operator.add, target="dpu") +def ol_add(x, y): + if isinstance(x, types.Integer) and isinstance(y, types.Integer): + + def impl(x, y): + return intrin_add(x, y) + + return impl + + +class TestTargetHierarchySelection(TestCase): + """This tests that the target hierarchy is scanned in the right order, + that appropriate functions are selected based on what's available and that + the DPU target is distinctly different to the CPU""" + + def test_0_dpu_registry(self): + """Checks that the DPU registry only contains the things added + + This test must be first to execute among all tests in this file to + ensure the no lazily loaded entries are added yet. + """ + self.assertFalse(dpu_function_registry.functions) + self.assertFalse(dpu_function_registry.getattrs) + # int literal -> int cast is registered + self.assertEqual(len(dpu_function_registry.casts), 1) + # int, float and dummy constants are registered + self.assertEqual(len(dpu_function_registry.constants), 3) + + def test_specialise_gpu(self): + def my_func(x): + pass + + # Can be used by both CPU and DPU + @overload(my_func, target="generic") + def ol_my_func1(x): + def impl(x): + return 1 + x + + return impl + + # Should be used by the DPU if there's no dpu specific one + @overload(my_func, target="gpu") + def ol_my_func2(x): + def impl(x): + return 10 + x + + return impl + + @djit() + def dpu_foo(): + return my_func(7) + + @njit() + def cpu_foo(): + return my_func(7) + + # DPU chooses the ol_my_func2 as it's most specific, and DPU subtracts + # for addition, so 10 + x -> 10 - 7 -> 3 + self.assertPreciseEqual(dpu_foo(), 3) + # CPU uses the generic one function ol_my_func1 and adds + self.assertPreciseEqual(cpu_foo(), 8) + + def test_specialise_dpu(self): + def my_func(x): + pass + + # Can be used by both CPU and DPU + @overload(my_func, target="generic") + def ol_my_func1(x): + def impl(x): + return 1 + x + + return impl + + # Should be used by the DPU if there's no dpu specific one + @overload(my_func, target="gpu") + def ol_my_func2(x): + def impl(x): + return 10 + x + + return impl + + # Should be used by the DPU only + @overload(my_func, target="dpu") + def ol_my_func3(x): + def impl(x): + return 100 + x + + return impl + + @djit() + def dpu_foo(): + return my_func(7) + + @njit() + def cpu_foo(): + return my_func(7) + + # DPU chooses the ol_my_func3 as it's most specific, and DPU subtracts + # for addition, so 100 + x -> 100 - 7 -> 93 + self.assertPreciseEqual(dpu_foo(), 93) + # CPU uses the generic one function ol_my_func1 and adds + self.assertPreciseEqual(cpu_foo(), 8) + + def test_no_specialisation_found(self): + + def my_func(x): + pass + + # only create a cuda specialisation + @overload(my_func, target='cuda') + def ol_my_func_cuda(x): + return lambda x: None + + @djit(nopython=True) + def dpu_foo(): + my_func(1) + + # new style errors raise UnsupportedError, old style ends up as + # TypingError + accept = (errors.UnsupportedError, errors.TypingError) + with self.assertRaises(accept) as raises: + dpu_foo() + + msgs = ["Function resolution cannot find any matches for function", + "test_no_specialisation_found..my_func", + "for the current target:", + "'numba.tests.test_target_extension.DPU'"] + + for msg in msgs: + self.assertIn(msg, str(raises.exception)) + + def test_invalid_target_jit(self): + + with self.assertRaises(errors.NonexistentTargetError) as raises: + @njit(_target='invalid_silicon') + def foo(): + pass + + foo() + + msg = "No target is registered against 'invalid_silicon'" + self.assertIn(msg, str(raises.exception)) + + def test_invalid_target_overload(self): + + def bar(): + pass + + # This is a typing error at present as it fails during typing when the + # overloads are walked. + with self.assertRaises(errors.NonexistentTargetError) as raises: + @overload(bar, target='invalid_silicon') + def ol_bar(): + return lambda : None + + @njit + def foo(): + bar() + + foo() + + msg = "No target is registered against 'invalid_silicon'" + self.assertIn(msg, str(raises.exception)) + + def test_intrinsic_selection(self): + """ + Test to make sure that targets can share generic implementations and + cannot reach implementations that are not in their target hierarchy. + """ + + # NOTE: The actual operation performed by these functions is irrelevant + @intrinsic(target="generic") + def intrin_math_generic(tyctx, x, y): + sig = x(x, y) + + def codegen(cgctx, builder, tyargs, llargs): + return builder.mul(*llargs) + + return sig, codegen + + @intrinsic(target="dpu") + def intrin_math_dpu(tyctx, x, y): + sig = x(x, y) + + def codegen(cgctx, builder, tyargs, llargs): + return builder.sub(*llargs) + + return sig, codegen + + @intrinsic(target="cpu") + def intrin_math_cpu(tyctx, x, y): + sig = x(x, y) + + def codegen(cgctx, builder, tyargs, llargs): + return builder.add(*llargs) + + return sig, codegen + + # CPU can use the CPU version + @njit + def cpu_foo_specific(): + return intrin_math_cpu(3, 4) + + self.assertEqual(cpu_foo_specific(), 7) + + # CPU can use the 'generic' version + @njit + def cpu_foo_generic(): + return intrin_math_generic(3, 4) + + self.assertEqual(cpu_foo_generic(), 12) + + # CPU cannot use the 'dpu' version + @njit + def cpu_foo_dpu(): + return intrin_math_dpu(3, 4) + + accept = (errors.UnsupportedError, errors.TypingError) + with self.assertRaises(accept) as raises: + cpu_foo_dpu() + + msgs = ["Function resolution cannot find any matches for function", + "intrinsic intrin_math_dpu", + "for the current target",] + for msg in msgs: + self.assertIn(msg, str(raises.exception)) + + # DPU can use the DPU version + @djit(nopython=True) + def dpu_foo_specific(): + return intrin_math_dpu(3, 4) + + self.assertEqual(dpu_foo_specific(), -1) + + # DPU can use the 'generic' version + @djit(nopython=True) + def dpu_foo_generic(): + return intrin_math_generic(3, 4) + + self.assertEqual(dpu_foo_generic(), 12) + + # DPU cannot use the 'cpu' version + @djit(nopython=True) + def dpu_foo_cpu(): + return intrin_math_cpu(3, 4) + + accept = (errors.UnsupportedError, errors.TypingError) + with self.assertRaises(accept) as raises: + dpu_foo_cpu() + + msgs = ["Function resolution cannot find any matches for function", + "intrinsic intrin_math_cpu", + "for the current target",] + for msg in msgs: + self.assertIn(msg, str(raises.exception)) + + def test_overload_allocation(self): + def cast_integer(context, builder, val, fromty, toty): + # XXX Shouldn't require this. + if toty.bitwidth == fromty.bitwidth: + # Just a change of signedness + return val + elif toty.bitwidth < fromty.bitwidth: + # Downcast + return builder.trunc(val, context.get_value_type(toty)) + elif fromty.signed: + # Signed upcast + return builder.sext(val, context.get_value_type(toty)) + else: + # Unsigned upcast + return builder.zext(val, context.get_value_type(toty)) + + @intrinsic(target='dpu') + def intrin_alloc(typingctx, allocsize, align): + """Intrinsic to call into the allocator for Array + """ + def codegen(context, builder, signature, args): + [allocsize, align] = args + + # XXX: error are being eaten. + # example: replace the next line with `align_u32 = align` + align_u32 = cast_integer(context, builder, align, + signature.args[1], types.uint32) + meminfo = context.nrt.meminfo_alloc_aligned(builder, allocsize, + align_u32) + return meminfo + + from numba.core.typing import signature + mip = types.MemInfoPointer(types.voidptr) # return untyped pointer + sig = signature(mip, allocsize, align) + return sig, codegen + + @overload_classmethod(types.Array, '_allocate', target='dpu', + jit_options={'nopython':True}) + def _ol_arr_allocate_dpu(cls, allocsize, align): + def impl(cls, allocsize, align): + return intrin_alloc(allocsize, align) + return impl + + @overload(np.empty, target='dpu', jit_options={'nopython':True}) + def ol_empty_impl(n): + def impl(n): + return types.Array._allocate(n, 7) + return impl + + def buffer_func(): + pass + + @overload(buffer_func, target='dpu', jit_options={'nopython':True}) + def ol_buffer_func_impl(): + def impl(): + return np.empty(10) + return impl + + from numba.core.target_extension import target_override + + # XXX: this should probably go inside the dispatcher + with target_override('dpu'): + @djit(nopython=True) + def foo(): + return buffer_func() + r = foo() + from numba.core.runtime import nrt + self.assertIsInstance(r, nrt.MemInfo) + + def test_overload_attribute_target(self): + MyDummy, MyDummyType = self.make_dummy_type() + mydummy_type = typeof(MyDummy()) + + @overload_attribute(MyDummyType, 'dpu_only', target='dpu') + def ov_dummy_dpu_attr(obj): + def imp(obj): + return 42 + + return imp + + # Ensure that we cannot use the DPU target-specific attribute on the + # CPU, and that an appropriate typing error is raised + with self.assertRaisesRegex(errors.TypingError, + "Unknown attribute 'dpu_only'"): + @njit(types.int64(mydummy_type)) + def illegal_target_attr_use(x): + return x.dpu_only + + # Ensure that the DPU target-specific attribute is usable and works + # correctly when the target is DPU - note eager compilation via + # signature + @djit(types.void(types.int64[::1], mydummy_type)) + def cuda_target_attr_use(res, dummy): + res[0] = dummy.dpu_only + + +class TestTargetOffload(TestCase): + """In this use case the CPU compilation pipeline is extended with a new + compilation pass that runs just prior to lowering. The pass looks for + function calls and when it finds one it sees if there's a DPU function + available that is a valid overload for the function call. If there is one + then it swaps the CPU implementation out for a DPU implementation. This + producing an "offload" effect. + """ + + def test_basic_offload(self): + + _DEBUG = False + + # This is the DPU function for sin, it'll return a pi-like constant + @overload(np.sin, target="dpu") + def ol_np_sin_DPU(x): + def dpu_sin_impl(x): + return 314159.0 + + return dpu_sin_impl + + # Check the DPU reports the correct overload value + @djit(nopython=True) + def foo(x): + return np.sin(x) + + self.assertPreciseEqual(foo(5), 314159.0) + + # Check the CPU call is correct + + @njit + def foo(x): + return np.sin(x) + + self.assertPreciseEqual(foo(5), np.sin(5)) + + @register_pass(mutates_CFG=False, analysis_only=False) + class DispatcherSwitcher(FunctionPass): + _name = "DispatcherSwitcher" + + def __init__(self): + FunctionPass.__init__(self) + + def run_pass(self, state): + func_ir = state.func_ir + mutated = False + for blk in func_ir.blocks.values(): + # find the assignment nodes in the block and walk them, if + # there's a DPU version then swap out for a call to that + for call in blk.find_exprs("call"): + function = state.typemap[call.func.name] + tname = "dpu" + + # Note: `target_override` context driven compilation can + # be done here, the DPU target is in use. + with target_override(tname): + try: + sig = function.get_call_type( + state.typingctx, + state.calltypes[call].args, + {}, + ) + disp = resolve_dispatcher_from_str(tname) + # force compile check + hw_ctx = disp.targetdescr.target_context + hw_ctx.get_function(function, sig) + except Exception as e: + if _DEBUG: + msg = ( + f"Failed to find and compile an " + f"overload for {function} for {tname} " + f"due to {e}" + ) + print(msg) + continue + + # This is a necessary hack at present so as to + # generate code into the same library. I.e. the DPU + # target is going to do code gen into the CPUs lib. + hw_ctx._codelib_stack = ( + state.targetctx._codelib_stack + ) + + # All is good, so switch IR node for one targeting + # this target. Should generate this, but for now + # just mutate as: + # ir.Expr.call(call.func, call.args, call.kws, + # call.loc, target='dpu') + call.target = tname + mutated = True + # return True if the IR was mutated, False if not. + return mutated + + # DPU compiler pipeline, compiles with offload to the DPU target + class DPUOffloadCompiler(CompilerBase): + def define_pipelines(self): + pm = DefaultPassBuilder.define_nopython_pipeline(self.state) + pm.add_pass_after(DispatcherSwitcher, PreLowerStripPhis) + pm.finalize() + return [pm] + + # Now compile for CPU, but with the DispatcherSwitcher pass in place + # that switches CPU calls for DPU calls + @njit(pipeline_class=DPUOffloadCompiler) + def foo(x): + return np.sin(x), np.cos(x) # np.sin is DPU, np.cos is CPU + + self.assertPreciseEqual(foo(5), (314159.0, np.cos(5))) + + +if __name__ == "__main__": + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_typeconv.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_typeconv.py new file mode 100644 index 0000000000000000000000000000000000000000..4042542b65b8e210f83134ee46959c650715a0da --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_typeconv.py @@ -0,0 +1,295 @@ +import itertools + +from numba.core import types +from numba.core.typeconv.typeconv import TypeManager, TypeCastingRules +from numba.core.typeconv import rules +from numba.core.typeconv import castgraph, Conversion +import unittest + + +class CompatibilityTestMixin(unittest.TestCase): + + def check_number_compatibility(self, check_compatible): + b = types.boolean + i8 = types.int8 + i16 = types.int16 + i32 = types.int32 + i64 = types.int64 + u8 = types.uint8 + u16 = types.uint16 + u32 = types.uint32 + u64 = types.uint64 + f16 = types.float16 + f32 = types.float32 + f64 = types.float64 + c64 = types.complex64 + c128 = types.complex128 + + self.assertEqual(check_compatible(i32, i32), Conversion.exact) + + self.assertEqual(check_compatible(b, i8), Conversion.safe) + self.assertEqual(check_compatible(b, u8), Conversion.safe) + self.assertEqual(check_compatible(i8, b), Conversion.unsafe) + self.assertEqual(check_compatible(u8, b), Conversion.unsafe) + + self.assertEqual(check_compatible(i32, i64), Conversion.promote) + self.assertEqual(check_compatible(i32, u32), Conversion.unsafe) + self.assertEqual(check_compatible(u32, i32), Conversion.unsafe) + self.assertEqual(check_compatible(u32, i64), Conversion.safe) + + self.assertEqual(check_compatible(i16, f16), Conversion.unsafe) + self.assertEqual(check_compatible(i32, f32), Conversion.unsafe) + self.assertEqual(check_compatible(u32, f32), Conversion.unsafe) + self.assertEqual(check_compatible(i32, f64), Conversion.safe) + self.assertEqual(check_compatible(u32, f64), Conversion.safe) + # Note this is inconsistent with i32 -> f32... + self.assertEqual(check_compatible(i64, f64), Conversion.safe) + self.assertEqual(check_compatible(u64, f64), Conversion.safe) + + self.assertEqual(check_compatible(f32, c64), Conversion.safe) + self.assertEqual(check_compatible(f64, c128), Conversion.safe) + self.assertEqual(check_compatible(f64, c64), Conversion.unsafe) + + # Propagated compatibility relationships + self.assertEqual(check_compatible(i16, f64), Conversion.safe) + self.assertEqual(check_compatible(i16, i64), Conversion.promote) + self.assertEqual(check_compatible(i32, c64), Conversion.unsafe) + self.assertEqual(check_compatible(i32, c128), Conversion.safe) + self.assertEqual(check_compatible(i32, u64), Conversion.unsafe) + + for ta, tb in itertools.product(types.number_domain, + types.number_domain): + if ta in types.complex_domain and tb not in types.complex_domain: + continue + self.assertTrue(check_compatible(ta, tb) is not None, + msg="No cast from %s to %s" % (ta, tb)) + + +class TestTypeConv(CompatibilityTestMixin, unittest.TestCase): + + def test_typeconv(self): + tm = TypeManager() + + i32 = types.int32 + i64 = types.int64 + f32 = types.float32 + + tm.set_promote(i32, i64) + tm.set_unsafe_convert(i32, f32) + + sig = (i32, f32) + ovs = [ + (i32, i32), + (f32, f32), + (i64, i64), + ] + + # allow_unsafe = True => a conversion from i32 to f32 is chosen + sel = tm.select_overload(sig, ovs, True, False) + self.assertEqual(sel, 1) + # allow_unsafe = False => no overload available + with self.assertRaises(TypeError): + sel = tm.select_overload(sig, ovs, False, False) + + def test_default_rules(self): + tm = rules.default_type_manager + self.check_number_compatibility(tm.check_compatible) + + def test_overload1(self): + tm = rules.default_type_manager + + i32 = types.int32 + i64 = types.int64 + + sig = (i64, i32, i32) + ovs = [ + (i32, i32, i32), + (i64, i64, i64), + ] + # The first overload is unsafe, the second is safe => the second + # is always chosen, regardless of allow_unsafe. + self.assertEqual(tm.select_overload(sig, ovs, True, False), 1) + self.assertEqual(tm.select_overload(sig, ovs, False, False), 1) + + def test_overload2(self): + tm = rules.default_type_manager + + i16 = types.int16 + i32 = types.int32 + i64 = types.int64 + + sig = (i32, i16, i32) + ovs = [ + # Three promotes + (i64, i64, i64), + # One promotes, two exact types + (i32, i32, i32), + # Two unsafe converts, one exact type + (i16, i16, i16), + ] + self.assertEqual(tm.select_overload(sig, ovs, allow_unsafe=False, + exact_match_required=False), 1) + self.assertEqual(tm.select_overload(sig, ovs, allow_unsafe=True, + exact_match_required=False), 1) + + # The same in reverse order + ovs.reverse() + self.assertEqual(tm.select_overload(sig, ovs, allow_unsafe=False, + exact_match_required=False), 1) + self.assertEqual(tm.select_overload(sig, ovs, allow_unsafe=True, + exact_match_required=False), 1) + + def test_overload3(self): + # Promotes should be preferred over safe converts + tm = rules.default_type_manager + + i32 = types.int32 + i64 = types.int64 + f64 = types.float64 + + sig = (i32, i32) + ovs = [ + # Two promotes + (i64, i64), + # Two safe converts + (f64, f64), + ] + self.assertEqual(tm.select_overload(sig, ovs, allow_unsafe=False, + exact_match_required=False), 0) + self.assertEqual(tm.select_overload(sig, ovs, allow_unsafe=True, + exact_match_required=False), 0) + + # The same in reverse order + ovs.reverse() + self.assertEqual(tm.select_overload(sig, ovs, allow_unsafe=False, + exact_match_required=False), 1) + self.assertEqual(tm.select_overload(sig, ovs, allow_unsafe=True, + exact_match_required=False), 1) + + def test_overload4(self): + tm = rules.default_type_manager + + i16 = types.int16 + i32 = types.int32 + i64 = types.int64 + f16 = types.float16 + f32 = types.float32 + + sig = (i16, f16, f16) + ovs = [ + # One unsafe, one promote, one exact + (f16, f32, f16), + # Two unsafe, one exact types + (f32, i32, f16), + ] + + self.assertEqual(tm.select_overload(sig, ovs, allow_unsafe=True, + exact_match_required=False), 0) + + def test_type_casting_rules(self): + tm = TypeManager() + tcr = TypeCastingRules(tm) + + i16 = types.int16 + i32 = types.int32 + i64 = types.int64 + f64 = types.float64 + f32 = types.float32 + f16 = types.float16 + made_up = types.Dummy("made_up") + + tcr.promote_unsafe(i32, i64) + tcr.safe_unsafe(i32, f64) + tcr.promote_unsafe(f32, f64) + tcr.promote_unsafe(f16, f32) + tcr.unsafe_unsafe(i16, f16) + + def base_test(): + # As declared + self.assertEqual(tm.check_compatible(i32, i64), Conversion.promote) + self.assertEqual(tm.check_compatible(i32, f64), Conversion.safe) + self.assertEqual(tm.check_compatible(f16, f32), Conversion.promote) + self.assertEqual(tm.check_compatible(f32, f64), Conversion.promote) + self.assertEqual(tm.check_compatible(i64, i32), Conversion.unsafe) + self.assertEqual(tm.check_compatible(f64, i32), Conversion.unsafe) + self.assertEqual(tm.check_compatible(f64, f32), Conversion.unsafe) + + # Propagated + self.assertEqual(tm.check_compatible(i64, f64), Conversion.unsafe) + self.assertEqual(tm.check_compatible(f64, i64), Conversion.unsafe) + self.assertEqual(tm.check_compatible(i64, f32), Conversion.unsafe) + self.assertEqual(tm.check_compatible(i32, f32), Conversion.unsafe) + self.assertEqual(tm.check_compatible(f32, i32), Conversion.unsafe) + self.assertEqual(tm.check_compatible(i16, f16), Conversion.unsafe) + self.assertEqual(tm.check_compatible(f16, i16), Conversion.unsafe) + + # Test base graph + base_test() + + self.assertIsNone(tm.check_compatible(i64, made_up)) + self.assertIsNone(tm.check_compatible(i32, made_up)) + self.assertIsNone(tm.check_compatible(f32, made_up)) + self.assertIsNone(tm.check_compatible(made_up, f64)) + self.assertIsNone(tm.check_compatible(made_up, i64)) + + # Add new test + tcr.promote(f64, made_up) + tcr.unsafe(made_up, i32) + + # Ensure the graph did not change by adding the new type + base_test() + + # To "made up" type + self.assertEqual(tm.check_compatible(i64, made_up), Conversion.unsafe) + self.assertEqual(tm.check_compatible(i32, made_up), Conversion.safe) + self.assertEqual(tm.check_compatible(f32, made_up), Conversion.promote) + self.assertEqual(tm.check_compatible(made_up, f64), Conversion.unsafe) + self.assertEqual(tm.check_compatible(made_up, i64), Conversion.unsafe) + + def test_castgraph_propagate(self): + saved = [] + + def callback(src, dst, rel): + saved.append((src, dst, rel)) + + tg = castgraph.TypeGraph(callback) + + i32 = types.int32 + i64 = types.int64 + f64 = types.float64 + f32 = types.float32 + + tg.insert_rule(i32, i64, Conversion.promote) + tg.insert_rule(i64, i32, Conversion.unsafe) + + saved.append(None) + + tg.insert_rule(i32, f64, Conversion.safe) + tg.insert_rule(f64, i32, Conversion.unsafe) + + saved.append(None) + + tg.insert_rule(f32, f64, Conversion.promote) + tg.insert_rule(f64, f32, Conversion.unsafe) + + self.assertIn((i32, i64, Conversion.promote), saved[0:2]) + self.assertIn((i64, i32, Conversion.unsafe), saved[0:2]) + self.assertIs(saved[2], None) + + self.assertIn((i32, f64, Conversion.safe), saved[3:7]) + self.assertIn((f64, i32, Conversion.unsafe), saved[3:7]) + self.assertIn((i64, f64, Conversion.unsafe), saved[3:7]) + self.assertIn((i64, f64, Conversion.unsafe), saved[3:7]) + self.assertIs(saved[7], None) + + self.assertIn((f32, f64, Conversion.promote), saved[8:14]) + self.assertIn((f64, f32, Conversion.unsafe), saved[8:14]) + self.assertIn((f32, i32, Conversion.unsafe), saved[8:14]) + self.assertIn((i32, f32, Conversion.unsafe), saved[8:14]) + self.assertIn((f32, i64, Conversion.unsafe), saved[8:14]) + self.assertIn((i64, f32, Conversion.unsafe), saved[8:14]) + self.assertEqual(len(saved[14:]), 0) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_typeguard.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_typeguard.py new file mode 100644 index 0000000000000000000000000000000000000000..37ab82dd8fc321fe560b87ed10f62fcfba36b277 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_typeguard.py @@ -0,0 +1,44 @@ +""" +Tests to ensure that typeguard is working as expected. +This mostly contains negative tests as proof that typeguard can catch errors. +""" +import unittest +from numba.tests.support import TestCase, skip_unless_typeguard + + +def guard_args(val: int): + return + + +def guard_ret(val) -> int: + return val + + +@skip_unless_typeguard +class TestTypeGuard(TestCase): + + def setUp(self): + super().setUp() + import typeguard + # This is a test class invariant but the Numba multiprocesses test + # runner doesn't respect `setUpClass` so just use `setUp`. + # typeguard 3+ uses typeguard.TypeCheckError, 2.x uses TypeError + self._exception_type = getattr(typeguard, 'TypeCheckError', TypeError) + + def test_check_args(self): + with self.assertRaises(self._exception_type): + guard_args(float(1.2)) + + def test_check_ret(self): + with self.assertRaises(self._exception_type): + guard_ret(float(1.2)) + + def test_check_does_not_work_with_inner_func(self): + def guard(val: int) -> int: + return + + guard(float(1.2)) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_typeof.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_typeof.py new file mode 100644 index 0000000000000000000000000000000000000000..077af16966037a3edb15f29ad91753669e32e6b9 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_typeof.py @@ -0,0 +1,601 @@ +""" +Tests for the typeof() machinery. +""" +import array +from collections import namedtuple +import enum +import mmap +import typing as py_typing +import random +import string + +import numpy as np + +import unittest +from numba import jit, _dispatcher +from numba.core import types +from numba.core.errors import NumbaValueError, NumbaTypeError +from numba.misc.special import typeof +from numba.core.dispatcher import OmittedArg +from numba._dispatcher import compute_fingerprint + +from numba.tests.support import TestCase, skip_unless_cffi, tag +from numba.tests.test_numpy_support import ValueTypingTestBase +from numba.tests.ctypes_usecases import * +from numba.tests.enum_usecases import * +from numba.np import numpy_support + + +recordtype = np.dtype([('a', np.float64), + ('b', np.int32), + ('c', np.complex64), + ('d', (np.str_, 5))]) + +recordtype2 = np.dtype([('e', np.int8), + ('f', np.float64)]) + +recordtype3 = np.dtype([('e', np.int8), + ('f', np.float64)], align=True) + +Point = namedtuple('Point', ('x', 'y')) + +Rect = namedtuple('Rect', ('width', 'height')) + + +class Custom(object): + + @property + def _numba_type_(self): + """ + Magic attribute expected by Numba to get the numba type that + represents this object. + """ + return types.UniTuple(types.boolean, 42) + + +class TestTypeof(ValueTypingTestBase, TestCase): + """ + Test typeof() and, implicitly, typing.Context.get_argument_type(). + """ + + def test_number_values(self): + """ + Test special.typeof() with scalar number values. + """ + self.check_number_values(typeof) + # These values mirror Dispatcher semantics + self.assertEqual(typeof(1), types.intp) + self.assertEqual(typeof(-1), types.intp) + self.assertEqual(typeof(2**40), types.int64) + self.assertEqual(typeof(2**63), types.uint64) + self.assertEqual(typeof(2**63 - 1), types.int64) + self.assertEqual(typeof(-2**63), types.int64) + + def test_datetime_values(self): + """ + Test special.typeof() with np.timedelta64 values. + """ + self.check_datetime_values(typeof) + + def test_timedelta_values(self): + """ + Test special.typeof() with np.timedelta64 values. + """ + self.check_timedelta_values(typeof) + + def test_array_values(self): + """ + Test special.typeof() with ndarray values. + """ + def check(arr, ndim, layout, mutable, aligned): + ty = typeof(arr) + self.assertIsInstance(ty, types.Array) + self.assertEqual(ty.ndim, ndim) + self.assertEqual(ty.layout, layout) + self.assertEqual(ty.mutable, mutable) + self.assertEqual(ty.aligned, aligned) + + a1 = np.arange(10) + check(a1, 1, 'C', True, True) + a2 = np.arange(10).reshape(2, 5) + check(a2, 2, 'C', True, True) + check(a2.T, 2, 'F', True, True) + a3 = (np.arange(60))[::2].reshape((2, 5, 3)) + check(a3, 3, 'A', True, True) + a4 = np.arange(1).reshape(()) + check(a4, 0, 'C', True, True) + a4.flags.writeable = False + check(a4, 0, 'C', False, True) + + # Unsupported dtype + a5 = a1.astype(a1.dtype.newbyteorder()) + with self.assertRaises(NumbaValueError) as raises: + typeof(a5) + self.assertIn("Unsupported array dtype: %s" % (a5.dtype,), + str(raises.exception)) + + # Unsupported array type (masked array) + with self.assertRaises(NumbaTypeError) as raises: + masked_arr = np.ma.MaskedArray([1]) + typeof(masked_arr) + self.assertIn(f"Unsupported array type: numpy.ma.MaskedArray", + str(raises.exception)) + + def test_structured_arrays(self): + def check(arr, dtype, ndim, layout, aligned): + ty = typeof(arr) + self.assertIsInstance(ty, types.Array) + self.assertEqual(ty.dtype, dtype) + self.assertEqual(ty.ndim, ndim) + self.assertEqual(ty.layout, layout) + self.assertEqual(ty.aligned, aligned) + + dtype = np.dtype([('m', np.int32), ('n', 'S5')]) + rec_ty = numpy_support.from_struct_dtype(dtype) + + arr = np.empty(4, dtype=dtype) + check(arr, rec_ty, 1, "C", False) + arr = np.recarray(4, dtype=dtype) + check(arr, rec_ty, 1, "C", False) + + dtype = np.dtype([('m', np.int32), ('n', 'S5')], align=True) + rec_ty = numpy_support.from_struct_dtype(dtype) + + arr = np.empty(4, dtype=dtype) + check(arr, rec_ty, 1, "C", True) + arr = np.recarray(4, dtype=dtype) + check(arr, rec_ty, 1, "C", True) + + def test_buffers(self): + b = b"xx" + ty = typeof(b) + self.assertEqual(ty, types.Bytes(types.uint8, 1, "C")) + self.assertFalse(ty.mutable) + ty = typeof(memoryview(b)) + self.assertEqual(ty, types.MemoryView(types.uint8, 1, "C", + readonly=True)) + self.assertFalse(ty.mutable) + ty = typeof(array.array('i', [0, 1, 2])) + self.assertEqual(ty, types.PyArray(types.int32, 1, "C")) + self.assertTrue(ty.mutable) + + b = bytearray(10) + ty = typeof(b) + self.assertEqual(ty, types.ByteArray(types.uint8, 1, "C")) + self.assertTrue(ty.mutable) + + def test_none(self): + ty = typeof(None) + self.assertEqual(ty, types.none) + + def test_ellipsis(self): + ty = typeof(Ellipsis) + self.assertEqual(ty, types.ellipsis) + + def test_str(self): + ty = typeof("abc") + self.assertEqual(ty, types.string) + + def test_slices(self): + for args in [(1,), (1, 2), (1, 2, 1), (1, 2, None)]: + v = slice(*args) + self.assertIs(typeof(v), types.slice2_type) + for args in [(1, 2, 2), (1, 2, -1), (None, None, -2)]: + v = slice(*args) + self.assertIs(typeof(v), types.slice3_type) + + def test_tuples(self): + v = (1, 2) + self.assertEqual(typeof(v), types.UniTuple(types.intp, 2)) + v = (1, (2.0, 3)) + self.assertEqual(typeof(v), + types.Tuple((types.intp, + types.Tuple((types.float64, types.intp)))) + ) + + def test_lists(self): + v = [1.0] * 100 + self.assertEqual(typeof(v), types.List(types.float64, reflected=True)) + + bad_v = [{1: 3}] + with self.assertRaises(ValueError) as raises: + typeof(bad_v) + self.assertIn("Cannot type list element type", str(raises.exception)) + + def test_sets(self): + v = set([1.0, 2.0, 3.0]) + self.assertEqual(typeof(v), types.Set(types.float64, reflected=True)) + v = frozenset(v) + with self.assertRaises(ValueError) as raises: + typeof(v) + self.assertIn("Cannot determine Numba type of", str(raises.exception)) + + def test_namedtuple(self): + v = Point(1, 2) + tp_point = typeof(v) + self.assertEqual(tp_point, + types.NamedUniTuple(types.intp, 2, Point)) + v = Point(1, 2.0) + self.assertEqual(typeof(v), + types.NamedTuple([types.intp, types.float64], Point)) + w = Rect(3, 4) + tp_rect = typeof(w) + self.assertEqual(tp_rect, + types.NamedUniTuple(types.intp, 2, Rect)) + self.assertNotEqual(tp_rect, tp_point) + self.assertNotEqual(tp_rect, types.UniTuple(tp_rect.dtype, tp_rect.count)) + + def test_enum(self): + tp_red = typeof(Color.red) + self.assertEqual(tp_red, types.EnumMember(Color, types.intp)) + self.assertEqual(tp_red, typeof(Color.blue)) + tp_choc = typeof(Shake.chocolate) + self.assertEqual(tp_choc, types.EnumMember(Shake, types.intp)) + self.assertEqual(tp_choc, typeof(Shake.mint)) + self.assertNotEqual(tp_choc, tp_red) + tp_404 = typeof(RequestError.not_found) + self.assertEqual(tp_404, types.IntEnumMember(RequestError, types.intp)) + self.assertEqual(tp_404, typeof(RequestError.internal_error)) + + with self.assertRaises(ValueError) as raises: + typeof(HeterogeneousEnum.red) + self.assertEqual(str(raises.exception), + "Cannot type heterogeneous enum: got value types complex128, float64") + + def test_enum_class(self): + tp_color = typeof(Color) + self.assertEqual(tp_color, types.EnumClass(Color, types.intp)) + tp_shake = typeof(Shake) + self.assertEqual(tp_shake, types.EnumClass(Shake, types.intp)) + self.assertNotEqual(tp_shake, tp_color) + tp_shape = typeof(Shape) + self.assertEqual(tp_shape, types.IntEnumClass(Shape, types.intp)) + tp_error = typeof(RequestError) + self.assertEqual(tp_error, + types.IntEnumClass(RequestError, types.intp)) + self.assertNotEqual(tp_error, tp_shape) + + with self.assertRaises(ValueError) as raises: + typeof(HeterogeneousEnum) + self.assertEqual(str(raises.exception), + "Cannot type heterogeneous enum: got value types complex128, float64") + + def test_dtype(self): + dtype = np.dtype('int64') + self.assertEqual(typeof(dtype), types.DType(types.int64)) + + dtype = np.dtype([('m', np.int32), ('n', 'S5')]) + rec_ty = numpy_support.from_struct_dtype(dtype) + self.assertEqual(typeof(dtype), types.DType(rec_ty)) + + def test_dtype_values(self): + self.assertEqual(typeof(np.int64), types.NumberClass(types.int64)) + self.assertEqual(typeof(np.float64), types.NumberClass(types.float64)) + self.assertEqual(typeof(np.int32), types.NumberClass(types.int32)) + self.assertEqual(typeof(np.int8), types.NumberClass(types.int8)) + + def test_ctypes(self): + ty_cos = typeof(c_cos) + ty_sin = typeof(c_sin) + self.assertIsInstance(ty_cos, types.ExternalFunctionPointer) + self.assertEqual(ty_cos.sig.args, (types.float64,)) + self.assertEqual(ty_cos.sig.return_type, types.float64) + self.assertEqual(ty_cos, ty_sin) + self.assertNotEqual(ty_cos.get_pointer(c_cos), + ty_sin.get_pointer(c_sin)) + + @skip_unless_cffi + def test_cffi(self): + from numba.tests import cffi_usecases as mod + mod.init() + ty_cffi_cos = typeof(mod.cffi_cos) + ty_cffi_sin = typeof(mod.cffi_sin) + ty_cffi_boolean = typeof(mod.cffi_bool) + self.assertIsInstance(ty_cffi_cos, types.ExternalFunctionPointer) + self.assertEqual(ty_cffi_boolean.sig.return_type, types.boolean) + self.assertEqual(ty_cffi_cos.sig.args, (types.float64,)) + self.assertEqual(ty_cffi_cos.sig.return_type, types.float64) + self.assertEqual(ty_cffi_cos, ty_cffi_sin) + ty_ctypes_cos = typeof(c_cos) + self.assertNotEqual(ty_cffi_cos, ty_ctypes_cos) + self.assertNotEqual(ty_cffi_cos.get_pointer(mod.cffi_cos), + ty_cffi_sin.get_pointer(mod.cffi_sin)) + self.assertEqual(ty_cffi_cos.get_pointer(mod.cffi_cos), + ty_ctypes_cos.get_pointer(c_cos)) + + def test_custom(self): + ty = typeof(Custom()) + self.assertEqual(ty, types.UniTuple(types.boolean, 42)) + + def test_omitted_args(self): + ty0 = typeof(OmittedArg(0.0)) + ty1 = typeof(OmittedArg(1)) + ty2 = typeof(OmittedArg(1.0)) + ty3 = typeof(OmittedArg(1.0)) + self.assertEqual(ty0, types.Omitted(0.0)) + self.assertEqual(ty1, types.Omitted(1)) + self.assertEqual(ty2, types.Omitted(1.0)) + self.assertEqual(len({ty0, ty1, ty2}), 3) + self.assertEqual(ty3, ty2) + + def test_np_random(self): + rng = np.random.default_rng() + ty_rng = typeof(rng) + ty_bitgen = typeof(rng.bit_generator) + + self.assertEqual(ty_rng, types.npy_rng) + self.assertEqual(ty_bitgen, types.npy_bitgen) + + +class DistinctChecker(object): + + def __init__(self): + self._distinct = set() + + def add(self, obj): + if obj in self._distinct: + raise AssertionError("%r already in %r" % (obj, self._distinct)) + self._distinct.add(obj) + + +class TestFingerprint(TestCase): + """ + Tests for _dispatcher.compute_fingerprint() + + Each fingerprint must denote values of only one Numba type (this is + the condition for correctness), but values of a Numba type may be + denoted by several distinct fingerprints (it only makes the cache + less efficient). + """ + + def test_floats(self): + s = compute_fingerprint(1.0) + self.assertEqual(compute_fingerprint(2.0), s) + s = compute_fingerprint(np.float32()) + self.assertEqual(compute_fingerprint(np.float32(2.0)), s) + self.assertNotEqual(compute_fingerprint(np.float64()), s) + + def test_ints(self): + s = compute_fingerprint(1) + for v in (-1, 2**60): + self.assertEqual(compute_fingerprint(v), s) + # Different int widths resolve to different fingerprints + distinct = set() + for tp in ('int8', 'int16', 'int32', 'int64', + 'uint8', 'uint16', 'uint32', 'uint64'): + tp = getattr(np, tp) + distinct.add(compute_fingerprint(tp())) + self.assertEqual(len(distinct), 8, distinct) + + def test_bool(self): + s = compute_fingerprint(True) + self.assertEqual(compute_fingerprint(False), s) + self.assertNotEqual(compute_fingerprint(1), s) + + def test_complex(self): + s = compute_fingerprint(1j) + self.assertEqual(s, compute_fingerprint(1+0j)) + s = compute_fingerprint(np.complex64()) + self.assertEqual(compute_fingerprint(np.complex64(2.0)), s) + self.assertNotEqual(compute_fingerprint(np.complex128()), s) + + def test_none(self): + compute_fingerprint(None) + + def test_enums(self): + # Enums should fail fingerprinting, even IntEnums + with self.assertRaises(NotImplementedError): + compute_fingerprint(Color.red) + with self.assertRaises(NotImplementedError): + compute_fingerprint(RequestError.not_found) + + def test_records(self): + d1 = np.dtype([('m', np.int32), ('n', np.int64)]) + d2 = np.dtype([('m', np.int32), ('n', np.int16)]) + v1 = np.empty(1, dtype=d1)[0] + v2 = np.empty(1, dtype=d2)[0] + self.assertNotEqual(compute_fingerprint(v1), + compute_fingerprint(v2)) + + def test_datetime(self): + a = np.datetime64(1, 'Y') + b = np.datetime64(2, 'Y') + c = np.datetime64(2, 's') + d = np.timedelta64(2, 's') + self.assertEqual(compute_fingerprint(a), + compute_fingerprint(b)) + distinct = set(compute_fingerprint(x) for x in (a, c, d)) + self.assertEqual(len(distinct), 3, distinct) + + def test_arrays(self): + distinct = DistinctChecker() + + # 1D + arr = np.empty(4, dtype=np.float64) + s = compute_fingerprint(arr) + distinct.add(s) + self.assertEqual(compute_fingerprint(arr[:1]), s) + # Non-contiguous + distinct.add(compute_fingerprint(arr[::2])) + # Other type + distinct.add(compute_fingerprint(arr.astype(np.complex64))) + # Readonly + arr.setflags(write=False) + distinct.add(compute_fingerprint(arr)) + + # 2D + arr = np.empty((4, 4), dtype=np.float64) + distinct.add(compute_fingerprint(arr)) + # F-contiguous + distinct.add(compute_fingerprint(arr.T)) + # Non-contiguous + distinct.add(compute_fingerprint(arr[::2])) + + # 0D + arr = np.empty((), dtype=np.float64) + distinct.add(compute_fingerprint(arr)) + + # Structured arrays + arr = np.empty(5, dtype=recordtype) + s = compute_fingerprint(arr) + distinct.add(s) + self.assertEqual(compute_fingerprint(arr[:1]), s) + arr = np.empty(5, dtype=recordtype2) + distinct.add(compute_fingerprint(arr)) + arr = np.empty(5, dtype=recordtype3) + distinct.add(compute_fingerprint(arr)) + + # np.recarray() is peculiar: it creates a new dtype instance in + # its constructor; check that the fingerprint remains efficient + a = np.recarray(1, dtype=recordtype) + b = np.recarray(1, dtype=recordtype) + self.assertEqual(compute_fingerprint(a), + compute_fingerprint(b)) + + def test_buffers(self): + distinct = DistinctChecker() + + s = compute_fingerprint(b'') + self.assertEqual(compute_fingerprint(b'xx'), s) + distinct.add(s) + distinct.add(compute_fingerprint(bytearray())) + distinct.add(compute_fingerprint(memoryview(b''))) + m_uint8_1d = compute_fingerprint(memoryview(bytearray())) + distinct.add(m_uint8_1d) + + arr = array.array('B', [42]) + distinct.add(compute_fingerprint(arr)) + self.assertEqual(compute_fingerprint(memoryview(arr)), m_uint8_1d) + for array_code in 'bi': + arr = array.array(array_code, [0, 1, 2]) + distinct.add(compute_fingerprint(arr)) + distinct.add(compute_fingerprint(memoryview(arr))) + + arr = np.empty(16, dtype=np.uint8) + distinct.add(compute_fingerprint(arr)) + self.assertEqual(compute_fingerprint(memoryview(arr)), m_uint8_1d) + arr = arr.reshape((4, 4)) + distinct.add(compute_fingerprint(arr)) + distinct.add(compute_fingerprint(memoryview(arr))) + arr = arr.T + distinct.add(compute_fingerprint(arr)) + distinct.add(compute_fingerprint(memoryview(arr))) + arr = arr[::2] + distinct.add(compute_fingerprint(arr)) + distinct.add(compute_fingerprint(memoryview(arr))) + + m = mmap.mmap(-1, 16384) + distinct.add(compute_fingerprint(m)) + self.assertEqual(compute_fingerprint(memoryview(m)), m_uint8_1d) + + def test_dtype(self): + distinct = DistinctChecker() + + s = compute_fingerprint(np.dtype('int64')) + self.assertEqual(compute_fingerprint(np.dtype('int64')), s) + distinct.add(s) + + for descr in ('int32', 'm8[s]', 'm8[W]', 'M8[s]'): + distinct.add(np.dtype(descr)) + + distinct.add(recordtype) + distinct.add(recordtype2) + + # np.recarray() is peculiar: it creates a new dtype instance in + # its constructor; check that the fingerprint remains efficient + a = np.recarray(1, dtype=recordtype) + b = np.recarray(1, dtype=recordtype) + self.assertEqual(compute_fingerprint(a.dtype), + compute_fingerprint(b.dtype)) + + def test_tuples(self): + distinct = DistinctChecker() + + s = compute_fingerprint((1,)) + self.assertEqual(compute_fingerprint((2,)), s) + distinct.add(s) + + distinct.add(compute_fingerprint(())) + distinct.add(compute_fingerprint((1, 2, 3))) + distinct.add(compute_fingerprint((1j, 2, 3))) + distinct.add(compute_fingerprint((1, (), np.empty(5)))) + distinct.add(compute_fingerprint((1, (), np.empty((5, 1))))) + + def test_lists(self): + distinct = DistinctChecker() + + s = compute_fingerprint([1]) + self.assertEqual(compute_fingerprint([2, 3]), s) + distinct.add(s) + + distinct.add(compute_fingerprint([1j])) + distinct.add(compute_fingerprint([4.5, 6.7])) + distinct.add(compute_fingerprint([(1,)])) + + with self.assertRaises(ValueError): + compute_fingerprint([]) + + def test_sets(self): + distinct = DistinctChecker() + + s = compute_fingerprint(set([1])) + self.assertEqual(compute_fingerprint(set([2, 3])), s) + distinct.add(s) + + distinct.add(compute_fingerprint([1])) + distinct.add(compute_fingerprint(set([1j]))) + distinct.add(compute_fingerprint(set([4.5, 6.7]))) + distinct.add(compute_fingerprint(set([(1,)]))) + + with self.assertRaises(ValueError): + compute_fingerprint(set()) + with self.assertRaises(NotImplementedError): + compute_fingerprint(frozenset([2, 3])) + + def test_omitted_args(self): + distinct = DistinctChecker() + + v0 = OmittedArg(0.0) + v1 = OmittedArg(1.0) + v2 = OmittedArg(1) + + s = compute_fingerprint(v0) + self.assertEqual(compute_fingerprint(v1), s) + distinct.add(s) + distinct.add(compute_fingerprint(v2)) + distinct.add(compute_fingerprint(0.0)) + distinct.add(compute_fingerprint(1)) + + def test_complicated_type(self): + # Generating a large fingerprint + t = None + for i in range(1000): + t = (t,) + s = compute_fingerprint(t) + + +class TestTypeOfMemCpy(TestCase): + + def test_memcpy_typeof_buffer(self): + # https://github.com/numba/numba/issues/9097 + # bug is fixed if the code below compiles + random.seed(0) + chars = string.ascii_letters + n = 256 + field = "".join([chars[random.randint(0, len(chars) - 1)] for x in range(n)]) + for i in range(1, n): + lfield = field[:i] + nt_ty = namedtuple("tuplename", lfield) + nt = nt_ty(1) + fp = _dispatcher.compute_fingerprint(nt) + nt_name = nt.__class__.__name__ + expected = f"{nt_name}({lfield}i)" + self.assertEqual( + expected, + fp.decode(), + f"iteration {i} failed, {expected} != {fp.decode()}" + ) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_unicode_names.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_unicode_names.py new file mode 100644 index 0000000000000000000000000000000000000000..0ed8fb756418ee993989ccded14f9b3cedb2521d --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_unicode_names.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- + + +from numba import njit, cfunc +from numba.tests.support import TestCase, unittest +from numba.core import cgutils + +unicode_name1 = u""" +def unicode_name1(ಠ_ರೃ, ಠਊಠ): + return (ಠ_ರೃ) + (ಠਊಠ) +""" + +unicode_name2 = u""" +def Ծ_Ծ(ಠ_ರೃ, ಠਊಠ): + return (ಠ_ರೃ) + (ಠਊಠ) +""" + + +class TestUnicodeNames(TestCase): + def make_testcase(self, src, fname): + glb = {} + exec(src, glb) + fn = glb[fname] + return fn + + def test_unicode_name1(self): + fn = self.make_testcase(unicode_name1, 'unicode_name1') + cfn = njit(fn) + self.assertEqual(cfn(1, 2), 3) + + def test_unicode_name2(self): + fn = self.make_testcase(unicode_name2, 'Ծ_Ծ') + cfn = njit(fn) + self.assertEqual(cfn(1, 2), 3) + + def test_cfunc(self): + fn = self.make_testcase(unicode_name2, 'Ծ_Ծ') + cfn = cfunc("int32(int32, int32)")(fn) + self.assertEqual(cfn.ctypes(1, 2), 3) + + +class TestUnicodeUtils(TestCase): + def test_normalize_ir_text(self): + # non-unicode input + out = cgutils.normalize_ir_text('abc') + # str returned + self.assertIsInstance(out, str) + # try encoding to latin + out.encode('latin1') + + def test_normalize_ir_text_unicode(self): + # unicode input + out = cgutils.normalize_ir_text(unicode_name2) + # str returned + self.assertIsInstance(out, str) + # try encoding to latin + out.encode('latin1') + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_unpack_sequence.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_unpack_sequence.py new file mode 100644 index 0000000000000000000000000000000000000000..55db569682664f4844cd289cc317994e83ad03ba --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_unpack_sequence.py @@ -0,0 +1,234 @@ +import numpy as np + +import unittest +from numba import jit, njit +from numba.core import errors, types +from numba import typeof +from numba.tests.support import TestCase, MemoryLeakMixin +from numba.tests.support import no_pyobj_flags as nullary_no_pyobj_flags +from numba.tests.support import force_pyobj_flags as nullary_force_pyobj_flags + +force_pyobj_flags = {'forceobj': True} +no_pyobj_flags = {'nopython': True} + + +def unpack_list(l): + a, b, c = l + return (a, b, c) + + +def unpack_shape(a): + x, y, z = a.shape + return x + y + z + + +def unpack_range(): + a, b, c = range(3) + return a + b + c + + +def unpack_range_too_small(): + a, b, c = range(2) + return a + b + c + + +def unpack_range_too_large(): + a, b, c = range(4) + return a + b + c + + +def unpack_tuple(): + a, b, c = (1, 2, 3) + return a + b + c + + +def unpack_tuple_too_small(): + a, b, c = (1, 2) + return a + b + c + + +def unpack_tuple_too_large(): + a, b, c = (1, 2, 3, 4) + return a + b + c + + +def unpack_heterogeneous_tuple_too_small(): + a, b, c = (1, 2.5j) + return a + b + c + + +def unpack_heterogeneous_tuple_too_large(): + a, b, c = (1, 2.5, 3j, 4) + return a + b + c + + +def unpack_heterogeneous_tuple(): + a, b, c = (1, 2.5, 3j) + return a + b + c + + +def unpack_nested_heterogeneous_tuple(): + a, (b, c) = (1, (2.5, 3j)) + return a + b + c + + +def unpack_arbitrary(seq): + a, b = seq + return b, a + + +def unpack_nrt(): + a = np.zeros(1) + b = np.zeros(2) + tup = b, a + alpha, beta = tup + return alpha, beta + + +def chained_unpack_assign1(x, y): + # Used to fail in object mode (issue #580) + a = (b, c) = (x, y) + (d, e) = a + return d + e + b + c + + +def conditional_swap(x, y): + # Used to produce invalid code (issue #977) + if x > 0: + x, y = y, x + return x, y + + +class TestUnpack(MemoryLeakMixin, TestCase): + + def check_nullary_npm(self, pyfunc): + cfunc = njit(pyfunc) + self.assertPreciseEqual(cfunc(), pyfunc()) + + def check_nullary_objmode(self, pyfunc): + cfunc = jit(forceobj=True)(pyfunc) + self.assertPreciseEqual(cfunc(), pyfunc()) + + def test_unpack_list(self): + pyfunc = unpack_list + cfunc = jit(forceobj=True)(pyfunc) + l = [1, 2, 3] + self.assertEqual(cfunc(l), pyfunc(l)) + + def test_unpack_shape(self): + pyfunc = unpack_shape + cfunc = jit((types.Array(dtype=types.int32, ndim=3, layout='C'),), + forceobj=True)(pyfunc) + a = np.zeros(shape=(1, 2, 3)).astype(np.int32) + self.assertPreciseEqual(cfunc(a), pyfunc(a)) + + def test_unpack_shape_npm(self): + pyfunc = unpack_shape + cfunc = njit((types.Array(dtype=types.int32, ndim=3, layout='C'),), + )(pyfunc) + a = np.zeros(shape=(1, 2, 3)).astype(np.int32) + self.assertPreciseEqual(cfunc(a), pyfunc(a)) + + def test_unpack_range(self): + self.check_nullary_objmode(unpack_range) + + def test_unpack_range_npm(self): + self.check_nullary_npm(unpack_range) + + def test_unpack_tuple(self): + self.check_nullary_objmode(unpack_tuple) + + def test_unpack_tuple_npm(self): + self.check_nullary_npm(unpack_tuple) + + def test_unpack_heterogeneous_tuple(self): + self.check_nullary_objmode(unpack_heterogeneous_tuple) + + def test_unpack_heterogeneous_tuple_npm(self): + self.check_nullary_npm(unpack_heterogeneous_tuple) + + def test_unpack_nested_heterogeneous_tuple(self): + self.check_nullary_objmode(unpack_nested_heterogeneous_tuple) + + def test_unpack_nested_heterogeneous_tuple_npm(self): + self.check_nullary_npm(unpack_nested_heterogeneous_tuple) + + def test_chained_unpack_assign(self, flags=force_pyobj_flags): + pyfunc = chained_unpack_assign1 + cfunc = jit((types.int32, types.int32), **flags)(pyfunc) + args = (4, 5) + self.assertPreciseEqual(cfunc(*args), pyfunc(*args)) + + def test_chained_unpack_assign_npm(self): + self.test_chained_unpack_assign(flags=no_pyobj_flags) + + def check_unpack_error(self, pyfunc, flags=force_pyobj_flags, + exc=ValueError): + with self.assertRaises(exc): + cfunc = jit((), **flags)(pyfunc) + cfunc() + + def test_unpack_tuple_too_small(self): + self.check_unpack_error(unpack_tuple_too_small) + self.check_unpack_error(unpack_heterogeneous_tuple_too_small) + + def test_unpack_tuple_too_small_npm(self): + self.check_unpack_error(unpack_tuple_too_small, no_pyobj_flags, + errors.TypingError) + self.check_unpack_error(unpack_heterogeneous_tuple_too_small, + no_pyobj_flags, errors.TypingError) + + def test_unpack_tuple_too_large(self): + self.check_unpack_error(unpack_tuple_too_large) + self.check_unpack_error(unpack_heterogeneous_tuple_too_large) + + def test_unpack_tuple_too_large_npm(self): + self.check_unpack_error(unpack_tuple_too_large, no_pyobj_flags, + errors.TypingError) + self.check_unpack_error(unpack_heterogeneous_tuple_too_large, + no_pyobj_flags, errors.TypingError) + + def test_unpack_range_too_small(self): + self.check_unpack_error(unpack_range_too_small) + + def test_unpack_range_too_small_npm(self): + self.check_unpack_error(unpack_range_too_small, no_pyobj_flags) + + def test_unpack_range_too_large(self): + self.check_unpack_error(unpack_range_too_large) + + def test_unpack_range_too_large_npm(self): + self.check_unpack_error(unpack_range_too_large, no_pyobj_flags) + + def check_conditional_swap(self, flags=force_pyobj_flags): + cfunc = jit((types.int32, types.int32), **flags)(conditional_swap) + self.assertPreciseEqual(cfunc(4, 5), (5, 4)) + self.assertPreciseEqual(cfunc(0, 5), (0, 5)) + + def test_conditional_swap(self): + self.check_conditional_swap() + + def test_conditional_swap_npm(self): + self.check_conditional_swap(no_pyobj_flags) + + def test_unpack_tuple_of_arrays(self): + tup = tuple(np.zeros(i + 1) for i in range(2)) + tupty = typeof(tup) + pyfunc = unpack_arbitrary + cfunc = njit((tupty,))(pyfunc) + self.assertPreciseEqual(cfunc(tup), pyfunc(tup)) + + def test_unpack_nrt(self): + pyfunc = unpack_nrt + cfunc = njit((),)(pyfunc) + self.assertPreciseEqual(cfunc(), pyfunc()) + + def test_invalid_unpack(self): + pyfunc = unpack_arbitrary + with self.assertRaises(errors.TypingError) as raises: + njit((types.int32,))(pyfunc) + self.assertIn("failed to unpack int32", str(raises.exception)) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_unpickle_without_module.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_unpickle_without_module.py new file mode 100644 index 0000000000000000000000000000000000000000..ddbfbd7512d75dabe9bfce41f57fbb81fa65d2b2 --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_unpickle_without_module.py @@ -0,0 +1,49 @@ +import unittest +import pickle +import sys +import tempfile +from pathlib import Path + + +class TestUnpickleDeletedModule(unittest.TestCase): + def test_loading_pickle_with_no_module(self): + """Create a module that uses Numba, import a function from it. + Then delete the module and pickle the function. The function + should load from the pickle without a problem. + + Note - This is a simplified version of how Numba might be used + on a distributed system using e.g. dask distributed. With the + pickle being sent to the worker but not the original module. + """ + + # Source code for temporary module we will make + source = "\n".join( + [ + "from numba import vectorize", + "@vectorize(['float64(float64)'])", + "def inc1(x):", + " return x + 1", + ] + ) + + # Create a temporary directory and add it to path. + modname = "tmp_module" + with tempfile.TemporaryDirectory() as tmp_dir: + sys.path.append(tmp_dir) + + # Create tmp_module.py in there with our source code above. + filename = Path(f"{tmp_dir}/{modname}.py") + f = open(filename, "a") + f.write(source) + f.close() + + # Import the temporary module before file is deleted + from tmp_module import inc1 + + # Remove from imported libraries + del sys.modules[modname] + + # Pickle function and assert that it loads correctly + pkl = pickle.dumps(inc1) + f = pickle.loads(pkl) + self.assertEqual(f(2), 3) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_unsafe_intrinsics.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_unsafe_intrinsics.py new file mode 100644 index 0000000000000000000000000000000000000000..4de35f2c209ff12130e82a68afc409f54881ecbb --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_unsafe_intrinsics.py @@ -0,0 +1,232 @@ +import random +import numpy as np + +from numba.tests.support import TestCase, captured_stdout +from numba import njit, literally +from numba.core import types +from numba.cpython.unsafe.tuple import tuple_setitem, build_full_slice_tuple +from numba.np.unsafe.ndarray import to_fixed_tuple, empty_inferred +from numba.core.unsafe.bytes import memcpy_region +from numba.core.unsafe.refcount import dump_refcount +from numba.cpython.unsafe.numbers import trailing_zeros, leading_zeros +from numba.core.errors import TypingError + + +class TestTupleIntrinsic(TestCase): + """Tests for numba.unsafe.tuple + """ + def test_tuple_setitem(self): + @njit + def foo(tup, idxs, vals): + out_tup = tup + for i, v in zip(idxs, vals): + out_tup = tuple_setitem(out_tup, i, v) + return tup, out_tup + + random.seed(123) + for _ in range(20): + # Random data + n = random.randint(1, 10) + tup = tuple([random.randint(0, n) for i in range(n)]) + vals = tuple([random.randint(10, 20) for i in range(n)]) + idxs = list(range(len(vals))) + random.shuffle(idxs) + idxs = tuple(idxs) + # Expect + expect_tup = tuple(tup) + expect_out = np.asarray(expect_tup) + expect_out[np.asarray(idxs)] = vals + # Got + got_tup, got_out = foo(tup, idxs, vals) + # Check + self.assertEqual(got_tup, expect_tup) + self.assertEqual(got_out, tuple(expect_out)) + + def test_slice_tuple(self): + @njit + def full_slice_array(a, n): + # Since numba slices can't be boxed at the moment + return a[build_full_slice_tuple(literally(n))] + + for n in range(1, 3): + a = np.random.random(np.arange(n) + 1) + for i in range(1, n + 1): + np.testing.assert_array_equal(a, full_slice_array(a, i)) + with self.assertRaises(TypingError): + # numpy would throw an IndexError here + full_slice_array(a, n + 1) + + +class TestNdarrayIntrinsic(TestCase): + """Tests for numba.unsafe.ndarray + """ + def test_to_fixed_tuple(self): + const = 3 + + @njit + def foo(array): + a = to_fixed_tuple(array, length=1) + b = to_fixed_tuple(array, 2) + c = to_fixed_tuple(array, const) + d = to_fixed_tuple(array, 0) + return a, b, c, d + + np.random.seed(123) + for _ in range(10): + # Random data + arr = np.random.random(3) + # Run + a, b, c, d = foo(arr) + # Check + self.assertEqual(a, tuple(arr[:1])) + self.assertEqual(b, tuple(arr[:2])) + self.assertEqual(c, tuple(arr[:3])) + self.assertEqual(d, ()) + + # Check error with ndim!=1 + with self.assertRaises(TypingError) as raises: + foo(np.random.random((1, 2))) + self.assertIn("Not supported on array.ndim=2", + str(raises.exception)) + + # Check error with non-constant length + @njit + def tuple_with_length(array, length): + return to_fixed_tuple(array, length) + + with self.assertRaises(TypingError) as raises: + tuple_with_length(np.random.random(3), 1) + expectmsg = "*length* argument must be a constant" + self.assertIn(expectmsg, str(raises.exception)) + + def test_issue_3586_variant1(self): + @njit + def func(): + S = empty_inferred((10,)) + a = 1.1 + for i in range(len(S)): + S[i] = a + 2 + return S + + got = func() + expect = np.asarray([3.1] * 10) + np.testing.assert_array_equal(got, expect) + + def test_issue_3586_variant2(self): + @njit + def func(): + S = empty_inferred((10,)) + a = 1.1 + for i in range(S.size): + S[i] = a + 2 + return S + + got = func() + expect = np.asarray([3.1] * 10) + np.testing.assert_array_equal(got, expect) + + +class TestBytesIntrinsic(TestCase): + """Tests for numba.unsafe.bytes + """ + def test_memcpy_region(self): + @njit + def foo(dst, dst_index, src, src_index, nbytes): + # last arg is assume 1 byte alignment + memcpy_region(dst.ctypes.data, dst_index, + src.ctypes.data, src_index, nbytes, 1) + + d = np.zeros(10, dtype=np.int8) + s = np.arange(10, dtype=np.int8) + + # copy s[1:6] to d[4:9] + foo(d, 4, s, 1, 5) + + expected = [0, 0, 0, 0, 1, 2, 3, 4, 5, 0] + np.testing.assert_array_equal(d, expected) + + +class TestRefCount(TestCase): + def test_dump_refcount(self): + @njit + def use_dump_refcount(): + a = np.ones(10) + b = (a, a) + dump_refcount(a) + dump_refcount(b) + + # Capture output to sys.stdout + with captured_stdout() as stream: + use_dump_refcount() + + output = stream.getvalue() + # Check that it printed + pat = "dump refct of {}" + aryty = types.float64[::1] + tupty = types.Tuple.from_types([aryty] * 2) + self.assertIn(pat.format(aryty), output) + self.assertIn(pat.format(tupty), output) + + +class TestZeroCounts(TestCase): + def test_zero_count(self): + lz = njit(lambda x: leading_zeros(x)) + tz = njit(lambda x: trailing_zeros(x)) + + evens = [2, 42, 126, 128] + + for T in types.unsigned_domain: + self.assertTrue(tz(T(0)) == lz(T(0)) == T.bitwidth) + for i in range(T.bitwidth): + val = T(2 ** i) + self.assertEqual(lz(val) + tz(val) + 1, T.bitwidth) + for n in evens: + self.assertGreater(tz(T(n)), 0) + self.assertEqual(tz(T(n + 1)), 0) + + for T in types.signed_domain: + self.assertTrue(tz(T(0)) == lz(T(0)) == T.bitwidth) + for i in range(T.bitwidth - 1): + val = T(2 ** i) + self.assertEqual(lz(val) + tz(val) + 1, T.bitwidth) + self.assertEqual(lz(-val), 0) + self.assertEqual(tz(val), tz(-val)) + for n in evens: + if not T.minval <= n <= T.maxval: + continue + self.assertGreater(tz(T(n)), 0) + self.assertEqual(tz(T(n + 1)), 0) + + def check_error_msg(self, func): + cfunc = njit(lambda *x: func(*x)) + func_name = func._name + + unsupported_types = filter( + lambda x: not isinstance(x, types.Integer), types.number_domain + ) + for typ in sorted(unsupported_types, key=str): + with self.assertRaises(TypingError) as e: + cfunc(typ(2)) + self.assertIn( + "{} is only defined for integers, but value passed was '{}'." + .format(func_name, typ), + str(e.exception), + ) + + # Testing w/ too many/few arguments + def check(args, string): + with self.assertRaises((TypingError, TypeError)) as e: + cfunc(*args) + self.assertIn( + "{}() ".format(func_name), + str(e.exception) + ) + + check((1, 2), "takes 2 positional arguments but 3 were given") + check((), "missing 1 required positional argument") + + def test_trailing_zeros_error(self): + self.check_error_msg(trailing_zeros) + + def test_leading_zeros_error(self): + self.check_error_msg(leading_zeros) diff --git a/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_warnings.py b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_warnings.py new file mode 100644 index 0000000000000000000000000000000000000000..92ea575f35c5742007f59abe48f269dc740daa1b --- /dev/null +++ b/data/conda_envs/evalclaw/lib/python3.11/site-packages/numba/tests/test_warnings.py @@ -0,0 +1,187 @@ +import os +import subprocess +import sys +import warnings +import numpy as np + +import unittest +from numba import jit +from numba.core.errors import ( + NumbaWarning, + deprecated, + NumbaDeprecationWarning, + NumbaPendingDeprecationWarning, +) +from numba.core import errors +from numba.tests.support import ignore_internal_warnings + + +class TestBuiltins(unittest.TestCase): + + def check_objmode_deprecation_warning(self, w): + # Object mode fall-back is slated for deprecation, check the warning + msg = ("Fall-back from the nopython compilation path to the object " + "mode compilation path has been detected") + self.assertEqual(w.category, NumbaDeprecationWarning) + self.assertIn(msg, str(w.message)) + + def check_nopython_kwarg_missing_warning(self, w): + # nopython default is scheduled to change when objmode fall-back is + # removed, check warning. + msg = ("The \'nopython\' keyword argument was not supplied") + self.assertEqual(w.category, NumbaDeprecationWarning) + self.assertIn(msg, str(w.message)) + + def test_return_type_warning_with_nrt(self): + """ + Rerun test_return_type_warning with nrt + """ + y = np.ones(4, dtype=np.float32) + + def return_external_array(): + return y + + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always', NumbaWarning) + ignore_internal_warnings() + + cfunc = jit(nopython=True)(return_external_array) + cfunc() + # No more warning + self.assertEqual(len(w), 0) + + def test_no_warning_with_forceobj(self): + def add(x, y): + a = [] # noqa dead + return x + y + + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always', NumbaWarning) + ignore_internal_warnings() + + cfunc = jit(add, forceobj=True) + cfunc(1, 2) + + self.assertEqual(len(w), 0) + + def test_deprecated(self): + @deprecated('foo') + def bar(): + pass + + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always') + ignore_internal_warnings() + bar() + + self.assertEqual(len(w), 1) + self.assertEqual(w[0].category, DeprecationWarning) + self.assertIn('bar', str(w[0].message)) + self.assertIn('foo', str(w[0].message)) + + def test_warnings_fixer(self): + # For some context, see #4083 + + wfix = errors.WarningsFixer(errors.NumbaWarning) + with wfix.catch_warnings('foo', 10): + warnings.warn(errors.NumbaWarning('same')) + warnings.warn(errors.NumbaDeprecationWarning('same')) + ignore_internal_warnings() + + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always') + ignore_internal_warnings() + wfix.flush() + + self.assertEqual(len(w), 2) + # the order of these will be backwards to the above, the + # WarningsFixer flush method sorts with a key based on str + # comparison + self.assertEqual(w[0].category, NumbaDeprecationWarning) + self.assertEqual(w[1].category, NumbaWarning) + self.assertIn('same', str(w[0].message)) + self.assertIn('same', str(w[1].message)) + + def test_disable_performance_warnings(self): + + not_found_ret_code = 55 + found_ret_code = 99 + expected = "'parallel=True' was specified but no transformation" + + # NOTE: the error_usecases is needed as the NumbaPerformanceWarning's + # for parallel=True failing to parallelise do not appear for functions + # defined by string eval/exec etc. + parallel_code = """if 1: + import warnings + from numba.tests.error_usecases import foo + import numba + from numba.tests.support import ignore_internal_warnings + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter('always') + ignore_internal_warnings() + foo() + for x in w: + if x.category == numba.errors.NumbaPerformanceWarning: + if "%s" in str(x.message): + exit(%s) + exit(%s) + """ % (expected, found_ret_code, not_found_ret_code) + + # run in the standard env, warning should raise + popen = subprocess.Popen([sys.executable, "-c", parallel_code]) + out, err = popen.communicate() + self.assertEqual(popen.returncode, found_ret_code) + + # run in an env with performance warnings disabled, should not warn + env = dict(os.environ) + env['NUMBA_DISABLE_PERFORMANCE_WARNINGS'] = "1" + popen = subprocess.Popen([sys.executable, "-c", parallel_code], env=env) + out, err = popen.communicate() + self.assertEqual(popen.returncode, not_found_ret_code) + + def test_filter_deprecation_warnings(self): + # Filter on base classes of deprecation warnings should apply to Numba's + # deprecation warnings + with warnings.catch_warnings(): + warnings.simplefilter('error') + warnings.simplefilter('ignore', category=DeprecationWarning) + warnings.simplefilter('ignore', category=PendingDeprecationWarning) + warnings.warn(DeprecationWarning("this is ignored")) + warnings.warn(PendingDeprecationWarning("this is ignored")) + warnings.warn(NumbaDeprecationWarning("this is ignored")) + warnings.warn(NumbaPendingDeprecationWarning("this is ignored")) + with self.assertRaises(NumbaWarning): + warnings.warn(NumbaWarning("this is not ignored")) + + def test_filter_ignore_numba_deprecation_only(self): + # Make a filter that ignores Numba's deprecation warnings but raises on + # other deprecation warnings + with warnings.catch_warnings(): + warnings.simplefilter('error', category=DeprecationWarning) + warnings.simplefilter('error', category=PendingDeprecationWarning) + warnings.simplefilter('ignore', category=NumbaDeprecationWarning) + warnings.simplefilter('ignore', + category=NumbaPendingDeprecationWarning) + + with self.assertRaises(DeprecationWarning): + warnings.warn(DeprecationWarning("this is not ignored")) + with self.assertRaises(PendingDeprecationWarning): + warnings.warn(PendingDeprecationWarning("this is not ignored")) + + warnings.warn(NumbaDeprecationWarning("this is ignored")) + warnings.warn(NumbaPendingDeprecationWarning("this is ignored")) + + # now make it so that Numba deprecation warnings are raising + warnings.simplefilter('error', category=NumbaDeprecationWarning) + warnings.simplefilter('error', + category=NumbaPendingDeprecationWarning) + + with self.assertRaises(DeprecationWarning): + warnings.warn(NumbaDeprecationWarning("this is not ignored")) + with self.assertRaises(PendingDeprecationWarning): + warnings.warn(NumbaPendingDeprecationWarning( + "this is not ignored")) + + +if __name__ == '__main__': + unittest.main()