Reputation: 9863
Consider this simple matrix equation:
from sympy import *
c_a, s_a = symbols('c_a s_a')
k_1, k_2, k_3, k_4, k_5, k_6 = symbols('k_1 k_2 k_3 k_4 k_5 k_6')
x,y,z = symbols('x y z')
equation = Eq(MatrixSymbol('R',4,4), Matrix([
[ c_a*k_1 - k_1 + 1, -c_a*k_4 + k_4 - s_a*z, -c_a*k_5 + k_5 + s_a*y, 0],
[-c_a*k_4 + k_4 + s_a*z, c_a*k_2 - k_2 + 1, -c_a*k_6 + k_6 - s_a*x, 0],
[-c_a*k_5 + k_5 - s_a*y, -c_a*k_6 + k_6 + s_a*x, c_a*k_3 - k_3 + 1, 0],
[ 0, 0, 0, c_a + s_a]]))
I've tried to simplify for a while with no success... as you can see there is a lot of possible factorizations (ie: k_1*(c_a-1), k_4(1-c_a), ...
). I've tried many of the existing available methods sympy has to simplify https://docs.sympy.org/latest/tutorial/simplification.html but no luck... factor, simplify, collect, applyfuncs(factor), simplifiy(force=True) etc.
I'm a newbie with sympy so probably there is some obvious way to simplify further these type of equations, if it's so, how?
Also, I'm just interested to simplify the rhs
of the equation, not the lhs
. Is it possible to simplify any of them or both?
Upvotes: 0
Views: 229
Reputation: 19047
This is a DIY case. Something like the following may work for you:
>>> def most_collect(eq):
... f = eq.free_symbols
... if not f: return eq
... F = sorted(f, key=lambda x: eq.count(x))
... return collect(eq, F[-1])
>>> equation.rhs.applyfunc(most_collect)
Matrix([
[ k_1*(c_a - 1) + 1, k_4*(1 - c_a) - s_a*z, k_5*(1 - c_a) + s_a*y, 0],
[k_4*(1 - c_a) + s_a*z, k_2*(c_a - 1) + 1, k_6*(1 - c_a) - s_a*x, 0],
[k_5*(1 - c_a) - s_a*y, k_6*(1 - c_a) + s_a*x, k_3*(c_a - 1) + 1, 0],
[ 0, 0, 0, c_a + s_a]])
Upvotes: 1