Skip to content

Check that vectors are not passed to matrix.block #40277

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
Jul 25, 2025

Conversation

user202729
Copy link
Contributor

@user202729 user202729 commented Jun 21, 2025

Currently if a vector is passed in, the following happens

sage: matrix.block([
....:     [matrix.zero(2), vector([0]*2)],
....:     ])
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
...
ValueError: insufficient information to determine dimensions.

sage: matrix.block([
....:     [matrix.zero(2), vector([0]*2)],
....:     [0, matrix.zero(2)],
....:     ])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
...
TypeError: ring must be a ring

which is rather confusing. This gives a more descriptive error message.

📝 Checklist

  • The title is concise and informative.
  • The description explains in detail what this PR is about.
  • I have linked a relevant issue or discussion.
  • I have created tests covering the changes.
  • I have updated the documentation and checked the documentation preview.

⌛ Dependencies

Copy link

github-actions bot commented Jun 21, 2025

Documentation preview for this PR (built with commit 0b29b37; changes) is ready! 🎉
This preview will update shortly after each push to this PR.

@tscrim
Copy link
Collaborator

tscrim commented Jun 26, 2025

I would say we should make the usual identification of vectors as $1 \times k$ matrices for this construction. So the implementation just needs a bit more care (or just modify your loop to convert them to matrices for a quick fix).

@user202729
Copy link
Contributor Author

I would say we should make the usual identification of vectors as 1 × k matrices for this construction. So the implementation just needs a bit more care (or just modify your loop to convert them to matrices for a quick fix).

I think vectors are more commonly considered $k × 1$ matrices. On the other hand, calling .row() or .column() on a vector is short enough.

@tscrim
Copy link
Collaborator

tscrim commented Jun 26, 2025

I would say we should make the usual identification of vectors as 1 × k matrices for this construction. So the implementation just needs a bit more care (or just modify your loop to convert them to matrices for a quick fix).

I think vectors are more commonly considered k × 1 matrices.

Yes, I completely agree. That was a typo on my part.

On the other hand, calling .row() or .column() on a vector is short enough.

True, but I would say a similar sort of thing is done for the scalars. Although I guess from the matrices, one could deduce if it was meant as a row or column vector. Well, I guess erroring out is okay… But perhaps we should instead check only for scalars and matrices (rather than only rule out vectors)?

@user202729
Copy link
Contributor Author

Yes, I completely agree. That was a typo on my part.

Maybe we can get by with considering them as column vector after all.

But perhaps we should instead check only for scalars and matrices (rather than only rule out vectors)?

Reasonable. But since the base ring may not be a priori known, we could check that they are ring elements instead.

(also, matrices are ring elements.)

@user202729
Copy link
Contributor Author

user202729 commented Jun 27, 2025

I thought isinstance(M, RingElement) would check if it's a scalar, but there are Python types too. I think we can overlook that because of duck typing.

Or is it better to use type_to_parent? The advantage is clearer error message for users, the disadvantage is more complicated code. I'm thinking of something like

diff --git a/src/sage/matrix/special.py b/src/sage/matrix/special.py
index 375cb0c3234..894cd26d457 100644
--- a/src/sage/matrix/special.py
+++ b/src/sage/matrix/special.py
@@ -2096,7 +2096,12 @@ def block_matrix(*args, **kwds):
             for M in row:
                 R = M.base_ring() if isinstance(M, Matrix) else parent(M)
                 if R is not ZZ:
-                    ring = sage.categories.pushout.pushout(ring, R)
+                    try:
+                        ring = sage.categories.pushout.pushout(ring, R)
+                    except:
+                        if not isinstance(M, Matrix) and type_to_parent(parent(M)) not in Rings():
+                            raise ValueError(f"{M} must be a scalar, vector or matrix")
+                        raise
 
     if sparse is None:
         sparse = True

