]> www.ginac.de Git - ginac.git/blobdiff - ginac/indexed.cpp
- simplify_indexed() simplifies c*(M).i.j -> (M').i.j (c: numeric, M: matrix)
[ginac.git] / ginac / indexed.cpp
index 4fa4256abfb286b86c95d427efa9a5c8de27c4c8..86fe6115d9b8863819c44e3a393d9c99cd0b01d4 100644 (file)
@@ -679,13 +679,21 @@ try_again:
        }
        find_free_and_dummy(un.begin(), un.end(), free_indices, dummy_indices);
 
+       ex r;
        if (something_changed) {
                if (non_commutative)
-                       return ncmul(v);
+                       r = ncmul(v);
                else
-                       return mul(v);
+                       r = mul(v);
        } else
-               return e;
+               r = e;
+
+       // Product of indexed object with a scalar?
+       if (is_ex_exactly_of_type(r, mul) && r.nops() == 2
+        && is_ex_exactly_of_type(r.op(1), numeric) && is_ex_of_type(r.op(0), indexed))
+               return r.op(0).op(0).bp->scalar_mul_indexed(r.op(0), ex_to_numeric(r.op(1)));
+       else
+               return r;
 }
 
 /** Simplify indexed expression, return list of free indices. */
@@ -705,15 +713,17 @@ ex simplify_indexed(const ex & e, exvector & free_indices, const scalar_products
        // Simplification of sum = sum of simplifications, check consistency of
        // free indices in each term
        if (is_ex_exactly_of_type(e_expanded, add)) {
-               ex sum = _ex0();
+               ex sum = simplify_indexed(e_expanded.op(0), free_indices, sp);
 
-               for (unsigned i=0; i<e_expanded.nops(); i++) {
+               for (unsigned i=1; i<e_expanded.nops(); i++) {
                        exvector free_indices_of_term;
-                       sum += simplify_indexed(e_expanded.op(i), free_indices_of_term, sp);
-                       if (i == 0)
-                               free_indices = free_indices_of_term;
-                       else if (!indices_consistent(free_indices, free_indices_of_term))
+                       ex term = simplify_indexed(e_expanded.op(i), free_indices_of_term, sp);
+                       if (!indices_consistent(free_indices, free_indices_of_term))
                                throw (std::runtime_error("simplify_indexed: inconsistent indices in sum"));
+                       if (is_ex_of_type(sum, indexed) && is_ex_of_type(term, indexed))
+                               sum = sum.op(0).bp->add_indexed(sum, term);
+                       else
+                               sum += term;
                }
 
                return sum;