3 * Implementation of GiNaC's indexed expressions. */
6 * GiNaC Copyright (C) 1999-2003 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(indexed, exprseq)
46 // default constructor
49 indexed::indexed() : symtree(sy_none())
51 tinfo_key = TINFO_indexed;
58 indexed::indexed(const ex & b) : inherited(b), symtree(sy_none())
60 tinfo_key = TINFO_indexed;
64 indexed::indexed(const ex & b, const ex & i1) : inherited(b, i1), symtree(sy_none())
66 tinfo_key = TINFO_indexed;
70 indexed::indexed(const ex & b, const ex & i1, const ex & i2) : inherited(b, i1, i2), symtree(sy_none())
72 tinfo_key = TINFO_indexed;
76 indexed::indexed(const ex & b, const ex & i1, const ex & i2, const ex & i3) : inherited(b, i1, i2, i3), symtree(sy_none())
78 tinfo_key = TINFO_indexed;
82 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())
84 tinfo_key = TINFO_indexed;
88 indexed::indexed(const ex & b, const symmetry & symm, const ex & i1, const ex & i2) : inherited(b, i1, i2), symtree(symm)
90 tinfo_key = TINFO_indexed;
94 indexed::indexed(const ex & b, const symmetry & symm, const ex & i1, const ex & i2, const ex & i3) : inherited(b, i1, i2, i3), symtree(symm)
96 tinfo_key = TINFO_indexed;
100 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)
102 tinfo_key = TINFO_indexed;
106 indexed::indexed(const ex & b, const exvector & v) : inherited(b), symtree(sy_none())
108 seq.insert(seq.end(), v.begin(), v.end());
109 tinfo_key = TINFO_indexed;
113 indexed::indexed(const ex & b, const symmetry & symm, const exvector & v) : inherited(b), symtree(symm)
115 seq.insert(seq.end(), v.begin(), v.end());
116 tinfo_key = TINFO_indexed;
120 indexed::indexed(const symmetry & symm, const exprseq & es) : inherited(es), symtree(symm)
122 tinfo_key = TINFO_indexed;
125 indexed::indexed(const symmetry & symm, const exvector & v, bool discardable) : inherited(v, discardable), symtree(symm)
127 tinfo_key = TINFO_indexed;
130 indexed::indexed(const symmetry & symm, exvector * vp) : inherited(vp), symtree(symm)
132 tinfo_key = TINFO_indexed;
139 indexed::indexed(const archive_node &n, lst &sym_lst) : inherited(n, sym_lst)
141 if (!n.find_ex("symmetry", symtree, sym_lst)) {
142 // GiNaC versions <= 0.9.0 had an unsigned "symmetry" property
144 n.find_unsigned("symmetry", symm);
156 const_cast<symmetry &>(ex_to<symmetry>(symtree)).validate(seq.size() - 1);
160 void indexed::archive(archive_node &n) const
162 inherited::archive(n);
163 n.add_ex("symmetry", symtree);
166 DEFAULT_UNARCHIVE(indexed)
169 // functions overriding virtual functions from base classes
172 void indexed::print(const print_context & c, unsigned level) const
174 GINAC_ASSERT(seq.size() > 0);
176 if (is_a<print_tree>(c)) {
178 c.s << std::string(level, ' ') << class_name()
179 << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
180 << ", " << seq.size()-1 << " indices"
181 << ", symmetry=" << symtree << std::endl;
182 unsigned delta_indent = static_cast<const print_tree &>(c).delta_indent;
183 seq[0].print(c, level + delta_indent);
184 printindices(c, level + delta_indent);
188 bool is_tex = is_a<print_latex>(c);
189 const ex & base = seq[0];
191 if (precedence() <= level)
192 c.s << (is_tex ? "{(" : "(");
195 base.print(c, precedence());
198 printindices(c, level);
199 if (precedence() <= level)
200 c.s << (is_tex ? ")}" : ")");
204 bool indexed::info(unsigned inf) const
206 if (inf == info_flags::indexed) return true;
207 if (inf == info_flags::has_indices) return seq.size() > 1;
208 return inherited::info(inf);
211 struct idx_is_not : public std::binary_function<ex, unsigned, bool> {
212 bool operator() (const ex & e, unsigned inf) const {
213 return !(ex_to<idx>(e).get_value().info(inf));
217 bool indexed::all_index_values_are(unsigned inf) const
219 // No indices? Then no property can be fulfilled
224 return find_if(seq.begin() + 1, seq.end(), bind2nd(idx_is_not(), inf)) == seq.end();
227 int indexed::compare_same_type(const basic & other) const
229 GINAC_ASSERT(is_a<indexed>(other));
230 return inherited::compare_same_type(other);
233 ex indexed::eval(int level) const
235 // First evaluate children, then we will end up here again
237 return indexed(ex_to<symmetry>(symtree), evalchildren(level));
239 const ex &base = seq[0];
241 // If the base object is 0, the whole object is 0
245 // If the base object is a product, pull out the numeric factor
246 if (is_exactly_a<mul>(base) && is_exactly_a<numeric>(base.op(base.nops() - 1))) {
248 ex f = ex_to<numeric>(base.op(base.nops() - 1));
250 return f * thiscontainer(v);
253 // Canonicalize indices according to the symmetry properties
254 if (seq.size() > 2) {
256 GINAC_ASSERT(is_exactly_a<symmetry>(symtree));
257 int sig = canonicalize(v.begin() + 1, ex_to<symmetry>(symtree));
258 if (sig != INT_MAX) {
259 // Something has changed while sorting indices, more evaluations later
262 return ex(sig) * thiscontainer(v);
266 // Let the class of the base object perform additional evaluations
267 return ex_to<basic>(base).eval_indexed(*this);
270 ex indexed::thiscontainer(const exvector & v) const
272 return indexed(ex_to<symmetry>(symtree), v);
275 ex indexed::thiscontainer(exvector * vp) const
277 return indexed(ex_to<symmetry>(symtree), vp);
280 ex indexed::expand(unsigned options) const
282 GINAC_ASSERT(seq.size() > 0);
284 if ((options & expand_options::expand_indexed) && is_exactly_a<add>(seq[0])) {
286 // expand_indexed expands (a+b).i -> a.i + b.i
287 const ex & base = seq[0];
289 for (size_t i=0; i<base.nops(); i++) {
292 sum += thiscontainer(s).expand();
297 return inherited::expand(options);
301 // virtual functions which can be overridden by derived classes
307 // non-virtual functions in this class
310 void indexed::printindices(const print_context & c, unsigned level) const
312 if (seq.size() > 1) {
314 exvector::const_iterator it=seq.begin() + 1, itend = seq.end();
316 if (is_a<print_latex>(c)) {
318 // TeX output: group by variance
320 bool covariant = true;
322 while (it != itend) {
323 bool cur_covariant = (is_a<varidx>(*it) ? ex_to<varidx>(*it).is_covariant() : true);
324 if (first || cur_covariant != covariant) { // Variance changed
325 // The empty {} prevents indices from ending up on top of each other
328 covariant = cur_covariant;
344 while (it != itend) {
352 /** Check whether all indices are of class idx and validate the symmetry
353 * tree. This function is used internally to make sure that all constructed
354 * indexed objects really carry indices and not some other classes. */
355 void indexed::validate() const
357 GINAC_ASSERT(seq.size() > 0);
358 exvector::const_iterator it = seq.begin() + 1, itend = seq.end();
359 while (it != itend) {
361 throw(std::invalid_argument("indices of indexed object must be of type idx"));
365 if (!symtree.is_zero()) {
366 if (!is_exactly_a<symmetry>(symtree))
367 throw(std::invalid_argument("symmetry of indexed object must be of type symmetry"));
368 const_cast<symmetry &>(ex_to<symmetry>(symtree)).validate(seq.size() - 1);
372 /** Implementation of ex::diff() for an indexed object always returns 0.
375 ex indexed::derivative(const symbol & s) const
384 struct idx_is_equal_ignore_dim : public std::binary_function<ex, ex, bool> {
385 bool operator() (const ex &lh, const ex &rh) const
391 // Replacing the dimension might cause an error (e.g. with
392 // index classes that only work in a fixed number of dimensions)
393 return lh.is_equal(ex_to<idx>(rh).replace_dim(ex_to<idx>(lh).get_dim()));
400 /** Check whether two sorted index vectors are consistent (i.e. equal). */
401 static bool indices_consistent(const exvector & v1, const exvector & v2)
403 // Number of indices must be the same
404 if (v1.size() != v2.size())
407 return equal(v1.begin(), v1.end(), v2.begin(), idx_is_equal_ignore_dim());
410 exvector indexed::get_indices() const
412 GINAC_ASSERT(seq.size() >= 1);
413 return exvector(seq.begin() + 1, seq.end());
416 exvector indexed::get_dummy_indices() const
418 exvector free_indices, dummy_indices;
419 find_free_and_dummy(seq.begin() + 1, seq.end(), free_indices, dummy_indices);
420 return dummy_indices;
423 exvector indexed::get_dummy_indices(const indexed & other) const
425 exvector indices = get_free_indices();
426 exvector other_indices = other.get_free_indices();
427 indices.insert(indices.end(), other_indices.begin(), other_indices.end());
428 exvector dummy_indices;
429 find_dummy_indices(indices, dummy_indices);
430 return dummy_indices;
433 bool indexed::has_dummy_index_for(const ex & i) const
435 exvector::const_iterator it = seq.begin() + 1, itend = seq.end();
436 while (it != itend) {
437 if (is_dummy_pair(*it, i))
444 exvector indexed::get_free_indices() const
446 exvector free_indices, dummy_indices;
447 find_free_and_dummy(seq.begin() + 1, seq.end(), free_indices, dummy_indices);
451 exvector add::get_free_indices() const
453 exvector free_indices;
454 for (size_t i=0; i<nops(); i++) {
456 free_indices = op(i).get_free_indices();
458 exvector free_indices_of_term = op(i).get_free_indices();
459 if (!indices_consistent(free_indices, free_indices_of_term))
460 throw (std::runtime_error("add::get_free_indices: inconsistent indices in sum"));
466 exvector mul::get_free_indices() const
468 // Concatenate free indices of all factors
470 for (size_t i=0; i<nops(); i++) {
471 exvector free_indices_of_factor = op(i).get_free_indices();
472 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
475 // And remove the dummy indices
476 exvector free_indices, dummy_indices;
477 find_free_and_dummy(un, free_indices, dummy_indices);
481 exvector ncmul::get_free_indices() const
483 // Concatenate free indices of all factors
485 for (size_t i=0; i<nops(); i++) {
486 exvector free_indices_of_factor = op(i).get_free_indices();
487 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
490 // And remove the dummy indices
491 exvector free_indices, dummy_indices;
492 find_free_and_dummy(un, free_indices, dummy_indices);
496 exvector power::get_free_indices() const
498 // Return free indices of basis
499 return basis.get_free_indices();
502 /** Rename dummy indices in an expression.
504 * @param e Expression to work on
505 * @param local_dummy_indices The set of dummy indices that appear in the
507 * @param global_dummy_indices The set of dummy indices that have appeared
508 * before and which we would like to use in "e", too. This gets updated
510 static ex rename_dummy_indices(const ex & e, exvector & global_dummy_indices, exvector & local_dummy_indices)
512 size_t global_size = global_dummy_indices.size(),
513 local_size = local_dummy_indices.size();
515 // Any local dummy indices at all?
519 if (global_size < local_size) {
521 // More local indices than we encountered before, add the new ones
523 size_t old_global_size = global_size;
524 int remaining = local_size - global_size;
525 exvector::const_iterator it = local_dummy_indices.begin(), itend = local_dummy_indices.end();
526 while (it != itend && remaining > 0) {
527 if (find_if(global_dummy_indices.begin(), global_dummy_indices.end(), bind2nd(op0_is_equal(), *it)) == global_dummy_indices.end()) {
528 global_dummy_indices.push_back(*it);
535 // If this is the first set of local indices, do nothing
536 if (old_global_size == 0)
539 GINAC_ASSERT(local_size <= global_size);
541 // Construct vectors of index symbols
542 exvector local_syms, global_syms;
543 local_syms.reserve(local_size);
544 global_syms.reserve(local_size);
545 for (size_t i=0; i<local_size; i++)
546 local_syms.push_back(local_dummy_indices[i].op(0));
547 shaker_sort(local_syms.begin(), local_syms.end(), ex_is_less(), ex_swap());
548 for (size_t i=0; i<local_size; i++) // don't use more global symbols than necessary
549 global_syms.push_back(global_dummy_indices[i].op(0));
550 shaker_sort(global_syms.begin(), global_syms.end(), ex_is_less(), ex_swap());
552 // Remove common indices
553 exvector local_uniq, global_uniq;
554 set_difference(local_syms.begin(), local_syms.end(), global_syms.begin(), global_syms.end(), std::back_insert_iterator<exvector>(local_uniq), ex_is_less());
555 set_difference(global_syms.begin(), global_syms.end(), local_syms.begin(), local_syms.end(), std::back_insert_iterator<exvector>(global_uniq), ex_is_less());
557 // Replace remaining non-common local index symbols by global ones
558 if (local_uniq.empty())
561 while (global_uniq.size() > local_uniq.size())
562 global_uniq.pop_back();
563 return e.subs(lst(local_uniq.begin(), local_uniq.end()), lst(global_uniq.begin(), global_uniq.end()));
567 /** Given a set of indices, extract those of class varidx. */
568 static void find_variant_indices(const exvector & v, exvector & variant_indices)
570 exvector::const_iterator it1, itend;
571 for (it1 = v.begin(), itend = v.end(); it1 != itend; ++it1) {
572 if (is_exactly_a<varidx>(*it1))
573 variant_indices.push_back(*it1);
577 /** Raise/lower dummy indices in a single indexed objects to canonicalize their
580 * @param e Object to work on
581 * @param variant_dummy_indices The set of indices that might need repositioning (will be changed by this function)
582 * @param moved_indices The set of indices that have been repositioned (will be changed by this function)
583 * @return true if 'e' was changed */
584 bool reposition_dummy_indices(ex & e, exvector & variant_dummy_indices, exvector & moved_indices)
586 bool something_changed = false;
588 // If a dummy index is encountered for the first time in the
589 // product, pull it up, otherwise, pull it down
590 exvector::const_iterator it2, it2start, it2end;
591 for (it2start = ex_to<indexed>(e).seq.begin(), it2end = ex_to<indexed>(e).seq.end(), it2 = it2start + 1; it2 != it2end; ++it2) {
592 if (!is_exactly_a<varidx>(*it2))
595 exvector::iterator vit, vitend;
596 for (vit = variant_dummy_indices.begin(), vitend = variant_dummy_indices.end(); vit != vitend; ++vit) {
597 if (it2->op(0).is_equal(vit->op(0))) {
598 if (ex_to<varidx>(*it2).is_covariant()) {
600 *it2 == ex_to<varidx>(*it2).toggle_variance(),
601 ex_to<varidx>(*it2).toggle_variance() == *it2
603 something_changed = true;
604 it2 = ex_to<indexed>(e).seq.begin() + (it2 - it2start);
605 it2start = ex_to<indexed>(e).seq.begin();
606 it2end = ex_to<indexed>(e).seq.end();
608 moved_indices.push_back(*vit);
609 variant_dummy_indices.erase(vit);
614 for (vit = moved_indices.begin(), vitend = moved_indices.end(); vit != vitend; ++vit) {
615 if (it2->op(0).is_equal(vit->op(0))) {
616 if (ex_to<varidx>(*it2).is_contravariant()) {
617 e = e.subs(*it2 == ex_to<varidx>(*it2).toggle_variance());
618 something_changed = true;
619 it2 = ex_to<indexed>(e).seq.begin() + (it2 - it2start);
620 it2start = ex_to<indexed>(e).seq.begin();
621 it2end = ex_to<indexed>(e).seq.end();
630 return something_changed;
633 /* Ordering that only compares the base expressions of indexed objects. */
634 struct ex_base_is_less : public std::binary_function<ex, ex, bool> {
635 bool operator() (const ex &lh, const ex &rh) const
637 return (is_a<indexed>(lh) ? lh.op(0) : lh).compare(is_a<indexed>(rh) ? rh.op(0) : rh) < 0;
641 /** Simplify product of indexed expressions (commutative, noncommutative and
642 * simple squares), return list of free indices. */
643 ex simplify_indexed_product(const ex & e, exvector & free_indices, exvector & dummy_indices, const scalar_products & sp)
645 // Remember whether the product was commutative or noncommutative
646 // (because we chop it into factors and need to reassemble later)
647 bool non_commutative = is_exactly_a<ncmul>(e);
649 // Collect factors in an exvector, store squares twice
651 v.reserve(e.nops() * 2);
653 if (is_exactly_a<power>(e)) {
654 // We only get called for simple squares, split a^2 -> a*a
655 GINAC_ASSERT(e.op(1).is_equal(_ex2));
656 v.push_back(e.op(0));
657 v.push_back(e.op(0));
659 for (size_t i=0; i<e.nops(); i++) {
661 if (is_exactly_a<power>(f) && f.op(1).is_equal(_ex2)) {
662 v.push_back(f.op(0));
663 v.push_back(f.op(0));
664 } else if (is_exactly_a<ncmul>(f)) {
665 // Noncommutative factor found, split it as well
666 non_commutative = true; // everything becomes noncommutative, ncmul will sort out the commutative factors later
667 for (size_t j=0; j<f.nops(); j++)
668 v.push_back(f.op(j));
674 // Perform contractions
675 bool something_changed = false;
676 GINAC_ASSERT(v.size() > 1);
677 exvector::iterator it1, itend = v.end(), next_to_last = itend - 1;
678 for (it1 = v.begin(); it1 != next_to_last; it1++) {
681 if (!is_a<indexed>(*it1))
684 bool first_noncommutative = (it1->return_type() != return_types::commutative);
686 // Indexed factor found, get free indices and look for contraction
688 exvector free1, dummy1;
689 find_free_and_dummy(ex_to<indexed>(*it1).seq.begin() + 1, ex_to<indexed>(*it1).seq.end(), free1, dummy1);
691 exvector::iterator it2;
692 for (it2 = it1 + 1; it2 != itend; it2++) {
694 if (!is_a<indexed>(*it2))
697 bool second_noncommutative = (it2->return_type() != return_types::commutative);
699 // Find free indices of second factor and merge them with free
700 // indices of first factor
702 find_free_and_dummy(ex_to<indexed>(*it2).seq.begin() + 1, ex_to<indexed>(*it2).seq.end(), un, dummy1);
703 un.insert(un.end(), free1.begin(), free1.end());
705 // Check whether the two factors share dummy indices
706 exvector free, dummy;
707 find_free_and_dummy(un, free, dummy);
708 size_t num_dummies = dummy.size();
709 if (num_dummies == 0)
712 // At least one dummy index, is it a defined scalar product?
713 bool contracted = false;
716 // Find minimal dimension of all indices of both factors
717 exvector::const_iterator dit = ex_to<indexed>(*it1).seq.begin() + 1, ditend = ex_to<indexed>(*it1).seq.end();
718 ex dim = ex_to<idx>(*dit).get_dim();
720 for (; dit != ditend; ++dit) {
721 dim = minimal_dim(dim, ex_to<idx>(*dit).get_dim());
723 dit = ex_to<indexed>(*it2).seq.begin() + 1;
724 ditend = ex_to<indexed>(*it2).seq.end();
725 for (; dit != ditend; ++dit) {
726 dim = minimal_dim(dim, ex_to<idx>(*dit).get_dim());
729 // User-defined scalar product?
730 if (sp.is_defined(*it1, *it2, dim)) {
732 // Yes, substitute it
733 *it1 = sp.evaluate(*it1, *it2, dim);
735 goto contraction_done;
739 // Try to contract the first one with the second one
740 contracted = ex_to<basic>(it1->op(0)).contract_with(it1, it2, v);
743 // That didn't work; maybe the second object knows how to
744 // contract itself with the first one
745 contracted = ex_to<basic>(it2->op(0)).contract_with(it2, it1, v);
749 if (first_noncommutative || second_noncommutative
750 || is_exactly_a<add>(*it1) || is_exactly_a<add>(*it2)
751 || is_exactly_a<mul>(*it1) || is_exactly_a<mul>(*it2)
752 || is_exactly_a<ncmul>(*it1) || is_exactly_a<ncmul>(*it2)) {
754 // One of the factors became a sum or product:
755 // re-expand expression and run again
756 // Non-commutative products are always re-expanded to give
757 // eval_ncmul() the chance to re-order and canonicalize
759 ex r = (non_commutative ? ex(ncmul(v, true)) : ex(mul(v)));
760 return simplify_indexed(r, free_indices, dummy_indices, sp);
763 // Both objects may have new indices now or they might
764 // even not be indexed objects any more, so we have to
766 something_changed = true;
772 // Find free indices (concatenate them all and call find_free_and_dummy())
773 // and all dummy indices that appear
774 exvector un, individual_dummy_indices;
775 for (it1 = v.begin(), itend = v.end(); it1 != itend; ++it1) {
776 exvector free_indices_of_factor;
777 if (is_a<indexed>(*it1)) {
778 exvector dummy_indices_of_factor;
779 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);
780 individual_dummy_indices.insert(individual_dummy_indices.end(), dummy_indices_of_factor.begin(), dummy_indices_of_factor.end());
782 free_indices_of_factor = it1->get_free_indices();
783 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
785 exvector local_dummy_indices;
786 find_free_and_dummy(un, free_indices, local_dummy_indices);
787 local_dummy_indices.insert(local_dummy_indices.end(), individual_dummy_indices.begin(), individual_dummy_indices.end());
789 // Filter out the dummy indices with variance
790 exvector variant_dummy_indices;
791 find_variant_indices(local_dummy_indices, variant_dummy_indices);
793 // Any indices with variance present at all?
794 if (!variant_dummy_indices.empty()) {
796 // Yes, bring the product into a canonical order that only depends on
797 // the base expressions of indexed objects
798 if (!non_commutative)
799 std::sort(v.begin(), v.end(), ex_base_is_less());
801 exvector moved_indices;
803 // Iterate over all indexed objects in the product
804 for (it1 = v.begin(), itend = v.end(); it1 != itend; ++it1) {
805 if (!is_a<indexed>(*it1))
808 if (reposition_dummy_indices(*it1, variant_dummy_indices, moved_indices))
809 something_changed = true;
814 if (something_changed)
815 r = non_commutative ? ex(ncmul(v, true)) : ex(mul(v));
819 // The result should be symmetric with respect to exchange of dummy
820 // indices, so if the symmetrization vanishes, the whole expression is
821 // zero. This detects things like eps.i.j.k * p.j * p.k = 0.
822 if (local_dummy_indices.size() >= 2) {
824 dummy_syms.reserve(local_dummy_indices.size());
825 for (exvector::const_iterator it = local_dummy_indices.begin(); it != local_dummy_indices.end(); ++it)
826 dummy_syms.push_back(it->op(0));
827 if (symmetrize(r, dummy_syms).is_zero()) {
828 free_indices.clear();
833 // Dummy index renaming
834 r = rename_dummy_indices(r, dummy_indices, local_dummy_indices);
836 // Product of indexed object with a scalar?
837 if (is_exactly_a<mul>(r) && r.nops() == 2
838 && is_exactly_a<numeric>(r.op(1)) && is_a<indexed>(r.op(0)))
839 return ex_to<basic>(r.op(0).op(0)).scalar_mul_indexed(r.op(0), ex_to<numeric>(r.op(1)));
844 /** This structure stores the original and symmetrized versions of terms
845 * obtained during the simplification of sums. */
848 terminfo(const ex & orig_, const ex & symm_) : orig(orig_), symm(symm_) {}
850 ex orig; /**< original term */
851 ex symm; /**< symmtrized term */
854 class terminfo_is_less {
856 bool operator() (const terminfo & ti1, const terminfo & ti2) const
858 return (ti1.symm.compare(ti2.symm) < 0);
862 /** This structure stores the individual symmetrized terms obtained during
863 * the simplification of sums. */
866 symminfo() : num(0) {}
868 symminfo(const ex & symmterm_, const ex & orig_, size_t num_) : orig(orig_), num(num_)
870 if (is_exactly_a<mul>(symmterm_) && is_exactly_a<numeric>(symmterm_.op(symmterm_.nops()-1))) {
871 coeff = symmterm_.op(symmterm_.nops()-1);
872 symmterm = symmterm_ / coeff;
875 symmterm = symmterm_;
879 ex symmterm; /**< symmetrized term */
880 ex coeff; /**< coefficient of symmetrized term */
881 ex orig; /**< original term */
882 size_t num; /**< how many symmetrized terms resulted from the original term */
885 class symminfo_is_less_by_symmterm {
887 bool operator() (const symminfo & si1, const symminfo & si2) const
889 return (si1.symmterm.compare(si2.symmterm) < 0);
893 class symminfo_is_less_by_orig {
895 bool operator() (const symminfo & si1, const symminfo & si2) const
897 return (si1.orig.compare(si2.orig) < 0);
901 /** Simplify indexed expression, return list of free indices. */
902 ex simplify_indexed(const ex & e, exvector & free_indices, exvector & dummy_indices, const scalar_products & sp)
904 // Expand the expression
905 ex e_expanded = e.expand();
907 // Simplification of single indexed object: just find the free indices
908 // and perform dummy index renaming/repositioning
909 if (is_a<indexed>(e_expanded)) {
911 // Find the dummy indices
912 const indexed &i = ex_to<indexed>(e_expanded);
913 exvector local_dummy_indices;
914 find_free_and_dummy(i.seq.begin() + 1, i.seq.end(), free_indices, local_dummy_indices);
916 // Filter out the dummy indices with variance
917 exvector variant_dummy_indices;
918 find_variant_indices(local_dummy_indices, variant_dummy_indices);
920 // Any indices with variance present at all?
921 if (!variant_dummy_indices.empty()) {
923 // Yes, reposition them
924 exvector moved_indices;
925 reposition_dummy_indices(e_expanded, variant_dummy_indices, moved_indices);
928 // Rename the dummy indices
929 return rename_dummy_indices(e_expanded, dummy_indices, local_dummy_indices);
932 // Simplification of sum = sum of simplifications, check consistency of
933 // free indices in each term
934 if (is_exactly_a<add>(e_expanded)) {
937 free_indices.clear();
939 for (size_t i=0; i<e_expanded.nops(); i++) {
940 exvector free_indices_of_term;
941 ex term = simplify_indexed(e_expanded.op(i), free_indices_of_term, dummy_indices, sp);
942 if (!term.is_zero()) {
944 free_indices = free_indices_of_term;
948 if (!indices_consistent(free_indices, free_indices_of_term)) {
949 std::ostringstream s;
950 s << "simplify_indexed: inconsistent indices in sum: ";
951 s << exprseq(free_indices) << " vs. " << exprseq(free_indices_of_term);
952 throw (std::runtime_error(s.str()));
954 if (is_a<indexed>(sum) && is_a<indexed>(term))
955 sum = ex_to<basic>(sum.op(0)).add_indexed(sum, term);
962 // If the sum turns out to be zero, we are finished
964 free_indices.clear();
968 // More than one term and more than one dummy index?
969 size_t num_terms_orig = (is_exactly_a<add>(sum) ? sum.nops() : 1);
970 if (num_terms_orig < 2 || dummy_indices.size() < 2)
973 // Yes, construct vector of all dummy index symbols
975 dummy_syms.reserve(dummy_indices.size());
976 for (exvector::const_iterator it = dummy_indices.begin(); it != dummy_indices.end(); ++it)
977 dummy_syms.push_back(it->op(0));
979 // Chop the sum into terms and symmetrize each one over the dummy
981 std::vector<terminfo> terms;
982 for (size_t i=0; i<sum.nops(); i++) {
983 const ex & term = sum.op(i);
984 ex term_symm = symmetrize(term, dummy_syms);
985 if (term_symm.is_zero())
987 terms.push_back(terminfo(term, term_symm));
990 // Sort by symmetrized terms
991 std::sort(terms.begin(), terms.end(), terminfo_is_less());
993 // Combine equal symmetrized terms
994 std::vector<terminfo> terms_pass2;
995 for (std::vector<terminfo>::const_iterator i=terms.begin(); i!=terms.end(); ) {
997 std::vector<terminfo>::const_iterator j = i + 1;
998 while (j != terms.end() && j->symm == i->symm) {
1002 terms_pass2.push_back(terminfo(i->orig * num, i->symm * num));
1006 // If there is only one term left, we are finished
1007 if (terms_pass2.size() == 1)
1008 return terms_pass2[0].orig;
1010 // Chop the symmetrized terms into subterms
1011 std::vector<symminfo> sy;
1012 for (std::vector<terminfo>::const_iterator i=terms_pass2.begin(); i!=terms_pass2.end(); ++i) {
1013 if (is_exactly_a<add>(i->symm)) {
1014 size_t num = i->symm.nops();
1015 for (size_t j=0; j<num; j++)
1016 sy.push_back(symminfo(i->symm.op(j), i->orig, num));
1018 sy.push_back(symminfo(i->symm, i->orig, 1));
1021 // Sort by symmetrized subterms
1022 std::sort(sy.begin(), sy.end(), symminfo_is_less_by_symmterm());
1024 // Combine equal symmetrized subterms
1025 std::vector<symminfo> sy_pass2;
1027 for (std::vector<symminfo>::const_iterator i=sy.begin(); i!=sy.end(); ) {
1029 // Combine equal terms
1030 std::vector<symminfo>::const_iterator j = i + 1;
1031 if (j != sy.end() && j->symmterm == i->symmterm) {
1033 // More than one term, collect the coefficients
1034 ex coeff = i->coeff;
1035 while (j != sy.end() && j->symmterm == i->symmterm) {
1040 // Add combined term to result
1041 if (!coeff.is_zero())
1042 result.push_back(coeff * i->symmterm);
1046 // Single term, store for second pass
1047 sy_pass2.push_back(*i);
1053 // Were there any remaining terms that didn't get combined?
1054 if (sy_pass2.size() > 0) {
1056 // Yes, sort by their original terms
1057 std::sort(sy_pass2.begin(), sy_pass2.end(), symminfo_is_less_by_orig());
1059 for (std::vector<symminfo>::const_iterator i=sy_pass2.begin(); i!=sy_pass2.end(); ) {
1061 // How many symmetrized terms of this original term are left?
1063 std::vector<symminfo>::const_iterator j = i + 1;
1064 while (j != sy_pass2.end() && j->orig == i->orig) {
1069 if (num == i->num) {
1071 // All terms left, then add the original term to the result
1072 result.push_back(i->orig);
1076 // Some terms were combined with others, add up the remaining symmetrized terms
1077 std::vector<symminfo>::const_iterator k;
1078 for (k=i; k!=j; k++)
1079 result.push_back(k->coeff * k->symmterm);
1086 // Add all resulting terms
1087 ex sum_symm = (new add(result))->setflag(status_flags::dynallocated);
1088 if (sum_symm.is_zero())
1089 free_indices.clear();
1093 // Simplification of products
1094 if (is_exactly_a<mul>(e_expanded)
1095 || is_exactly_a<ncmul>(e_expanded)
1096 || (is_exactly_a<power>(e_expanded) && is_a<indexed>(e_expanded.op(0)) && e_expanded.op(1).is_equal(_ex2)))
1097 return simplify_indexed_product(e_expanded, free_indices, dummy_indices, sp);
1099 // Cannot do anything
1100 free_indices.clear();
1104 /** Simplify/canonicalize expression containing indexed objects. This
1105 * performs contraction of dummy indices where possible and checks whether
1106 * the free indices in sums are consistent.
1108 * @return simplified expression */
1109 ex ex::simplify_indexed() const
1111 exvector free_indices, dummy_indices;
1113 return GiNaC::simplify_indexed(*this, free_indices, dummy_indices, sp);
1116 /** Simplify/canonicalize expression containing indexed objects. This
1117 * performs contraction of dummy indices where possible, checks whether
1118 * the free indices in sums are consistent, and automatically replaces
1119 * scalar products by known values if desired.
1121 * @param sp Scalar products to be replaced automatically
1122 * @return simplified expression */
1123 ex ex::simplify_indexed(const scalar_products & sp) const
1125 exvector free_indices, dummy_indices;
1126 return GiNaC::simplify_indexed(*this, free_indices, dummy_indices, sp);
1129 /** Symmetrize expression over its free indices. */
1130 ex ex::symmetrize() const
1132 return GiNaC::symmetrize(*this, get_free_indices());
1135 /** Antisymmetrize expression over its free indices. */
1136 ex ex::antisymmetrize() const
1138 return GiNaC::antisymmetrize(*this, get_free_indices());
1141 /** Symmetrize expression by cyclic permutation over its free indices. */
1142 ex ex::symmetrize_cyclic() const
1144 return GiNaC::symmetrize_cyclic(*this, get_free_indices());
1151 spmapkey::spmapkey(const ex & v1_, const ex & v2_, const ex & dim_) : dim(dim_)
1153 // If indexed, extract base objects
1154 ex s1 = is_a<indexed>(v1_) ? v1_.op(0) : v1_;
1155 ex s2 = is_a<indexed>(v2_) ? v2_.op(0) : v2_;
1157 // Enforce canonical order in pair
1158 if (s1.compare(s2) > 0) {
1167 bool spmapkey::operator==(const spmapkey &other) const
1169 if (!v1.is_equal(other.v1))
1171 if (!v2.is_equal(other.v2))
1173 if (is_a<wildcard>(dim) || is_a<wildcard>(other.dim))
1176 return dim.is_equal(other.dim);
1179 bool spmapkey::operator<(const spmapkey &other) const
1181 int cmp = v1.compare(other.v1);
1184 cmp = v2.compare(other.v2);
1188 // Objects are equal, now check dimensions
1189 if (is_a<wildcard>(dim) || is_a<wildcard>(other.dim))
1192 return dim.compare(other.dim) < 0;
1195 void spmapkey::debugprint() const
1197 std::cerr << "(" << v1 << "," << v2 << "," << dim << ")";
1200 void scalar_products::add(const ex & v1, const ex & v2, const ex & sp)
1202 spm[spmapkey(v1, v2)] = sp;
1205 void scalar_products::add(const ex & v1, const ex & v2, const ex & dim, const ex & sp)
1207 spm[spmapkey(v1, v2, dim)] = sp;
1210 void scalar_products::add_vectors(const lst & l, const ex & dim)
1212 // Add all possible pairs of products
1213 for (lst::const_iterator it1 = l.begin(); it1 != l.end(); ++it1)
1214 for (lst::const_iterator it2 = l.begin(); it2 != l.end(); ++it2)
1215 add(*it1, *it2, *it1 * *it2);
1218 void scalar_products::clear()
1223 /** Check whether scalar product pair is defined. */
1224 bool scalar_products::is_defined(const ex & v1, const ex & v2, const ex & dim) const
1226 return spm.find(spmapkey(v1, v2, dim)) != spm.end();
1229 /** Return value of defined scalar product pair. */
1230 ex scalar_products::evaluate(const ex & v1, const ex & v2, const ex & dim) const
1232 return spm.find(spmapkey(v1, v2, dim))->second;
1235 void scalar_products::debugprint() const
1237 std::cerr << "map size=" << spm.size() << std::endl;
1238 spmap::const_iterator i = spm.begin(), end = spm.end();
1240 const spmapkey & k = i->first;
1241 std::cerr << "item key=";
1243 std::cerr << ", value=" << i->second << std::endl;
1248 } // namespace GiNaC