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
15 changes: 14 additions & 1 deletion sparsediffpy/_expression.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,19 @@ def _check_shape(d1, d2):
raise TypeError(f"Shape dimensions must be integers, got ({d1!r}, {d2!r})")
if d1 <= 0 or d2 <= 0:
raise ValueError(f"Shape dimensions must be positive, got ({d1}, {d2})")
return (int(d1), int(d2))
shape = (int(d1), int(d2))
_check_size(shape)
return shape


_MAX_SIZE = 2**31 - 1 # the engine stores sizes as C int


def _check_size(shape):
"""Raise if a shape has more entries than the engine can index."""
if shape[0] * shape[1] > _MAX_SIZE:
raise ValueError(f"Shape {shape} has {shape[0] * shape[1]} entries; "
f"the engine supports at most {_MAX_SIZE}")


class Expression:
Expand Down Expand Up @@ -101,6 +113,7 @@ def __init__(self, make, args, shape):
self.make = make
self.args = tuple(args)
self.shape = tuple(shape)
_check_size(self.shape)


class Constant(Expression):
Expand Down
12 changes: 12 additions & 0 deletions tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,18 @@ def test_invalid_shapes(scope, shape):
scope.Variable(*shape)


def test_too_many_entries(scope):
"""Sizes are C ints in the engine; larger shapes must fail before reaching C."""
big = (65536, 65537) # 2**32 + 65536 entries
x = scope.Variable(1, 1)
a, b = scope.Variable(65536, 1), scope.Variable(1, 65537)
for make in (lambda: scope.Variable(*big), lambda: scope.Parameter(*big),
lambda: sp.broadcast(x, big), lambda: a @ b):
with pytest.raises(ValueError, match="at most"):
make()
assert sp.broadcast(x, (2**31 - 1, 1)).size == 2**31 - 1


def test_reevaluates_at_new_values(scope):
x = scope.Variable(2, 1)
fn = sp.compile(sp.exp(x))
Expand Down
Loading