3 * Implementation of GiNaC's indexed expressions. */
6 * GiNaC Copyright (C) 1999-2005 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"
43 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(indexed, exprseq,
44 print_func<print_context>(&indexed::do_print).
45 print_func<print_latex>(&indexed::do_print_latex).
46 print_func<print_tree>(&indexed::do_print_tree))
49 // default constructor
52 indexed::indexed() : symtree(not_symmetric())
54 tinfo_key = TINFO_indexed;
61 indexed::indexed(const ex & b) : inherited(b), symtree(not_symmetric())
63 tinfo_key = TINFO_indexed;
67 indexed::indexed(const ex & b, const ex & i1) : inherited(b, i1), symtree(not_symmetric())
69 tinfo_key = TINFO_indexed;
73 indexed::indexed(const ex & b, const ex & i1, const ex & i2) : inherited(b, i1, i2), symtree(not_symmetric())
75 tinfo_key = TINFO_indexed;
79 indexed::indexed(const ex & b, const ex & i1, const ex & i2, const ex & i3) : inherited(b, i1, i2, i3), symtree(not_symmetric())
81 tinfo_key = TINFO_indexed;
85 indexed::indexed(const ex & b, const ex & i1, const ex & i2, const ex & i3, const ex & i4) : inherited(b, i1, i2, i3, i4), symtree(not_symmetric())
87 tinfo_key = TINFO_indexed;
91 indexed::indexed(const ex & b, const symmetry & symm, const ex & i1, const ex & i2) : inherited(b, i1, i2), symtree(symm)
93 tinfo_key = TINFO_indexed;
97 indexed::indexed(const ex & b, const symmetry & symm, const ex & i1, const ex & i2, const ex & i3) : inherited(b, i1, i2, i3), symtree(symm)
99 tinfo_key = TINFO_indexed;
103 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)
105 tinfo_key = TINFO_indexed;
109 indexed::indexed(const ex & b, const exvector & v) : inherited(b), symtree(not_symmetric())
111 seq.insert(seq.end(), v.begin(), v.end());
112 tinfo_key = TINFO_indexed;
116 indexed::indexed(const ex & b, const symmetry & symm, const exvector & v) : inherited(b), symtree(symm)
118 seq.insert(seq.end(), v.begin(), v.end());
119 tinfo_key = TINFO_indexed;
123 indexed::indexed(const symmetry & symm, const exprseq & es) : inherited(es), symtree(symm)
125 tinfo_key = TINFO_indexed;
128 indexed::indexed(const symmetry & symm, const exvector & v, bool discardable) : inherited(v, discardable), symtree(symm)
130 tinfo_key = TINFO_indexed;
133 indexed::indexed(const symmetry & symm, std::auto_ptr<exvector> vp) : inherited(vp), symtree(symm)
135 tinfo_key = TINFO_indexed;
142 indexed::indexed(const archive_node &n, lst &sym_lst) : inherited(n, sym_lst)
144 if (!n.find_ex("symmetry", symtree, sym_lst)) {
145 // GiNaC versions <= 0.9.0 had an unsigned "symmetry" property
147 n.find_unsigned("symmetry", symm);
156 symtree = not_symmetric();
159 const_cast<symmetry &>(ex_to<symmetry>(symtree)).validate(seq.size() - 1);
163 void indexed::archive(archive_node &n) const
165 inherited::archive(n);
166 n.add_ex("symmetry", symtree);
169 DEFAULT_UNARCHIVE(indexed)
172 // functions overriding virtual functions from base classes
175 void indexed::printindices(const print_context & c, unsigned level) const
177 if (seq.size() > 1) {
179 exvector::const_iterator it=seq.begin() + 1, itend = seq.end();
181 if (is_a<print_latex>(c)) {
183 // TeX output: group by variance
185 bool covariant = true;
187 while (it != itend) {
188 bool cur_covariant = (is_a<varidx>(*it) ? ex_to<varidx>(*it).is_covariant() : true);
189 if (first || cur_covariant != covariant) { // Variance changed
190 // The empty {} prevents indices from ending up on top of each other
193 covariant = cur_covariant;
209 while (it != itend) {
217 void indexed::print_indexed(const print_context & c, const char *openbrace, const char *closebrace, unsigned level) const
219 if (precedence() <= level)
220 c.s << openbrace << '(';
222 seq[0].print(c, precedence());
224 printindices(c, level);
225 if (precedence() <= level)
226 c.s << ')' << closebrace;
229 void indexed::do_print(const print_context & c, unsigned level) const
231 print_indexed(c, "", "", level);
234 void indexed::do_print_latex(const print_latex & c, unsigned level) const
236 print_indexed(c, "{", "}", level);
239 void indexed::do_print_tree(const print_tree & c, unsigned level) const
241 c.s << std::string(level, ' ') << class_name() << " @" << this
242 << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
243 << ", " << seq.size()-1 << " indices"
244 << ", symmetry=" << symtree << std::endl;
245 seq[0].print(c, level + c.delta_indent);
246 printindices(c, level + c.delta_indent);
249 bool indexed::info(unsigned inf) const
251 if (inf == info_flags::indexed) return true;
252 if (inf == info_flags::has_indices) return seq.size() > 1;
253 return inherited::info(inf);
256 struct idx_is_not : public std::binary_function<ex, unsigned, bool> {
257 bool operator() (const ex & e, unsigned inf) const {
258 return !(ex_to<idx>(e).get_value().info(inf));
262 bool indexed::all_index_values_are(unsigned inf) const
264 // No indices? Then no property can be fulfilled
269 return find_if(seq.begin() + 1, seq.end(), bind2nd(idx_is_not(), inf)) == seq.end();
272 int indexed::compare_same_type(const basic & other) const
274 GINAC_ASSERT(is_a<indexed>(other));
275 return inherited::compare_same_type(other);
278 ex indexed::eval(int level) const
280 // First evaluate children, then we will end up here again
282 return indexed(ex_to<symmetry>(symtree), evalchildren(level));
284 const ex &base = seq[0];
286 // If the base object is 0, the whole object is 0
290 // If the base object is a product, pull out the numeric factor
291 if (is_exactly_a<mul>(base) && is_exactly_a<numeric>(base.op(base.nops() - 1))) {
293 ex f = ex_to<numeric>(base.op(base.nops() - 1));
295 return f * thiscontainer(v);
298 // Canonicalize indices according to the symmetry properties
299 if (seq.size() > 2) {
301 GINAC_ASSERT(is_exactly_a<symmetry>(symtree));
302 int sig = canonicalize(v.begin() + 1, ex_to<symmetry>(symtree));
303 if (sig != INT_MAX) {
304 // Something has changed while sorting indices, more evaluations later
307 return ex(sig) * thiscontainer(v);
311 // Let the class of the base object perform additional evaluations
312 return ex_to<basic>(base).eval_indexed(*this);
315 ex indexed::thiscontainer(const exvector & v) const
317 return indexed(ex_to<symmetry>(symtree), v);
320 ex indexed::thiscontainer(std::auto_ptr<exvector> vp) const
322 return indexed(ex_to<symmetry>(symtree), vp);
325 ex indexed::expand(unsigned options) const
327 GINAC_ASSERT(seq.size() > 0);
329 if (options & expand_options::expand_indexed) {
330 ex newbase = seq[0].expand(options);
331 if (is_exactly_a<add>(newbase)) {
333 for (size_t i=0; i<newbase.nops(); i++) {
335 s[0] = newbase.op(i);
336 sum += thiscontainer(s).expand(options);
340 if (!are_ex_trivially_equal(newbase, seq[0])) {
343 return ex_to<indexed>(thiscontainer(s)).inherited::expand(options);
346 return inherited::expand(options);
350 // virtual functions which can be overridden by derived classes
356 // non-virtual functions in this class
359 /** Check whether all indices are of class idx and validate the symmetry
360 * tree. This function is used internally to make sure that all constructed
361 * indexed objects really carry indices and not some other classes. */
362 void indexed::validate() const
364 GINAC_ASSERT(seq.size() > 0);
365 exvector::const_iterator it = seq.begin() + 1, itend = seq.end();
366 while (it != itend) {
368 throw(std::invalid_argument("indices of indexed object must be of type idx"));
372 if (!symtree.is_zero()) {
373 if (!is_exactly_a<symmetry>(symtree))
374 throw(std::invalid_argument("symmetry of indexed object must be of type symmetry"));
375 const_cast<symmetry &>(ex_to<symmetry>(symtree)).validate(seq.size() - 1);
379 /** Implementation of ex::diff() for an indexed object always returns 0.
382 ex indexed::derivative(const symbol & s) const
391 struct idx_is_equal_ignore_dim : public std::binary_function<ex, ex, bool> {
392 bool operator() (const ex &lh, const ex &rh) const
398 // Replacing the dimension might cause an error (e.g. with
399 // index classes that only work in a fixed number of dimensions)
400 return lh.is_equal(ex_to<idx>(rh).replace_dim(ex_to<idx>(lh).get_dim()));
407 /** Check whether two sorted index vectors are consistent (i.e. equal). */
408 static bool indices_consistent(const exvector & v1, const exvector & v2)
410 // Number of indices must be the same
411 if (v1.size() != v2.size())
414 return equal(v1.begin(), v1.end(), v2.begin(), idx_is_equal_ignore_dim());
417 exvector indexed::get_indices() const
419 GINAC_ASSERT(seq.size() >= 1);
420 return exvector(seq.begin() + 1, seq.end());
423 exvector indexed::get_dummy_indices() const
425 exvector free_indices, dummy_indices;
426 find_free_and_dummy(seq.begin() + 1, seq.end(), free_indices, dummy_indices);
427 return dummy_indices;
430 exvector indexed::get_dummy_indices(const indexed & other) const
432 exvector indices = get_free_indices();
433 exvector other_indices = other.get_free_indices();
434 indices.insert(indices.end(), other_indices.begin(), other_indices.end());
435 exvector dummy_indices;
436 find_dummy_indices(indices, dummy_indices);
437 return dummy_indices;
440 bool indexed::has_dummy_index_for(const ex & i) const
442 exvector::const_iterator it = seq.begin() + 1, itend = seq.end();
443 while (it != itend) {
444 if (is_dummy_pair(*it, i))
451 exvector indexed::get_free_indices() const
453 exvector free_indices, dummy_indices;
454 find_free_and_dummy(seq.begin() + 1, seq.end(), free_indices, dummy_indices);
458 exvector add::get_free_indices() const
460 exvector free_indices;
461 for (size_t i=0; i<nops(); i++) {
463 free_indices = op(i).get_free_indices();
465 exvector free_indices_of_term = op(i).get_free_indices();
466 if (!indices_consistent(free_indices, free_indices_of_term))
467 throw (std::runtime_error("add::get_free_indices: inconsistent indices in sum"));
473 exvector mul::get_free_indices() const
475 // Concatenate free indices of all factors
477 for (size_t i=0; i<nops(); i++) {
478 exvector free_indices_of_factor = op(i).get_free_indices();
479 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
482 // And remove the dummy indices
483 exvector free_indices, dummy_indices;
484 find_free_and_dummy(un, free_indices, dummy_indices);
488 exvector ncmul::get_free_indices() const
490 // Concatenate free indices of all factors
492 for (size_t i=0; i<nops(); i++) {
493 exvector free_indices_of_factor = op(i).get_free_indices();
494 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
497 // And remove the dummy indices
498 exvector free_indices, dummy_indices;
499 find_free_and_dummy(un, free_indices, dummy_indices);
503 struct is_summation_idx : public std::unary_function<ex, bool> {
504 bool operator()(const ex & e)
506 return is_dummy_pair(e, e);
510 exvector power::get_free_indices() const
512 // Get free indices of basis
513 exvector basis_indices = basis.get_free_indices();
515 if (exponent.info(info_flags::even)) {
516 // If the exponent is an even number, then any "free" index that
517 // forms a dummy pair with itself is actually a summation index
518 exvector really_free;
519 std::remove_copy_if(basis_indices.begin(), basis_indices.end(),
520 std::back_inserter(really_free), is_summation_idx());
523 return basis_indices;
526 exvector integral::get_free_indices() const
528 if (a.get_free_indices().size() || b.get_free_indices().size())
529 throw (std::runtime_error("integral::get_free_indices: boundary values should not have free indices"));
530 return f.get_free_indices();
533 /** Rename dummy indices in an expression.
535 * @param e Expression to work on
536 * @param local_dummy_indices The set of dummy indices that appear in the
538 * @param global_dummy_indices The set of dummy indices that have appeared
539 * before and which we would like to use in "e", too. This gets updated
541 static ex rename_dummy_indices(const ex & e, exvector & global_dummy_indices, exvector & local_dummy_indices)
543 size_t global_size = global_dummy_indices.size(),
544 local_size = local_dummy_indices.size();
546 // Any local dummy indices at all?
550 if (global_size < local_size) {
552 // More local indices than we encountered before, add the new ones
554 size_t old_global_size = global_size;
555 int remaining = local_size - global_size;
556 exvector::const_iterator it = local_dummy_indices.begin(), itend = local_dummy_indices.end();
557 while (it != itend && remaining > 0) {
558 if (find_if(global_dummy_indices.begin(), global_dummy_indices.end(), bind2nd(op0_is_equal(), *it)) == global_dummy_indices.end()) {
559 global_dummy_indices.push_back(*it);
566 // If this is the first set of local indices, do nothing
567 if (old_global_size == 0)
570 GINAC_ASSERT(local_size <= global_size);
572 // Construct vectors of index symbols
573 exvector local_syms, global_syms;
574 local_syms.reserve(local_size);
575 global_syms.reserve(local_size);
576 for (size_t i=0; i<local_size; i++)
577 local_syms.push_back(local_dummy_indices[i].op(0));
578 shaker_sort(local_syms.begin(), local_syms.end(), ex_is_less(), ex_swap());
579 for (size_t i=0; i<local_size; i++) // don't use more global symbols than necessary
580 global_syms.push_back(global_dummy_indices[i].op(0));
581 shaker_sort(global_syms.begin(), global_syms.end(), ex_is_less(), ex_swap());
583 // Remove common indices
584 exvector local_uniq, global_uniq;
585 set_difference(local_syms.begin(), local_syms.end(), global_syms.begin(), global_syms.end(), std::back_insert_iterator<exvector>(local_uniq), ex_is_less());
586 set_difference(global_syms.begin(), global_syms.end(), local_syms.begin(), local_syms.end(), std::back_insert_iterator<exvector>(global_uniq), ex_is_less());
588 // Replace remaining non-common local index symbols by global ones
589 if (local_uniq.empty())
592 while (global_uniq.size() > local_uniq.size())
593 global_uniq.pop_back();
594 return e.subs(lst(local_uniq.begin(), local_uniq.end()), lst(global_uniq.begin(), global_uniq.end()), subs_options::no_pattern);
598 /** Given a set of indices, extract those of class varidx. */
599 static void find_variant_indices(const exvector & v, exvector & variant_indices)
601 exvector::const_iterator it1, itend;
602 for (it1 = v.begin(), itend = v.end(); it1 != itend; ++it1) {
603 if (is_exactly_a<varidx>(*it1))
604 variant_indices.push_back(*it1);
608 /** Raise/lower dummy indices in a single indexed objects to canonicalize their
611 * @param e Object to work on
612 * @param variant_dummy_indices The set of indices that might need repositioning (will be changed by this function)
613 * @param moved_indices The set of indices that have been repositioned (will be changed by this function)
614 * @return true if 'e' was changed */
615 bool reposition_dummy_indices(ex & e, exvector & variant_dummy_indices, exvector & moved_indices)
617 bool something_changed = false;
619 // If a dummy index is encountered for the first time in the
620 // product, pull it up, otherwise, pull it down
621 exvector::const_iterator it2, it2start, it2end;
622 for (it2start = ex_to<indexed>(e).seq.begin(), it2end = ex_to<indexed>(e).seq.end(), it2 = it2start + 1; it2 != it2end; ++it2) {
623 if (!is_exactly_a<varidx>(*it2))
626 exvector::iterator vit, vitend;
627 for (vit = variant_dummy_indices.begin(), vitend = variant_dummy_indices.end(); vit != vitend; ++vit) {
628 if (it2->op(0).is_equal(vit->op(0))) {
629 if (ex_to<varidx>(*it2).is_covariant()) {
631 *it2 == ex_to<varidx>(*it2).toggle_variance(),
632 ex_to<varidx>(*it2).toggle_variance() == *it2
633 ), subs_options::no_pattern);
634 something_changed = true;
635 it2 = ex_to<indexed>(e).seq.begin() + (it2 - it2start);
636 it2start = ex_to<indexed>(e).seq.begin();
637 it2end = ex_to<indexed>(e).seq.end();
639 moved_indices.push_back(*vit);
640 variant_dummy_indices.erase(vit);
645 for (vit = moved_indices.begin(), vitend = moved_indices.end(); vit != vitend; ++vit) {
646 if (it2->op(0).is_equal(vit->op(0))) {
647 if (ex_to<varidx>(*it2).is_contravariant()) {
648 e = e.subs(*it2 == ex_to<varidx>(*it2).toggle_variance(), subs_options::no_pattern);
649 something_changed = true;
650 it2 = ex_to<indexed>(e).seq.begin() + (it2 - it2start);
651 it2start = ex_to<indexed>(e).seq.begin();
652 it2end = ex_to<indexed>(e).seq.end();
661 return something_changed;
664 /* Ordering that only compares the base expressions of indexed objects. */
665 struct ex_base_is_less : public std::binary_function<ex, ex, bool> {
666 bool operator() (const ex &lh, const ex &rh) const
668 return (is_a<indexed>(lh) ? lh.op(0) : lh).compare(is_a<indexed>(rh) ? rh.op(0) : rh) < 0;
672 /** Simplify product of indexed expressions (commutative, noncommutative and
673 * simple squares), return list of free indices. */
674 ex simplify_indexed_product(const ex & e, exvector & free_indices, exvector & dummy_indices, const scalar_products & sp)
676 // Remember whether the product was commutative or noncommutative
677 // (because we chop it into factors and need to reassemble later)
678 bool non_commutative = is_exactly_a<ncmul>(e);
680 // Collect factors in an exvector, store squares twice
682 v.reserve(e.nops() * 2);
684 if (is_exactly_a<power>(e)) {
685 // We only get called for simple squares, split a^2 -> a*a
686 GINAC_ASSERT(e.op(1).is_equal(_ex2));
687 v.push_back(e.op(0));
688 v.push_back(e.op(0));
690 for (size_t i=0; i<e.nops(); i++) {
692 if (is_exactly_a<power>(f) && f.op(1).is_equal(_ex2)) {
693 v.push_back(f.op(0));
694 v.push_back(f.op(0));
695 } else if (is_exactly_a<ncmul>(f)) {
696 // Noncommutative factor found, split it as well
697 non_commutative = true; // everything becomes noncommutative, ncmul will sort out the commutative factors later
698 for (size_t j=0; j<f.nops(); j++)
699 v.push_back(f.op(j));
705 // Perform contractions
706 bool something_changed = false;
707 GINAC_ASSERT(v.size() > 1);
708 exvector::iterator it1, itend = v.end(), next_to_last = itend - 1;
709 for (it1 = v.begin(); it1 != next_to_last; it1++) {
712 if (!is_a<indexed>(*it1))
715 bool first_noncommutative = (it1->return_type() != return_types::commutative);
717 // Indexed factor found, get free indices and look for contraction
719 exvector free1, dummy1;
720 find_free_and_dummy(ex_to<indexed>(*it1).seq.begin() + 1, ex_to<indexed>(*it1).seq.end(), free1, dummy1);
722 exvector::iterator it2;
723 for (it2 = it1 + 1; it2 != itend; it2++) {
725 if (!is_a<indexed>(*it2))
728 bool second_noncommutative = (it2->return_type() != return_types::commutative);
730 // Find free indices of second factor and merge them with free
731 // indices of first factor
733 find_free_and_dummy(ex_to<indexed>(*it2).seq.begin() + 1, ex_to<indexed>(*it2).seq.end(), un, dummy1);
734 un.insert(un.end(), free1.begin(), free1.end());
736 // Check whether the two factors share dummy indices
737 exvector free, dummy;
738 find_free_and_dummy(un, free, dummy);
739 size_t num_dummies = dummy.size();
740 if (num_dummies == 0)
743 // At least one dummy index, is it a defined scalar product?
744 bool contracted = false;
747 // Find minimal dimension of all indices of both factors
748 exvector::const_iterator dit = ex_to<indexed>(*it1).seq.begin() + 1, ditend = ex_to<indexed>(*it1).seq.end();
749 ex dim = ex_to<idx>(*dit).get_dim();
751 for (; dit != ditend; ++dit) {
752 dim = minimal_dim(dim, ex_to<idx>(*dit).get_dim());
754 dit = ex_to<indexed>(*it2).seq.begin() + 1;
755 ditend = ex_to<indexed>(*it2).seq.end();
756 for (; dit != ditend; ++dit) {
757 dim = minimal_dim(dim, ex_to<idx>(*dit).get_dim());
760 // User-defined scalar product?
761 if (sp.is_defined(*it1, *it2, dim)) {
763 // Yes, substitute it
764 *it1 = sp.evaluate(*it1, *it2, dim);
766 goto contraction_done;
770 // Try to contract the first one with the second one
771 contracted = ex_to<basic>(it1->op(0)).contract_with(it1, it2, v);
774 // That didn't work; maybe the second object knows how to
775 // contract itself with the first one
776 contracted = ex_to<basic>(it2->op(0)).contract_with(it2, it1, v);
780 if (first_noncommutative || second_noncommutative
781 || is_exactly_a<add>(*it1) || is_exactly_a<add>(*it2)
782 || is_exactly_a<mul>(*it1) || is_exactly_a<mul>(*it2)
783 || is_exactly_a<ncmul>(*it1) || is_exactly_a<ncmul>(*it2)) {
785 // One of the factors became a sum or product:
786 // re-expand expression and run again
787 // Non-commutative products are always re-expanded to give
788 // eval_ncmul() the chance to re-order and canonicalize
790 ex r = (non_commutative ? ex(ncmul(v, true)) : ex(mul(v)));
791 return simplify_indexed(r, free_indices, dummy_indices, sp);
794 // Both objects may have new indices now or they might
795 // even not be indexed objects any more, so we have to
797 something_changed = true;
803 // Find free indices (concatenate them all and call find_free_and_dummy())
804 // and all dummy indices that appear
805 exvector un, individual_dummy_indices;
806 for (it1 = v.begin(), itend = v.end(); it1 != itend; ++it1) {
807 exvector free_indices_of_factor;
808 if (is_a<indexed>(*it1)) {
809 exvector dummy_indices_of_factor;
810 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);
811 individual_dummy_indices.insert(individual_dummy_indices.end(), dummy_indices_of_factor.begin(), dummy_indices_of_factor.end());
813 free_indices_of_factor = it1->get_free_indices();
814 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
816 exvector local_dummy_indices;
817 find_free_and_dummy(un, free_indices, local_dummy_indices);
818 local_dummy_indices.insert(local_dummy_indices.end(), individual_dummy_indices.begin(), individual_dummy_indices.end());
820 // Filter out the dummy indices with variance
821 exvector variant_dummy_indices;
822 find_variant_indices(local_dummy_indices, variant_dummy_indices);
824 // Any indices with variance present at all?
825 if (!variant_dummy_indices.empty()) {
827 // Yes, bring the product into a canonical order that only depends on
828 // the base expressions of indexed objects
829 if (!non_commutative)
830 std::sort(v.begin(), v.end(), ex_base_is_less());
832 exvector moved_indices;
834 // Iterate over all indexed objects in the product
835 for (it1 = v.begin(), itend = v.end(); it1 != itend; ++it1) {
836 if (!is_a<indexed>(*it1))
839 if (reposition_dummy_indices(*it1, variant_dummy_indices, moved_indices))
840 something_changed = true;
845 if (something_changed)
846 r = non_commutative ? ex(ncmul(v, true)) : ex(mul(v));
850 // The result should be symmetric with respect to exchange of dummy
851 // indices, so if the symmetrization vanishes, the whole expression is
852 // zero. This detects things like eps.i.j.k * p.j * p.k = 0.
853 if (local_dummy_indices.size() >= 2) {
855 dummy_syms.reserve(local_dummy_indices.size());
856 for (exvector::const_iterator it = local_dummy_indices.begin(); it != local_dummy_indices.end(); ++it)
857 dummy_syms.push_back(it->op(0));
858 if (symmetrize(r, dummy_syms).is_zero()) {
859 free_indices.clear();
864 // Dummy index renaming
865 r = rename_dummy_indices(r, dummy_indices, local_dummy_indices);
867 // Product of indexed object with a scalar?
868 if (is_exactly_a<mul>(r) && r.nops() == 2
869 && is_exactly_a<numeric>(r.op(1)) && is_a<indexed>(r.op(0)))
870 return ex_to<basic>(r.op(0).op(0)).scalar_mul_indexed(r.op(0), ex_to<numeric>(r.op(1)));
875 /** This structure stores the original and symmetrized versions of terms
876 * obtained during the simplification of sums. */
879 terminfo(const ex & orig_, const ex & symm_) : orig(orig_), symm(symm_) {}
881 ex orig; /**< original term */
882 ex symm; /**< symmtrized term */
885 class terminfo_is_less {
887 bool operator() (const terminfo & ti1, const terminfo & ti2) const
889 return (ti1.symm.compare(ti2.symm) < 0);
893 /** This structure stores the individual symmetrized terms obtained during
894 * the simplification of sums. */
897 symminfo() : num(0) {}
899 symminfo(const ex & symmterm_, const ex & orig_, size_t num_) : orig(orig_), num(num_)
901 if (is_exactly_a<mul>(symmterm_) && is_exactly_a<numeric>(symmterm_.op(symmterm_.nops()-1))) {
902 coeff = symmterm_.op(symmterm_.nops()-1);
903 symmterm = symmterm_ / coeff;
906 symmterm = symmterm_;
910 ex symmterm; /**< symmetrized term */
911 ex coeff; /**< coefficient of symmetrized term */
912 ex orig; /**< original term */
913 size_t num; /**< how many symmetrized terms resulted from the original term */
916 class symminfo_is_less_by_symmterm {
918 bool operator() (const symminfo & si1, const symminfo & si2) const
920 return (si1.symmterm.compare(si2.symmterm) < 0);
924 class symminfo_is_less_by_orig {
926 bool operator() (const symminfo & si1, const symminfo & si2) const
928 return (si1.orig.compare(si2.orig) < 0);
932 /** Simplify indexed expression, return list of free indices. */
933 ex simplify_indexed(const ex & e, exvector & free_indices, exvector & dummy_indices, const scalar_products & sp)
935 // Expand the expression
936 ex e_expanded = e.expand();
938 // Simplification of single indexed object: just find the free indices
939 // and perform dummy index renaming/repositioning
940 if (is_a<indexed>(e_expanded)) {
942 // Find the dummy indices
943 const indexed &i = ex_to<indexed>(e_expanded);
944 exvector local_dummy_indices;
945 find_free_and_dummy(i.seq.begin() + 1, i.seq.end(), free_indices, local_dummy_indices);
947 // Filter out the dummy indices with variance
948 exvector variant_dummy_indices;
949 find_variant_indices(local_dummy_indices, variant_dummy_indices);
951 // Any indices with variance present at all?
952 if (!variant_dummy_indices.empty()) {
954 // Yes, reposition them
955 exvector moved_indices;
956 reposition_dummy_indices(e_expanded, variant_dummy_indices, moved_indices);
959 // Rename the dummy indices
960 return rename_dummy_indices(e_expanded, dummy_indices, local_dummy_indices);
963 // Simplification of sum = sum of simplifications, check consistency of
964 // free indices in each term
965 if (is_exactly_a<add>(e_expanded)) {
968 free_indices.clear();
970 for (size_t i=0; i<e_expanded.nops(); i++) {
971 exvector free_indices_of_term;
972 ex term = simplify_indexed(e_expanded.op(i), free_indices_of_term, dummy_indices, sp);
973 if (!term.is_zero()) {
975 free_indices = free_indices_of_term;
979 if (!indices_consistent(free_indices, free_indices_of_term)) {
980 std::ostringstream s;
981 s << "simplify_indexed: inconsistent indices in sum: ";
982 s << exprseq(free_indices) << " vs. " << exprseq(free_indices_of_term);
983 throw (std::runtime_error(s.str()));
985 if (is_a<indexed>(sum) && is_a<indexed>(term))
986 sum = ex_to<basic>(sum.op(0)).add_indexed(sum, term);
993 // If the sum turns out to be zero, we are finished
995 free_indices.clear();
999 // More than one term and more than one dummy index?
1000 size_t num_terms_orig = (is_exactly_a<add>(sum) ? sum.nops() : 1);
1001 if (num_terms_orig < 2 || dummy_indices.size() < 2)
1004 // Yes, construct vector of all dummy index symbols
1005 exvector dummy_syms;
1006 dummy_syms.reserve(dummy_indices.size());
1007 for (exvector::const_iterator it = dummy_indices.begin(); it != dummy_indices.end(); ++it)
1008 dummy_syms.push_back(it->op(0));
1010 // Chop the sum into terms and symmetrize each one over the dummy
1012 std::vector<terminfo> terms;
1013 for (size_t i=0; i<sum.nops(); i++) {
1014 const ex & term = sum.op(i);
1015 ex term_symm = symmetrize(term, dummy_syms);
1016 if (term_symm.is_zero())
1018 terms.push_back(terminfo(term, term_symm));
1021 // Sort by symmetrized terms
1022 std::sort(terms.begin(), terms.end(), terminfo_is_less());
1024 // Combine equal symmetrized terms
1025 std::vector<terminfo> terms_pass2;
1026 for (std::vector<terminfo>::const_iterator i=terms.begin(); i!=terms.end(); ) {
1028 std::vector<terminfo>::const_iterator j = i + 1;
1029 while (j != terms.end() && j->symm == i->symm) {
1033 terms_pass2.push_back(terminfo(i->orig * num, i->symm * num));
1037 // If there is only one term left, we are finished
1038 if (terms_pass2.size() == 1)
1039 return terms_pass2[0].orig;
1041 // Chop the symmetrized terms into subterms
1042 std::vector<symminfo> sy;
1043 for (std::vector<terminfo>::const_iterator i=terms_pass2.begin(); i!=terms_pass2.end(); ++i) {
1044 if (is_exactly_a<add>(i->symm)) {
1045 size_t num = i->symm.nops();
1046 for (size_t j=0; j<num; j++)
1047 sy.push_back(symminfo(i->symm.op(j), i->orig, num));
1049 sy.push_back(symminfo(i->symm, i->orig, 1));
1052 // Sort by symmetrized subterms
1053 std::sort(sy.begin(), sy.end(), symminfo_is_less_by_symmterm());
1055 // Combine equal symmetrized subterms
1056 std::vector<symminfo> sy_pass2;
1058 for (std::vector<symminfo>::const_iterator i=sy.begin(); i!=sy.end(); ) {
1060 // Combine equal terms
1061 std::vector<symminfo>::const_iterator j = i + 1;
1062 if (j != sy.end() && j->symmterm == i->symmterm) {
1064 // More than one term, collect the coefficients
1065 ex coeff = i->coeff;
1066 while (j != sy.end() && j->symmterm == i->symmterm) {
1071 // Add combined term to result
1072 if (!coeff.is_zero())
1073 result.push_back(coeff * i->symmterm);
1077 // Single term, store for second pass
1078 sy_pass2.push_back(*i);
1084 // Were there any remaining terms that didn't get combined?
1085 if (sy_pass2.size() > 0) {
1087 // Yes, sort by their original terms
1088 std::sort(sy_pass2.begin(), sy_pass2.end(), symminfo_is_less_by_orig());
1090 for (std::vector<symminfo>::const_iterator i=sy_pass2.begin(); i!=sy_pass2.end(); ) {
1092 // How many symmetrized terms of this original term are left?
1094 std::vector<symminfo>::const_iterator j = i + 1;
1095 while (j != sy_pass2.end() && j->orig == i->orig) {
1100 if (num == i->num) {
1102 // All terms left, then add the original term to the result
1103 result.push_back(i->orig);
1107 // Some terms were combined with others, add up the remaining symmetrized terms
1108 std::vector<symminfo>::const_iterator k;
1109 for (k=i; k!=j; k++)
1110 result.push_back(k->coeff * k->symmterm);
1117 // Add all resulting terms
1118 ex sum_symm = (new add(result))->setflag(status_flags::dynallocated);
1119 if (sum_symm.is_zero())
1120 free_indices.clear();
1124 // Simplification of products
1125 if (is_exactly_a<mul>(e_expanded)
1126 || is_exactly_a<ncmul>(e_expanded)
1127 || (is_exactly_a<power>(e_expanded) && is_a<indexed>(e_expanded.op(0)) && e_expanded.op(1).is_equal(_ex2)))
1128 return simplify_indexed_product(e_expanded, free_indices, dummy_indices, sp);
1130 // Cannot do anything
1131 free_indices.clear();
1135 /** Simplify/canonicalize expression containing indexed objects. This
1136 * performs contraction of dummy indices where possible and checks whether
1137 * the free indices in sums are consistent.
1139 * @param options Simplification options (currently unused)
1140 * @return simplified expression */
1141 ex ex::simplify_indexed(unsigned options) const
1143 exvector free_indices, dummy_indices;
1145 return GiNaC::simplify_indexed(*this, free_indices, dummy_indices, sp);
1148 /** Simplify/canonicalize expression containing indexed objects. This
1149 * performs contraction of dummy indices where possible, checks whether
1150 * the free indices in sums are consistent, and automatically replaces
1151 * scalar products by known values if desired.
1153 * @param sp Scalar products to be replaced automatically
1154 * @param options Simplification options (currently unused)
1155 * @return simplified expression */
1156 ex ex::simplify_indexed(const scalar_products & sp, unsigned options) const
1158 exvector free_indices, dummy_indices;
1159 return GiNaC::simplify_indexed(*this, free_indices, dummy_indices, sp);
1162 /** Symmetrize expression over its free indices. */
1163 ex ex::symmetrize() const
1165 return GiNaC::symmetrize(*this, get_free_indices());
1168 /** Antisymmetrize expression over its free indices. */
1169 ex ex::antisymmetrize() const
1171 return GiNaC::antisymmetrize(*this, get_free_indices());
1174 /** Symmetrize expression by cyclic permutation over its free indices. */
1175 ex ex::symmetrize_cyclic() const
1177 return GiNaC::symmetrize_cyclic(*this, get_free_indices());
1184 spmapkey::spmapkey(const ex & v1_, const ex & v2_, const ex & dim_) : dim(dim_)
1186 // If indexed, extract base objects
1187 ex s1 = is_a<indexed>(v1_) ? v1_.op(0) : v1_;
1188 ex s2 = is_a<indexed>(v2_) ? v2_.op(0) : v2_;
1190 // Enforce canonical order in pair
1191 if (s1.compare(s2) > 0) {
1200 bool spmapkey::operator==(const spmapkey &other) const
1202 if (!v1.is_equal(other.v1))
1204 if (!v2.is_equal(other.v2))
1206 if (is_a<wildcard>(dim) || is_a<wildcard>(other.dim))
1209 return dim.is_equal(other.dim);
1212 bool spmapkey::operator<(const spmapkey &other) const
1214 int cmp = v1.compare(other.v1);
1217 cmp = v2.compare(other.v2);
1221 // Objects are equal, now check dimensions
1222 if (is_a<wildcard>(dim) || is_a<wildcard>(other.dim))
1225 return dim.compare(other.dim) < 0;
1228 void spmapkey::debugprint() const
1230 std::cerr << "(" << v1 << "," << v2 << "," << dim << ")";
1233 void scalar_products::add(const ex & v1, const ex & v2, const ex & sp)
1235 spm[spmapkey(v1, v2)] = sp;
1238 void scalar_products::add(const ex & v1, const ex & v2, const ex & dim, const ex & sp)
1240 spm[spmapkey(v1, v2, dim)] = sp;
1243 void scalar_products::add_vectors(const lst & l, const ex & dim)
1245 // Add all possible pairs of products
1246 for (lst::const_iterator it1 = l.begin(); it1 != l.end(); ++it1)
1247 for (lst::const_iterator it2 = l.begin(); it2 != l.end(); ++it2)
1248 add(*it1, *it2, *it1 * *it2);
1251 void scalar_products::clear()
1256 /** Check whether scalar product pair is defined. */
1257 bool scalar_products::is_defined(const ex & v1, const ex & v2, const ex & dim) const
1259 return spm.find(spmapkey(v1, v2, dim)) != spm.end();
1262 /** Return value of defined scalar product pair. */
1263 ex scalar_products::evaluate(const ex & v1, const ex & v2, const ex & dim) const
1265 return spm.find(spmapkey(v1, v2, dim))->second;
1268 void scalar_products::debugprint() const
1270 std::cerr << "map size=" << spm.size() << std::endl;
1271 spmap::const_iterator i = spm.begin(), end = spm.end();
1273 const spmapkey & k = i->first;
1274 std::cerr << "item key=";
1276 std::cerr << ", value=" << i->second << std::endl;
1281 } // namespace GiNaC