简体   繁体   中英

How to minimize sympy partial derivative expression after matrix/vector multiplication?

I'm using sympy to compute the partial derivative of a matrix/vector multiplication (see code below) but the resultant expression is to complicated and I would like to know if there is a way to simplify it.

from sympy import symbols, MatrixSymbol, diff, Matrix, symarray, expand, factor, simplify
import numpy as np

Ca = Matrix(symarray('Ca', (2, 4)))
Cb = Matrix(symarray('Cb', (2, 4)))
Cc = Matrix(symarray('Cc', (2, 4)))

qi = Matrix(symarray('qi', (4, 1)))
qj = Matrix(symarray('qj', (4, 1)))

R90 = Matrix(symarray('R90', (2, 2)))

u = (Ca*qi - Cb*qj)
v = (Cc*qj - Cb*qj)

u_tilde = R90*u

# Equation
constr_eq = (u_tilde).T*v

# Partial derivatives
u_diff = u.diff(qi)

constr_eq_diff_wrt_qi  = constr_eq.diff(qi)
constr_eq_diff_wrt_qj  = constr_eq.diff(qj)

The output of

print('u_diff : ', u_diff)

is

[[[[Ca_0_0], [Ca_1_0]]], [[[Ca_0_1], [Ca_1_1]]], [[[Ca_0_2], [Ca_1_2]]], [[[Ca_0_3], [Ca_1_3]]]]

and I would like to be just

Ca

Consequently the output of

'constr_eq_diff_wrt_qi' 

and

constr_eq_diff_wrt_qj

is unreadable.

Thank you. Ivo

Based on @asmeurer help here is a working example:

from sympy import MatrixSymbol, diff

# Initialize simbolic matrices 
Ca = MatrixSymbol('Ca', 2, 4)
Cb = MatrixSymbol('Cb', 2, 4)
Cc = MatrixSymbol('Cc', 2, 4)

qi = MatrixSymbol('qi', 4, 1)
qj = MatrixSymbol('qj', 4, 1)

R90 = MatrixSymbol('R90', 2, 2)

# Initialize vectors 
u = (Ca*qi - Cb*qj)
v = (Cc*qj - Cb*qj)

u_tilde = R90*u

# Constraint Equation
constr_eq = (u_tilde).T*v

# Partial derivatives
generalized_coordinates = [qi, qj]

# Get contraint equations partial derivatives 
for _ in generalized_coordinates:
    print('jacobian wrt ' + str(_) + ' : ', constr_eq.diff(_))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM