3 * Implementation of GiNaC's indexed expressions. */
6 * GiNaC Copyright (C) 1999-2001 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
39 GINAC_IMPLEMENT_REGISTERED_CLASS(indexed, exprseq)
42 // default constructor, destructor, copy constructor assignment operator and helpers
45 indexed::indexed() : symmetry(unknown)
47 debugmsg("indexed default constructor", LOGLEVEL_CONSTRUCT);
48 tinfo_key = TINFO_indexed;
51 void indexed::copy(const indexed & other)
53 inherited::copy(other);
54 symmetry = other.symmetry;
57 DEFAULT_DESTROY(indexed)
63 indexed::indexed(const ex & b) : inherited(b), symmetry(unknown)
65 debugmsg("indexed constructor from ex", LOGLEVEL_CONSTRUCT);
66 tinfo_key = TINFO_indexed;
67 assert_all_indices_of_type_idx();
70 indexed::indexed(const ex & b, const ex & i1) : inherited(b, i1), symmetry(unknown)
72 debugmsg("indexed constructor from ex,ex", LOGLEVEL_CONSTRUCT);
73 tinfo_key = TINFO_indexed;
74 assert_all_indices_of_type_idx();
77 indexed::indexed(const ex & b, const ex & i1, const ex & i2) : inherited(b, i1, i2), symmetry(unknown)
79 debugmsg("indexed constructor from ex,ex,ex", LOGLEVEL_CONSTRUCT);
80 tinfo_key = TINFO_indexed;
81 assert_all_indices_of_type_idx();
84 indexed::indexed(const ex & b, const ex & i1, const ex & i2, const ex & i3) : inherited(b, i1, i2, i3), symmetry(unknown)
86 debugmsg("indexed constructor from ex,ex,ex,ex", LOGLEVEL_CONSTRUCT);
87 tinfo_key = TINFO_indexed;
88 assert_all_indices_of_type_idx();
91 indexed::indexed(const ex & b, const ex & i1, const ex & i2, const ex & i3, const ex & i4) : inherited(b, i1, i2, i3, i4), symmetry(unknown)
93 debugmsg("indexed constructor from ex,ex,ex,ex,ex", LOGLEVEL_CONSTRUCT);
94 tinfo_key = TINFO_indexed;
95 assert_all_indices_of_type_idx();
98 indexed::indexed(const ex & b, symmetry_type symm, const ex & i1, const ex & i2) : inherited(b, i1, i2), symmetry(symm)
100 debugmsg("indexed constructor from ex,symmetry,ex,ex", LOGLEVEL_CONSTRUCT);
101 tinfo_key = TINFO_indexed;
102 assert_all_indices_of_type_idx();
105 indexed::indexed(const ex & b, symmetry_type symm, const ex & i1, const ex & i2, const ex & i3) : inherited(b, i1, i2, i3), symmetry(symm)
107 debugmsg("indexed constructor from ex,symmetry,ex,ex,ex", LOGLEVEL_CONSTRUCT);
108 tinfo_key = TINFO_indexed;
109 assert_all_indices_of_type_idx();
112 indexed::indexed(const ex & b, symmetry_type symm, const ex & i1, const ex & i2, const ex & i3, const ex & i4) : inherited(b, i1, i2, i3, i4), symmetry(symm)
114 debugmsg("indexed constructor from ex,symmetry,ex,ex,ex,ex", LOGLEVEL_CONSTRUCT);
115 tinfo_key = TINFO_indexed;
116 assert_all_indices_of_type_idx();
119 indexed::indexed(const ex & b, const exvector & v) : inherited(b), symmetry(unknown)
121 debugmsg("indexed constructor from ex,exvector", LOGLEVEL_CONSTRUCT);
122 seq.insert(seq.end(), v.begin(), v.end());
123 tinfo_key = TINFO_indexed;
124 assert_all_indices_of_type_idx();
127 indexed::indexed(const ex & b, symmetry_type symm, const exvector & v) : inherited(b), symmetry(symm)
129 debugmsg("indexed constructor from ex,symmetry,exvector", LOGLEVEL_CONSTRUCT);
130 seq.insert(seq.end(), v.begin(), v.end());
131 tinfo_key = TINFO_indexed;
132 assert_all_indices_of_type_idx();
135 indexed::indexed(symmetry_type symm, const exprseq & es) : inherited(es), symmetry(symm)
137 debugmsg("indexed constructor from symmetry,exprseq", LOGLEVEL_CONSTRUCT);
138 tinfo_key = TINFO_indexed;
139 assert_all_indices_of_type_idx();
142 indexed::indexed(symmetry_type symm, const exvector & v, bool discardable) : inherited(v, discardable), symmetry(symm)
144 debugmsg("indexed constructor from symmetry,exvector", LOGLEVEL_CONSTRUCT);
145 tinfo_key = TINFO_indexed;
146 assert_all_indices_of_type_idx();
149 indexed::indexed(symmetry_type symm, exvector * vp) : inherited(vp), symmetry(symm)
151 debugmsg("indexed constructor from symmetry,exvector *", LOGLEVEL_CONSTRUCT);
152 tinfo_key = TINFO_indexed;
153 assert_all_indices_of_type_idx();
160 indexed::indexed(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
162 debugmsg("indexed constructor from archive_node", LOGLEVEL_CONSTRUCT);
164 if (!(n.find_unsigned("symmetry", symm)))
165 throw (std::runtime_error("unknown indexed symmetry type in archive"));
168 void indexed::archive(archive_node &n) const
170 inherited::archive(n);
171 n.add_unsigned("symmetry", symmetry);
174 DEFAULT_UNARCHIVE(indexed)
177 // functions overriding virtual functions from bases classes
180 void indexed::print(const print_context & c, unsigned level) const
182 debugmsg("indexed print", LOGLEVEL_PRINT);
183 GINAC_ASSERT(seq.size() > 0);
185 if (is_of_type(c, print_tree)) {
187 c.s << std::string(level, ' ') << class_name()
188 << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
189 << ", " << seq.size()-1 << " indices";
191 case symmetric: c.s << ", symmetric"; break;
192 case antisymmetric: c.s << ", antisymmetric"; break;
196 unsigned delta_indent = static_cast<const print_tree &>(c).delta_indent;
197 seq[0].print(c, level + delta_indent);
198 printindices(c, level + delta_indent);
202 bool is_tex = is_of_type(c, print_latex);
203 const ex & base = seq[0];
204 bool need_parens = is_ex_exactly_of_type(base, add) || is_ex_exactly_of_type(base, mul)
205 || is_ex_exactly_of_type(base, ncmul) || is_ex_exactly_of_type(base, power)
206 || is_ex_of_type(base, indexed);
216 printindices(c, level);
220 bool indexed::info(unsigned inf) const
222 if (inf == info_flags::indexed) return true;
223 if (inf == info_flags::has_indices) return seq.size() > 1;
224 return inherited::info(inf);
227 bool indexed::all_index_values_are(unsigned inf) const
229 // No indices? Then no property can be fulfilled
234 exvector::const_iterator it = seq.begin() + 1, itend = seq.end();
235 while (it != itend) {
236 GINAC_ASSERT(is_ex_of_type(*it, idx));
237 if (!ex_to_idx(*it).get_value().info(inf))
244 int indexed::compare_same_type(const basic & other) const
246 GINAC_ASSERT(is_of_type(other, indexed));
247 return inherited::compare_same_type(other);
250 // The main difference between sort_index_vector() and canonicalize_indices()
251 // is that the latter takes the symmetry of the object into account. Once we
252 // implement mixed symmetries, canonicalize_indices() will only be able to
253 // reorder index pairs with known symmetry properties, while sort_index_vector()
254 // always sorts the whole vector.
256 /** Bring a vector of indices into a canonic order (don't care about the
257 * symmetry of the objects carrying the indices). Dummy indices will lie
258 * next to each other after the sorting.
260 * @param v Index vector to be sorted */
261 static void sort_index_vector(exvector &v)
263 // Nothing to sort if less than 2 elements
267 // Simple bubble sort algorithm should be sufficient for the small
268 // number of indices expected
269 exvector::iterator it1 = v.begin(), itend = v.end(), next_to_last_idx = itend - 1;
270 while (it1 != next_to_last_idx) {
271 exvector::iterator it2 = it1 + 1;
272 while (it2 != itend) {
273 if (it1->compare(*it2) > 0)
281 /** Bring a vector of indices into a canonic order. This operation only makes
282 * sense if the object carrying these indices is either symmetric or totally
283 * antisymmetric with respect to the indices.
285 * @param itbegin Start of index vector
286 * @param itend End of index vector
287 * @param antisymm Whether the object is antisymmetric
288 * @return the sign introduced by the reordering of the indices if the object
289 * is antisymmetric (or 0 if two equal indices are encountered). For
290 * symmetric objects, this is always +1. If the index vector was
291 * already in a canonic order this function returns INT_MAX. */
292 static int canonicalize_indices(exvector::iterator itbegin, exvector::iterator itend, bool antisymm)
294 bool something_changed = false;
297 // Simple bubble sort algorithm should be sufficient for the small
298 // number of indices expected
299 exvector::iterator it1 = itbegin, next_to_last_idx = itend - 1;
300 while (it1 != next_to_last_idx) {
301 exvector::iterator it2 = it1 + 1;
302 while (it2 != itend) {
303 int cmpval = it1->compare(*it2);
306 something_changed = true;
309 } else if (cmpval == 0 && antisymm) {
310 something_changed = true;
318 return something_changed ? sig : INT_MAX;
321 ex indexed::eval(int level) const
323 // First evaluate children, then we will end up here again
325 return indexed(symmetry, evalchildren(level));
327 const ex &base = seq[0];
329 // If the base object is 0, the whole object is 0
333 // If the base object is a product, pull out the numeric factor
334 if (is_ex_exactly_of_type(base, mul) && is_ex_exactly_of_type(base.op(base.nops() - 1), numeric)) {
336 ex f = ex_to_numeric(base.op(base.nops() - 1));
338 return f * thisexprseq(v);
341 // Canonicalize indices according to the symmetry properties
342 if (seq.size() > 2 && (symmetry != unknown && symmetry != mixed)) {
344 int sig = canonicalize_indices(v.begin() + 1, v.end(), symmetry == antisymmetric);
345 if (sig != INT_MAX) {
346 // Something has changed while sorting indices, more evaluations later
349 return ex(sig) * thisexprseq(v);
353 // Let the class of the base object perform additional evaluations
354 return base.bp->eval_indexed(*this);
357 int indexed::degree(const ex & s) const
359 return is_equal(*s.bp) ? 1 : 0;
362 int indexed::ldegree(const ex & s) const
364 return is_equal(*s.bp) ? 1 : 0;
367 ex indexed::coeff(const ex & s, int n) const
370 return n==1 ? _ex1() : _ex0();
372 return n==0 ? ex(*this) : _ex0();
375 ex indexed::thisexprseq(const exvector & v) const
377 return indexed(symmetry, v);
380 ex indexed::thisexprseq(exvector * vp) const
382 return indexed(symmetry, vp);
385 ex indexed::expand(unsigned options) const
387 GINAC_ASSERT(seq.size() > 0);
389 if ((options & expand_options::expand_indexed) && is_ex_exactly_of_type(seq[0], add)) {
391 // expand_indexed expands (a+b).i -> a.i + b.i
392 const ex & base = seq[0];
394 for (unsigned i=0; i<base.nops(); i++) {
397 sum += thisexprseq(s).expand();
402 return inherited::expand(options);
406 // virtual functions which can be overridden by derived classes
412 // non-virtual functions in this class
415 void indexed::printindices(const print_context & c, unsigned level) const
417 if (seq.size() > 1) {
419 exvector::const_iterator it=seq.begin() + 1, itend = seq.end();
421 if (is_of_type(c, print_latex)) {
423 // TeX output: group by variance
425 bool covariant = true;
427 while (it != itend) {
428 bool cur_covariant = (is_ex_of_type(*it, varidx) ? ex_to_varidx(*it).is_covariant() : true);
429 if (first || cur_covariant != covariant) {
432 covariant = cur_covariant;
448 while (it != itend) {
456 /** Check whether all indices are of class idx. This function is used
457 * internally to make sure that all constructed indexed objects really
458 * carry indices and not some other classes. */
459 void indexed::assert_all_indices_of_type_idx(void) const
461 GINAC_ASSERT(seq.size() > 0);
462 exvector::const_iterator it = seq.begin() + 1, itend = seq.end();
463 while (it != itend) {
464 if (!is_ex_of_type(*it, idx))
465 throw(std::invalid_argument("indices of indexed object must be of type idx"));
474 /** Check whether two sorted index vectors are consistent (i.e. equal). */
475 static bool indices_consistent(const exvector & v1, const exvector & v2)
477 // Number of indices must be the same
478 if (v1.size() != v2.size())
481 // And also the indices themselves
482 exvector::const_iterator ait = v1.begin(), aitend = v1.end(),
483 bit = v2.begin(), bitend = v2.end();
484 while (ait != aitend) {
485 if (!ait->is_equal(*bit))
492 exvector indexed::get_indices(void) const
494 GINAC_ASSERT(seq.size() >= 1);
495 return exvector(seq.begin() + 1, seq.end());
498 exvector indexed::get_dummy_indices(void) const
500 exvector free_indices, dummy_indices;
501 find_free_and_dummy(seq.begin() + 1, seq.end(), free_indices, dummy_indices);
502 return dummy_indices;
505 exvector indexed::get_dummy_indices(const indexed & other) const
507 exvector indices = get_free_indices();
508 exvector other_indices = other.get_free_indices();
509 indices.insert(indices.end(), other_indices.begin(), other_indices.end());
510 exvector dummy_indices;
511 find_dummy_indices(indices, dummy_indices);
512 return dummy_indices;
515 exvector indexed::get_free_indices(void) const
517 exvector free_indices, dummy_indices;
518 find_free_and_dummy(seq.begin() + 1, seq.end(), free_indices, dummy_indices);
522 exvector add::get_free_indices(void) const
524 exvector free_indices;
525 for (unsigned i=0; i<nops(); i++) {
527 free_indices = op(i).get_free_indices();
529 exvector free_indices_of_term = op(i).get_free_indices();
530 if (!indices_consistent(free_indices, free_indices_of_term))
531 throw (std::runtime_error("add::get_free_indices: inconsistent indices in sum"));
537 exvector mul::get_free_indices(void) const
539 // Concatenate free indices of all factors
541 for (unsigned i=0; i<nops(); i++) {
542 exvector free_indices_of_factor = op(i).get_free_indices();
543 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
546 // And remove the dummy indices
547 exvector free_indices, dummy_indices;
548 find_free_and_dummy(un, free_indices, dummy_indices);
552 exvector ncmul::get_free_indices(void) const
554 // Concatenate free indices of all factors
556 for (unsigned i=0; i<nops(); i++) {
557 exvector free_indices_of_factor = op(i).get_free_indices();
558 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
561 // And remove the dummy indices
562 exvector free_indices, dummy_indices;
563 find_free_and_dummy(un, free_indices, dummy_indices);
567 exvector power::get_free_indices(void) const
569 // Return free indices of basis
570 return basis.get_free_indices();
573 /** Simplify product of indexed expressions (commutative, noncommutative and
574 * simple squares), return list of free indices. */
575 ex simplify_indexed_product(const ex & e, exvector & free_indices, const scalar_products & sp)
577 // Remember whether the product was commutative or noncommutative
578 // (because we chop it into factors and need to reassemble later)
579 bool non_commutative = is_ex_exactly_of_type(e, ncmul);
581 // Collect factors in an exvector, store squares twice
583 v.reserve(e.nops() * 2);
585 if (is_ex_exactly_of_type(e, power)) {
586 // We only get called for simple squares, split a^2 -> a*a
587 GINAC_ASSERT(e.op(1).is_equal(_ex2()));
588 v.push_back(e.op(0));
589 v.push_back(e.op(0));
591 for (int i=0; i<e.nops(); i++) {
593 if (is_ex_exactly_of_type(f, power) && f.op(1).is_equal(_ex2())) {
594 v.push_back(f.op(0));
595 v.push_back(f.op(0));
596 } else if (is_ex_exactly_of_type(f, ncmul)) {
597 // Noncommutative factor found, split it as well
598 non_commutative = true; // everything becomes noncommutative, ncmul will sort out the commutative factors later
599 for (int j=0; j<f.nops(); j++)
600 v.push_back(f.op(j));
606 // Perform contractions
607 bool something_changed = false;
608 GINAC_ASSERT(v.size() > 1);
609 exvector::iterator it1, itend = v.end(), next_to_last = itend - 1;
610 for (it1 = v.begin(); it1 != next_to_last; it1++) {
613 if (!is_ex_of_type(*it1, indexed))
616 // Indexed factor found, get free indices and look for contraction
618 exvector free1, dummy1;
619 find_free_and_dummy(ex_to_indexed(*it1).seq.begin() + 1, ex_to_indexed(*it1).seq.end(), free1, dummy1);
621 exvector::iterator it2;
622 for (it2 = it1 + 1; it2 != itend; it2++) {
624 if (!is_ex_of_type(*it2, indexed))
627 // Find free indices of second factor and merge them with free
628 // indices of first factor
630 find_free_and_dummy(ex_to_indexed(*it2).seq.begin() + 1, ex_to_indexed(*it2).seq.end(), un, dummy1);
631 un.insert(un.end(), free1.begin(), free1.end());
633 // Check whether the two factors share dummy indices
634 exvector free, dummy;
635 find_free_and_dummy(un, free, dummy);
636 if (dummy.size() == 0)
639 // At least one dummy index, is it a defined scalar product?
640 bool contracted = false;
641 if (free.size() == 0) {
642 if (sp.is_defined(*it1, *it2)) {
643 *it1 = sp.evaluate(*it1, *it2);
645 goto contraction_done;
649 // Contraction of symmetric with antisymmetric object is zero
650 if ((ex_to_indexed(*it1).symmetry == indexed::symmetric &&
651 ex_to_indexed(*it2).symmetry == indexed::antisymmetric
652 || ex_to_indexed(*it1).symmetry == indexed::antisymmetric &&
653 ex_to_indexed(*it2).symmetry == indexed::symmetric)
654 && dummy.size() > 1) {
655 free_indices.clear();
659 // Try to contract the first one with the second one
660 contracted = it1->op(0).bp->contract_with(it1, it2, v);
663 // That didn't work; maybe the second object knows how to
664 // contract itself with the first one
665 contracted = it2->op(0).bp->contract_with(it2, it1, v);
669 if (is_ex_exactly_of_type(*it1, add) || is_ex_exactly_of_type(*it2, add)
670 || is_ex_exactly_of_type(*it1, mul) || is_ex_exactly_of_type(*it2, mul)
671 || is_ex_exactly_of_type(*it1, ncmul) || is_ex_exactly_of_type(*it2, ncmul)) {
673 // One of the factors became a sum or product:
674 // re-expand expression and run again
675 ex r = (non_commutative ? ex(ncmul(v)) : ex(mul(v)));
676 return simplify_indexed(r, free_indices, sp);
679 // Both objects may have new indices now or they might
680 // even not be indexed objects any more, so we have to
682 something_changed = true;
688 // Find free indices (concatenate them all and call find_free_and_dummy())
689 exvector un, dummy_indices;
690 it1 = v.begin(); itend = v.end();
691 while (it1 != itend) {
692 exvector free_indices_of_factor = it1->get_free_indices();
693 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
696 find_free_and_dummy(un, free_indices, dummy_indices);
699 if (something_changed)
700 r = non_commutative ? ex(ncmul(v)) : ex(mul(v));
704 // Product of indexed object with a scalar?
705 if (is_ex_exactly_of_type(r, mul) && r.nops() == 2
706 && is_ex_exactly_of_type(r.op(1), numeric) && is_ex_of_type(r.op(0), indexed))
707 return r.op(0).op(0).bp->scalar_mul_indexed(r.op(0), ex_to_numeric(r.op(1)));
712 /** Simplify indexed expression, return list of free indices. */
713 ex simplify_indexed(const ex & e, exvector & free_indices, const scalar_products & sp)
715 // Expand the expression
716 ex e_expanded = e.expand();
718 // Simplification of single indexed object: just find the free indices
719 if (is_ex_of_type(e_expanded, indexed)) {
720 const indexed &i = ex_to_indexed(e_expanded);
721 exvector dummy_indices;
722 find_free_and_dummy(i.seq.begin() + 1, i.seq.end(), free_indices, dummy_indices);
726 // Simplification of sum = sum of simplifications, check consistency of
727 // free indices in each term
728 if (is_ex_exactly_of_type(e_expanded, add)) {
731 free_indices.clear();
733 for (unsigned i=0; i<e_expanded.nops(); i++) {
734 exvector free_indices_of_term;
735 ex term = simplify_indexed(e_expanded.op(i), free_indices_of_term, sp);
736 if (!term.is_zero()) {
738 free_indices = free_indices_of_term;
742 if (!indices_consistent(free_indices, free_indices_of_term))
743 throw (std::runtime_error("simplify_indexed: inconsistent indices in sum"));
744 if (is_ex_of_type(sum, indexed) && is_ex_of_type(term, indexed))
745 sum = sum.op(0).bp->add_indexed(sum, term);
755 // Simplification of products
756 if (is_ex_exactly_of_type(e_expanded, mul)
757 || is_ex_exactly_of_type(e_expanded, ncmul)
758 || (is_ex_exactly_of_type(e_expanded, power) && is_ex_of_type(e_expanded.op(0), indexed) && e_expanded.op(1).is_equal(_ex2())))
759 return simplify_indexed_product(e_expanded, free_indices, sp);
761 // Cannot do anything
762 free_indices.clear();
766 ex simplify_indexed(const ex & e)
768 exvector free_indices;
770 return simplify_indexed(e, free_indices, sp);
773 ex simplify_indexed(const ex & e, const scalar_products & sp)
775 exvector free_indices;
776 return simplify_indexed(e, free_indices, sp);
783 void scalar_products::add(const ex & v1, const ex & v2, const ex & sp)
785 spm[make_key(v1, v2)] = sp;
788 void scalar_products::clear(void)
793 /** Check whether scalar product pair is defined. */
794 bool scalar_products::is_defined(const ex & v1, const ex & v2) const
796 return spm.find(make_key(v1, v2)) != spm.end();
799 /** Return value of defined scalar product pair. */
800 ex scalar_products::evaluate(const ex & v1, const ex & v2) const
802 return spm.find(make_key(v1, v2))->second;
805 void scalar_products::debugprint(void) const
807 std::cerr << "map size=" << spm.size() << std::endl;
808 for (spmap::const_iterator cit=spm.begin(); cit!=spm.end(); ++cit) {
809 const spmapkey & k = cit->first;
810 std::cerr << "item key=(" << k.first << "," << k.second;
811 std::cerr << "), value=" << cit->second << std::endl;
815 /** Make key from object pair. */
816 spmapkey scalar_products::make_key(const ex & v1, const ex & v2)
818 // If indexed, extract base objects
819 ex s1 = is_ex_of_type(v1, indexed) ? v1.op(0) : v1;
820 ex s2 = is_ex_of_type(v2, indexed) ? v2.op(0) : v2;
822 // Enforce canonical order in pair
823 if (s1.compare(s2) > 0)
824 return spmapkey(s2, s1);
826 return spmapkey(s1, s2);