Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion sparsediffpy/_expression.py
Original file line number Diff line number Diff line change
Expand Up @@ -354,12 +354,15 @@ def _matmul_with_data(make, A):
def index_flat(x, flat_indices, shape):
"""Gather entries of ``x`` by column-major flat indices into ``shape``."""
x = cast_to_const(x)
idx = np.asarray(flat_indices, dtype=np.int32).ravel()
idx = np.asarray(flat_indices).ravel()
if idx.size and not np.issubdtype(idx.dtype, np.integer):
raise TypeError(f"flat indices must be integers, got dtype {idx.dtype}")
shape = _check_shape(*shape)
if idx.size != shape[0] * shape[1]:
raise ValueError(f"{idx.size} indices do not fill shape {shape}")
if idx.size and (idx.min() < 0 or idx.max() >= x.size):
raise IndexError(f"flat index out of range for size {x.size}")
idx = idx.astype(np.int32) # safe now that all are in range; also copies
return Node(lambda c: _C.make_index(c, shape[0], shape[1], idx), [x], shape)


Expand Down
15 changes: 15 additions & 0 deletions tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,21 @@ def test_index_flat_wraps_constants(scope):
np.testing.assert_array_equal(fn.forward(), [[7.0]])


def test_index_flat_checks_before_casting(scope):
"""Indices are validated as given, not after conversion to int32."""
x = scope.Variable(3, 1)
with pytest.raises(IndexError):
sp.index_flat(x, np.array([2**32 + 1]), (1, 1)) # would wrap to 1
for bad in ([1.7], [True]):
with pytest.raises(TypeError):
sp.index_flat(x, bad, (1, 1))
idx = np.array([0, 1], dtype=np.int32)
e = sp.index_flat(x, idx, (2, 1))
idx[1] = 10**6 # editing the array afterwards must not reach the engine
x.value = [10.0, 20.0, 30.0]
np.testing.assert_array_equal(sp.compile(e).forward(), [[10.0], [20.0]])


def test_numpy_scalar_exponent(scope):
x = scope.Variable(2, 1)
f1, f2 = sp.compile(x ** np.int64(2)), sp.compile(x ** np.float32(2))
Expand Down
Loading