Reduced form of symbolic expressions in sagemath

47 Views Asked by At

I am working in symbolic ring with two symbols: q and h. The relation between them is $q=e^h$. I want to do some algebra of matrices with symbolic entries. The entries of the input matrices consist of both q and h. I want that the entries of the output matrix to only contain q i.e. any expression in h should be converted into expressions in q. The following is my code:

q = SR.var('q')
h = SR.var('h')
relation = q == exp(h)

Q = matrix(SR,[[0,0,0,e^(-h)+e^(h)],[1,0,1,0],[-e^h,0,e^(-h),0],[0,1,0,0]]) 
Qi= Q.inverse() 
R=matrix(SR,[[q,0,0,0],[0,q-q^-1,1,0],[0,1,0,0],[0,0,0,q]])
print(Qi*R.subs({e^h:q},{e^-h:q^-1}).simplify_full())

Here is the output:

[                                                       0 -(q^2 - 1)*(e^h/(e^(-h) + e^h) - 1)/q - 1/(e^(-h) + e^h)                                  -e^h/(e^(-h) + e^h) + 1                                                        0]
[                                                       0                                                        0                                                        0                                                        q]
[                                                       0      (q^2 - 1)*e^h/(q*(e^(-h) + e^h)) + 1/(e^(-h) + e^h)                                       e^h/(e^(-h) + e^h)                                                        0]
[                                        q/(e^(-h) + e^h)                                                        0                                                        0                                                        0]

How can I fix this? If I add .subs(..) at the end of both the matrices then all h expressions are changed into expressions of q. However they are still not reduced, for example I get expressions like below

-q/(q^2 + 1) + (q^2 - 1)/((q^2 + 1)*q)
1

There are 1 best solutions below

0
On

The fractions do not simplify because they do not live in the fraction field of a polynomial ring.

I would suggest the following way, first replacing h by log(q) and then changing base to the correct ring.

sage: q = SR.var('q')
sage: h = SR.var('h')
sage: D = {h: log(q)}
sage: ring = QQ['q'].fraction_field()

sage: Q = matrix(SR,[[0,0,0,e^(-h)+e^(h)],[1,0,1,0],[-e^h,0,e^(-h),0],[0,1,0,0]])
sage: Q.apply_map(lambda cf:cf.subs(D)).change_ring(ring)
[          0           0           0 (q^2 + 1)/q]
[          1           0           1           0]
[         -q           0         1/q           0]
[          0           1           0           0]