Skip to content

Check for square matrix in make_node to Det #861

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 28, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
10 changes: 9 additions & 1 deletion pytensor/tensor/nlinalg.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,15 @@ class Det(Op):

def make_node(self, x):
x = as_tensor_variable(x)
assert x.ndim == 2
if x.ndim != 2:
raise ValueError(
f"Input passed is not a valid 2D matrix. Current ndim {x.ndim} != 2"
)
# Check for known shapes and square matrix
if None not in x.type.shape and (x.type.shape[0] != x.type.shape[1]):
raise ValueError(
f"Det not defined for non-square matrix inputs. Shape received is {x.type.shape}"
)
o = scalar(dtype=x.dtype)
return Apply(self, [x], [o])

Expand Down
5 changes: 5 additions & 0 deletions tests/tensor/test_nlinalg.py
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,11 @@ def test_det():
assert np.allclose(np.linalg.det(r), f(r))


def test_det_non_square():
with pytest.raises(ValueError, match="Det not defined"):
det(tensor("x", shape=(5, 7)))


def test_det_grad():
rng = np.random.default_rng(utt.fetch_seed())

Expand Down