Hello,
I've attempted to calculate the Jacobian of a simple expression with
indexed variables, and it appears that the diff() function cannot
currently work with the IndexedBase class.
Running the sample code below results in the following traceback:
Traceback (most recent call last):
File "test-Jacobian.py", line 21, in <module>
main()
File "test-Jacobian.py", line 18, in main
test_function()
File "test-Jacobian.py", line 13, in test_function
J = vec.jacobian(var)
File
"/usr/local/lib/python2.6/dist-packages/sympy/matrices/matrices.py",
line 981, in jacobian
return Matrix(m, n, lambda j, i: self[j].diff(X[i]))
File
"/usr/local/lib/python2.6/dist-packages/sympy/matrices/matrices.py",
line 95, in __init__
self.mat.append(sympify(operation(i, j)))
File
"/usr/local/lib/python2.6/dist-packages/sympy/matrices/matrices.py",
line 981, in <lambda>
return Matrix(m, n, lambda j, i: self[j].diff(X[i]))
File "/usr/local/lib/python2.6/dist-packages/sympy/core/expr.py",
line 844, in diff
ret = Derivative(self, *new_symbols, **assumptions)
File "/usr/local/lib/python2.6/dist-packages/sympy/core/function.py",
line 585, in __new__
raise ValueError('Invalid literal: %s is not a valid variable' % s)
ValueError: Invalid literal: p[1, 1] is not a valid variable
I've modified line 584 in the file /core/function.py to read:
if not isinstance(s, C.Symbol) and not isinstance(s, C.Indexed):
This modification allows for the script to proceed without error, but
the output does not appear to be correct:
[-2*D(p[1, 1], p[1, 1]) + 2*p[1, 1]**2*D(p[1, 1], p[1, 1])/p[1,
1], -D(p[1, 2], p[1, 2])]
[ 2*p[1, 1]**2*D(p[1, 1], p[1, 1])/p[1, 1],
8*p[1, 2]**2*D(p[1, 2], p[1, 2])/p[1, 2]]
As far as I understand, the output should be something similar to the
following, assuming (of course) that p[1,1] and p[1,2] are variables.
[-2 + 2*p[1,1] -1]
[2*p[1,1] 8*p[1,2]]
Is there a way around this, or can the code in diff() be easily fixed to
support expressions with IndexedBase? I think that it would be very
exciting for diff() to work with IndexedBase, if this is indeed the issue.
Nicholas
#begin sample code
from sympy import *
from sympy.tensor import Indexed, Idx, IndexedBase
from sympy.matrices import *
p = IndexedBase('p')
def test_function():
expr1 = p[1,1]**2 - 2*p[1,1] - p[1,2] + 0.5
expr2 = p[1,1]**2 + 4*p[1,2]**2 - 4
vec = Matrix([expr1, expr2])
var = Matrix([p[1,1], p[1,2]])
J = vec.jacobian(var)
print J
def main():
test_function()
if __name__ == "__main__":
main()
--
You received this message because you are subscribed to the Google Groups
"sympy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/sympy?hl=en.