Skip to content

Support matrix multiplication for quantities - #284

Open
KennyMcSimpson wants to merge 1 commit into
python-quantities:masterfrom
KennyMcSimpson:fix/matmul-dimensionality
Open

KennyMcSimpson wants to merge 1 commit into
python-quantities:masterfrom
KennyMcSimpson:fix/matmul-dimensionality

Conversation

@KennyMcSimpson

Copy link
Copy Markdown

Quantity arrays currently raise ValueError: ufunc <ufunc 'matmul'> not supported by quantities for both @ and numpy.matmul. For example, the matrix from #231 cannot be multiplied by its transpose.

This adds a matrix-multiplication dimensionality rule that multiplies the operand units while NumPy handles the numerical operation, shapes and broadcasting. It also updates quantity output units on NumPy 1.x, where generalized ufuncs do not call __array_prepare__. The rule rejects UncertainQuantity inputs and outputs on paths that produce Quantity metadata, so enabling matrix multiplication does not produce a quantity with invalid uncertainty metadata. Explicit plain ndarray output bypasses metadata hooks, as it already does for other ufuncs and for matmul before this change; that existing behavior is unchanged. The type stubs, tutorial and changelog are updated.

Fixes #231.

Validation:

  • The new regressions fail against the original master. They cover vector/matrix products, broadcasting, plain-array operands on either side, complex values, output buffers and output views, shape errors, and unsupported uncertainty propagation.
  • Python 3.10 / NumPy 1.24.4: 197 passed, 1 skipped, 3 expected failures, 48 subtests passed. The skip is @=, which NumPy added in 1.25.
  • Python 3.11 / NumPy 1.26.4: 198 passed, 3 expected failures, 48 subtests passed, including native @=.
  • Python 3.13 and 3.14 / NumPy 2.4.6: 198 passed, 3 expected failures, 48 subtests passed each.
  • Mypy, README/tutorial doctests, Ruff on the new test module, sdist/wheel builds and Twine checks pass. Whole-project advisory Ruff output is unchanged: 528 existing diagnostics, none added.
  • An independent Python scalar multiply-and-sum reference checks 2,970 cases on each of NumPy 1.24 and 2.4, plus 2,970 cases using the installed wheel. These include integer, float and complex data, empty dimensions, broadcasted batches and physical unit scale factors; all agree.

Prepared with AI assistance. All validation described above was run locally.

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.

ufunc 'matmul' not supported by quantities

1 participant