%mathpiper,def="TSimplify"

/* Tensor package. This code intends to simplify tensorial expressions.
 */

/* TSimplify : expand brackets, and send the expression of addition
   of terms to TSimplifyAux */
TSimplify(TSum(_indices)(_f)) <--
[
  TSimplifyAux(TSum(indices)ExpandBrackets(f));
];


/* TSimplifyAux : simplify each term independently */
10 # TSimplifyAux(TSum(_indices)((_f) + (_g))) <--
     TSimplifyAux(TSum(FlatCopy(indices))(f)) +
     TSimplifyAux(TSum(FlatCopy(indices))(g));
10 # TSimplifyAux(TSum(_indices)((_f) - (_g))) <--
     TSimplifyAux(TSum(FlatCopy(indices))(f)) -
     TSimplifyAux(TSum(FlatCopy(indices))(g));
10 # TSimplifyAux(TSum(_indices)(   - (_g))) <--
                                    -  TSimplifyAux(TSum(indices)(g));

40 # TSimplifyAux(TSum(_indices)_body) <--
[
  Local(flat);

  /* Convert expressions of the form (a*b*c) to {a,b,c} */
  flat:=Flatten(body,"*");

  /* Move the deltas to the front. */
  flat:=MoveDeltas(flat);

  /* Simplify the deltas away (removing the required indices) */
  flat:=TSumRest(flat);

  /* Determine if there are indices the summand still depends on */
  Local(varlist,independ,nrdims);
  varlist:=VarList(flat);
  independ:=Intersection(indices,varlist);
  nrdims:=Length(indices)-Length(independ);

  /* Return result, still summing over the indices not removed by deltas */
  Ndim^nrdims*TSum(independ)flat;
];

%/mathpiper