Exemplo n.º 1
0
def test_tensor_element():
    L = TensorIndexType("L")
    i, j, k, l, m, n = tensor_indices("i j k l m n", L)

    A = TensorHead("A", [L, L], TensorSymmetry.no_symmetry(2))

    a = A(i, j)

    assert isinstance(TensorElement(a, {}), Tensor)
    assert isinstance(TensorElement(a, {k: 1}), Tensor)

    te1 = TensorElement(a, {Symbol("i"): 1})
    assert te1.free == [(j, 0)]
    assert te1.get_free_indices() == [j]
    assert te1.dum == []

    te2 = TensorElement(a, {i: 1})
    assert te2.free == [(j, 0)]
    assert te2.get_free_indices() == [j]
    assert te2.dum == []

    assert te1 == te2

    array = Array([[1, 2], [3, 4]])
    assert te1.replace_with_arrays({A(i, j): array}, [j]) == array[1, :]
Exemplo n.º 2
0
    def __new__(cls, dim=4, eps_dim=4):
        key = (dim, eps_dim)
        if key in GammaMatrixHead._gmhd:
            return GammaMatrixHead._gmhd[key]

        lorentz = _LorentzContainer(*key)

        gmh = TensorHead.__new__(cls, "gamma", TensorType(Tuple(lorentz), tensorsymmetry([1])), comm=2)
        GammaMatrixHead._gmhd[key] = gmh
        gmh.Lorentz = lorentz
        return gmh
Exemplo n.º 3
0
    def __new__(cls, dim=4, eps_dim=4):
        key = (dim, eps_dim)
        if key in GammaMatrixHead._gmhd:
            return GammaMatrixHead._gmhd[key]

        lorentz = _LorentzContainer(*key)

        gmh = TensorHead.__new__(cls, "gamma", TensorType(Tuple(lorentz, DiracSpinorIndex, DiracSpinorIndex), tensorsymmetry([1], [1], [1])), comm=2, matrix_behavior=True)
        GammaMatrixHead._gmhd[key] = gmh
        gmh.LorentzIndex = lorentz
        return gmh
Exemplo n.º 4
0
def test_gamma_matrix_class():
    i, j, k = tensor_indices("i,j,k", LorentzIndex)

    # define another type of TensorHead to see if exprs are correctly handled:
    A = TensorHead("A", [LorentzIndex])

    t = A(k) * G(i) * G(-i)
    ts = simplify_gamma_expression(t)
    assert _is_tensor_eq(
        ts, Matrix([[4, 0, 0, 0], [0, 4, 0, 0], [0, 0, 4, 0], [0, 0, 0, 4]]) * A(k)
    )

    t = G(i) * A(k) * G(j)
    ts = simplify_gamma_expression(t)
    assert _is_tensor_eq(ts, A(k) * G(i) * G(j))

    execute_gamma_simplify_tests_for_function(simplify_gamma_expression, D=4)
Exemplo n.º 5
0
from sympy.tensor.toperators import PartialDerivative
from sympy.tensor.tensor import (TensorIndexType, tensor_indices, TensorHead,
                                 tensor_heads)
from sympy import symbols, diag
from sympy import Array, Rational

from random import randint

L = TensorIndexType("L")
i, j, k, m, m1, m2, m3, m4 = tensor_indices("i j k m m1 m2 m3 m4", L)
i0 = tensor_indices("i0", L)
L_0, L_1 = tensor_indices("L_0 L_1", L)

A, B, C, D = tensor_heads("A B C D", [L])

H = TensorHead("H", [L, L])


def test_invalid_partial_derivative_valence():
    raises(ValueError, lambda: PartialDerivative(C(j), D(-j)))
    raises(ValueError, lambda: PartialDerivative(C(-j), D(j)))


def test_tensor_partial_deriv():
    # Test flatten:
    expr = PartialDerivative(PartialDerivative(A(i), A(j)), A(i))
    assert expr.expr == A(L_0)
    assert expr.variables == (A(j), A(L_0))

    expr1 = PartialDerivative(A(i), A(j))
    assert expr1.expr == A(i)
Exemplo n.º 6
0
    metric(LorentzIndex,LorentzIndex)

