# How to collect the derivatives in an expression for a scalar field

Please consider the following example; it calculates the commutator of two vector fields acting on a scalar field, that is to say it calculates [u,v]f.

from sage.all import *

%display latex

M = Manifold(4, 'M', latex_name=r'\mathcal{M}', structure='Lorentzian')
X.<t,x,y,z> = M.chart()

u0 = function(r'u_0')(t,x,y,z)
u1 = function(r'u_1')(t,x,y,z)
u2 = function(r'u_2')(t,x,y,z)
u3 = function(r'u_3')(t,x,y,z)
u = M.vector_field(u0,u1,u2,u3, latex_name=r'\mathbf{u}')
v0 = function(r'v_0')(t,x,y,z)
v1 = function(r'v_1')(t,x,y,z)
v2 = function(r'v_2')(t,x,y,z)
v3 = function(r'v_3')(t,x,y,z)
v = M.vector_field(v0,v1,v2,v3, latex_name=r'\mathbf{v}')

f = M.scalar_field(function('f')(t,x,y,z), latex_name='f')
commutator_f = u(v(f)) - v(u(f))
commutator_f


This works. Now I can look at the expression for [u,v]f using

commutator_f.expr()


This also works but has many terms that I would like to collect - I would like all terms that are derivatives of f to "go to the right". I tried

commutator_f.expr().collect(f)


but that does not work: TypeError: no canonical coercion from Algebra of differentiable scalar fields on the 4-dimensional Lorentzian manifold M to Symbolic Ring.

How can I do this please?

Using SageMath version 9.5, Release Date: 2022-01-30, on Ubuntu 22.04.

Thank you

GPN

edit retag close merge delete

1

Maybe commutator_f.expr().collect(f.expr()) ?

( 2023-12-04 22:46:31 +0200 )edit

Thanks for the suggestion, I tried. It gets rid of the error but nothing is collected. I then also tried

commutator_f.expr().collect(diff(f).expr())


but no luck: now a different error AttributeError: 'DiffFormFreeModule_with_category.element_class' object has no attribute 'expr'.

( 2023-12-04 23:32:27 +0200 )edit
1

It should be diff(f)[i].expr() for $\partial f /\partial x^i$, so I guess

commutator_f.expr().collect(diff(f)[0].expr())


should work (for $\partial f /\partial x^0$).

( 2023-12-05 09:43:43 +0200 )edit

cool, I will try that

( 2023-12-05 15:38:51 +0200 )edit

Sort by » oldest newest most voted

Based on the advice from @max and @eric_g - the following works:

commutator_f.expr() \
.collect(diff(f)[0].expr()) \
.collect(diff(f)[1].expr()) \
.collect(diff(f)[2].expr()) \
.collect(diff(f)[3].expr())


Many thanks GPN

more

2

Tip: use parentheses and skip end-of-line backslash.

(
commutator_f.expr()
.collect(diff(f)[0].expr())
.collect(diff(f)[1].expr())
.collect(diff(f)[2].expr())
.collect(diff(f)[3].expr())
)

( 2023-12-05 15:51:31 +0200 )edit

@slelievre thanks.

( 2023-12-05 16:13:47 +0200 )edit