I've found that the easiest way to do this is by using the
capabilities of xPert in combination with VarD. What follows is the
example for metric GR (I haven't thought about doing Palatini
variation or metric-affine; somebody else may chime in).
Define a manifold, metric, and metric perturbation. I'll call my
metric met[-a,-b] and my metric perturbation metpert[LI[1], -a, -b].
Define the action, with the volume element:
LEH = Sqrt[-Detmet[]] RicciScalarCD[]
Find the first perturbed of the action:
LEHpert1 = Perturbation[LEH] // ExpandPerturbation // ContractMetric
// ToCanonical
It is a property of Lagrangians that varying the first perturbed
action with respect to the first perturbation gives the zeroth order
Euler-Lagrange equations (this is not a really deep statement). Go
ahead and vary the first perturbed action:
EOM0 = VarD[metpert[LI[1], a, b], CD][-LEHpert1]/Sqrt[-Detmet[]] /.
delta[-LI[1], LI[1]] -> 1 // ToCanonical
You will find the result:
RicciCD[-a, -b] - 1/2 met[-a, -b] RicciScalarCD[]
A few comments about this: you need the volume element in the action
(Sqrt[-Detmet[]]), and then you divide through by it in the end to get
the normal looking field equations. The default derivative operator
that VarD assumes is PD, which does not lead to covariant equations.
Putting the volume element in there and specifying CD as the second
argument to VarD gives you the correct covariant equations of motion.
The metric perturbation has a label index which is used to denote the
order of the perturbation; after the variation, VarD makes a bunch of
delta functions on the label index. If you had multiple orders in
there (if say you did second order perturbation theory on the action)
you would end up with delta[-LI[1], LI[2]], for example. These delta
functions are not automatically simplified, so you have to replace
them yourself. You can do this procedure on an arbitrary action to get
the equations of motion of some modified gravity theory (I've been
doing this).
Alternatively, you can dig into the guts of VarD, define
ImplicitTensorDepQ for various curvature tensors to be dependent on
the metric, and define (by hand) the variation of those curvature
tensors with respect to the metric. This would work but would also be
a lot of work on your part. xPert already does all of the work that
you would have to do in order to get the above to work, so using xPert
is easier. I think if you wanted to do Palatini variation, you would
have to use the latter approach and define how the variation of
curvature tensors depend on the connection.
Hope this helps,
Leo