Skip to content

Commit

Permalink
Resolve linting issues.
Browse files Browse the repository at this point in the history
  • Loading branch information
hameerabbasi committed Jan 4, 2024
1 parent 959c697 commit d4d74fd
Show file tree
Hide file tree
Showing 13 changed files with 63 additions and 50 deletions.
22 changes: 12 additions & 10 deletions sparse/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,10 +204,10 @@ def matmul(a, b):
"""
check_zero_fill_value(a, b)
if not hasattr(a, "ndim") or not hasattr(b, "ndim"):
raise TypeError("Cannot perform dot product on types %s, %s" % (type(a), type(b)))
raise TypeError(f"Cannot perform dot product on types {type(a)}, {type(b)}")

if check_class_nan(a) or check_class_nan(b):
warnings.warn("Nan will not be propagated in matrix multiplication", RuntimeWarning)
warnings.warn("Nan will not be propagated in matrix multiplication", RuntimeWarning, stacklevel=1)

# When b is 2-d, it is equivalent to dot
if b.ndim <= 2:
Expand Down Expand Up @@ -283,7 +283,7 @@ def dot(a, b):
"""
check_zero_fill_value(a, b)
if not hasattr(a, "ndim") or not hasattr(b, "ndim"):
raise TypeError("Cannot perform dot product on types %s, %s" % (type(a), type(b)))
raise TypeError(f"Cannot perform dot product on types {type(a)}, {type(b)}")

Check warning on line 286 in sparse/_common.py

View check run for this annotation

Codecov / codecov/patch

sparse/_common.py#L286

Added line #L286 was not covered by tests

