# How to compute functional derivative against vector in xAct, xTensor or xTras?

I want to compute the functional derivative against vectors.

For example, I have an object that looks like this $$R = h_{ijkl}a^i a^j a^k a^l$$

I need to compute $$\frac{\delta R}{\delta a^p}= 4 h_{pjkl} a^j a^k a^l$$

The VarD method in xTensor is able to compute this with the following code

VarD[A[p]][H[-i, -j, -k, -l]*A[i]*A[j]*A[k]*A[l]] // CollectTensors


But when I want to compute the second-order derivate it gives me an error because the argument is not a scalar.

$$\frac{\delta}{\delta a^m} \frac{\delta R}{\delta a^p}= 12 h_{pmkl} a^k a^l$$

Here is my setup for the following problem. Thank you in advance.

 << xActxTras;
DefManifold[M, dim, IndexRange[a, m]];

DefMetric[-1, metric[-a, -b], PD, PrintAs -> "\[Eta]",
FlatMetric -> True, SymbolOfCovD -> {",", "\[PartialD]"}];
SetOptions[SymmetryOf, ConstantMetric -> True];

DefTensor[H[-a, -b, -c, -d], M, Symmetric[{-a, -b, -c, -d}], PrintAs -> "h"]
DefTensor[A[a], M , PrintAs -> "a"]


In my opinion it only makes sense to take variational derivatives of scalar actions, that is, of the integral of a scalar Lagrangian times a volume form. Hence, xTensor complains if you try to differentiate a non-scalar object. However, it is simple to solve that: if you want to differentiate something with, say, three free indices, then you contract it with an arbitrary tensor field (without any symmetry) with three free indices. Then you can take the variational derivative of that scalar object, and remove the arbitrary tensor at the end. You must decide what "remove" means, because the arbitrary tensor will be differentiated in general in the result, if you had derivatives initially, due to eventual integrations by parts.

In your case this is easy because there were no derivatives in the input. (Note that you are using an index p, while the declared range was IndexRange[a, m], so I changed that to IndexRange[a, p]):

DefTensor[B[a], M]

expr = H[-i, -j, -k, -l] A[i] A[j] A[k] A[l];

VarD[A[p]][expr] // ToCanonical

VarD[A[m]][% B[p]] // ToCanonical

% /. B[c_] -> delta[c, -p] // ToCanonical
(* 12 A[a] A[b] H[-m, -p, -a, -b] *)