Skip to content
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

Fixes incorrect behaviour when taking the derivative of a constant matrix #39451

Merged
merged 5 commits into from
Feb 10, 2025
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
11 changes: 10 additions & 1 deletion src/sage/matrix/matrix_dense.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ TESTS::
cimport sage.matrix.matrix as matrix

from sage.structure.richcmp cimport richcmp_item, rich_to_bool
from sage.calculus.functional import derivative
import sage.matrix.matrix_space
import sage.structure.sequence

Expand Down Expand Up @@ -275,11 +276,19 @@ cdef class Matrix_dense(matrix.Matrix):
sage: m._derivative(x) # needs sage.symbolic
[ 0 1]
[ 2*x 3*x^2]

TESTS:

Verify that :issue:`15067` is fixed::

sage: u = matrix(1, 2, [-1, 1])
sage: derivative(u, x)
[0 0]
"""
# We could just use apply_map
if self._nrows==0 or self._ncols==0:
return self.__copy__()
v = [z.derivative(var) for z in self.list()]
v = [sage.calculus.functional.derivative(z, var) for z in self.list()]
if R is None:
v = sage.structure.sequence.Sequence(v)
R = v.universe()
Expand Down
13 changes: 12 additions & 1 deletion src/sage/matrix/matrix_sparse.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ from cysignals.signals cimport sig_check
cimport sage.matrix.matrix as matrix
cimport sage.matrix.matrix0 as matrix0
from sage.categories.rings import Rings
from sage.calculus.functional import derivative
from sage.structure.element cimport Element, Vector
from sage.structure.richcmp cimport richcmp_item, rich_to_bool

Expand Down Expand Up @@ -810,13 +811,23 @@ cdef class Matrix_sparse(matrix.Matrix):
sage: m._derivative(x) # needs sage.symbolic
[ 0 1]
[ 2*x 3*x^2]

TESTS:

Verify that :issue:`15067` is fixed::

sage: m = matrix(3, 3, {(1, 1): 2, (0,2): 5})
sage: derivative(m, x)
[0 0 0]
[0 0 0]
[0 0 0]
"""
# We would just use apply_map, except that Cython does not
# allow lambda functions

if self._nrows==0 or self._ncols==0:
return self.__copy__()
v = [(ij, z.derivative(var)) for ij, z in self.dict().iteritems()]
v = [(ij, sage.calculus.functional.derivative(z, var)) for ij, z in self.dict().iteritems()]
if R is None:
w = [x for _, x in v]
w = sage.structure.sequence.Sequence(w)
Expand Down
Loading