diff --git a/.flake8 b/.flake8 new file mode 100644 index 000000000000..abc2ecebefdd --- /dev/null +++ b/.flake8 @@ -0,0 +1,64 @@ +[flake8] +extend-ignore = + # whitespace before ':' (currently conflicts with black formatting): + E203, + # line too long (in docstrings): + E501, + # ‘from module import *’ used; unable to detect undefined names: + F403, + # name may be undefined, or defined from star imports: module: + F405, + # doc line too long (105 > 80 characters): + W505, + # missing docstring in public module: + D100, + # missing docstring in public class: + D101, + # missing docstring in public method: + D102, + # missing docstring in public function: + D103, + # missing docstring in public package: + D104, + # missing docstring in magic method: + D105, + # missing docstring in __init__: + D107, + # no blank lines allowed after function docstring: + D202, + # first line should end with a period: + D400, + # first line should be in imperative mood: + D401, + # first line should not be the function's "signature": + D402, + # section has no content: + D414 + +per-file-ignores = + __init__.py: E402, F401 + dpnp/dpnp_algo/__init__.py: F401 + dpnp/dpnp_algo/__init__.py: F401 + dpnp/fft/__init__.py: F401 + dpnp/linalg/__init__.py: F401 + dpnp/random/__init__.py: F401 + dpnp/dpnp_iface.py: D205 + +filename = *.py, *.pyx, *.pxi, *.pxd +max_line_length = 80 +max-doc-length = 80 +show-source = True + +exclude = + .git, + benchmarks/*.py, + build, + dpnp/to_numba/*.py, + conda.recipe, + tests/*.py, + tests_external/*.py, + version.py, + +# Print detailed statistic if any issue detected +count = True +statistics = True diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index a5c845a318f3..16d0fd756476 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -39,6 +39,14 @@ repos: - id: isort name: isort (pyi) types: [pyi] +- repo: https://github.com/pycqa/flake8 + rev: 6.0.0 + hooks: + - id: flake8 + args: ["--config=.flake8"] + additional_dependencies: + - flake8-docstrings==1.7.0 + - flake8-bugbear==23.6.5 - repo: https://github.com/pocc/pre-commit-hooks rev: v1.3.5 hooks: diff --git a/dpnp/dpnp_algo/dpnp_elementwise_common.py b/dpnp/dpnp_algo/dpnp_elementwise_common.py index 3319f3c9ab0a..a4dd92cec747 100644 --- a/dpnp/dpnp_algo/dpnp_elementwise_common.py +++ b/dpnp/dpnp_algo/dpnp_elementwise_common.py @@ -30,7 +30,6 @@ import dpctl import dpctl.tensor as dpt import dpctl.tensor._tensor_impl as ti -import numpy from dpctl.tensor._elementwise_common import BinaryElementwiseFunc import dpnp @@ -67,6 +66,7 @@ def dpnp_add(x1, x2, out=None, order="K"): """ Invokes add() from dpctl.tensor implementation for add() function. + TODO: add a pybind11 extension of add() from OneMKL VM where possible and would be performance effective. @@ -111,21 +111,28 @@ def dpnp_add(x1, x2, out=None, order="K"): def dpnp_divide(x1, x2, out=None, order="K"): """ Invokes div() function from pybind11 extension of OneMKL VM if possible. + Otherwise fully relies on dpctl.tensor implementation for divide() function. """ - def _call_divide(src1, src2, dst, sycl_queue, depends=[]): + def _call_divide(src1, src2, dst, sycl_queue, depends=None): """A callback to register in BinaryElementwiseFunc class of dpctl.tensor""" + if depends is None: + depends = [] + if vmi._can_call_div(sycl_queue, src1, src2, dst): # call pybind11 extension for div() function from OneMKL VM return vmi._div(sycl_queue, src1, src2, dst, depends) return ti._divide(src1, src2, dst, sycl_queue, depends) - def _call_divide_inplace(lhs, rhs, sycl_queue, depends=[]): + def _call_divide_inplace(lhs, rhs, sycl_queue, depends=None): """In place workaround until dpctl.tensor provides the functionality.""" + if depends is None: + depends = [] + # allocate temporary memory for out array out = dpt.empty_like(lhs, dtype=dpnp.result_type(lhs.dtype, rhs.dtype)) @@ -182,6 +189,7 @@ def _call_divide_inplace(lhs, rhs, sycl_queue, depends=[]): def dpnp_multiply(x1, x2, out=None, order="K"): """ Invokes multiply() from dpctl.tensor implementation for multiply() function. + TODO: add a pybind11 extension of mul() from OneMKL VM where possible and would be performance effective. @@ -230,6 +238,7 @@ def dpnp_multiply(x1, x2, out=None, order="K"): def dpnp_subtract(x1, x2, out=None, order="K"): """ Invokes subtract() from dpctl.tensor implementation for subtract() function. + TODO: add a pybind11 extension of sub() from OneMKL VM where possible and would be performance effective. diff --git a/dpnp/dpnp_array.py b/dpnp/dpnp_array.py index c0fc412df106..0ff1ca4a8e2a 100644 --- a/dpnp/dpnp_array.py +++ b/dpnp/dpnp_array.py @@ -32,6 +32,8 @@ def _get_unwrapped_index_key(key): """ + Get an unwrapped index key. + Return a key where each nested instance of DPNP array is unwrapped into USM ndarray for futher processing in DPCTL advanced indexing functions. @@ -109,9 +111,7 @@ def T(self): return self.transpose() def to_device(self, target_device): - """ - Transfer array to target device - """ + """Transfer array to target device.""" return dpnp_array( shape=self.shape, buffer=self.get_array().to_device(target_device) @@ -276,9 +276,7 @@ def __le__(self, other): return dpnp.less_equal(self, other) def __len__(self): - """ - Performs the operation __len__. - """ + """Performs the operation __len__.""" return self._array_obj.__len__() @@ -335,7 +333,7 @@ def __rmatmul__(self, other): return dpnp.matmul(other, self) def __rmod__(self, other): - return remainder(other, self) + return dpnp.remainder(other, self) def __rmul__(self, other): return dpnp.multiply(other, self) @@ -499,8 +497,7 @@ def argmin(self, axis=None, out=None): def argsort(self, axis=-1, kind=None, order=None): """ - Return an ndarray of indices that sort the array along the - specified axis. + Return an ndarray of indices that sort the array along the specified axis. Parameters ---------- @@ -584,10 +581,7 @@ def astype(self, dtype, order="K", casting="unsafe", subok=True, copy=True): # 'byteswap', def choose(input, choices, out=None, mode="raise"): - """ - Construct an array from an index array and a set of arrays to choose from. - - """ + """Construct an array from an index array and a set of arrays to choose from.""" return dpnp.choose(input, choices, out, mode) @@ -655,7 +649,7 @@ def dot(self, other, out=None): @property def dtype(self): - """ """ + """Returns NumPy's dtype corresponding to the type of the array elements.""" return self._array_obj.dtype @@ -689,19 +683,13 @@ def fill(self, value): @property def flags(self): - """ - Return information about the memory layout of the array. - - """ + """Return information about the memory layout of the array.""" return self._array_obj.flags @property def flat(self): - """ - Return a flat iterator, or set a flattened version of self to value. - - """ + """Return a flat iterator, or set a flattened version of self to value.""" return dpnp.flatiter(self) @@ -787,10 +775,7 @@ def item(self, id=None): @property def itemsize(self): - """ - Size of one array element in bytes. - - """ + """Size of one array element in bytes.""" return self._array_obj.itemsize @@ -802,16 +787,12 @@ def max( initial=numpy._NoValue, where=numpy._NoValue, ): - """ - Return the maximum along an axis. - """ + """Return the maximum along an axis.""" return dpnp.max(self, axis, out, keepdims, initial, where) def mean(self, axis=None, **kwargs): - """ - Returns the average of the array elements. - """ + """Returns the average of the array elements.""" return dpnp.mean(self, axis=axis, **kwargs) @@ -823,27 +804,19 @@ def min( initial=numpy._NoValue, where=numpy._NoValue, ): - """ - Return the minimum along a given axis. - """ + """Return the minimum along a given axis.""" return dpnp.min(self, axis, out, keepdims, initial, where) @property def nbytes(self): - """ - Total bytes consumed by the elements of the array. - - """ + """Total bytes consumed by the elements of the array.""" return self._array_obj.nbytes @property def ndim(self): - """ - Number of array dimensions. - - """ + """Number of array dimensions.""" return self._array_obj.ndim @@ -854,6 +827,8 @@ def nonzero(self): def partition(self, kth, axis=-1, kind="introselect", order=None): """ + Return a partitioned copy of an array. + Rearranges the elements in the array in such a way that the value of the element in kth position is in the position it would be in a sorted array. @@ -968,7 +943,10 @@ def shape(self): @shape.setter def shape(self, newshape): - """Set new lengths of axes. A tuple of numbers represents size of each dimention. + """ + Set new lengths of axes. + + A tuple of numbers represents size of each dimention. It involves reshaping without copy. If the array cannot be reshaped without copy, it raises an exception. @@ -980,7 +958,7 @@ def shape(self, newshape): @property def size(self): - """ """ + """Number of elements in the array.""" return self._array_obj.size @@ -1009,7 +987,17 @@ def std(self, axis=None, dtype=None, out=None, ddof=0, keepdims=False): @property def strides(self): - """ """ + """ + Get strides of an array. + + Returns memory displacement in array elements, upon unit + change of respective index. + + E.g. for strides (s1, s2, s3) and multi-index (i1, i2, i3) + + a[i1, i2, i3] == (&a[0,0,0])[ s1*s1 + s2*i2 + s3*i3] + + """ return self._array_obj.strides diff --git a/dpnp/dpnp_container.py b/dpnp/dpnp_container.py index e39fdbfe1c5f..bd77c0998c8d 100644 --- a/dpnp/dpnp_container.py +++ b/dpnp/dpnp_container.py @@ -47,7 +47,8 @@ "eye", "full", "linspace", - "ones" "tril", + "ones", + "tril", "triu", "zeros", ] @@ -297,7 +298,7 @@ def ones( def tril(x1, /, *, k=0): - """ "Creates `dpnp_array` as lower triangular part of an input array.""" + """Creates `dpnp_array` as lower triangular part of an input array.""" array_obj = dpt.tril( x1.get_array() if isinstance(x1, dpnp_array) else x1, k ) @@ -305,7 +306,7 @@ def tril(x1, /, *, k=0): def triu(x1, /, *, k=0): - """ "Creates `dpnp_array` as upper triangular part of an input array.""" + """Creates `dpnp_array` as upper triangular part of an input array.""" array_obj = dpt.triu( x1.get_array() if isinstance(x1, dpnp_array) else x1, k ) diff --git a/dpnp/dpnp_flatiter.py b/dpnp/dpnp_flatiter.py index 3022df88170f..4370d1e09eb2 100644 --- a/dpnp/dpnp_flatiter.py +++ b/dpnp/dpnp_flatiter.py @@ -24,10 +24,7 @@ # THE POSSIBILITY OF SUCH DAMAGE. # ***************************************************************************** -""" -Implementation of flatiter - -""" +"""Implementation of flatiter.""" import dpnp diff --git a/dpnp/dpnp_iface.py b/dpnp/dpnp_iface.py index 0b907cfeb676..3c80458f94ac 100644 --- a/dpnp/dpnp_iface.py +++ b/dpnp/dpnp_iface.py @@ -40,15 +40,12 @@ """ -import collections import os import dpctl import dpctl.tensor as dpt import numpy -import numpy.lib.stride_tricks as np_st -import dpnp.config as config from dpnp.dpnp_algo import * from dpnp.dpnp_array import dpnp_array from dpnp.dpnp_utils import * @@ -190,9 +187,7 @@ def astype(x1, dtype, order="K", casting="unsafe", subok=True, copy=True): def convert_single_elem_array_to_scalar(obj, keepdims=False): - """ - Convert array with single element to scalar - """ + """Convert array with single element to scalar.""" if (obj.ndim > 0) and (obj.size == 1) and (keepdims is False): return obj.dtype.type(obj[0]) @@ -339,9 +334,7 @@ def get_dpnp_descriptor( def get_include(): - """ - Return the directory that contains the DPNP C++ backend \\*.h header files. - """ + r"""Return the directory that contains the DPNP C++ backend \*.h header files.""" dpnp_path = os.path.join(os.path.dirname(__file__), "backend", "include") diff --git a/dpnp/dpnp_iface_arraycreation.py b/dpnp/dpnp_iface_arraycreation.py index a5961698c279..3be59df4eb3a 100644 --- a/dpnp/dpnp_iface_arraycreation.py +++ b/dpnp/dpnp_iface_arraycreation.py @@ -42,12 +42,10 @@ import operator -import dpctl import dpctl.tensor as dpt import numpy import dpnp -import dpnp.config as config import dpnp.dpnp_container as dpnp_container from dpnp.dpnp_algo import * from dpnp.dpnp_utils import * @@ -619,6 +617,7 @@ def eye( ): """ Return a 2-D array with ones on the diagonal and zeros elsewhere. + For full documentation refer to :obj:`numpy.eye`. Limitations @@ -998,7 +997,7 @@ def linspace( def loadtxt(fname, **kwargs): - """ + r""" Load data from a text file. Each row in the text file must have the same number of values. diff --git a/dpnp/dpnp_iface_counting.py b/dpnp/dpnp_iface_counting.py index c012c2be3360..1b5a6e6fe991 100644 --- a/dpnp/dpnp_iface_counting.py +++ b/dpnp/dpnp_iface_counting.py @@ -43,7 +43,6 @@ import numpy import dpnp -import dpnp.config as config from dpnp.dpnp_algo.dpnp_algo import * # TODO need to investigate why dpnp.dpnp_algo can not be used from dpnp.dpnp_utils import * diff --git a/dpnp/dpnp_iface_indexing.py b/dpnp/dpnp_iface_indexing.py index 556855efc25f..a0b352c4317a 100644 --- a/dpnp/dpnp_iface_indexing.py +++ b/dpnp/dpnp_iface_indexing.py @@ -241,6 +241,7 @@ def diagonal(x1, offset=0, axis1=0, axis2=1): def extract(condition, x): """ Return the elements of an array that satisfy some condition. + For full documentation refer to :obj:`numpy.extract`. Returns @@ -256,8 +257,9 @@ def extract(condition, x): Otherwise the function will be executed sequentially on CPU. """ - check_input_type = lambda x: isinstance(x, (dpnp_array, dpt.usm_ndarray)) - if check_input_type(condition) and check_input_type(x): + if dpnp.is_supported_array_type(condition) and dpnp.is_supported_array_type( + x + ): if condition.shape != x.shape: pass else: @@ -392,6 +394,7 @@ def nonzero(x, /): def place(x, mask, vals, /): """ Change elements of an array based on conditional and input values. + For full documentation refer to :obj:`numpy.place`. Limitations @@ -401,11 +404,10 @@ def place(x, mask, vals, /): Otherwise the function will be executed sequentially on CPU. """ - check_input_type = lambda x: isinstance(x, (dpnp_array, dpt.usm_ndarray)) if ( - check_input_type(x) - and check_input_type(mask) - and check_input_type(vals) + dpnp.is_supported_array_type(x) + and dpnp.is_supported_array_type(mask) + and dpnp.is_supported_array_type(vals) ): dpt_array = x.get_array() if isinstance(x, dpnp_array) else x dpt_mask = mask.get_array() if isinstance(mask, dpnp_array) else mask @@ -418,6 +420,7 @@ def place(x, mask, vals, /): def put(x1, ind, v, mode="raise"): """ Replaces specified elements of an array with given values. + For full documentation refer to :obj:`numpy.put`. Limitations @@ -447,6 +450,7 @@ def put(x1, ind, v, mode="raise"): def put_along_axis(x1, indices, values, axis): """ Put values into the destination array by matching 1d index and data slices. + For full documentation refer to :obj:`numpy.put_along_axis`. See Also @@ -481,6 +485,7 @@ def put_along_axis(x1, indices, values, axis): def putmask(x1, mask, values): """ Changes elements of an array based on conditional and input values. + For full documentation refer to :obj:`numpy.putmask`. Limitations @@ -504,6 +509,7 @@ def putmask(x1, mask, values): def select(condlist, choicelist, default=0): """ Return an array drawn from elements in choicelist, depending on conditions. + For full documentation refer to :obj:`numpy.select`. Limitations @@ -536,6 +542,7 @@ def select(condlist, choicelist, default=0): def take(x1, indices, axis=None, out=None, mode="raise"): """ Take elements from an array. + For full documentation refer to :obj:`numpy.take`. Limitations @@ -570,6 +577,7 @@ def take(x1, indices, axis=None, out=None, mode="raise"): def take_along_axis(x1, indices, axis): """ Take values from the input array by matching 1d index and data slices. + For full documentation refer to :obj:`numpy.take_along_axis`. See Also @@ -646,6 +654,7 @@ def tril_indices(n, k=0, m=None): def tril_indices_from(x1, k=0): """ Return the indices for the lower-triangle of arr. + See `tril_indices` for full details. Parameters @@ -706,6 +715,7 @@ def triu_indices(n, k=0, m=None): def triu_indices_from(x1, k=0): """ Return the indices for the lower-triangle of arr. + See `tril_indices` for full details. Parameters diff --git a/dpnp/dpnp_iface_libmath.py b/dpnp/dpnp_iface_libmath.py index 4d2c17b1e8f8..046767f22e25 100644 --- a/dpnp/dpnp_iface_libmath.py +++ b/dpnp/dpnp_iface_libmath.py @@ -64,7 +64,6 @@ def erf(in_array1): Examples -------- - >>> import dpnp as np >>> x = np.linspace(2.0, 3.0, num=5) >>> [i for i in x] diff --git a/dpnp/dpnp_iface_linearalgebra.py b/dpnp/dpnp_iface_linearalgebra.py index 3a322370bf20..ab33ece608e1 100644 --- a/dpnp/dpnp_iface_linearalgebra.py +++ b/dpnp/dpnp_iface_linearalgebra.py @@ -45,7 +45,6 @@ import dpnp from dpnp.dpnp_algo import * -from dpnp.dpnp_array import dpnp_array from dpnp.dpnp_utils import * __all__ = [ @@ -167,6 +166,8 @@ def einsum(*args, **kwargs): def einsum_path(*args, **kwargs): """ + einsum_path(subscripts, *operands, optimize='greedy') + Evaluates the lowest cost contraction order for an einsum expression by considering the creation of intermediate arrays. diff --git a/dpnp/dpnp_iface_logic.py b/dpnp/dpnp_iface_logic.py index 33db91d85b41..658459bd3039 100644 --- a/dpnp/dpnp_iface_logic.py +++ b/dpnp/dpnp_iface_logic.py @@ -43,7 +43,6 @@ import numpy import dpnp -import dpnp.config as config from dpnp.dpnp_algo import * from dpnp.dpnp_utils import * diff --git a/dpnp/dpnp_iface_manipulation.py b/dpnp/dpnp_iface_manipulation.py index 7a0708f44ef6..be2c427cf0e3 100644 --- a/dpnp/dpnp_iface_manipulation.py +++ b/dpnp/dpnp_iface_manipulation.py @@ -40,8 +40,6 @@ """ -import collections.abc - import dpctl.tensor as dpt import numpy @@ -108,6 +106,7 @@ def asfarray(x1, dtype=None): def atleast_1d(*arys): """ Convert inputs to arrays with at least one dimension. + Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved. @@ -605,7 +604,7 @@ def reshape(x, /, newshape, order="C", copy=None): if order is None: order = "C" - elif not order in "cfCF": + elif order not in "cfCF": raise ValueError(f"order must be one of 'C' or 'F' (got {order})") usm_arr = dpnp.get_usm_ndarray(x) @@ -615,6 +614,8 @@ def reshape(x, /, newshape, order="C", copy=None): def result_type(*arrays_and_dtypes): """ + result_type(*arrays_and_dtypes) + Returns the type that results from applying the NumPy type promotion rules to the arguments. diff --git a/dpnp/dpnp_iface_mathematical.py b/dpnp/dpnp_iface_mathematical.py index 7151a6902bd1..eaf3bfca3e17 100644 --- a/dpnp/dpnp_iface_mathematical.py +++ b/dpnp/dpnp_iface_mathematical.py @@ -114,6 +114,8 @@ def _check_nd_call( **kwargs, ): """ + Checks arguments and calls a function. + Chooses a common internal elementwise function to call in DPNP based on input arguments or to fallback on NumPy call if any passed argument is not currently supported. diff --git a/dpnp/dpnp_iface_searching.py b/dpnp/dpnp_iface_searching.py index a976f0b22b41..bb19e547fe33 100644 --- a/dpnp/dpnp_iface_searching.py +++ b/dpnp/dpnp_iface_searching.py @@ -217,10 +217,7 @@ def where(condition, x=None, y=None, /): elif missing == 2: return dpnp.nonzero(condition) elif missing == 0: - check_input_type = lambda x: isinstance( - x, (dpnp_array, dpt.usm_ndarray) - ) - if check_input_type(condition): + if dpnp.is_supported_array_type(condition): if numpy.isscalar(x) or numpy.isscalar(y): # get USM type and queue to copy scalar from the host memory into a USM allocation usm_type, queue = get_usm_allocations([condition, x, y]) @@ -234,7 +231,9 @@ def where(condition, x=None, y=None, /): if numpy.isscalar(y) else y ) - if check_input_type(x) and check_input_type(y): + if dpnp.is_supported_array_type(x) and dpnp.is_supported_array_type( + y + ): dpt_condition = ( condition.get_array() if isinstance(condition, dpnp_array) diff --git a/dpnp/dpnp_iface_sorting.py b/dpnp/dpnp_iface_sorting.py index a0c7c5dc3aec..c02fbddd8d24 100644 --- a/dpnp/dpnp_iface_sorting.py +++ b/dpnp/dpnp_iface_sorting.py @@ -101,6 +101,7 @@ def argsort(in_array1, axis=-1, kind=None, order=None): def partition(x1, kth, axis=-1, kind="introselect", order=None): """ Return a partitioned copy of an array. + For full documentation refer to :obj:`numpy.partition`. Limitations @@ -133,6 +134,7 @@ def partition(x1, kth, axis=-1, kind="introselect", order=None): def searchsorted(x1, x2, side="left", sorter=None): """ Find indices where elements should be inserted to maintain order. + For full documentation refer to :obj:`numpy.searchsorted`. Limitations diff --git a/dpnp/dpnp_iface_statistics.py b/dpnp/dpnp_iface_statistics.py index a2c66b735bf3..2594901039f0 100644 --- a/dpnp/dpnp_iface_statistics.py +++ b/dpnp/dpnp_iface_statistics.py @@ -250,7 +250,8 @@ def cov( *, dtype=None, ): - """cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None, *, dtype=None): + """ + cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None, aweights=None, *, dtype=None) Estimate a covariance matrix, given data and weights. @@ -317,7 +318,9 @@ def cov( def histogram(a, bins=10, range=None, density=None, weights=None): """ Compute the histogram of a dataset. + For full documentation refer to :obj:`numpy.histogram`. + Examples -------- >>> import dpnp @@ -336,6 +339,7 @@ def histogram(a, bins=10, range=None, density=None, weights=None): >>> res = dpnp.sum(hist * dpnp.diff(bin_edges)) >>> print(res) 1.0 + """ return call_origin( diff --git a/dpnp/dpnp_iface_types.py b/dpnp/dpnp_iface_types.py index c836c5af1721..68da06583fec 100644 --- a/dpnp/dpnp_iface_types.py +++ b/dpnp/dpnp_iface_types.py @@ -173,9 +173,7 @@ def issubsctype(arg1, arg2): def is_type_supported(obj_type): - """ - Return True if type is supported by DPNP python level. - """ + """Return True if type is supported by DPNP python level.""" if ( obj_type == float64 diff --git a/dpnp/dpnp_utils/dpnp_utils_statistics.py b/dpnp/dpnp_utils/dpnp_utils_statistics.py index 66b27573b4f2..3e8df0aa3cb2 100644 --- a/dpnp/dpnp_utils/dpnp_utils_statistics.py +++ b/dpnp/dpnp_utils/dpnp_utils_statistics.py @@ -40,6 +40,8 @@ def dpnp_cov(m, y=None, rowvar=True, dtype=None): """ + dpnp_cov(m, y=None, rowvar=True, dtype=None) + Estimate a covariance matrix based on passed data. No support for given weights is provided now. diff --git a/dpnp/linalg/dpnp_iface_linalg.py b/dpnp/linalg/dpnp_iface_linalg.py index 400497a03124..0b96df5e141b 100644 --- a/dpnp/linalg/dpnp_iface_linalg.py +++ b/dpnp/linalg/dpnp_iface_linalg.py @@ -69,6 +69,7 @@ def cholesky(input): """ Cholesky decomposition. + Return the Cholesky decomposition, `L * L.H`, of the square matrix `input`, where `L` is lower-triangular and .H is the conjugate transpose operator (which is the ordinary transpose if `input` is real-valued). `input` must be @@ -111,6 +112,7 @@ def cholesky(input): def cond(input, p=None): """ Compute the condition number of a matrix. + For full documentation refer to :obj:`numpy.linalg.cond`. Limitations @@ -179,6 +181,8 @@ def eig(x1): def eigh(a, UPLO="L"): """ + eigh(a, UPLO="L") + Return the eigenvalues and eigenvectors of a complex Hermitian (conjugate symmetric) or a real symmetric matrix. @@ -246,6 +250,7 @@ def eigh(a, UPLO="L"): def eigvals(input): """ Compute the eigenvalues of a general matrix. + Main difference between `eigvals` and `eig`: the eigenvectors aren't returned. @@ -317,7 +322,7 @@ def matrix_power(input, count): if not use_origin_backend() and count > 0: result = input - for id in range(count - 1): + for _ in range(count - 1): result = dpnp.matmul(result, input) return result @@ -327,7 +332,8 @@ def matrix_power(input, count): def matrix_rank(input, tol=None, hermitian=False): """ - Return matrix rank of array + Return matrix rank of array. + Rank of the array is the number of singular values of the array that are greater than `tol`. @@ -406,6 +412,7 @@ def multi_dot(arrays, out=None): def norm(x1, ord=None, axis=None, keepdims=False): """ Matrix or vector norm. + This function is able to return one of eight different matrix norms, or one of an infinite number of vector norms (described below), depending on the value of the ``ord`` parameter. @@ -547,11 +554,11 @@ def svd(x1, full_matrices=True, compute_uv=True, hermitian=False): if x1_desc: if not x1_desc.ndim == 2: pass - elif not full_matrices == True: + elif full_matrices is not True: pass - elif not compute_uv == True: + elif compute_uv is not True: pass - elif not hermitian == False: + elif hermitian is not False: pass else: result_tup = dpnp_svd(x1_desc, full_matrices, compute_uv, hermitian) diff --git a/dpnp/linalg/dpnp_utils_linalg.py b/dpnp/linalg/dpnp_utils_linalg.py index 87ea0d26c5ab..e818835ecbee 100644 --- a/dpnp/linalg/dpnp_utils_linalg.py +++ b/dpnp/linalg/dpnp_utils_linalg.py @@ -40,6 +40,8 @@ def dpnp_eigh(a, UPLO): """ + dpnp_eigh(a, UPLO) + Return the eigenvalues and eigenvectors of a complex Hermitian (conjugate symmetric) or a real symmetric matrix. diff --git a/dpnp/random/dpnp_iface_random.py b/dpnp/random/dpnp_iface_random.py index 6ec3f2764007..f8d380db2ece 100644 --- a/dpnp/random/dpnp_iface_random.py +++ b/dpnp/random/dpnp_iface_random.py @@ -508,10 +508,10 @@ def hypergeometric(ngood, nbad, nsample, size=None): elif nsample < 1: pass else: - m = int(ngood) - l = int(ngood) + int(nbad) - s = int(nsample) - return dpnp_rng_hypergeometric(l, s, m, size).get_pyobj() + _m = int(ngood) + _l = int(ngood) + int(nbad) + _s = int(nsample) + return dpnp_rng_hypergeometric(_l, _s, _m, size).get_pyobj() return call_origin(numpy.random.hypergeometric, ngood, nbad, nsample, size) @@ -583,7 +583,7 @@ def logistic(loc=0.0, scale=1.0, size=None): pass else: result = dpnp_rng_logistic(loc, scale, size).get_pyobj() - if size == None or size == 1: + if size is None or size == 1: return result[0] else: return result @@ -686,7 +686,7 @@ def multinomial(n, pvals, size=None): else: try: shape = (operator.index(size), d) - except: + except Exception: shape = tuple(size) + (d,) return dpnp_rng_multinomial(int(n), pvals_desc, shape).get_pyobj() @@ -1181,6 +1181,7 @@ def randn(d0, *dn, device=None, usm_type="device", sycl_queue=None): def random(size=None, device=None, usm_type="device", sycl_queue=None): """ Return random floats in the half-open interval [0.0, 1.0). + Alias for random_sample. For full documentation refer to :obj:`numpy.random.random`. @@ -1328,6 +1329,7 @@ def random_sample(size=None, device=None, usm_type="device", sycl_queue=None): def ranf(size=None, device=None, usm_type="device", sycl_queue=None): """ Return random floats in the half-open interval [0.0, 1.0). + This is an alias of random_sample. For full documentation refer to :obj:`numpy.random.ranf`. @@ -1406,6 +1408,7 @@ def rayleigh(scale=1.0, size=None): def sample(size=None, device=None, usm_type="device", sycl_queue=None): """ Return random floats in the half-open interval [0.0, 1.0). + This is an alias of random_sample. For full documentation refer to :obj:`numpy.random.sample`. @@ -1787,7 +1790,8 @@ def uniform( def vonmises(mu, kappa, size=None): - """von Mises distribution. + """ + Von Mises distribution. Draw samples from a von Mises distribution. diff --git a/dpnp/random/dpnp_random_state.py b/dpnp/random/dpnp_random_state.py index b95ef3a534ae..4d6f8d22a716 100644 --- a/dpnp/random/dpnp_random_state.py +++ b/dpnp/random/dpnp_random_state.py @@ -119,18 +119,14 @@ def __getstate__(self): return self.get_state() def _is_finite_scalar(self, x): - """ - Test a scalar for finiteness (not infinity and not Not a Number). - """ + """Test a scalar for finiteness (not infinity and not Not a Number).""" # TODO: replace with dpnp.isfinite() once function is available in DPNP, # but for now use direct numpy calls without call_origin() wrapper, since data is a scalar return numpy.isfinite(x) def _is_signbit_scalar(self, x): - """ - Test a scalar if sign bit is set for it (less than zero). - """ + """Test a scalar if sign bit is set for it (less than zero).""" # TODO: replace with dpnp.signbit() once function is available in DPNP, # but for now use direct numpy calls without call_origin() wrapper, since data is a scalar @@ -138,6 +134,8 @@ def _is_signbit_scalar(self, x): def _validate_float_dtype(self, dtype, supported_types): """ + Validate an input floating type. + Test an input floating type if it is listed in `supported_types` and if it is supported by the used SYCL device. If `dtype` is ``None``, default floating type will be validating. @@ -147,7 +145,7 @@ def _validate_float_dtype(self, dtype, supported_types): if dtype is None: dtype = self._def_float_type - if not dtype in supported_types: + if dtype not in supported_types: raise TypeError(f"dtype={dtype} is unsupported.") elif dtype != map_dtype_to_device(dtype, self._sycl_device): raise RuntimeError( diff --git a/examples/example1.py b/examples/example1.py index b83d4ec7e7d5..7d86c0a15e92 100644 --- a/examples/example1.py +++ b/examples/example1.py @@ -61,7 +61,7 @@ def run_dgemm(executor, name, size, test_type, repetition): ) times = [] - for iteration in range(repetition): + for _ in range(repetition): start_time = time.perf_counter() result = executor.matmul(x1, x2) # print("result[5]=%f" % (result.item(5))) diff --git a/examples/example2.py b/examples/example2.py index e1747f82a1f3..f2a4d06a4dc1 100644 --- a/examples/example2.py +++ b/examples/example2.py @@ -63,7 +63,7 @@ def get_package_specific_input_data_type(input_type, size): def run_third_party_function(input, repetition): times = [] - for iteration in range(repetition): + for _ in range(repetition): start_time = time.time() result = common_function_one_input(input) end_time = time.time() diff --git a/examples/example6.py b/examples/example6.py index 27b3b1cee675..96a494bc437a 100644 --- a/examples/example6.py +++ b/examples/example6.py @@ -44,10 +44,6 @@ import dpnp -import time - -import numpy - if __name__ == "__main__": # TODO # as is example1.py diff --git a/examples/example7.py b/examples/example7.py index 89e7f979d8bd..1e5ee8ce5964 100644 --- a/examples/example7.py +++ b/examples/example7.py @@ -58,7 +58,7 @@ def run_function(executor, name, size, test_type, repetition): ) times = [] - for iteration in range(repetition): + for _ in range(repetition): start_time = time.perf_counter() result = executor.sum(x) # print("result[5]=%f" % (result.item(5))) diff --git a/scripts/build_locally.py b/scripts/build_locally.py index 6bdfb8c5469f..e3e21915178a 100644 --- a/scripts/build_locally.py +++ b/scripts/build_locally.py @@ -48,7 +48,7 @@ def run( elif sys.platform in ["win32", "cygwin"]: build_system = "Ninja" else: - assert False, sys.platform + " not supported" + raise AssertionError(sys.platform + " not supported") setup_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) cmake_args = [ diff --git a/scripts/gen_coverage.py b/scripts/gen_coverage.py index 51ee61a84c49..fa8adcde76e3 100644 --- a/scripts/gen_coverage.py +++ b/scripts/gen_coverage.py @@ -16,7 +16,7 @@ def run( elif sys.platform in ["win32", "cygwin"]: pass else: - assert False, sys.platform + " not supported" + raise AssertionError(sys.platform + " not supported") if not IS_LIN: raise RuntimeError( diff --git a/tests_external/numpy/runtests.py b/tests_external/numpy/runtests.py index 7d67d513924e..44ac16bb9d1f 100644 --- a/tests_external/numpy/runtests.py +++ b/tests_external/numpy/runtests.py @@ -39,7 +39,6 @@ import site import sys import types -import unittest from pathlib import Path import numpy