if a.ndim == 1 and b.ndim == 1:
if isinstance(a, SparseArray):
Expand Down Expand Up @@ -813,7 +813,6 @@ def _dot_csc_ndarray_sparse(a_shape, b_shape, a_data, a_indices, a_indptr, b):
mask[ind] = head
head = ind
length += 1
start = nnz
for _ in range(length):
if sums[head] != 0:
indices[nnz] = head
Expand Down Expand Up @@ -953,7 +952,6 @@ def _dot_coo_coo(out_shape, a_coords, b_coords, a_data, b_data, a_indptr, b_indp
head = k
length += 1

start = nnz
for _ in range(length):
if next_[head] != -1:
coords[0, nnz] = i
Expand Down Expand Up @@ -1199,7 +1197,7 @@ def _parse_einsum_input(operands):
tmp_operands = list(operands)
operand_list = []
subscript_list = []
for p in range(len(operands) // 2):
for _ in range(len(operands) // 2):
operand_list.append(tmp_operands.pop(0))
subscript_list.append(tmp_operands.pop(0))

Expand Down Expand Up @@ -1361,7 +1359,7 @@ def _einsum_single(lhs, rhs, operand):
where.setdefault(ix, []).append(i)

selector = None
for ix, locs in where.items():
for locs in where.values():
loc0, *rlocs = locs
if rlocs:
# repeated index
Expand Down Expand Up @@ -1956,7 +1954,9 @@ def pad(array, pad_width, mode="constant", **kwargs):
Sparse array which is to be padded.
pad_width : {sequence, array_like, int}
Number of values padded to the edges of each axis. ((before_1, after_1), … (before_N, after_N)) unique pad widths for each axis. ((before, after),) yields same before and after pad for each axis. (pad,) or int is a shortcut for before = after = pad width for all axes.
Number of values padded to the edges of each axis. ((before_1, after_1), … (before_N, after_N)) unique pad
widths for each axis. ((before, after),) yields same before and after pad for each axis. (pad,) or int is a
shortcut for before = after = pad width for all axes.
mode : str
Pads to a constant value which is fill value. Currently only constant mode is implemented
Expand Down Expand Up @@ -2059,7 +2059,7 @@ def asarray(obj, /, *, dtype=None, format="coo", backend="pydata", device=None,
if backend == "pydata":
if isinstance(obj, (COO, DOK, GCXS)):
# TODO: consider `format` argument
warnings.warn("`format` argument was ignored")
warnings.warn("`format` argument was ignored", RuntimeWarning, stacklevel=1)
return obj

elif isinstance(obj, spmatrix):
Expand Down Expand Up @@ -2092,7 +2092,9 @@ def wrapper_func(*args, **kwargs):
if isinstance(x, (np.ndarray, np.number)):
warnings.warn(
f"Sparse {func.__name__} received dense NumPy array instead "
"of sparse array. Dispatching to NumPy function."
"of sparse array. Dispatching to NumPy function.",
RuntimeWarning,
stacklevel=2,
)
return getattr(np, func.__name__)(*args, **kwargs)
else:
Expand Down
4 changes: 2 additions & 2 deletions sparse/_compressed/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def compute_flat(increments, cols, operations): # pragma: no cover
end = increments[-1].shape[0]
positions = np.zeros(len(increments) - 1, dtype=np.intp)
pos = len(increments) - 2
for i in range(operations):
for _ in range(operations):
to_add = 0
for j in range(len(increments) - 1):
to_add += increments[j][positions[j]]
Expand Down Expand Up @@ -314,7 +314,7 @@ def _convert_coords(
new_compressed_shape,
transpose,
): # pragma: no cover
if transpose == True:
if transpose:
for i, n in enumerate(linear):
# c ordering
current_coords = unravel_index(n, reordered_shape)[sorted_axis_order]
Expand Down
9 changes: 6 additions & 3 deletions sparse/_coo/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -787,9 +787,11 @@ def roll(a, shift, axis=None):
for sh, ax in zip(shift, axis):
coords[ax] += sh
coords[ax] %= a.shape[ax]
except UFuncTypeError:
except UFuncTypeError as e:
if is_unsigned_dtype(coords.dtype):
raise ValueError(f"rolling with coords.dtype as {coords.dtype} is not safe. Try using a signed dtype.")
raise ValueError(
f"rolling with coords.dtype as {coords.dtype} is not safe. Try using a signed dtype."
) from e

return COO(
coords,
Expand Down Expand Up @@ -870,7 +872,8 @@ def diagonalize(a, axis=0):
"""
Diagonalize a COO array. The new dimension is appended at the end.
.. WARNING:: :obj:`diagonalize` is not :obj:`numpy` compatible as there is no direct :obj:`numpy` equivalent. The API may change in the future.
.. WARNING:: :obj:`diagonalize` is not :obj:`numpy` compatible as there is no direct :obj:`numpy` equivalent. The
API may change in the future.
Parameters
----------
Expand Down
5 changes: 4 additions & 1 deletion sparse/_coo/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,7 @@ def __init__(
warnings.warn(
"coords should be an ndarray. This will raise a ValueError in the future.",
DeprecationWarning,
stacklevel=1,
)

if data is None:
Expand Down Expand Up @@ -249,6 +250,7 @@ def __init__(
warnings.warn(
"shape should be provided. This will raise a ValueError in the future.",
DeprecationWarning,
stacklevel=1,
)
if self.coords.nbytes:
shape = tuple(self.coords.max(axis=1) + 1)
Expand Down Expand Up @@ -292,6 +294,7 @@ def __init__(
"memory than than an equivalent dense array. You may want to "
"use a dense array here instead.",
RuntimeWarning,
stacklevel=1,
)

if not sorted:
Expand Down Expand Up @@ -1134,7 +1137,7 @@ def resize(self, *args, refcheck=True, coords_dtype=np.intp):
numpy.ndarray.resize : The equivalent Numpy function.
"""
warnings.warn("resize is deprecated on all SpraseArray objects.", DeprecationWarning)
warnings.warn("resize is deprecated on all SpraseArray objects.", DeprecationWarning, stacklevel=1)
if len(args) == 1 and isinstance(args[0], tuple):
shape = args[0]
elif all(isinstance(arg, int) for arg in args):
Expand Down
15 changes: 8 additions & 7 deletions sparse/_coo/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,8 @@ def _mask(coords, indices, shape):
for ai in adv_idx:
if len(ai) != adv_ix_len:
raise IndexError(
"shape mismatch: indexing arrays could not be broadcast together. Ensure all indexing arrays are of the same length."
"shape mismatch: indexing arrays could not be broadcast together. Ensure all indexing arrays "
"are of the same length."
)
if ai.ndim != 1:
raise IndexError("Only one-dimensional iterable indices supported.")
Expand Down Expand Up @@ -241,15 +242,15 @@ def _prune_indices(indices, shape, prune_none=True):
indices = [idx for idx in indices if idx is not None]

i = 0
for idx, l in zip(indices[::-1], shape[::-1]):
for idx, sh in zip(indices[::-1], shape[::-1]):
if not isinstance(idx, slice):
break

if idx.start == 0 and idx.stop == l and idx.step == 1:
if idx.start == 0 and idx.stop == sh and idx.step == 1:
i += 1
continue

if idx.start == l - 1 and idx.stop == -1 and idx.step == -1:
if idx.start == sh - 1 and idx.stop == -1 and idx.step == -1:
i += 1
continue

Expand Down Expand Up @@ -648,12 +649,12 @@ def _join_adjacent_pairs(starts_old, stops_old): # pragma: no cover


@numba.jit(nopython=True, nogil=True)
def array_from_list_intp(l): # pragma: no cover
n = len(l)
def array_from_list_intp(x): # pragma: no cover
n = len(x)
a = np.empty(n, dtype=np.intp)

for i in range(n):
a[i] = l[i]
a[i] = x[i]

return a

Expand Down
2 changes: 1 addition & 1 deletion sparse/_coo/numba_extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ def unbox_COO(typ: COOType, obj: COO, c) -> NativeValue:


@box(COOType)
def box_COO(typ: COOType, val: "some LLVM thing", c) -> COO:
def box_COO(typ: COOType, val, c) -> COO:
ret_ptr = cgutils.alloca_once(c.builder, c.pyapi.pyobj)
fail_obj = c.pyapi.get_null_object()

Expand Down
4 changes: 2 additions & 2 deletions sparse/_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,5 +128,5 @@ def load_npz(filename):
fill_value=fill_value,
compressed_axes=comp_axes,
)
except KeyError:
raise RuntimeError(f"The file {filename!s} does not contain a valid sparse matrix")
except KeyError as e:
raise RuntimeError(f"The file {filename!s} does not contain a valid sparse matrix") from e
10 changes: 5 additions & 5 deletions sparse/_sparse_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,10 @@ def __init__(self, shape, fill_value=None):
if not isinstance(shape, Iterable):
shape = (shape,)

if not all(isinstance(l, Integral) and int(l) >= 0 for l in shape):
if not all(isinstance(sh, Integral) and int(sh) >= 0 for sh in shape):
raise ValueError("shape must be an non-negative integer or a tuple " "of non-negative integers.")

Check warning on line 37 in sparse/_sparse_array.py

View check run for this annotation

Codecov / codecov/patch

sparse/_sparse_array.py#L37

Added line #L37 was not covered by tests

self.shape = tuple(int(l) for l in shape)
self.shape = tuple(int(sh) for sh in shape)

if fill_value is not None:
if not hasattr(fill_value, "dtype") or fill_value.dtype != self.dtype:
Expand Down Expand Up @@ -348,8 +348,8 @@ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
(out,) = out
if out.shape != result.shape:
raise ValueError(
"non-broadcastable output operand with shape %s "
"doesn't match the broadcast shape %s" % (out.shape, result.shape)
f"non-broadcastable output operand with shape {out.shape} "
f"doesn't match the broadcast shape {result.shape}"
)

out._make_shallow_copy_of(result)
Expand Down Expand Up @@ -787,7 +787,7 @@ def var(self, axis=None, dtype=None, out=None, ddof=0, keepdims=False):
rcount = reduce(operator.mul, (self.shape[a] for a in axis), 1)
# Make this warning show up on top.
if ddof >= rcount:
warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning)
warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning, stacklevel=1)

Check warning on line 790 in sparse/_sparse_array.py

View check run for this annotation

Codecov / codecov/patch

sparse/_sparse_array.py#L790

Added line #L790 was not covered by tests

# Cast bool, unsigned int, and int to float64 by default
if dtype is None and issubclass(self.dtype.type, (np.integer, np.bool_)):
Expand Down
14 changes: 7 additions & 7 deletions sparse/_umath.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,9 +115,9 @@ def _get_nary_broadcast_shape(*shapes):
for shape in shapes:
try:
result_shape = _get_broadcast_shape(shape, result_shape)
except ValueError:
except ValueError as e:

Check warning on line 118 in sparse/_umath.py

View check run for this annotation

Codecov / codecov/patch

sparse/_umath.py#L118

Added line #L118 was not covered by tests
shapes_str = ", ".join(str(shape) for shape in shapes)
raise ValueError("operands could not be broadcast together with shapes %s" % shapes_str)
raise ValueError(f"operands could not be broadcast together with shapes {shapes_str}") from e

Check warning on line 120 in sparse/_umath.py

View check run for this annotation

Codecov / codecov/patch

sparse/_umath.py#L120

Added line #L120 was not covered by tests

return result_shape

Expand Down Expand Up @@ -145,7 +145,7 @@ def _get_broadcast_shape(shape1, shape2, is_result=False):
"""
# https://stackoverflow.com/a/47244284/774273
if not all((l1 == l2) or (l1 == 1) or ((l2 == 1) and not is_result) for l1, l2 in zip(shape1[::-1], shape2[::-1])):
raise ValueError("operands could not be broadcast together with shapes %s, %s" % (shape1, shape2))
raise ValueError(f"operands could not be broadcast together with shapes {shape1}, {shape2}")

Check warning on line 148 in sparse/_umath.py

View check run for this annotation

Codecov / codecov/patch

sparse/_umath.py#L148

Added line #L148 was not covered by tests

result_shape = tuple(l1 if l1 != 1 else l2 for l1, l2 in zip_longest(shape1[::-1], shape2[::-1], fillvalue=1))[::-1]

Expand Down Expand Up @@ -214,7 +214,7 @@ def _get_reduced_shape(shape, params):
reduced_coords : np.ndarray
The reduced coordinates.
"""
reduced_shape = tuple(l for l, p in zip(shape, params) if p)
reduced_shape = tuple(sh for sh, p in zip(shape, params) if p)

return reduced_shape

Expand Down Expand Up @@ -244,13 +244,13 @@ def _get_expanded_coords_data(coords, data, params, broadcast_shape):
"""
first_dim = -1
expand_shapes = []
for d, p, l in zip(range(len(broadcast_shape)), params, broadcast_shape):
for d, p, sh in zip(range(len(broadcast_shape)), params, broadcast_shape):
if p and first_dim == -1:
expand_shapes.append(coords.shape[1])
first_dim = d

if not p:
expand_shapes.append(l)
expand_shapes.append(sh)

all_idx = _cartesian_product(*(np.arange(d, dtype=np.intp) for d in expand_shapes))

Expand All @@ -266,7 +266,7 @@ def _get_expanded_coords_data(coords, data, params, broadcast_shape):
expanded_data = np.repeat(data, np.prod(broadcast_shape, dtype=np.int64))
return np.asarray(expanded_coords), np.asarray(expanded_data)

for d, p, l in zip(range(len(broadcast_shape)), params, broadcast_shape):
for d, p in zip(range(len(broadcast_shape)), params):
if p:
expanded_coords[d] = coords[dim, all_idx[first_dim]]
else:
Expand Down
6 changes: 3 additions & 3 deletions sparse/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ def algD(n, N, random_state=None):
random_state = seed for random number generation
"""

if random_state != None:
if random_state is not None:

Check warning on line 113 in sparse/_utils.py

View check run for this annotation

Codecov / codecov/patch

sparse/_utils.py#L113

Added line #L113 was not covered by tests
np.random.seed(random_state)
n = np.int64(n + 1)
N = np.int64(N)
Expand Down Expand Up @@ -169,7 +169,7 @@ def algA(n, N, random_state=None):
N = size of system (elements)
random_state = seed for random number generation
"""
if random_state != None:
if random_state is not None:

Check warning on line 172 in sparse/_utils.py

View check run for this annotation

Codecov / codecov/patch

sparse/_utils.py#L172

Added line #L172 was not covered by tests
np.random.seed(random_state)
n = np.int64(n)
N = np.int64(N)
Expand Down Expand Up @@ -498,7 +498,7 @@ def html_table(arr):
info.append(str(arr.compressed_axes))

for h, i in zip(headings, info):
table += "<tr>" '<th style="text-align: left">%s</th>' '<td style="text-align: left">%s</td>' "</tr>" % (h, i)
table += "<tr>" f'<th style="text-align: left">{h}</th>' f'<td style="text-align: left">{i}</td>' "</tr>"
table += "</tbody>"
table += "</table>"
return table
Expand Down
12 changes: 6 additions & 6 deletions sparse/tests/test_coo.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ def test_resize(a, b):
orig_size = s.size
x = s.todense()

x.resize(b)
x = np.resize(x, b)
s.resize(b)
temp = x.reshape(x.size)
temp[orig_size:] = s.fill_value
Expand Down Expand Up @@ -304,7 +304,7 @@ def test_moveaxis_error(source, destination):
[(), ()],
],
)
def test_resize(a, b):
def test_resize_2(a, b):
s = sparse.random(a, density=0.5)
orig_size = s.size
x = s.todense()
Expand Down Expand Up @@ -839,7 +839,7 @@ def test_caching():

x = COO({(1, 1, 1, 1, 1, 1, 1, 2): 1}, cache=True)

for i in range(x.ndim):
for _ in range(x.ndim):
x.reshape(x.size)

assert len(x._cache["reshape"]) < 5
Expand Down Expand Up @@ -1238,7 +1238,7 @@ def test_pickle():
x = sparse.COO.from_numpy([1, 0, 0, 0, 0]).reshape((5, 1))
# Enable caching and add some data to it
x.enable_caching()
x.T
x.T # noqa: B018
assert x._cache is not None
# Pickle sends data but not cache
x2 = pickle.loads(pickle.dumps(x))
Expand All @@ -1251,7 +1251,7 @@ def test_copy(deep):
x = sparse.COO.from_numpy([1, 0, 0, 0, 0]).reshape((5, 1))
# Enable caching and add some data to it
x.enable_caching()
x.T
x.T # noqa: B018
assert x._cache is not None

x2 = x.copy(deep)
Expand Down Expand Up @@ -1650,7 +1650,7 @@ def test_array_as_shape():
coords = [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
data = [10, 20, 30, 40, 50]

s = sparse.COO(coords, data, shape=np.array((5, 5)))
sparse.COO(coords, data, shape=np.array((5, 5)))


@pytest.mark.parametrize(
Expand Down
Loading

0 comments on commit d4d74fd

Please sign in to comment.