"""
from sympy.core.mul import Mul
from sympy.core.singleton import S
from sympy.matrices.dense import eye
from sympy.matrices.expressions.trace import trace
from sympy.tensor.tensor import TensorIndexType, TensorIndex,\
    TensMul, TensAdd, tensor_mul, Tensor, TensorHead, TensorSymmetry

# DiracSpinorIndex = TensorIndexType('DiracSpinorIndex', dim=4, dummy_name="S")

LorentzIndex = TensorIndexType('LorentzIndex', dim=4, dummy_name="L")

GammaMatrix = TensorHead("GammaMatrix", [LorentzIndex],
                         TensorSymmetry.no_symmetry(1),
                         comm=None)


def extract_type_tens(expression, component):
    """
    Extract from a ``TensExpr`` all tensors with `component`.

    Returns two tensor expressions:

    * the first contains all ``Tensor`` of having `component`.
    * the second contains all remaining.


    """
    if isinstance(expression, Tensor):
Exemplo n.º 7
0
    def __new__(cls, symbol, matrix, metric, **kwargs):
        """
        Create a new Tensor object.

        Parameters
        ----------
        symbol : str
            Name of the tensor and the symbol to denote it by when printed.
        matrix : (list, tuple, ~sympy.Matrix, ~sympy.Array)
            Matrix representation of the tensor to be used in substitution.
            Can be of any type that is acceptable by ~sympy.Array.
        metric : Metric
            Classify the tensor as being defined in terms of a metric.

        Notes
        -----
        If the parameter ``symmetry`` is passed, the tensor object will defined
        using a specific symmetry. Example values are (see sympy documentation
        for the function ``tensorsymmetry``):
        ``[[1]]``         vector
        ``[[1]*n]``       symmetric tensor of rank ``n``
        ``[[n]]``         antisymmetric tensor of rank ``n``
        ``[[2, 2]]``      monoterm slot symmetry of the Riemann tensor
        ``[[1],[1]]``     vector*vector
        ``[[2],[1],[1]]`` (antisymmetric tensor)*vector*vector

        Additionally, the parameter ``covar`` indicates that the passed array
        corresponds to the covariance of the tensor it is intended to describe.

        Lastly, the parameter ``comm`` is used to indicate what commutation
        group the tensor belongs to. In other words, it describes what other
        types of tensors the one being created is allowed to commute with.
        There are three commutation groups: ``general`` for ordinary tensors,
        ``metric`` for metric tensors, and ``partial`` for partial derivatives.

        Examples
        --------
        >>> from sympy import diag, symbols
        >>> from einsteinpy.symbolic.tensor import Tensor, indices, expand_tensor
        >>> from einsteinpy.symbolic.metric import Metric
        >>> E1, E2, E3, B1, B2, B3 = symbols('E1:4 B1:4')
        >>> em = [[0, -E1, -E2, -E3],
                  [E1, 0, -B3, B2],
                  [E2, B3, 0, -B1],
                  [E3, -B2, B1, 0]]
        >>> t, x, y, z = symbols('t x y z')
        >>> eta = Metric('eta', [t, x, y, z], diag(1, -1, -1, -1))
        >>> F = Tensor('F', em, eta, symmetry=[[2]])
        >>> mu, nu = indices('mu nu', eta)
        >>> expr = F(mu, nu) + F(nu, mu)
        >>> expand_tensor(expr)
        0
        >>> expr = F(mu, nu) * F(-mu, -nu)
        >>> expand_tensor(expr)
        2*B_1**2 + 2*B_2**2 + 2*B_3**2 - 2*E_1**2 - 2*E_2**2 - 2*E_3**2

        """
        array = Array(matrix)
        sym = kwargs.pop("symmetry", [[1] * array.rank()])
        sym = tensorsymmetry(*sym)
        symtype = TensorType(array.rank() * [metric], sym)
        comm = kwargs.pop("comm", "general")
        covar = tuple(kwargs.pop("covar", array.rank() * [1]))
        if len(covar) != array.rank():
            raise ValueError(
                "covariance signature {} does not match tensor rank {}".format(
                    covar, array.rank()))

        count = defaultdict(int)  # type: dict

        def dummy_fmt_gen(idxtype):
            # generate a generic index for the entry in ReplacementManager.
            fmt = idxtype.dummy_fmt
            n = count[idxtype]
            count[idxtype] += 1
            return fmt % n

        obj = TensorHead.__new__(cls, symbol, symtype, comm=comm, **kwargs)
        obj = AbstractTensor.__new__(cls, obj, array)
        # resolves a bug with pretty printing.
        obj.__class__.__name__ = "TensorHead"
        obj.covar = covar
        idx_names = map(dummy_fmt_gen, obj.index_types)
        idx_generator = map(Index, idx_names, obj.index_types)
        idxs = [
            idx if covar[pos] > 0 else -idx
            for pos, idx in enumerate(idx_generator)
        ]
        ReplacementManager[obj(*idxs)] = array
        return obj