diff --git a/.basedpyright/baseline.json b/.basedpyright/baseline.json index 3286d2742..afaf69ef9 100644 --- a/.basedpyright/baseline.json +++ b/.basedpyright/baseline.json @@ -905,6 +905,38 @@ "lineCount": 1 } }, + { + "code": "reportUnknownVariableType", + "range": { + "startColumn": 8, + "endColumn": 11, + "lineCount": 1 + } + }, + { + "code": "reportUnknownMemberType", + "range": { + "startColumn": 14, + "endColumn": 37, + "lineCount": 1 + } + }, + { + "code": "reportAttributeAccessIssue", + "range": { + "startColumn": 23, + "endColumn": 37, + "lineCount": 1 + } + }, + { + "code": "reportUnknownVariableType", + "range": { + "startColumn": 15, + "endColumn": 18, + "lineCount": 1 + } + }, { "code": "reportArgumentType", "range": { @@ -1973,14 +2005,6 @@ "lineCount": 1 } }, - { - "code": "reportUnknownVariableType", - "range": { - "startColumn": 38, - "endColumn": 62, - "lineCount": 1 - } - }, { "code": "reportUnknownVariableType", "range": { @@ -2213,14 +2237,6 @@ "lineCount": 1 } }, - { - "code": "reportArgumentType", - "range": { - "startColumn": 12, - "endColumn": 16, - "lineCount": 1 - } - }, { "code": "reportUnknownMemberType", "range": { @@ -7870,24 +7886,24 @@ { "code": "reportUnknownArgumentType", "range": { - "startColumn": 29, - "endColumn": 32, + "startColumn": 39, + "endColumn": 42, "lineCount": 1 } }, { "code": "reportUnknownArgumentType", "range": { - "startColumn": 42, - "endColumn": 51, + "startColumn": 52, + "endColumn": 61, "lineCount": 1 } }, { "code": "reportUnknownVariableType", "range": { - "startColumn": 28, - "endColumn": 31, + "startColumn": 24, + "endColumn": 27, "lineCount": 1 } }, @@ -8358,24 +8374,24 @@ { "code": "reportUnknownArgumentType", "range": { - "startColumn": 29, - "endColumn": 32, + "startColumn": 39, + "endColumn": 42, "lineCount": 1 } }, { "code": "reportUnknownArgumentType", "range": { - "startColumn": 42, - "endColumn": 51, + "startColumn": 52, + "endColumn": 61, "lineCount": 1 } }, { "code": "reportUnknownVariableType", "range": { - "startColumn": 28, - "endColumn": 31, + "startColumn": 24, + "endColumn": 27, "lineCount": 1 } }, @@ -8662,24 +8678,24 @@ { "code": "reportUnknownArgumentType", "range": { - "startColumn": 29, - "endColumn": 32, + "startColumn": 39, + "endColumn": 42, "lineCount": 1 } }, { "code": "reportUnknownArgumentType", "range": { - "startColumn": 42, - "endColumn": 51, + "startColumn": 52, + "endColumn": 61, "lineCount": 1 } }, { "code": "reportUnknownVariableType", "range": { - "startColumn": 28, - "endColumn": 31, + "startColumn": 24, + "endColumn": 27, "lineCount": 1 } }, @@ -12208,16 +12224,16 @@ { "code": "reportUnknownArgumentType", "range": { - "startColumn": 25, - "endColumn": 37, + "startColumn": 26, + "endColumn": 38, "lineCount": 1 } }, { "code": "reportUnknownArgumentType", "range": { - "startColumn": 39, - "endColumn": 49, + "startColumn": 40, + "endColumn": 50, "lineCount": 1 } }, @@ -13051,126 +13067,6 @@ "lineCount": 1 } }, - { - "code": "reportUnknownParameterType", - "range": { - "startColumn": 29, - "endColumn": 32, - "lineCount": 1 - } - }, - { - "code": "reportMissingParameterType", - "range": { - "startColumn": 29, - "endColumn": 32, - "lineCount": 1 - } - }, - { - "code": "reportUnknownParameterType", - "range": { - "startColumn": 34, - "endColumn": 37, - "lineCount": 1 - } - }, - { - "code": "reportMissingParameterType", - "range": { - "startColumn": 34, - "endColumn": 37, - "lineCount": 1 - } - }, - { - "code": "reportUnknownMemberType", - "range": { - "startColumn": 7, - "endColumn": 19, - "lineCount": 1 - } - }, - { - "code": "reportUnknownMemberType", - "range": { - "startColumn": 7, - "endColumn": 24, - "lineCount": 1 - } - }, - { - "code": "reportUnknownMemberType", - "range": { - "startColumn": 40, - "endColumn": 48, - "lineCount": 1 - } - }, - { - "code": "reportUnknownMemberType", - "range": { - "startColumn": 7, - "endColumn": 19, - "lineCount": 1 - } - }, - { - "code": "reportUnknownMemberType", - "range": { - "startColumn": 7, - "endColumn": 24, - "lineCount": 1 - } - }, - { - "code": "reportUnknownMemberType", - "range": { - "startColumn": 40, - "endColumn": 52, - "lineCount": 1 - } - }, - { - "code": "reportUnknownArgumentType", - "range": { - "startColumn": 40, - "endColumn": 52, - "lineCount": 1 - } - }, - { - "code": "reportOptionalOperand", - "range": { - "startColumn": 11, - "endColumn": 23, - "lineCount": 1 - } - }, - { - "code": "reportOptionalOperand", - "range": { - "startColumn": 13, - "endColumn": 25, - "lineCount": 1 - } - }, - { - "code": "reportUnknownArgumentType", - "range": { - "startColumn": 71, - "endColumn": 74, - "lineCount": 1 - } - }, - { - "code": "reportUnknownArgumentType", - "range": { - "startColumn": 76, - "endColumn": 79, - "lineCount": 1 - } - }, { "code": "reportUnknownParameterType", "range": { diff --git a/contrib/fortran-to-opencl/translate.py b/contrib/fortran-to-opencl/translate.py index b2cb1059a..a42ac5d9b 100644 --- a/contrib/fortran-to-opencl/translate.py +++ b/contrib/fortran-to-opencl/translate.py @@ -135,16 +135,16 @@ class FortranExpressionParser(ExpressionParserBase): # FIXME double/single prec literals lex_table: ClassVar[list[tuple[str, str]]] = [ - (_less_than, pytools.lex.RE(r"\.lt\.", re.I)), - (_greater_than, pytools.lex.RE(r"\.gt\.", re.I)), - (_less_equal, pytools.lex.RE(r"\.le\.", re.I)), - (_greater_equal, pytools.lex.RE(r"\.ge\.", re.I)), - (_equal, pytools.lex.RE(r"\.eq\.", re.I)), - (_not_equal, pytools.lex.RE(r"\.ne\.", re.I)), - - (_not, pytools.lex.RE(r"\.not\.", re.I)), - (_and, pytools.lex.RE(r"\.and\.", re.I)), - (_or, pytools.lex.RE(r"\.or\.", re.I)), + (_less_than, pytools.lex.RE(r"\.lt\.", re.IGNORECASE)), + (_greater_than, pytools.lex.RE(r"\.gt\.", re.IGNORECASE)), + (_less_equal, pytools.lex.RE(r"\.le\.", re.IGNORECASE)), + (_greater_equal, pytools.lex.RE(r"\.ge\.", re.IGNORECASE)), + (_equal, pytools.lex.RE(r"\.eq\.", re.IGNORECASE)), + (_not_equal, pytools.lex.RE(r"\.ne\.", re.IGNORECASE)), + + (_not, pytools.lex.RE(r"\.not\.", re.IGNORECASE)), + (_and, pytools.lex.RE(r"\.and\.", re.IGNORECASE)), + (_or, pytools.lex.RE(r"\.or\.", re.IGNORECASE)), *ExpressionParserBase.lex_table] def __init__(self, tree_walker): @@ -221,7 +221,7 @@ def parse_terminal(self, pstate): } def parse_prefix(self, pstate, min_precedence=0): - import pymbolic.primitives as primitives + from pymbolic import primitives from pymbolic.parser import _PREC_UNARY pstate.expect_not_end() @@ -483,7 +483,7 @@ def __init__(self, translator, scope): def map_subscript(self, expr, enclosing_prec): idx_dtype = self.infer_type(expr.index) - if not "i" == idx_dtype.kind or "u" == idx_dtype.kind: + if "i" != idx_dtype.kind or "u" == idx_dtype.kind: ind_prefix = "(int) " else: ind_prefix = "" @@ -1383,10 +1383,8 @@ def f2cl(source, free_form=False, strict=True, source = F2CLTranslator(addr_space_hints, force_casts, arg_info, use_restrict_pointers=use_restrict_pointers)(tree) - func_decls = [] - for entry in source: - if isinstance(entry, cgen.FunctionBody): - func_decls.append(entry.fdecl) + func_decls = [entry.fdecl + for entry in source if isinstance(entry, cgen.FunctionBody)] mod = cgen.Module([*func_decls, cgen.Line(), *source]) @@ -1408,8 +1406,10 @@ def f2cl(source, free_form=False, strict=True, def f2cl_files(source_file, target_file, **kwargs): - mod = f2cl(open(source_file).read(), **kwargs) - open(target_file, "w").write(mod) + with open(source_file) as inf: + mod = f2cl(inf.read(), **kwargs) + with open(target_file, "w") as outf: + outf.write(mod) if __name__ == "__main__": diff --git a/examples/black-hole-accretion.py b/examples/black-hole-accretion.py index 33122e0e1..022ec8be9 100644 --- a/examples/black-hole-accretion.py +++ b/examples/black-hole-accretion.py @@ -1,5 +1,3 @@ -#!/usr/bin/env python3 -# # TrouNoir model using PyOpenCL or PyCUDA # # CC BY-NC-SA 2019 : @@ -43,8 +41,7 @@ def DictionariesAPI(): - PhysicsList = {"Einstein": 0, "Newton": 1} - return PhysicsList + return {"Einstein": 0, "Newton": 1} # @@ -779,7 +776,7 @@ def DictionariesAPI(): def KernelCodeCuda(): - BlobCUDA = """ + return """ #define PI (float)3.14159265359 #define nbr 256 @@ -1493,7 +1490,6 @@ def KernelCodeCuda(): } """ - return BlobCUDA # def ImageOutput(sigma,prefix,Colors): @@ -1588,7 +1584,7 @@ def BlackHoleCL(zImage, fImage, InputCL): # Je recupere les flag possibles pour les buffers mf = cl.mem_flags - if Method == "TrajectoPixel" or Method == "TrajectoCircle": + if Method in {"TrajectoPixel", "TrajectoCircle"}: TrajectoriesCL = cl.Buffer( ctx, mf.WRITE_ONLY | mf.COPY_HOST_PTR, hostbuf=Trajectories ) @@ -1706,7 +1702,7 @@ def BlackHoleCL(zImage, fImage, InputCL): cl.enqueue_copy(queue, zImage, zImageCL).wait() cl.enqueue_copy(queue, fImage, fImageCL).wait() - if Method == "TrajectoPixel" or Method == "TrajectoCircle": + if Method in {"TrajectoPixel", "TrajectoCircle"}: cl.enqueue_copy(queue, Trajectories, TrajectoriesCL).wait() cl.enqueue_copy(queue, IdLast, IdLastCL).wait() elapsed = time.time() - start_time @@ -1738,7 +1734,7 @@ def BlackHoleCL(zImage, fImage, InputCL): zImageCL.release() fImageCL.release() - if Method == "TrajectoPixel" or Method == "TrajectoCircle": + if Method in {"TrajectoPixel", "TrajectoCircle"}: if not NoImage: AngleStep = 4 * numpy.pi / TrackPoints Angles = numpy.arange(0.0, 4 * numpy.pi, AngleStep) @@ -1936,7 +1932,7 @@ def BlackHoleCUDA(zImage, fImage, InputCL): cuda.memcpy_dtoh(zImage, zImageCU) cuda.memcpy_dtoh(fImage, fImageCU) - if Method == "TrajectoPixel" or Method == "TrajectoCircle": + if Method in {"TrajectoPixel", "TrajectoCircle"}: cuda.memcpy_dtoh(Trajectories, TrajectoriesCU) elapsed = time.time() - start_time print("\nCompute Time : %f" % compute) @@ -1969,7 +1965,7 @@ def BlackHoleCUDA(zImage, fImage, InputCL): Context.detach() - if Method == "TrajectoPixel" or Method == "TrajectoCircle": + if Method in {"TrajectoPixel", "TrajectoCircle"}: if not NoImage: AngleStep = 4 * numpy.pi / TrackPoints Angles = numpy.arange(0.0, 4 * numpy.pi, AngleStep) @@ -1997,7 +1993,6 @@ def BlackHoleCUDA(zImage, fImage, InputCL): Mass = 1.0 # Internal Radius 3 times de Schwarzschild Radius InternalRadius = 6.0 * Mass - # ExternalRadius = 12.0 # # Angle with normal to disc 10 degrees diff --git a/examples/demo.py b/examples/demo.py index 29e145edb..2d534920c 100644 --- a/examples/demo.py +++ b/examples/demo.py @@ -1,5 +1,3 @@ -#!/usr/bin/env python - import numpy as np import pyopencl as cl diff --git a/examples/dump-properties.py b/examples/dump-properties.py index c6132f22f..8a391122e 100644 --- a/examples/dump-properties.py +++ b/examples/dump-properties.py @@ -69,8 +69,7 @@ def str_chd_type(chdtype): result = result.replace("UNSIGNED", "U") result = result.replace("SIGNED", "S") result = result.replace("NORM", "N") - result = result.replace("FLOAT", "F") - return result + return result.replace("FLOAT", "F") formats = ", ".join( "{}-{}".format( diff --git a/examples/image_filters_using_image2d_t.py b/examples/image_filters_using_image2d_t.py index 8e9c5de8a..19ec72b16 100644 --- a/examples/image_filters_using_image2d_t.py +++ b/examples/image_filters_using_image2d_t.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python3 # this example shows how to blur, gray scale or brightness adjust the picture # using pyopencl and image2d_t buffer objects # this python script will ask you for: diff --git a/examples/n-body.py b/examples/n-body.py index b86832de9..555b898d3 100644 --- a/examples/n-body.py +++ b/examples/n-body.py @@ -1,5 +1,3 @@ -#!/usr/bin/env python3 - """ NBody Demonstrator implemented in OpenCL, rendering OpenGL @@ -525,8 +523,7 @@ def MainOpenCL(clDataX, clDataV, Step, Method): queue, (Number, 1), None, clDataX, clDataV, Step ) CLLaunch.wait() - Elapsed = time.time() - time_start - return Elapsed + return time.time() - time_start def display(*args): diff --git a/examples/pi-monte-carlo.py b/examples/pi-monte-carlo.py index 3c42922d8..44f32b63b 100644 --- a/examples/pi-monte-carlo.py +++ b/examples/pi-monte-carlo.py @@ -1,5 +1,3 @@ -#!/usr/bin/env python3 - # # Pi-by-MonteCarlo using PyCUDA/PyOpenCL # @@ -138,7 +136,7 @@ def Mylq2(N, T1, s, c1, c2, p): def KernelCodeCuda(): - KERNEL_CODE_CUDA = """ + return """ #define TCONG 0 #define TSHR3 1 #define TMWC 2 @@ -285,11 +283,10 @@ def KernelCodeCuda(): } """ - return KERNEL_CODE_CUDA def KernelCodeOpenCL(): - KERNEL_CODE_OPENCL = """ + return """ #define TCONG 0 #define TSHR3 1 #define TMWC 2 @@ -438,7 +435,6 @@ def KernelCodeOpenCL(): } """ - return KERNEL_CODE_OPENCL def MetropolisCuda(InputCU): @@ -643,13 +639,12 @@ def MetropolisOpenCL(InputCL): circleCL.release() - OutputCL = { + return { "Inside": sum(circle), "NewIterations": numpy.uint64(iterationsCL * jobs), "Duration": MyDuration, } # print(OutputCL) - return OutputCL def FitAndPrint(N, D, Curves): diff --git a/examples/svm.py b/examples/svm.py index 7c0ce69e4..876f03eaa 100644 --- a/examples/svm.py +++ b/examples/svm.py @@ -1,5 +1,3 @@ -#!/usr/bin/env python - import numpy as np import pyopencl as cl diff --git a/examples/transpose.py b/examples/transpose.py index d8f86e237..8a64fd1b2 100644 --- a/examples/transpose.py +++ b/examples/transpose.py @@ -189,9 +189,9 @@ def benchmark_transpose(): method(queue, a_t_buf, a_buf, source.shape) count = 12 - events = [] - for _i in range(count): - events.append(method(queue, a_t_buf, a_buf, source.shape)) + events = [ + method(queue, a_t_buf, a_buf, source.shape) + for _i in range(count)] events[-1].wait() time = sum(evt.profile.end - evt.profile.start for evt in events) diff --git a/pyopencl/__init__.py b/pyopencl/__init__.py index 2eea3c626..8b7f5a8f2 100644 --- a/pyopencl/__init__.py +++ b/pyopencl/__init__.py @@ -50,7 +50,7 @@ os.environ["PYOPENCL_HOME"] = os.path.dirname(os.path.abspath(__file__)) try: - import pyopencl._cl as _cl + from pyopencl import _cl except ImportError: from os.path import dirname, join, realpath if realpath(join(os.getcwd(), "pyopencl")) == realpath(dirname(__file__)): @@ -316,7 +316,7 @@ def unquote(path: str): option_idx = 0 while option_idx < len(options): option = options[option_idx].strip() - if option.startswith("-I") or option.startswith("/I"): + if option.startswith(("-I", "/I")): if len(option) == 2: if option_idx+1 < len(options): include_path.append(unquote(options[option_idx+1])) @@ -607,11 +607,9 @@ def _build_and_catch_errors(self, if source is not None: from tempfile import NamedTemporaryFile - srcfile = NamedTemporaryFile(mode="wt", delete=False, suffix=".cl") - try: + with NamedTemporaryFile(mode="wt", delete=False, suffix=".cl") \ + as srcfile: srcfile.write(source) - finally: - srcfile.close() msg = msg + "\n(source saved as %s)" % srcfile.name @@ -881,7 +879,6 @@ def parse_device(choice): raise Error("no devices found") elif len(devices) == 1 and not answers: cc_print(f"Choosing only available device: {devices[0]}") - pass else: if not answers: cc_print("Choose device(s):") @@ -1494,7 +1491,7 @@ def enqueue_fill(queue: CommandQueue, } try: np.float16 # noqa: B018 -except Exception: +except Exception: # noqa: S110 pass else: DTYPE_TO_CHANNEL_TYPE[np.dtype(np.float16)] = channel_type.HALF_FLOAT @@ -1511,7 +1508,7 @@ def image_from_array( ctx: Context, ary: NDArray[Any], num_channels: int | None = None, - mode: Literal["r"] | Literal["w"] = "r", + mode: Literal["r", "w"] = "r", norm_int: bool = False ) -> Image: if not ary.flags.c_contiguous: @@ -1668,7 +1665,7 @@ def svm_empty( flags: svm_mem_flags, shape: int | tuple[int, ...], dtype: DTypeT, - order: Literal["F"] | Literal["C"] = "C", + order: Literal["F", "C"] = "C", alignment: int | None = None, queue: CommandQueue | None = None, ) -> np.ndarray[tuple[int, ...], DTypeT]: @@ -1782,7 +1779,7 @@ def csvm_empty( ctx: Context, shape: int | tuple[int, ...], dtype: DTypeT, - order: Literal["F"] | Literal["C"] = "C", + order: Literal["F", "C"] = "C", alignment: int | None = None, queue: CommandQueue | None = None, ) -> np.ndarray[tuple[int, ...], DTypeT]: @@ -1814,7 +1811,7 @@ def fsvm_empty( ctx: Context, shape: int | tuple[int, ...], dtype: DTypeT, - order: Literal["F"] | Literal["C"] = "C", + order: Literal["F", "C"] = "C", alignment: int | None = None, queue: CommandQueue | None = None, ) -> np.ndarray[tuple[int, ...], DTypeT]: diff --git a/pyopencl/_cl.pyi b/pyopencl/_cl.pyi index 45a0a1124..3497426cc 100644 --- a/pyopencl/_cl.pyi +++ b/pyopencl/_cl.pyi @@ -49,13 +49,13 @@ class Error(Exception): __str__ = pyopencl._monkeypatch.error_str class MemoryError(Error): - pass + ... class LogicError(Error): - pass + ... class RuntimeError(Error): - pass + ... class status_code(IntEnum): # noqa: N801 SUCCESS = auto() @@ -1136,7 +1136,7 @@ class MemoryObjectHolder: def get_host_array(self, shape: tuple[int, ...], dtype: DTypeT, - order: Literal["C"] | Literal["F"] = "C" + order: Literal["C", "F"] = "C" ) -> np.ndarray[tuple[int, ...], DTypeT]: ... @overload @@ -1510,7 +1510,7 @@ def enqueue_map_buffer( offset: int, shape: tuple[int, ...], dtype: DTypeT, - order: Literal["C"] | Literal["F"] = "C", + order: Literal["C", "F"] = "C", strides: tuple[int, ...] | None = None, wait_for: WaitList = None, is_blocking: bool = True @@ -1524,7 +1524,7 @@ def enqueue_map_image( region: tuple[int, ...], shape: tuple[int, ...], dtype: DTypeT, - order: Literal["C"] | Literal["F"] = "C", + order: Literal["C", "F"] = "C", strides: tuple[int, ...] | None = None, wait_for: WaitList = None, is_blocking: bool = True diff --git a/pyopencl/_monkeypatch.py b/pyopencl/_monkeypatch.py index 2322ff0ba..03f36f89e 100644 --- a/pyopencl/_monkeypatch.py +++ b/pyopencl/_monkeypatch.py @@ -37,7 +37,7 @@ import numpy as np -import pyopencl._cl as _cl +from pyopencl import _cl if TYPE_CHECKING: @@ -1063,7 +1063,7 @@ def add_get_info( info_class: type[InfoT], cacheable_attrs: Collection[str] = (), ) -> None: - for info_name, _info_value in info_class.__dict__.items(): + for info_name in info_class.__dict__: if info_name == "to_string" or info_name.startswith("_"): continue diff --git a/pyopencl/algorithm.py b/pyopencl/algorithm.py index f2bd77b6f..448372d4e 100644 --- a/pyopencl/algorithm.py +++ b/pyopencl/algorithm.py @@ -348,9 +348,8 @@ def _make_sort_scan_type( ) -> tuple[str, np.dtype[Any], str]: name = f"pyopencl_sort_scan_{index_dtype.type.__name__}_{bits}bits_t" - fields: list[tuple[str, np.dtype[np.integer[Any]]]] = [] - for mnr in range(2**bits): - fields.append((f"c{_padded_bin(mnr, bits)}", index_dtype)) + fields: list[tuple[str, np.dtype[np.integer[Any]]]] = [ + (f"c{_padded_bin(mnr, bits)}", index_dtype) for mnr in range(2**bits)] dtype = np.dtype(fields) from pyopencl.tools import get_or_register_dtype, match_dtype_to_c_struct diff --git a/pyopencl/array.py b/pyopencl/array.py index 3f395bf85..1c48ad276 100644 --- a/pyopencl/array.py +++ b/pyopencl/array.py @@ -50,8 +50,7 @@ from typing_extensions import Self, TypeIs, override import pyopencl as cl -import pyopencl.elementwise as elementwise -from pyopencl import cltypes +from pyopencl import cltypes, elementwise from pyopencl.characterize import has_double_support from pyopencl.compyte.array import ( ArrayFlags as _ArrayFlags, @@ -655,15 +654,14 @@ def __init__( self._flags: _ArrayFlags | None = _flags - if __debug__: - if queue is not None and isinstance( - self.base_data, _SVMPointer_or_nothing): - mem_queue = getattr(self.base_data, "_queue", _NOT_PRESENT) - if mem_queue is not _NOT_PRESENT and mem_queue != queue: - warn("Array has different queue from backing SVM memory. " - "This may lead to the array getting deallocated sooner " - "than expected, potentially leading to crashes.", - InconsistentOpenCLQueueWarning, stacklevel=2) + if __debug__ and queue is not None and isinstance( + self.base_data, _SVMPointer_or_nothing): + mem_queue = getattr(self.base_data, "_queue", _NOT_PRESENT) + if mem_queue is not _NOT_PRESENT and mem_queue != queue: + warn("Array has different queue from backing SVM memory. " + "This may lead to the array getting deallocated sooner " + "than expected, potentially leading to crashes.", + InconsistentOpenCLQueueWarning, stacklevel=2) @property def ndim(self) -> int: @@ -1281,7 +1279,7 @@ def __rsub__(self, other) -> Self: def __iadd__(self, other) -> Self: if isinstance(other, Array): - if other.shape != self.shape and other.shape != (): + if other.shape not in (self.shape, ()): raise NotImplementedError("Broadcasting binary op with shapes:" f" {self.shape}, {other.shape}.") self.add_event( @@ -1299,7 +1297,7 @@ def __iadd__(self, other) -> Self: def __isub__(self, other) -> Self: if isinstance(other, Array): - if other.shape != self.shape and other.shape != (): + if other.shape not in (self.shape, ()): raise NotImplementedError("Broadcasting binary op with shapes:" f" {self.shape}, {other.shape}.") self.add_event( @@ -1349,7 +1347,7 @@ def __rmul__(self, other) -> Self: def __imul__(self, other) -> Self: if isinstance(other, Array): - if other.shape != self.shape and other.shape != (): + if other.shape not in (self.shape, ()): raise NotImplementedError("Broadcasting binary op with shapes:" f" {self.shape}, {other.shape}.") self.add_event( @@ -1415,7 +1413,7 @@ def __itruediv__(self, other) -> Self: "Cannot cast {!r} to {!r}".format(self.dtype, common_dtype)) if isinstance(other, Array): - if other.shape != self.shape and other.shape != (): + if other.shape not in (self.shape, ()): raise NotImplementedError("Broadcasting binary op with shapes:" f" {self.shape}, {other.shape}.") self.add_event( @@ -1500,7 +1498,7 @@ def __iand__(self, other) -> Self: raise TypeError(f"Integral types only: {common_dtype}") if isinstance(other, Array): - if other.shape != self.shape and other.shape != (): + if other.shape not in (self.shape, ()): raise NotImplementedError("Broadcasting binary op with shapes:" f" {self.shape}, {other.shape}.") self.add_event(self._array_binop(self, self, other, op="&")) @@ -1519,7 +1517,7 @@ def __ior__(self, other) -> Self: raise TypeError(f"Integral types only: {common_dtype}") if isinstance(other, Array): - if other.shape != self.shape and other.shape != (): + if other.shape not in (self.shape, ()): raise NotImplementedError("Broadcasting binary op with shapes:" f" {self.shape}, {other.shape}.") self.add_event(self._array_binop(self, self, other, op="|")) @@ -1538,7 +1536,7 @@ def __ixor__(self, other) -> Self: raise TypeError(f"Integral types only: {common_dtype}") if isinstance(other, Array): - if other.shape != self.shape and other.shape != (): + if other.shape not in (self.shape, ()): raise NotImplementedError("Broadcasting binary op with shapes:" f" {self.shape}, {other.shape}.") self.add_event(self._array_binop(self, self, other, op="^")) @@ -1900,7 +1898,7 @@ def reshape(self, *shape, **kwargs): # raise RuntimeError("only contiguous arrays may " # "be used as arguments to this operation") - if isinstance(shape[0], tuple) or isinstance(shape[0], list): + if isinstance(shape[0], (tuple, list)): shape = tuple(shape[0]) if -1 in shape: @@ -2399,7 +2397,7 @@ def zeros( queue: cl.CommandQueue, shape: int | tuple[int, ...], dtype: DTypeLike, - order: Literal["C"] | Literal["F"] = "C", + order: Literal["C", "F"] = "C", allocator: Allocator | None = None, ) -> Array: """Same as :func:`empty`, but the :class:`Array` is zero-initialized before @@ -2765,10 +2763,9 @@ def multi_put( array_lengths = np.ndarray((chunk_size,), dtype=np.int64) def make_func_for_chunk_size(chunk_size): - knl = elementwise.get_put_kernel( + return elementwise.get_put_kernel( context, a_dtype, dest_indices.dtype, vec_count=chunk_size) - return knl knl = make_func_for_chunk_size(chunk_size) @@ -2849,12 +2846,11 @@ def concatenate(arrays, axis=0, queue: cl.CommandQueue | None = None, allocator= shape = tuple(shape) dtype = np.result_type(*[ary.dtype for ary in arrays]) - if __debug__: - if builtins.any(type(ary) != type(arrays[0]) # noqa: E721 - for ary in arrays[1:]): - warn("Elements of 'arrays' not of the same type, returning " - "an instance of the type of arrays[0]", - stacklevel=2) + if __debug__ and builtins.any(type(ary) != type(arrays[0]) # noqa: E721 + for ary in arrays[1:]): + warn("Elements of 'arrays' not of the same type, returning " + "an instance of the type of arrays[0]", + stacklevel=2) result = arrays[0].__class__(queue, shape, dtype, allocator=allocator) @@ -2916,12 +2912,11 @@ def hstack(arrays, queue: cl.CommandQueue | None = None): w = builtins.sum(ary.shape[-1] for ary in arrays) - if __debug__: - if builtins.any(type(ary) != type(arrays[0]) # noqa: E721 - for ary in arrays[1:]): - warn("Elements of 'arrays' not of the same type, returning " - "an instance of the type of arrays[0]", - stacklevel=2) + if __debug__ and builtins.any(type(ary) != type(arrays[0]) # noqa: E721 + for ary in arrays[1:]): + warn("Elements of 'arrays' not of the same type, returning " + "an instance of the type of arrays[0]", + stacklevel=2) result = arrays[0].__class__(queue, (*lead_shape, w), arrays[0].dtype, allocator=arrays[0].allocator) @@ -2974,12 +2969,11 @@ def stack(arrays, axis=0, queue: cl.CommandQueue | None = None): result_shape = (*input_shape[:axis], len(arrays), *input_shape[axis:]) - if __debug__: - if builtins.any(type(ary) != type(arrays[0]) # noqa: E721 - for ary in arrays[1:]): - warn("Elements of 'arrays' not of the same type, returning " - "an instance of the type of arrays[0]", - stacklevel=2) + if __debug__ and builtins.any(type(ary) != type(arrays[0]) # noqa: E721 + for ary in arrays[1:]): + warn("Elements of 'arrays' not of the same type, returning " + "an instance of the type of arrays[0]", + stacklevel=2) result = arrays[0].__class__(queue, result_shape, np.result_type(*(ary.dtype diff --git a/pyopencl/bitonic_sort.py b/pyopencl/bitonic_sort.py index b9eb9ea6f..7eb599506 100644 --- a/pyopencl/bitonic_sort.py +++ b/pyopencl/bitonic_sort.py @@ -162,8 +162,7 @@ def get_program(self, letter, argsort, params): kid = mako.template.Template(self.kernels_srcs[letter]).render(argsort=argsort) - prg = cl.Program(self.context, defs + kid).build() - return prg + return cl.Program(self.context, defs + kid).build() @memoize_method def sort_b_prepare_wl(self, argsort, key_dtype, idx_dtype, shape, axis): diff --git a/pyopencl/cache.py b/pyopencl/cache.py index 62b97f918..f343347a1 100644 --- a/pyopencl/cache.py +++ b/pyopencl/cache.py @@ -35,7 +35,7 @@ from typing_extensions import Buffer, override -import pyopencl._cl as _cl +from pyopencl import _cl logger = logging.getLogger(__name__) @@ -210,7 +210,7 @@ def _inner(src: bytes): if included_file_name not in result: try: - src_file = open(included_file_name, "rb") + src_file = open(included_file_name, "rb") # noqa: SIM115 except OSError: continue @@ -251,12 +251,8 @@ def _inner(src: bytes): def get_file_md5sum(fname: str) -> str: checksum = new_hash() - inf = open(fname) - try: - contents = inf.read() - finally: - inf.close() - update_checksum(checksum, contents) + with open(fname) as inf: + update_checksum(checksum, inf.read()) return checksum.hexdigest() @@ -318,7 +314,7 @@ class _InvalidInfoFileError(RuntimeError): from pickle import load try: - info_file = open(info_path, "rb") + info_file = open(info_path, "rb") # noqa: SIM115 except OSError as err: raise _InvalidInfoFileError() from err @@ -342,11 +338,8 @@ class _InvalidInfoFileError(RuntimeError): # {{{ load binary - binary_file = open(binary_path, "rb") - try: + with open(binary_path, "rb") as binary_file: binary = binary_file.read() - finally: - binary_file.close() # }}} @@ -506,11 +499,10 @@ def _create_built_program_from_source_cached( outf.write(binary) from pickle import dump - info_file = open(info_path, "wb") - dump(_SourceInfo( - dependencies=get_dependencies(src, include_path or []), - log=logs[i]), info_file) - info_file.close() + with open(info_path, "wb") as info_file: + dump(_SourceInfo( + dependencies=get_dependencies(src, include_path or []), + log=logs[i]), info_file) except Exception: cleanup_m.error_clean_up() diff --git a/pyopencl/characterize/__init__.py b/pyopencl/characterize/__init__.py index 45c7ef06a..f4940b543 100644 --- a/pyopencl/characterize/__init__.py +++ b/pyopencl/characterize/__init__.py @@ -56,7 +56,7 @@ def reasonable_work_group_size_multiple( ): try: return dev.warp_size_nv - except Exception: + except Exception: # noqa: S110 pass if ctx is None: @@ -285,7 +285,7 @@ def get_simd_group_size(dev: cl.Device, type_size: int): """ try: return dev.warp_size_nv - except Exception: + except Exception: # noqa: S110 pass lc_plat_vendor = dev.platform.vendor.lower() @@ -381,7 +381,10 @@ def _check_for_pocl_arg_count_bug( return result -def has_struct_arg_count_bug(dev, ctx=None): +def has_struct_arg_count_bug( + dev: cl.Device, + ctx: cl.Context | None = None + ): """Checks whether the device is expected to have the `argument counting bug `__. """ @@ -390,9 +393,9 @@ def has_struct_arg_count_bug(dev, ctx=None): return "apple" if dev.platform.name == "Portable Computing Language": pocl_version = get_pocl_version(dev.platform, fallback_value=(0, 14)) - if pocl_version <= (0, 13): - return "pocl" - elif pocl_version <= (0, 14) and _check_for_pocl_arg_count_bug(dev, ctx): + assert pocl_version is not None + if (pocl_version <= (0, 13) + or (pocl_version <= (0, 14) and _check_for_pocl_arg_count_bug(dev, ctx))): return "pocl" return False diff --git a/pyopencl/clmath.py b/pyopencl/clmath.py index 4a40b825c..2c92a5ef3 100644 --- a/pyopencl/clmath.py +++ b/pyopencl/clmath.py @@ -26,7 +26,7 @@ import numpy as np import pyopencl.array as cl_array -import pyopencl.elementwise as elementwise +from pyopencl import elementwise from pyopencl.array import _get_common_dtype diff --git a/pyopencl/clrandom.py b/pyopencl/clrandom.py index 2805535b6..98cf8f515 100644 --- a/pyopencl/clrandom.py +++ b/pyopencl/clrandom.py @@ -58,7 +58,7 @@ import pyopencl as cl import pyopencl.array as cl_array -import pyopencl.cltypes as cltypes +from pyopencl import cltypes from pyopencl.tools import first_arg_dependent_memoize diff --git a/pyopencl/compyte b/pyopencl/compyte index 46d7320a3..80ed45de9 160000 --- a/pyopencl/compyte +++ b/pyopencl/compyte @@ -1 +1 @@ -Subproject commit 46d7320a34ac4782a13d8bb2add1a57207cd6038 +Subproject commit 80ed45de98b5432341763b9fa52a00fdac870b89 diff --git a/pyopencl/elementwise.py b/pyopencl/elementwise.py index dde4f04f2..e31e6d1c3 100644 --- a/pyopencl/elementwise.py +++ b/pyopencl/elementwise.py @@ -158,10 +158,9 @@ def get_elwise_kernel_and_types( #define PYOPENCL_DEFINE_CDOUBLE """) have_double_pragma = True - if arg.dtype.kind == "c": - if not have_complex_include: - includes.append("#include \n") - have_complex_include = True + if arg.dtype.kind == "c" and not have_complex_include: + includes.append("#include \n") + have_complex_include = True if pragmas or includes: preamble = "\n".join(pragmas+includes) + "\n" + preamble diff --git a/pyopencl/invoker.py b/pyopencl/invoker.py index a7e524c24..9f26b3f14 100644 --- a/pyopencl/invoker.py +++ b/pyopencl/invoker.py @@ -34,7 +34,7 @@ from pytools.py_codegen import Indentation, PythonCodeGenerator import pyopencl as cl -import pyopencl._cl as _cl +from pyopencl import _cl from pyopencl.tools import VectorArg, _NumpyTypesKeyBuilder @@ -352,9 +352,7 @@ def _check_arg_size(function_name, num_cl_args, arg_types, devs): if arg_types: for arg_type in arg_types: - if arg_type is None: - total_arg_size += dev_ptr_size - elif isinstance(arg_type, VectorArg): + if arg_type is None or isinstance(arg_type, VectorArg): total_arg_size += dev_ptr_size else: total_arg_size += np.dtype(arg_type).itemsize diff --git a/pyopencl/scan.py b/pyopencl/scan.py index 243b9a945..df4a2ce80 100644 --- a/pyopencl/scan.py +++ b/pyopencl/scan.py @@ -770,89 +770,62 @@ def _round_down_to_power_of_2(val: int) -> int: return result -_PREFIX_WORDS = set(""" - ldata partial_scan_buffer global scan_offset - segment_start_in_k_group carry - g_first_segment_start_in_interval IS_SEG_START tmp Z - val l_first_segment_start_in_subtree unit_size - index_type interval_begin interval_size offset_end K - SCAN_EXPR do_update WG_SIZE - first_segment_start_in_k_group scan_type - segment_start_in_subtree offset interval_results interval_end - first_segment_start_in_subtree unit_base - first_segment_start_in_interval k INPUT_EXPR - prev_group_sum prev pv value partial_val pgs - is_seg_start update_i scan_item_at_i seq_i read_i - l_ o_mod_k o_div_k l_segment_start_flags scan_value sum - first_seg_start_in_interval g_segment_start_flags - group_base seg_end my_val DEBUG ARGS - ints_to_store ints_per_wg scan_types_per_int linear_index - linear_scan_data_idx dest src store_base wrapped_scan_type - dummy scan_tmp tmp_aux - - LID_2 LID_1 LID_0 - LDIM_0 LDIM_1 LDIM_2 - GDIM_0 GDIM_1 GDIM_2 - GID_0 GID_1 GID_2 - """.split()) - -_IGNORED_WORDS = set(""" - 4 8 32 - - typedef for endfor if void while endwhile endfor endif else const printf - None return bool n char true false ifdef pycl_printf str range assert - np iinfo max itemsize __packed__ struct restrict ptrdiff_t - - set iteritems len setdefault - - GLOBAL_MEM LOCAL_MEM_ARG WITHIN_KERNEL LOCAL_MEM KERNEL REQD_WG_SIZE - local_barrier - CLK_LOCAL_MEM_FENCE OPENCL EXTENSION - pragma __attribute__ __global __kernel __local - get_local_size get_local_id cl_khr_fp64 reqd_work_group_size - get_num_groups barrier get_group_id - CL_VERSION_1_1 __OPENCL_C_VERSION__ 120 - - _final_update _debug_scan kernel_name - - positions all padded integer its previous write based writes 0 - has local worth scan_expr to read cannot not X items False bank - four beginning follows applicable item min each indices works side - scanning right summed relative used id out index avoid current state - boundary True across be This reads groups along Otherwise undetermined - store of times prior s update first regardless Each number because - array unit from segment conflicts two parallel 2 empty define direction - CL padding work tree bounds values and adds - scan is allowed thus it an as enable at in occur sequentially end no - storage data 1 largest may representable uses entry Y meaningful - computations interval At the left dimension know d - A load B group perform shift tail see last OR - this add fetched into are directly need - gets them stenciled that undefined - there up any ones or name only relevant populated - even wide we Prepare int seg Note re below place take variable must - intra Therefore find code assumption - branch workgroup complicated granularity phase remainder than simpler - We smaller look ifs lots self behind allow barriers whole loop - after already Observe achieve contiguous stores hard go with by math - size won t way divisible bit so Avoid declare adding single type - - is_tail is_first_level input_expr argument_signature preamble - double_support neutral output_statement - k_group_size name_prefix is_segmented index_dtype scan_dtype - wg_size is_segment_start_expr fetch_expr_offsets - arg_ctypes ife_offsets input_fetch_exprs def - ife_offset arg_name local_fetch_expr_args update_body - update_loop_lookbehind update_loop_plain update_loop - use_lookbehind_update store_segment_start_flags - update_loop first_seg scan_dtype dtype_to_ctype - is_gpu use_bank_conflict_avoidance - - a b prev_item i last_item prev_value - N NO_SEG_BOUNDARY across_seg_boundary - - arg_offset_adjustment - """.split()) +_PREFIX_WORDS = {"ldata", "partial_scan_buffer", "global", "scan_offset", +"segment_start_in_k_group", "carry", "g_first_segment_start_in_interval", +"IS_SEG_START", "tmp", "Z", "val", "l_first_segment_start_in_subtree", +"unit_size", "index_type", "interval_begin", "interval_size", "offset_end", "K", +"SCAN_EXPR", "do_update", "WG_SIZE", "first_segment_start_in_k_group", "scan_type", +"segment_start_in_subtree", "offset", "interval_results", "interval_end", +"first_segment_start_in_subtree", "unit_base", "first_segment_start_in_interval", +"k", "INPUT_EXPR", "prev_group_sum", "prev", "pv", "value", "partial_val", "pgs", +"is_seg_start", "update_i", "scan_item_at_i", "seq_i", "read_i", "l_", "o_mod_k", +"o_div_k", "l_segment_start_flags", "scan_value", "sum", "first_seg_start_in_interval", +"g_segment_start_flags", "group_base", "seg_end", "my_val", "DEBUG", "ARGS", +"ints_to_store", "ints_per_wg", "scan_types_per_int", "linear_index", +"linear_scan_data_idx", "dest", "src", "store_base", "wrapped_scan_type", "dummy", +"scan_tmp", "tmp_aux", "LID_2", "LID_1", "LID_0", "LDIM_0", "LDIM_1", "LDIM_2", +"GDIM_0", "GDIM_1", "GDIM_2", "GID_0", "GID_1", "GID_2"} + +_IGNORED_WORDS = {"4", "8", "32", "typedef", "for", "endfor", "if", "void", "while", +"endwhile", "endif", "else", "const", "printf", "None", "return", "bool", "n", "char", +"true", "false", "ifdef", "pycl_printf", "str", "range", "assert", "np", "iinfo", +"max", "itemsize", "__packed__", "struct", "restrict", "ptrdiff_t", "set", "iteritems", +"len", "setdefault", "GLOBAL_MEM", "LOCAL_MEM_ARG", "WITHIN_KERNEL", "LOCAL_MEM", +"KERNEL", "REQD_WG_SIZE", "local_barrier", "CLK_LOCAL_MEM_FENCE", "OPENCL", "EXTENSION", +"pragma", "__attribute__", "__global", "__kernel", "__local", "get_local_size", +"get_local_id", "cl_khr_fp64", "reqd_work_group_size", "get_num_groups", "barrier", +"get_group_id", "CL_VERSION_1_1", "__OPENCL_C_VERSION__", "120", "_final_update", +"_debug_scan", "kernel_name", "positions", "all", "padded", "integer", "its", +"previous", "write", "based", "writes", "0", "has", "local", "worth", "scan_expr", "to", +"read", "cannot", "not", "X", "items", "False", "bank", "four", "beginning", "follows", +"applicable", "item", "min", "each", "indices", "works", "side", "scanning", "right", +"summed", "relative", "used", "id", "out", "index", "avoid", "current", "state", +"boundary", "True", "across", "be", "This", "reads", "groups", "along", "Otherwise", +"undetermined", "store", "of", "times", "prior", "s", "update", "first", "regardless", +"Each", "number", "because", "array", "unit", "from", "segment", "conflicts", "two", +"parallel", "2", "empty", "define", "direction", "CL", "padding", "work", "tree", +"bounds", "values", "and", "adds", "scan", "is", "allowed", "thus", "it", "an", "as", +"enable", "at", "in", "occur", "sequentially", "end", "no", "storage", "data", "1", +"largest", "may", "representable", "uses", "entry", "Y", "meaningful", "computations", +"interval", "At", "the", "left", "dimension", "know", "d", "A", "load", "B", "group", +"perform", "shift", "tail", "see", "last", "OR", "this", "add", "fetched", "into", +"are", "directly", "need", "gets", "them", "stenciled", "that", "undefined", "there", +"up", "any", "ones", "or", "name", "only", "relevant", "populated", "even", "wide", +"we", "Prepare", "int", "seg", "Note", "re", "below", "place", "take", "variable", +"must", "intra", "Therefore", "find", "code", "assumption", "branch", "workgroup", +"complicated", "granularity", "phase", "remainder", "than", "simpler", "We", "smaller", +"look", "ifs", "lots", "self", "behind", "allow", "barriers", "whole", "loop", +"after", "already", "Observe", "achieve", "contiguous", "stores", "hard", "go", +"with", "by", "math", "size", "won", "t", "way", "divisible", "bit", "so", "Avoid", +"declare", "adding", "single", "type", "is_tail", "is_first_level", "input_expr", +"argument_signature", "preamble", "double_support", "neutral", "output_statement", +"k_group_size", "name_prefix", "is_segmented", "index_dtype", "scan_dtype", +"wg_size", "is_segment_start_expr", "fetch_expr_offsets", "arg_ctypes", "ife_offsets", +"input_fetch_exprs", "def", "ife_offset", "arg_name", "local_fetch_expr_args", +"update_body", "update_loop_lookbehind", "update_loop_plain", "update_loop", +"use_lookbehind_update", "store_segment_start_flags", "first_seg", "dtype_to_ctype", +"is_gpu", "use_bank_conflict_avoidance", "a", "b", "prev_item", "i", "last_item", +"prev_value", "N", "NO_SEG_BOUNDARY", "across_seg_boundary", "arg_offset_adjustment"} def _make_template(s: str) -> mako.template.Template: @@ -1314,7 +1287,7 @@ def _finish_setup_impl(self) -> None: # division by that number. solutions: list[tuple[int, int, int]] = [] - for k_exp in range(0, 9): + for k_exp in range(9): for wg_size in range(wg_size_multiples, max_scan_wg_size+1, wg_size_multiples): diff --git a/pyopencl/tools.py b/pyopencl/tools.py index 869545a24..efe931502 100644 --- a/pyopencl/tools.py +++ b/pyopencl/tools.py @@ -655,7 +655,7 @@ def _find_cl_obj( ) -> DeviceOrPlatformT: try: num = int(identifier) - except Exception: + except Exception: # noqa: S110 pass else: return objs[num] diff --git a/pyproject.toml b/pyproject.toml index 2f7dfc43a..b48c43449 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -18,7 +18,7 @@ license = "MIT" authors = [ { name = "Andreas Kloeckner", email = "inform@tiker.net" }, ] -requires-python = "~=3.10" +requires-python = ">=3.10,<4" classifiers = [ "Development Status :: 5 - Production/Stable", "Environment :: Console", @@ -100,9 +100,15 @@ extend-ignore = [ "C90", # McCabe complexity "UP031", # use f-strings instead of % "UP032", # use f-strings instead of .format + "TRY004", + "BLE001", + "TRY300", # FIXME: This is a longer discussion... "RUF067", # __init__ should only contain reexports + + # FIXME + "SIM102", ] exclude = [ "examples/gl_interop_demo.py", @@ -112,15 +118,17 @@ exclude = [ [tool.ruff.lint.per-file-ignores] "examples/pi-monte-carlo.py" = ["N", "B", "F841"] -"examples/black-hole-accretion.py" = ["N", "E501", "B"] -"examples/n-body.py" = ["N", "E501"] +"examples/black-hole-accretion.py" = ["N", "E501", "B", "SIM"] +"examples/n-body.py" = ["N", "E501", "PLW"] "pyopencl/__init__.py" = ["I001"] "contrib/fortran-to-opencl/translate.py" = ["N802", "N815", "B"] -"doc/*.py" = ["I002"] +"doc/*.py" = ["I002", "S102"] "examples/*.py" = ["I002"] -"test/*.py" = ["I002"] +"test/*.py" = ["I002", "BLE001"] +"test/test_*.py" = ["I002", "S102"] "contrib/**/*.py" = ["I002"] "*.ipynb" = ["I002"] +"pyopencl/_cl.pyi" = ["PYI052", "PYI002"] [tool.ruff.lint.flake8-quotes] inline-quotes = "double" diff --git a/test/test_algorithm.py b/test/test_algorithm.py index 36eb3a7c1..c68624e05 100644 --- a/test/test_algorithm.py +++ b/test/test_algorithm.py @@ -1085,7 +1085,7 @@ def test_bitonic_sort(ctx_factory: cl.CtxFactory, size, dtype): # Requires https://github.com/intel/llvm/releases/tag/2022-WW50 or newer to pass # on Intel CL. - import pyopencl.clrandom as clrandom + from pyopencl import clrandom from pyopencl.bitonic_sort import BitonicSort s = clrandom.rand(queue, (2, size, 3,), dtype, luxury=None, a=0, b=239482333) @@ -1153,7 +1153,7 @@ def test_bitonic_argsort(ctx_factory: cl.CtxFactory, size, dtype): from pytest import skip skip("double precision not supported on %s" % dev) - import pyopencl.clrandom as clrandom + from pyopencl import clrandom from pyopencl.bitonic_sort import BitonicSort index = cl_array.arange(queue, 0, size, 1, dtype=np.int32) diff --git a/test/test_array.py b/test/test_array.py index b0d5800e1..7c615d032 100644 --- a/test/test_array.py +++ b/test/test_array.py @@ -1,5 +1,3 @@ -#! /usr/bin/env python - __copyright__ = "Copyright (C) 2009 Andreas Kloeckner" __license__ = """ @@ -34,8 +32,8 @@ import pyopencl as cl import pyopencl.array as cl_array import pyopencl.characterize as cl_characterize -import pyopencl.cltypes as cltypes import pyopencl.tools as cl_tools +from pyopencl import cltypes from pyopencl.characterize import has_double_support, has_struct_arg_count_bug from pyopencl.clrandom import PhiloxGenerator, ThreefryGenerator from pyopencl.tools import ( @@ -934,7 +932,7 @@ def test_random_int_in_range(ctx_factory: cl.CtxFactory, def test_numpy_integer_shape(ctx_factory: cl.CtxFactory): try: list(np.int32(17)) - except Exception: + except Exception: # noqa: S110 pass else: from pytest import skip diff --git a/test/test_arrays_in_structs.py b/test/test_arrays_in_structs.py index bf64b7d40..3a3d3b100 100644 --- a/test/test_arrays_in_structs.py +++ b/test/test_arrays_in_structs.py @@ -23,9 +23,8 @@ import numpy as np import pyopencl as cl -import pyopencl.cltypes as cltypes import pyopencl.tools as cl_tools -from pyopencl import mem_flags +from pyopencl import cltypes, mem_flags from pyopencl.tools import ( pytest_generate_tests_for_pyopencl as pytest_generate_tests, # noqa: F401 ) @@ -60,9 +59,7 @@ def test_struct_with_array_fields(ctx_factory): ([57, 38], -54, [[74, 90, 38, 67], [77, 30, 99, 18], [91, 3, 63, 67]]) ], dtype=my_struct) - expected_res = [] - for x in my_struct_arr: - expected_res.append(int(np.sum(x[0]) + x[1] + np.sum(x[2]))) + expected_res = [int(np.sum(x[0]) + x[1] + np.sum(x[2])) for x in my_struct_arr] expected_res = np.array(expected_res, dtype=cltypes.int) kernel_src = """%s diff --git a/test/test_clmath.py b/test/test_clmath.py index b3d4816d8..e2957ecf6 100644 --- a/test/test_clmath.py +++ b/test/test_clmath.py @@ -27,7 +27,7 @@ import pyopencl as cl import pyopencl.array as cl_array -import pyopencl.clmath as clmath +from pyopencl import clmath from pyopencl.characterize import has_double_support, has_struct_arg_count_bug from pyopencl.tools import ( pytest_generate_tests_for_pyopencl as pytest_generate_tests, # noqa: F401 @@ -282,7 +282,7 @@ def get_err(check, ref): a_dev = cl_array.to_device(queue, a) - for n in range(0, nterms): + for n in range(nterms): cl_bessel = cl_func(n, a_dev).get() scipy_bessel = scipy_func(n, a) @@ -302,7 +302,7 @@ def get_err(check, ref): assert not np.isnan(cl_bessel).any() - if 0 and n == 15: + if False: import matplotlib.pyplot as pt # pt.plot(scipy_bessel) diff --git a/test/test_clrandom.py b/test/test_clrandom.py index 4e881a03e..f1fc861f8 100644 --- a/test/test_clrandom.py +++ b/test/test_clrandom.py @@ -24,8 +24,7 @@ import pytest import pyopencl as cl -import pyopencl.clrandom as clrandom -import pyopencl.cltypes as cltypes +from pyopencl import clrandom, cltypes from pyopencl.characterize import has_double_support from pyopencl.tools import ( pytest_generate_tests_for_pyopencl as pytest_generate_tests, # noqa: F401 diff --git a/test/test_enqueue_copy.py b/test/test_enqueue_copy.py index 91ed0ddfd..ca3129d3e 100644 --- a/test/test_enqueue_copy.py +++ b/test/test_enqueue_copy.py @@ -1,5 +1,3 @@ -#! /usr/bin/env python - __copyright__ = "Copyright (C) 2016 Shane J. Latham" __license__ = """ diff --git a/test/test_wrapper.py b/test/test_wrapper.py index 4c9b44f10..5bd31c0a4 100644 --- a/test/test_wrapper.py +++ b/test/test_wrapper.py @@ -26,8 +26,7 @@ import pyopencl as cl import pyopencl.array as cl_array -import pyopencl.clrandom as clrandom -import pyopencl.cltypes as cltypes +from pyopencl import clrandom, cltypes from pyopencl.characterize import get_pocl_version from pyopencl.tools import ( DeferredAllocator,