
"""
   General relativity package for Cadabra.
   NOTE: this is a proof of concept, not something that is finished in any sense.
"""

import cadabra2

__cdbkernel__ = cadabra2.__cdbkernel__
server        = __cdbkernel__.server
display       = __cdbkernel__.display

#import cadabra2
from cadabra2 import *

setup_done=False

def setup():
    global setup_done
    if setup_done==False:
        {\mu,\nu,\rho,\sigma,\kappa,\gamma,\lambda}::Indices(spacetime, position=fixed);
        \partial{#}::PartialDerivative.
        setup_done=True

def riemann_from_christoffel(R=$R$, c=$\Gamma$):
    """ Return the Riemann tensor expressed in terms of Christoffel symbols. """
    setup()
            # FIXME: need to create_scope_from_global, then
            # create new index declaration in there, with e.g. name "cdb.relativity.spacetime".
            # Then generate the equation using the symbol (need 'head'!) passed in
            # as R and c. Then find name of index set on those function arguments
            # and finally do a rename_dummies/indices.
    ex:= @(R)^{\rho}_{\sigma\mu\nu} =
          \partial_{\mu}{@(c)^{\rho}_{\nu\sigma}}
         -\partial_{\nu}{@(c)^{\rho}_{\mu\sigma}}
         + @(c)^{\rho}_{\mu\lambda} @(c)^{\lambda}_{\nu\sigma}
         - @(c)^{\rho}_{\nu\lambda} @(c)^{\lambda}_{\mu\sigma}.
    return ex

def christoffel_from_metric(c=Ex(r'\Gamma'), g=Ex(r'g')):
    setup()
    ex:= @(c)^{\lambda}_{\mu\nu} = 1/2 g^{\lambda\kappa} ( \partial_{\mu}{ g_{\kappa\nu} }
                                                           + \partial_{\nu}{ g_{\kappa\mu} } - \partial_{\kappa}{ g_{\mu\nu} } ).
    return ex

def expand_covariant_derivative():
    setup()
    ex = Ex(r'\nabla_{\mu}{A?^{\nu}} = \partial_{\mu}{A?^{\nu}} + \Gamma^{\nu}_{\mu\rho} A?^{\rho}')
    return ex

def riemann_to_ricci(ex):
    """ Convert contractions of Riemann tensors to Ricci tensors or scalars. """

    rl1:= R^{a?}_{b? a? c?}     =  R_{b? c?}, R^{a?}_{b? c? a?}     = -R_{b? c?}.
    rl2:= R_{a?}_{b?}^{a?}_{c?} =  R_{b? c?}, R_{a?}_{b? c?}^{a?}   = -R_{b? c?}.
    rl3:= R_{b?}^{a?}_{c? a?}   =  R_{b? c?}, R_{b?}^{a?}_{a? c?}   = -R_{b? c?}.
    rl4:= R_{b?}_{a?}^{c? a?}   =  R_{b?}^{c?}.
    rl5:= R^{a?}_{a?} = R, R_{a?}^{a?} = R.

    substitute(ex, rl1+rl2+rl3+rl4+rl5, repeat=True)

    return ex