(on an unrelated note, it's probably better to use common_parent instead of this)

@tscrim
Copy link
Collaborator

tscrim commented Jun 30, 2025

I thought isinstance(M, RingElement) would check if it's a scalar, but there are Python types too. I think we can overlook that because of duck typing.

Indeed, that is not a good test as many (commutative) ring elements do not inherit from this class (in fact, it would make things a bit easier for us to get rid of that class and just use Element IMO).

Or is it better to use type_to_parent? The advantage is clearer error message for users, the disadvantage is more complicated code.

My initial reaction was to keep the code simple. Yet, this is such a fundamental function (in the sense of the mathematics where 1st year students could use it), so my current belief is we should have the more clear error message. Do you want to make that change on this PR as well?

(on an unrelated note, it's probably better to use common_parent instead of this)

Yea, probably common_parent is better.

@user202729
Copy link
Contributor Author

so something like this? If we want to go the whitelist (instead of blacklist) route

# assume is neither matrix or vector
R = parent(M)
if isinstance(R, type): R = type_to_parent(R)
if R in Rings(): ...

there might not be that large of an improvement though, since other than vectors what other invalid things could people reasonably pass in? (str? list? tuple?)

@tscrim
Copy link
Collaborator

tscrim commented Jul 2, 2025

It shouldn't know how to process those things currently, right? So it is at least implicitly a whitelist as implemented; at least that is my interpretation from briefly looking at the code. I might be mistaken though.

Copy link
Collaborator

@tscrim tscrim left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you. LGTM.

vbraun pushed a commit to vbraun/sage that referenced this pull request Jul 14, 2025
sagemathgh-40277: Check that vectors are not passed to matrix.block
    
Currently if a vector is passed in, the following happens

```
sage: matrix.block([
....:     [matrix.zero(2), vector([0]*2)],
....:     ])
------------------------------------------------------------------------
---
ValueError                                Traceback (most recent call
last)
...
ValueError: insufficient information to determine dimensions.

sage: matrix.block([
....:     [matrix.zero(2), vector([0]*2)],
....:     [0, matrix.zero(2)],
....:     ])
------------------------------------------------------------------------
---
TypeError                                 Traceback (most recent call
last)
...
TypeError: ring must be a ring
```

which is rather confusing. This gives a more descriptive error message.

### 📝 Checklist

<!-- Put an `x` in all the boxes that apply. -->

- [x] The title is concise and informative.
- [x] The description explains in detail what this PR is about.
- [ ] I have linked a relevant issue or discussion.
- [x] I have created tests covering the changes.
- [x] I have updated the documentation and checked the documentation
preview.

### ⌛ Dependencies

<!-- List all open PRs that this PR logically depends on. For example,
-->
<!-- - sagemath#12345: short description why this is a dependency -->
<!-- - sagemath#34567: ... -->
    
URL: sagemath#40277
Reported by: user202729
Reviewer(s): Travis Scrimshaw
vbraun pushed a commit to vbraun/sage that referenced this pull request Jul 18, 2025
sagemathgh-40277: Check that vectors are not passed to matrix.block
    
Currently if a vector is passed in, the following happens

```
sage: matrix.block([
....:     [matrix.zero(2), vector([0]*2)],
....:     ])
------------------------------------------------------------------------
---
ValueError                                Traceback (most recent call
last)
...
ValueError: insufficient information to determine dimensions.

sage: matrix.block([
....:     [matrix.zero(2), vector([0]*2)],
....:     [0, matrix.zero(2)],
....:     ])
------------------------------------------------------------------------
---
TypeError                                 Traceback (most recent call
last)
...
TypeError: ring must be a ring
```

which is rather confusing. This gives a more descriptive error message.

### 📝 Checklist

<!-- Put an `x` in all the boxes that apply. -->

- [x] The title is concise and informative.
- [x] The description explains in detail what this PR is about.
- [ ] I have linked a relevant issue or discussion.
- [x] I have created tests covering the changes.
- [x] I have updated the documentation and checked the documentation
preview.

### ⌛ Dependencies

<!-- List all open PRs that this PR logically depends on. For example,
-->
<!-- - sagemath#12345: short description why this is a dependency -->
<!-- - sagemath#34567: ... -->
    
URL: sagemath#40277
Reported by: user202729
Reviewer(s): Travis Scrimshaw
@vbraun vbraun merged commit a0be0fe into sagemath:develop Jul 25, 2025
35 of 40 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants