3 * Implementation of GiNaC's indexed expressions. */
6 * GiNaC Copyright (C) 1999-2004 Johannes Gutenberg University Mainz, Germany
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
33 #include "relational.h"
35 #include "operators.h"
42 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(indexed, exprseq,
43 print_func<print_context>(&indexed::do_print).
44 print_func<print_latex>(&indexed::do_print_latex).
45 print_func<print_tree>(&indexed::do_print_tree))
48 // default constructor
51 indexed::indexed() : symtree(sy_none())
53 tinfo_key = TINFO_indexed;
60 indexed::indexed(const ex & b) : inherited(b), symtree(sy_none())
62 tinfo_key = TINFO_indexed;
66 indexed::indexed(const ex & b, const ex & i1) : inherited(b, i1), symtree(sy_none())
68 tinfo_key = TINFO_indexed;
72 indexed::indexed(const ex & b, const ex & i1, const ex & i2) : inherited(b, i1, i2), symtree(sy_none())
74 tinfo_key = TINFO_indexed;
78 indexed::indexed(const ex & b, const ex & i1, const ex & i2, const ex & i3) : inherited(b, i1, i2, i3), symtree(sy_none())
80 tinfo_key = TINFO_indexed;
84 indexed::indexed(const ex & b, const ex & i1, const ex & i2, const ex & i3, const ex & i4) : inherited(b, i1, i2, i3, i4), symtree(sy_none())
86 tinfo_key = TINFO_indexed;
90 indexed::indexed(const ex & b, const symmetry & symm, const ex & i1, const ex & i2) : inherited(b, i1, i2), symtree(symm)
92 tinfo_key = TINFO_indexed;
96 indexed::indexed(const ex & b, const symmetry & symm, const ex & i1, const ex & i2, const ex & i3) : inherited(b, i1, i2, i3), symtree(symm)
98 tinfo_key = TINFO_indexed;
102 indexed::indexed(const ex & b, const symmetry & symm, const ex & i1, const ex & i2, const ex & i3, const ex & i4) : inherited(b, i1, i2, i3, i4), symtree(symm)
104 tinfo_key = TINFO_indexed;
108 indexed::indexed(const ex & b, const exvector & v) : inherited(b), symtree(sy_none())
110 seq.insert(seq.end(), v.begin(), v.end());
111 tinfo_key = TINFO_indexed;
115 indexed::indexed(const ex & b, const symmetry & symm, const exvector & v) : inherited(b), symtree(symm)
117 seq.insert(seq.end(), v.begin(), v.end());
118 tinfo_key = TINFO_indexed;
122 indexed::indexed(const symmetry & symm, const exprseq & es) : inherited(es), symtree(symm)
124 tinfo_key = TINFO_indexed;
127 indexed::indexed(const symmetry & symm, const exvector & v, bool discardable) : inherited(v, discardable), symtree(symm)
129 tinfo_key = TINFO_indexed;
132 indexed::indexed(const symmetry & symm, std::auto_ptr<exvector> vp) : inherited(vp), symtree(symm)
134 tinfo_key = TINFO_indexed;
141 indexed::indexed(const archive_node &n, lst &sym_lst) : inherited(n, sym_lst)
143 if (!n.find_ex("symmetry", symtree, sym_lst)) {
144 // GiNaC versions <= 0.9.0 had an unsigned "symmetry" property
146 n.find_unsigned("symmetry", symm);
158 const_cast<symmetry &>(ex_to<symmetry>(symtree)).validate(seq.size() - 1);
162 void indexed::archive(archive_node &n) const
164 inherited::archive(n);
165 n.add_ex("symmetry", symtree);
168 DEFAULT_UNARCHIVE(indexed)
171 // functions overriding virtual functions from base classes
174 void indexed::printindices(const print_context & c, unsigned level) const
176 if (seq.size() > 1) {
178 exvector::const_iterator it=seq.begin() + 1, itend = seq.end();
180 if (is_a<print_latex>(c)) {
182 // TeX output: group by variance
184 bool covariant = true;
186 while (it != itend) {
187 bool cur_covariant = (is_a<varidx>(*it) ? ex_to<varidx>(*it).is_covariant() : true);
188 if (first || cur_covariant != covariant) { // Variance changed
189 // The empty {} prevents indices from ending up on top of each other
192 covariant = cur_covariant;
208 while (it != itend) {
216 void indexed::print_indexed(const print_context & c, const char *openbrace, const char *closebrace, unsigned level) const
218 if (precedence() <= level)
219 c.s << openbrace << '(';
221 seq[0].print(c, precedence());
223 printindices(c, level);
224 if (precedence() <= level)
225 c.s << ')' << closebrace;
228 void indexed::do_print(const print_context & c, unsigned level) const
230 print_indexed(c, "", "", level);
233 void indexed::do_print_latex(const print_latex & c, unsigned level) const
235 print_indexed(c, "{", "}", level);
238 void indexed::do_print_tree(const print_tree & c, unsigned level) const
240 c.s << std::string(level, ' ') << class_name() << " @" << this
241 << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
242 << ", " << seq.size()-1 << " indices"
243 << ", symmetry=" << symtree << std::endl;
244 seq[0].print(c, level + c.delta_indent);
245 printindices(c, level + c.delta_indent);
248 bool indexed::info(unsigned inf) const
250 if (inf == info_flags::indexed) return true;
251 if (inf == info_flags::has_indices) return seq.size() > 1;
252 return inherited::info(inf);
255 struct idx_is_not : public std::binary_function<ex, unsigned, bool> {
256 bool operator() (const ex & e, unsigned inf) const {
257 return !(ex_to<idx>(e).get_value().info(inf));
261 bool indexed::all_index_values_are(unsigned inf) const
263 // No indices? Then no property can be fulfilled
268 return find_if(seq.begin() + 1, seq.end(), bind2nd(idx_is_not(), inf)) == seq.end();
271 int indexed::compare_same_type(const basic & other) const
273 GINAC_ASSERT(is_a<indexed>(other));
274 return inherited::compare_same_type(other);
277 ex indexed::eval(int level) const
279 // First evaluate children, then we will end up here again
281 return indexed(ex_to<symmetry>(symtree), evalchildren(level));
283 const ex &base = seq[0];
285 // If the base object is 0, the whole object is 0
289 // If the base object is a product, pull out the numeric factor
290 if (is_exactly_a<mul>(base) && is_exactly_a<numeric>(base.op(base.nops() - 1))) {
292 ex f = ex_to<numeric>(base.op(base.nops() - 1));
294 return f * thiscontainer(v);
297 // Canonicalize indices according to the symmetry properties
298 if (seq.size() > 2) {
300 GINAC_ASSERT(is_exactly_a<symmetry>(symtree));
301 int sig = canonicalize(v.begin() + 1, ex_to<symmetry>(symtree));
302 if (sig != INT_MAX) {
303 // Something has changed while sorting indices, more evaluations later
306 return ex(sig) * thiscontainer(v);
310 // Let the class of the base object perform additional evaluations
311 return ex_to<basic>(base).eval_indexed(*this);
314 ex indexed::thiscontainer(const exvector & v) const
316 return indexed(ex_to<symmetry>(symtree), v);
319 ex indexed::thiscontainer(std::auto_ptr<exvector> vp) const
321 return indexed(ex_to<symmetry>(symtree), vp);
324 ex indexed::expand(unsigned options) const
326 GINAC_ASSERT(seq.size() > 0);
328 if ((options & expand_options::expand_indexed) && is_exactly_a<add>(seq[0])) {
330 // expand_indexed expands (a+b).i -> a.i + b.i
331 const ex & base = seq[0];
333 for (size_t i=0; i<base.nops(); i++) {
336 sum += thiscontainer(s).expand();
341 return inherited::expand(options);
345 // virtual functions which can be overridden by derived classes
351 // non-virtual functions in this class
354 /** Check whether all indices are of class idx and validate the symmetry
355 * tree. This function is used internally to make sure that all constructed
356 * indexed objects really carry indices and not some other classes. */
357 void indexed::validate() const
359 GINAC_ASSERT(seq.size() > 0);
360 exvector::const_iterator it = seq.begin() + 1, itend = seq.end();
361 while (it != itend) {
363 throw(std::invalid_argument("indices of indexed object must be of type idx"));
367 if (!symtree.is_zero()) {
368 if (!is_exactly_a<symmetry>(symtree))
369 throw(std::invalid_argument("symmetry of indexed object must be of type symmetry"));
370 const_cast<symmetry &>(ex_to<symmetry>(symtree)).validate(seq.size() - 1);
374 /** Implementation of ex::diff() for an indexed object always returns 0.
377 ex indexed::derivative(const symbol & s) const
386 struct idx_is_equal_ignore_dim : public std::binary_function<ex, ex, bool> {
387 bool operator() (const ex &lh, const ex &rh) const
393 // Replacing the dimension might cause an error (e.g. with
394 // index classes that only work in a fixed number of dimensions)
395 return lh.is_equal(ex_to<idx>(rh).replace_dim(ex_to<idx>(lh).get_dim()));
402 /** Check whether two sorted index vectors are consistent (i.e. equal). */
403 static bool indices_consistent(const exvector & v1, const exvector & v2)
405 // Number of indices must be the same
406 if (v1.size() != v2.size())
409 return equal(v1.begin(), v1.end(), v2.begin(), idx_is_equal_ignore_dim());
412 exvector indexed::get_indices() const
414 GINAC_ASSERT(seq.size() >= 1);
415 return exvector(seq.begin() + 1, seq.end());
418 exvector indexed::get_dummy_indices() const
420 exvector free_indices, dummy_indices;
421 find_free_and_dummy(seq.begin() + 1, seq.end(), free_indices, dummy_indices);
422 return dummy_indices;
425 exvector indexed::get_dummy_indices(const indexed & other) const
427 exvector indices = get_free_indices();
428 exvector other_indices = other.get_free_indices();
429 indices.insert(indices.end(), other_indices.begin(), other_indices.end());
430 exvector dummy_indices;
431 find_dummy_indices(indices, dummy_indices);
432 return dummy_indices;
435 bool indexed::has_dummy_index_for(const ex & i) const
437 exvector::const_iterator it = seq.begin() + 1, itend = seq.end();
438 while (it != itend) {
439 if (is_dummy_pair(*it, i))
446 exvector indexed::get_free_indices() const
448 exvector free_indices, dummy_indices;
449 find_free_and_dummy(seq.begin() + 1, seq.end(), free_indices, dummy_indices);
453 exvector add::get_free_indices() const
455 exvector free_indices;
456 for (size_t i=0; i<nops(); i++) {
458 free_indices = op(i).get_free_indices();
460 exvector free_indices_of_term = op(i).get_free_indices();
461 if (!indices_consistent(free_indices, free_indices_of_term))
462 throw (std::runtime_error("add::get_free_indices: inconsistent indices in sum"));
468 exvector mul::get_free_indices() const
470 // Concatenate free indices of all factors
472 for (size_t i=0; i<nops(); i++) {
473 exvector free_indices_of_factor = op(i).get_free_indices();
474 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
477 // And remove the dummy indices
478 exvector free_indices, dummy_indices;
479 find_free_and_dummy(un, free_indices, dummy_indices);
483 exvector ncmul::get_free_indices() const
485 // Concatenate free indices of all factors
487 for (size_t i=0; i<nops(); i++) {
488 exvector free_indices_of_factor = op(i).get_free_indices();
489 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
492 // And remove the dummy indices
493 exvector free_indices, dummy_indices;
494 find_free_and_dummy(un, free_indices, dummy_indices);
498 exvector power::get_free_indices() const
500 // Return free indices of basis
501 return basis.get_free_indices();
504 /** Rename dummy indices in an expression.
506 * @param e Expression to work on
507 * @param local_dummy_indices The set of dummy indices that appear in the
509 * @param global_dummy_indices The set of dummy indices that have appeared
510 * before and which we would like to use in "e", too. This gets updated
512 static ex rename_dummy_indices(const ex & e, exvector & global_dummy_indices, exvector & local_dummy_indices)
514 size_t global_size = global_dummy_indices.size(),
515 local_size = local_dummy_indices.size();
517 // Any local dummy indices at all?
521 if (global_size < local_size) {
523 // More local indices than we encountered before, add the new ones
525 size_t old_global_size = global_size;
526 int remaining = local_size - global_size;
527 exvector::const_iterator it = local_dummy_indices.begin(), itend = local_dummy_indices.end();
528 while (it != itend && remaining > 0) {
529 if (find_if(global_dummy_indices.begin(), global_dummy_indices.end(), bind2nd(op0_is_equal(), *it)) == global_dummy_indices.end()) {
530 global_dummy_indices.push_back(*it);
537 // If this is the first set of local indices, do nothing
538 if (old_global_size == 0)
541 GINAC_ASSERT(local_size <= global_size);
543 // Construct vectors of index symbols
544 exvector local_syms, global_syms;
545 local_syms.reserve(local_size);
546 global_syms.reserve(local_size);
547 for (size_t i=0; i<local_size; i++)
548 local_syms.push_back(local_dummy_indices[i].op(0));
549 shaker_sort(local_syms.begin(), local_syms.end(), ex_is_less(), ex_swap());
550 for (size_t i=0; i<local_size; i++) // don't use more global symbols than necessary
551 global_syms.push_back(global_dummy_indices[i].op(0));
552 shaker_sort(global_syms.begin(), global_syms.end(), ex_is_less(), ex_swap());
554 // Remove common indices
555 exvector local_uniq, global_uniq;
556 set_difference(local_syms.begin(), local_syms.end(), global_syms.begin(), global_syms.end(), std::back_insert_iterator<exvector>(local_uniq), ex_is_less());
557 set_difference(global_syms.begin(), global_syms.end(), local_syms.begin(), local_syms.end(), std::back_insert_iterator<exvector>(global_uniq), ex_is_less());
559 // Replace remaining non-common local index symbols by global ones
560 if (local_uniq.empty())
563 while (global_uniq.size() > local_uniq.size())
564 global_uniq.pop_back();
565 return e.subs(lst(local_uniq.begin(), local_uniq.end()), lst(global_uniq.begin(), global_uniq.end()), subs_options::no_pattern);
569 /** Given a set of indices, extract those of class varidx. */
570 static void find_variant_indices(const exvector & v, exvector & variant_indices)
572 exvector::const_iterator it1, itend;
573 for (it1 = v.begin(), itend = v.end(); it1 != itend; ++it1) {
574 if (is_exactly_a<varidx>(*it1))
575 variant_indices.push_back(*it1);
579 /** Raise/lower dummy indices in a single indexed objects to canonicalize their
582 * @param e Object to work on
583 * @param variant_dummy_indices The set of indices that might need repositioning (will be changed by this function)
584 * @param moved_indices The set of indices that have been repositioned (will be changed by this function)
585 * @return true if 'e' was changed */
586 bool reposition_dummy_indices(ex & e, exvector & variant_dummy_indices, exvector & moved_indices)
588 bool something_changed = false;
590 // If a dummy index is encountered for the first time in the
591 // product, pull it up, otherwise, pull it down
592 exvector::const_iterator it2, it2start, it2end;
593 for (it2start = ex_to<indexed>(e).seq.begin(), it2end = ex_to<indexed>(e).seq.end(), it2 = it2start + 1; it2 != it2end; ++it2) {
594 if (!is_exactly_a<varidx>(*it2))
597 exvector::iterator vit, vitend;
598 for (vit = variant_dummy_indices.begin(), vitend = variant_dummy_indices.end(); vit != vitend; ++vit) {
599 if (it2->op(0).is_equal(vit->op(0))) {
600 if (ex_to<varidx>(*it2).is_covariant()) {
602 *it2 == ex_to<varidx>(*it2).toggle_variance(),
603 ex_to<varidx>(*it2).toggle_variance() == *it2
604 ), subs_options::no_pattern);
605 something_changed = true;
606 it2 = ex_to<indexed>(e).seq.begin() + (it2 - it2start);
607 it2start = ex_to<indexed>(e).seq.begin();
608 it2end = ex_to<indexed>(e).seq.end();
610 moved_indices.push_back(*vit);
611 variant_dummy_indices.erase(vit);
616 for (vit = moved_indices.begin(), vitend = moved_indices.end(); vit != vitend; ++vit) {
617 if (it2->op(0).is_equal(vit->op(0))) {
618 if (ex_to<varidx>(*it2).is_contravariant()) {
619 e = e.subs(*it2 == ex_to<varidx>(*it2).toggle_variance(), subs_options::no_pattern);
620 something_changed = true;
621 it2 = ex_to<indexed>(e).seq.begin() + (it2 - it2start);
622 it2start = ex_to<indexed>(e).seq.begin();
623 it2end = ex_to<indexed>(e).seq.end();
632 return something_changed;
635 /* Ordering that only compares the base expressions of indexed objects. */
636 struct ex_base_is_less : public std::binary_function<ex, ex, bool> {
637 bool operator() (const ex &lh, const ex &rh) const
639 return (is_a<indexed>(lh) ? lh.op(0) : lh).compare(is_a<indexed>(rh) ? rh.op(0) : rh) < 0;
643 /** Simplify product of indexed expressions (commutative, noncommutative and
644 * simple squares), return list of free indices. */
645 ex simplify_indexed_product(const ex & e, exvector & free_indices, exvector & dummy_indices, const scalar_products & sp)
647 // Remember whether the product was commutative or noncommutative
648 // (because we chop it into factors and need to reassemble later)
649 bool non_commutative = is_exactly_a<ncmul>(e);
651 // Collect factors in an exvector, store squares twice
653 v.reserve(e.nops() * 2);
655 if (is_exactly_a<power>(e)) {
656 // We only get called for simple squares, split a^2 -> a*a
657 GINAC_ASSERT(e.op(1).is_equal(_ex2));
658 v.push_back(e.op(0));
659 v.push_back(e.op(0));
661 for (size_t i=0; i<e.nops(); i++) {
663 if (is_exactly_a<power>(f) && f.op(1).is_equal(_ex2)) {
664 v.push_back(f.op(0));
665 v.push_back(f.op(0));
666 } else if (is_exactly_a<ncmul>(f)) {
667 // Noncommutative factor found, split it as well
668 non_commutative = true; // everything becomes noncommutative, ncmul will sort out the commutative factors later
669 for (size_t j=0; j<f.nops(); j++)
670 v.push_back(f.op(j));
676 // Perform contractions
677 bool something_changed = false;
678 GINAC_ASSERT(v.size() > 1);
679 exvector::iterator it1, itend = v.end(), next_to_last = itend - 1;
680 for (it1 = v.begin(); it1 != next_to_last; it1++) {
683 if (!is_a<indexed>(*it1))
686 bool first_noncommutative = (it1->return_type() != return_types::commutative);
688 // Indexed factor found, get free indices and look for contraction
690 exvector free1, dummy1;
691 find_free_and_dummy(ex_to<indexed>(*it1).seq.begin() + 1, ex_to<indexed>(*it1).seq.end(), free1, dummy1);
693 exvector::iterator it2;
694 for (it2 = it1 + 1; it2 != itend; it2++) {
696 if (!is_a<indexed>(*it2))
699 bool second_noncommutative = (it2->return_type() != return_types::commutative);
701 // Find free indices of second factor and merge them with free
702 // indices of first factor
704 find_free_and_dummy(ex_to<indexed>(*it2).seq.begin() + 1, ex_to<indexed>(*it2).seq.end(), un, dummy1);
705 un.insert(un.end(), free1.begin(), free1.end());
707 // Check whether the two factors share dummy indices
708 exvector free, dummy;
709 find_free_and_dummy(un, free, dummy);
710 size_t num_dummies = dummy.size();
711 if (num_dummies == 0)
714 // At least one dummy index, is it a defined scalar product?
715 bool contracted = false;
718 // Find minimal dimension of all indices of both factors
719 exvector::const_iterator dit = ex_to<indexed>(*it1).seq.begin() + 1, ditend = ex_to<indexed>(*it1).seq.end();
720 ex dim = ex_to<idx>(*dit).get_dim();
722 for (; dit != ditend; ++dit) {
723 dim = minimal_dim(dim, ex_to<idx>(*dit).get_dim());
725 dit = ex_to<indexed>(*it2).seq.begin() + 1;
726 ditend = ex_to<indexed>(*it2).seq.end();
727 for (; dit != ditend; ++dit) {
728 dim = minimal_dim(dim, ex_to<idx>(*dit).get_dim());
731 // User-defined scalar product?
732 if (sp.is_defined(*it1, *it2, dim)) {
734 // Yes, substitute it
735 *it1 = sp.evaluate(*it1, *it2, dim);
737 goto contraction_done;
741 // Try to contract the first one with the second one
742 contracted = ex_to<basic>(it1->op(0)).contract_with(it1, it2, v);
745 // That didn't work; maybe the second object knows how to
746 // contract itself with the first one
747 contracted = ex_to<basic>(it2->op(0)).contract_with(it2, it1, v);
751 if (first_noncommutative || second_noncommutative
752 || is_exactly_a<add>(*it1) || is_exactly_a<add>(*it2)
753 || is_exactly_a<mul>(*it1) || is_exactly_a<mul>(*it2)
754 || is_exactly_a<ncmul>(*it1) || is_exactly_a<ncmul>(*it2)) {
756 // One of the factors became a sum or product:
757 // re-expand expression and run again
758 // Non-commutative products are always re-expanded to give
759 // eval_ncmul() the chance to re-order and canonicalize
761 ex r = (non_commutative ? ex(ncmul(v, true)) : ex(mul(v)));
762 return simplify_indexed(r, free_indices, dummy_indices, sp);
765 // Both objects may have new indices now or they might
766 // even not be indexed objects any more, so we have to
768 something_changed = true;
774 // Find free indices (concatenate them all and call find_free_and_dummy())
775 // and all dummy indices that appear
776 exvector un, individual_dummy_indices;
777 for (it1 = v.begin(), itend = v.end(); it1 != itend; ++it1) {
778 exvector free_indices_of_factor;
779 if (is_a<indexed>(*it1)) {
780 exvector dummy_indices_of_factor;
781 find_free_and_dummy(ex_to<indexed>(*it1).seq.begin() + 1, ex_to<indexed>(*it1).seq.end(), free_indices_of_factor, dummy_indices_of_factor);
782 individual_dummy_indices.insert(individual_dummy_indices.end(), dummy_indices_of_factor.begin(), dummy_indices_of_factor.end());
784 free_indices_of_factor = it1->get_free_indices();
785 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
787 exvector local_dummy_indices;
788 find_free_and_dummy(un, free_indices, local_dummy_indices);
789 local_dummy_indices.insert(local_dummy_indices.end(), individual_dummy_indices.begin(), individual_dummy_indices.end());
791 // Filter out the dummy indices with variance
792 exvector variant_dummy_indices;
793 find_variant_indices(local_dummy_indices, variant_dummy_indices);
795 // Any indices with variance present at all?
796 if (!variant_dummy_indices.empty()) {
798 // Yes, bring the product into a canonical order that only depends on
799 // the base expressions of indexed objects
800 if (!non_commutative)
801 std::sort(v.begin(), v.end(), ex_base_is_less());
803 exvector moved_indices;
805 // Iterate over all indexed objects in the product
806 for (it1 = v.begin(), itend = v.end(); it1 != itend; ++it1) {
807 if (!is_a<indexed>(*it1))
810 if (reposition_dummy_indices(*it1, variant_dummy_indices, moved_indices))
811 something_changed = true;
816 if (something_changed)
817 r = non_commutative ? ex(ncmul(v, true)) : ex(mul(v));
821 // The result should be symmetric with respect to exchange of dummy
822 // indices, so if the symmetrization vanishes, the whole expression is
823 // zero. This detects things like eps.i.j.k * p.j * p.k = 0.
824 if (local_dummy_indices.size() >= 2) {
826 dummy_syms.reserve(local_dummy_indices.size());
827 for (exvector::const_iterator it = local_dummy_indices.begin(); it != local_dummy_indices.end(); ++it)
828 dummy_syms.push_back(it->op(0));
829 if (symmetrize(r, dummy_syms).is_zero()) {
830 free_indices.clear();
835 // Dummy index renaming
836 r = rename_dummy_indices(r, dummy_indices, local_dummy_indices);
838 // Product of indexed object with a scalar?
839 if (is_exactly_a<mul>(r) && r.nops() == 2
840 && is_exactly_a<numeric>(r.op(1)) && is_a<indexed>(r.op(0)))
841 return ex_to<basic>(r.op(0).op(0)).scalar_mul_indexed(r.op(0), ex_to<numeric>(r.op(1)));
846 /** This structure stores the original and symmetrized versions of terms
847 * obtained during the simplification of sums. */
850 terminfo(const ex & orig_, const ex & symm_) : orig(orig_), symm(symm_) {}
852 ex orig; /**< original term */
853 ex symm; /**< symmtrized term */
856 class terminfo_is_less {
858 bool operator() (const terminfo & ti1, const terminfo & ti2) const
860 return (ti1.symm.compare(ti2.symm) < 0);
864 /** This structure stores the individual symmetrized terms obtained during
865 * the simplification of sums. */
868 symminfo() : num(0) {}
870 symminfo(const ex & symmterm_, const ex & orig_, size_t num_) : orig(orig_), num(num_)
872 if (is_exactly_a<mul>(symmterm_) && is_exactly_a<numeric>(symmterm_.op(symmterm_.nops()-1))) {
873 coeff = symmterm_.op(symmterm_.nops()-1);
874 symmterm = symmterm_ / coeff;
877 symmterm = symmterm_;
881 ex symmterm; /**< symmetrized term */
882 ex coeff; /**< coefficient of symmetrized term */
883 ex orig; /**< original term */
884 size_t num; /**< how many symmetrized terms resulted from the original term */
887 class symminfo_is_less_by_symmterm {
889 bool operator() (const symminfo & si1, const symminfo & si2) const
891 return (si1.symmterm.compare(si2.symmterm) < 0);
895 class symminfo_is_less_by_orig {
897 bool operator() (const symminfo & si1, const symminfo & si2) const
899 return (si1.orig.compare(si2.orig) < 0);
903 /** Simplify indexed expression, return list of free indices. */
904 ex simplify_indexed(const ex & e, exvector & free_indices, exvector & dummy_indices, const scalar_products & sp)
906 // Expand the expression
907 ex e_expanded = e.expand();
909 // Simplification of single indexed object: just find the free indices
910 // and perform dummy index renaming/repositioning
911 if (is_a<indexed>(e_expanded)) {
913 // Find the dummy indices
914 const indexed &i = ex_to<indexed>(e_expanded);
915 exvector local_dummy_indices;
916 find_free_and_dummy(i.seq.begin() + 1, i.seq.end(), free_indices, local_dummy_indices);
918 // Filter out the dummy indices with variance
919 exvector variant_dummy_indices;
920 find_variant_indices(local_dummy_indices, variant_dummy_indices);
922 // Any indices with variance present at all?
923 if (!variant_dummy_indices.empty()) {
925 // Yes, reposition them
926 exvector moved_indices;
927 reposition_dummy_indices(e_expanded, variant_dummy_indices, moved_indices);
930 // Rename the dummy indices
931 return rename_dummy_indices(e_expanded, dummy_indices, local_dummy_indices);
934 // Simplification of sum = sum of simplifications, check consistency of
935 // free indices in each term
936 if (is_exactly_a<add>(e_expanded)) {
939 free_indices.clear();
941 for (size_t i=0; i<e_expanded.nops(); i++) {
942 exvector free_indices_of_term;
943 ex term = simplify_indexed(e_expanded.op(i), free_indices_of_term, dummy_indices, sp);
944 if (!term.is_zero()) {
946 free_indices = free_indices_of_term;
950 if (!indices_consistent(free_indices, free_indices_of_term)) {
951 std::ostringstream s;
952 s << "simplify_indexed: inconsistent indices in sum: ";
953 s << exprseq(free_indices) << " vs. " << exprseq(free_indices_of_term);
954 throw (std::runtime_error(s.str()));
956 if (is_a<indexed>(sum) && is_a<indexed>(term))
957 sum = ex_to<basic>(sum.op(0)).add_indexed(sum, term);
964 // If the sum turns out to be zero, we are finished
966 free_indices.clear();
970 // More than one term and more than one dummy index?
971 size_t num_terms_orig = (is_exactly_a<add>(sum) ? sum.nops() : 1);
972 if (num_terms_orig < 2 || dummy_indices.size() < 2)
975 // Yes, construct vector of all dummy index symbols
977 dummy_syms.reserve(dummy_indices.size());
978 for (exvector::const_iterator it = dummy_indices.begin(); it != dummy_indices.end(); ++it)
979 dummy_syms.push_back(it->op(0));
981 // Chop the sum into terms and symmetrize each one over the dummy
983 std::vector<terminfo> terms;
984 for (size_t i=0; i<sum.nops(); i++) {
985 const ex & term = sum.op(i);
986 ex term_symm = symmetrize(term, dummy_syms);
987 if (term_symm.is_zero())
989 terms.push_back(terminfo(term, term_symm));
992 // Sort by symmetrized terms
993 std::sort(terms.begin(), terms.end(), terminfo_is_less());
995 // Combine equal symmetrized terms
996 std::vector<terminfo> terms_pass2;
997 for (std::vector<terminfo>::const_iterator i=terms.begin(); i!=terms.end(); ) {
999 std::vector<terminfo>::const_iterator j = i + 1;
1000 while (j != terms.end() && j->symm == i->symm) {
1004 terms_pass2.push_back(terminfo(i->orig * num, i->symm * num));
1008 // If there is only one term left, we are finished
1009 if (terms_pass2.size() == 1)
1010 return terms_pass2[0].orig;
1012 // Chop the symmetrized terms into subterms
1013 std::vector<symminfo> sy;
1014 for (std::vector<terminfo>::const_iterator i=terms_pass2.begin(); i!=terms_pass2.end(); ++i) {
1015 if (is_exactly_a<add>(i->symm)) {
1016 size_t num = i->symm.nops();
1017 for (size_t j=0; j<num; j++)
1018 sy.push_back(symminfo(i->symm.op(j), i->orig, num));
1020 sy.push_back(symminfo(i->symm, i->orig, 1));
1023 // Sort by symmetrized subterms
1024 std::sort(sy.begin(), sy.end(), symminfo_is_less_by_symmterm());
1026 // Combine equal symmetrized subterms
1027 std::vector<symminfo> sy_pass2;
1029 for (std::vector<symminfo>::const_iterator i=sy.begin(); i!=sy.end(); ) {
1031 // Combine equal terms
1032 std::vector<symminfo>::const_iterator j = i + 1;
1033 if (j != sy.end() && j->symmterm == i->symmterm) {
1035 // More than one term, collect the coefficients
1036 ex coeff = i->coeff;
1037 while (j != sy.end() && j->symmterm == i->symmterm) {
1042 // Add combined term to result
1043 if (!coeff.is_zero())
1044 result.push_back(coeff * i->symmterm);
1048 // Single term, store for second pass
1049 sy_pass2.push_back(*i);
1055 // Were there any remaining terms that didn't get combined?
1056 if (sy_pass2.size() > 0) {
1058 // Yes, sort by their original terms
1059 std::sort(sy_pass2.begin(), sy_pass2.end(), symminfo_is_less_by_orig());
1061 for (std::vector<symminfo>::const_iterator i=sy_pass2.begin(); i!=sy_pass2.end(); ) {
1063 // How many symmetrized terms of this original term are left?
1065 std::vector<symminfo>::const_iterator j = i + 1;
1066 while (j != sy_pass2.end() && j->orig == i->orig) {
1071 if (num == i->num) {
1073 // All terms left, then add the original term to the result
1074 result.push_back(i->orig);
1078 // Some terms were combined with others, add up the remaining symmetrized terms
1079 std::vector<symminfo>::const_iterator k;
1080 for (k=i; k!=j; k++)
1081 result.push_back(k->coeff * k->symmterm);
1088 // Add all resulting terms
1089 ex sum_symm = (new add(result))->setflag(status_flags::dynallocated);
1090 if (sum_symm.is_zero())
1091 free_indices.clear();
1095 // Simplification of products
1096 if (is_exactly_a<mul>(e_expanded)
1097 || is_exactly_a<ncmul>(e_expanded)
1098 || (is_exactly_a<power>(e_expanded) && is_a<indexed>(e_expanded.op(0)) && e_expanded.op(1).is_equal(_ex2)))
1099 return simplify_indexed_product(e_expanded, free_indices, dummy_indices, sp);
1101 // Cannot do anything
1102 free_indices.clear();
1106 /** Simplify/canonicalize expression containing indexed objects. This
1107 * performs contraction of dummy indices where possible and checks whether
1108 * the free indices in sums are consistent.
1110 * @return simplified expression */
1111 ex ex::simplify_indexed(unsigned options) const
1113 exvector free_indices, dummy_indices;
1115 return GiNaC::simplify_indexed(*this, free_indices, dummy_indices, sp);
1118 /** Simplify/canonicalize expression containing indexed objects. This
1119 * performs contraction of dummy indices where possible, checks whether
1120 * the free indices in sums are consistent, and automatically replaces
1121 * scalar products by known values if desired.
1123 * @param sp Scalar products to be replaced automatically
1124 * @return simplified expression */
1125 ex ex::simplify_indexed(const scalar_products & sp, unsigned options) const
1127 exvector free_indices, dummy_indices;
1128 return GiNaC::simplify_indexed(*this, free_indices, dummy_indices, sp);
1131 /** Symmetrize expression over its free indices. */
1132 ex ex::symmetrize() const
1134 return GiNaC::symmetrize(*this, get_free_indices());
1137 /** Antisymmetrize expression over its free indices. */
1138 ex ex::antisymmetrize() const
1140 return GiNaC::antisymmetrize(*this, get_free_indices());
1143 /** Symmetrize expression by cyclic permutation over its free indices. */
1144 ex ex::symmetrize_cyclic() const
1146 return GiNaC::symmetrize_cyclic(*this, get_free_indices());
1153 spmapkey::spmapkey(const ex & v1_, const ex & v2_, const ex & dim_) : dim(dim_)
1155 // If indexed, extract base objects
1156 ex s1 = is_a<indexed>(v1_) ? v1_.op(0) : v1_;
1157 ex s2 = is_a<indexed>(v2_) ? v2_.op(0) : v2_;
1159 // Enforce canonical order in pair
1160 if (s1.compare(s2) > 0) {
1169 bool spmapkey::operator==(const spmapkey &other) const
1171 if (!v1.is_equal(other.v1))
1173 if (!v2.is_equal(other.v2))
1175 if (is_a<wildcard>(dim) || is_a<wildcard>(other.dim))
1178 return dim.is_equal(other.dim);
1181 bool spmapkey::operator<(const spmapkey &other) const
1183 int cmp = v1.compare(other.v1);
1186 cmp = v2.compare(other.v2);
1190 // Objects are equal, now check dimensions
1191 if (is_a<wildcard>(dim) || is_a<wildcard>(other.dim))
1194 return dim.compare(other.dim) < 0;
1197 void spmapkey::debugprint() const
1199 std::cerr << "(" << v1 << "," << v2 << "," << dim << ")";
1202 void scalar_products::add(const ex & v1, const ex & v2, const ex & sp)
1204 spm[spmapkey(v1, v2)] = sp;
1207 void scalar_products::add(const ex & v1, const ex & v2, const ex & dim, const ex & sp)
1209 spm[spmapkey(v1, v2, dim)] = sp;
1212 void scalar_products::add_vectors(const lst & l, const ex & dim)
1214 // Add all possible pairs of products
1215 for (lst::const_iterator it1 = l.begin(); it1 != l.end(); ++it1)
1216 for (lst::const_iterator it2 = l.begin(); it2 != l.end(); ++it2)
1217 add(*it1, *it2, *it1 * *it2);
1220 void scalar_products::clear()
1225 /** Check whether scalar product pair is defined. */
1226 bool scalar_products::is_defined(const ex & v1, const ex & v2, const ex & dim) const
1228 return spm.find(spmapkey(v1, v2, dim)) != spm.end();
1231 /** Return value of defined scalar product pair. */
1232 ex scalar_products::evaluate(const ex & v1, const ex & v2, const ex & dim) const
1234 return spm.find(spmapkey(v1, v2, dim))->second;
1237 void scalar_products::debugprint() const
1239 std::cerr << "map size=" << spm.size() << std::endl;
1240 spmap::const_iterator i = spm.begin(), end = spm.end();
1242 const spmapkey & k = i->first;
1243 std::cerr << "item key=";
1245 std::cerr << ", value=" << i->second << std::endl;
1250 } // namespace GiNaC