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
37 GINAC_IMPLEMENT_REGISTERED_CLASS(indexed, exprseq)
40 // default constructor, destructor, copy constructor assignment operator and helpers
43 indexed::indexed() : symmetry(unknown)
45 debugmsg("indexed default constructor", LOGLEVEL_CONSTRUCT);
46 tinfo_key = TINFO_indexed;
49 void indexed::copy(const indexed & other)
51 inherited::copy(other);
52 symmetry = other.symmetry;
55 DEFAULT_DESTROY(indexed)
61 indexed::indexed(const ex & b) : inherited(b), symmetry(unknown)
63 debugmsg("indexed constructor from ex", LOGLEVEL_CONSTRUCT);
64 tinfo_key = TINFO_indexed;
65 assert_all_indices_of_type_idx();
68 indexed::indexed(const ex & b, const ex & i1) : inherited(b, i1), symmetry(unknown)
70 debugmsg("indexed constructor from ex,ex", LOGLEVEL_CONSTRUCT);
71 tinfo_key = TINFO_indexed;
72 assert_all_indices_of_type_idx();
75 indexed::indexed(const ex & b, const ex & i1, const ex & i2) : inherited(b, i1, i2), symmetry(unknown)
77 debugmsg("indexed constructor from ex,ex,ex", LOGLEVEL_CONSTRUCT);
78 tinfo_key = TINFO_indexed;
79 assert_all_indices_of_type_idx();
82 indexed::indexed(const ex & b, const ex & i1, const ex & i2, const ex & i3) : inherited(b, i1, i2, i3), symmetry(unknown)
84 debugmsg("indexed constructor from ex,ex,ex,ex", LOGLEVEL_CONSTRUCT);
85 tinfo_key = TINFO_indexed;
86 assert_all_indices_of_type_idx();
89 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)
91 debugmsg("indexed constructor from ex,ex,ex,ex,ex", LOGLEVEL_CONSTRUCT);
92 tinfo_key = TINFO_indexed;
93 assert_all_indices_of_type_idx();
96 indexed::indexed(const ex & b, symmetry_type symm, const ex & i1, const ex & i2) : inherited(b, i1, i2), symmetry(symm)
98 debugmsg("indexed constructor from ex,symmetry,ex,ex", LOGLEVEL_CONSTRUCT);
99 tinfo_key = TINFO_indexed;
100 assert_all_indices_of_type_idx();
103 indexed::indexed(const ex & b, symmetry_type symm, const ex & i1, const ex & i2, const ex & i3) : inherited(b, i1, i2, i3), symmetry(symm)
105 debugmsg("indexed constructor from ex,symmetry,ex,ex,ex", LOGLEVEL_CONSTRUCT);
106 tinfo_key = TINFO_indexed;
107 assert_all_indices_of_type_idx();
110 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)
112 debugmsg("indexed constructor from ex,symmetry,ex,ex,ex,ex", LOGLEVEL_CONSTRUCT);
113 tinfo_key = TINFO_indexed;
114 assert_all_indices_of_type_idx();
117 indexed::indexed(const ex & b, const exvector & v) : inherited(b), symmetry(unknown)
119 debugmsg("indexed constructor from ex,exvector", LOGLEVEL_CONSTRUCT);
120 seq.insert(seq.end(), v.begin(), v.end());
121 tinfo_key = TINFO_indexed;
122 assert_all_indices_of_type_idx();
125 indexed::indexed(const ex & b, symmetry_type symm, const exvector & v) : inherited(b), symmetry(symm)
127 debugmsg("indexed constructor from ex,symmetry,exvector", LOGLEVEL_CONSTRUCT);
128 seq.insert(seq.end(), v.begin(), v.end());
129 tinfo_key = TINFO_indexed;
130 assert_all_indices_of_type_idx();
133 indexed::indexed(symmetry_type symm, const exprseq & es) : inherited(es), symmetry(symm)
135 debugmsg("indexed constructor from symmetry,exprseq", LOGLEVEL_CONSTRUCT);
136 tinfo_key = TINFO_indexed;
137 assert_all_indices_of_type_idx();
140 indexed::indexed(symmetry_type symm, const exvector & v, bool discardable) : inherited(v, discardable), symmetry(symm)
142 debugmsg("indexed constructor from symmetry,exvector", LOGLEVEL_CONSTRUCT);
143 tinfo_key = TINFO_indexed;
144 assert_all_indices_of_type_idx();
147 indexed::indexed(symmetry_type symm, exvector * vp) : inherited(vp), symmetry(symm)
149 debugmsg("indexed constructor from symmetry,exvector *", LOGLEVEL_CONSTRUCT);
150 tinfo_key = TINFO_indexed;
151 assert_all_indices_of_type_idx();
158 indexed::indexed(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
160 debugmsg("indexed constructor from archive_node", LOGLEVEL_CONSTRUCT);
162 if (!(n.find_unsigned("symmetry", symm)))
163 throw (std::runtime_error("unknown indexed symmetry type in archive"));
166 void indexed::archive(archive_node &n) const
168 inherited::archive(n);
169 n.add_unsigned("symmetry", symmetry);
172 DEFAULT_UNARCHIVE(indexed)
175 // functions overriding virtual functions from bases classes
178 void indexed::printraw(std::ostream & os) const
180 debugmsg("indexed printraw", LOGLEVEL_PRINT);
181 GINAC_ASSERT(seq.size() > 0);
183 os << class_name() << "(";
187 os << ",hash=" << hashvalue << ",flags=" << flags << ")";
190 void indexed::printtree(std::ostream & os, unsigned indent) const
192 debugmsg("indexed printtree", LOGLEVEL_PRINT);
193 GINAC_ASSERT(seq.size() > 0);
195 os << std::string(indent, ' ') << class_name() << ", " << seq.size()-1 << " indices";
196 os << ",hash=" << hashvalue << ",flags=" << flags << std::endl;
197 printtreeindices(os, indent);
200 void indexed::print(std::ostream & os, unsigned upper_precedence) const
202 debugmsg("indexed print", LOGLEVEL_PRINT);
203 GINAC_ASSERT(seq.size() > 0);
205 const ex & base = seq[0];
206 bool need_parens = is_ex_exactly_of_type(base, add) || is_ex_exactly_of_type(base, mul)
207 || is_ex_exactly_of_type(base, ncmul) || is_ex_exactly_of_type(base, power);
216 bool indexed::info(unsigned inf) const
218 if (inf == info_flags::indexed) return true;
219 if (inf == info_flags::has_indices) return seq.size() > 1;
220 return inherited::info(inf);
223 bool indexed::all_index_values_are(unsigned inf) const
225 // No indices? Then no property can be fulfilled
230 exvector::const_iterator it = seq.begin() + 1, itend = seq.end();
231 while (it != itend) {
232 GINAC_ASSERT(is_ex_of_type(*it, idx));
233 if (!ex_to_idx(*it).get_value().info(inf))
240 int indexed::compare_same_type(const basic & other) const
242 GINAC_ASSERT(is_of_type(other, indexed));
243 return inherited::compare_same_type(other);
246 // The main difference between sort_index_vector() and canonicalize_indices()
247 // is that the latter takes the symmetry of the object into account. Once we
248 // implement mixed symmetries, canonicalize_indices() will only be able to
249 // reorder index pairs with known symmetry properties, while sort_index_vector()
250 // always sorts the whole vector.
252 /** Bring a vector of indices into a canonic order (don't care about the
253 * symmetry of the objects carrying the indices). Dummy indices will lie
254 * next to each other after the sorting.
256 * @param v Index vector to be sorted */
257 static void sort_index_vector(exvector &v)
259 // Nothing to sort if less than 2 elements
263 // Simple bubble sort algorithm should be sufficient for the small
264 // number of indices expected
265 exvector::iterator it1 = v.begin(), itend = v.end(), next_to_last_idx = itend - 1;
266 while (it1 != next_to_last_idx) {
267 exvector::iterator it2 = it1 + 1;
268 while (it2 != itend) {
269 if (it1->compare(*it2) > 0)
277 /** Bring a vector of indices into a canonic order. This operation only makes
278 * sense if the object carrying these indices is either symmetric or totally
279 * antisymmetric with respect to the indices.
281 * @param itbegin Start of index vector
282 * @param itend End of index vector
283 * @param antisymm Whether the object is antisymmetric
284 * @return the sign introduced by the reordering of the indices if the object
285 * is antisymmetric (or 0 if two equal indices are encountered). For
286 * symmetric objects, this is always +1. If the index vector was
287 * already in a canonic order this function returns INT_MAX. */
288 static int canonicalize_indices(exvector::iterator itbegin, exvector::iterator itend, bool antisymm)
290 bool something_changed = false;
293 // Simple bubble sort algorithm should be sufficient for the small
294 // number of indices expected
295 exvector::iterator it1 = itbegin, next_to_last_idx = itend - 1;
296 while (it1 != next_to_last_idx) {
297 exvector::iterator it2 = it1 + 1;
298 while (it2 != itend) {
299 int cmpval = it1->compare(*it2);
302 something_changed = true;
305 } else if (cmpval == 0 && antisymm) {
306 something_changed = true;
314 return something_changed ? sig : INT_MAX;
317 ex indexed::eval(int level) const
319 // First evaluate children, then we will end up here again
321 return indexed(symmetry, evalchildren(level));
323 const ex &base = seq[0];
325 // If the base object is 0, the whole object is 0
329 // If the base object is a product, pull out the numeric factor
330 if (is_ex_exactly_of_type(base, mul) && is_ex_exactly_of_type(base.op(base.nops() - 1), numeric)) {
332 ex f = ex_to_numeric(base.op(base.nops() - 1));
334 return f * thisexprseq(v);
337 // Canonicalize indices according to the symmetry properties
338 if (seq.size() > 2 && (symmetry != unknown && symmetry != mixed)) {
340 int sig = canonicalize_indices(v.begin() + 1, v.end(), symmetry == antisymmetric);
341 if (sig != INT_MAX) {
342 // Something has changed while sorting indices, more evaluations later
345 return ex(sig) * thisexprseq(v);
349 // Let the class of the base object perform additional evaluations
350 return base.bp->eval_indexed(*this);
353 ex indexed::thisexprseq(const exvector & v) const
355 return indexed(symmetry, v);
358 ex indexed::thisexprseq(exvector * vp) const
360 return indexed(symmetry, vp);
363 ex indexed::expand(unsigned options) const
365 GINAC_ASSERT(seq.size() > 0);
367 if ((options & expand_options::expand_indexed) && is_ex_exactly_of_type(seq[0], add)) {
369 // expand_indexed expands (a+b).i -> a.i + b.i
370 const ex & base = seq[0];
372 for (unsigned i=0; i<base.nops(); i++) {
375 sum += thisexprseq(s).expand();
380 return inherited::expand(options);
384 // virtual functions which can be overridden by derived classes
390 // non-virtual functions in this class
393 void indexed::printrawindices(std::ostream & os) const
395 if (seq.size() > 1) {
396 exvector::const_iterator it=seq.begin() + 1, itend = seq.end();
397 while (it != itend) {
406 void indexed::printtreeindices(std::ostream & os, unsigned indent) const
408 if (seq.size() > 1) {
409 exvector::const_iterator it=seq.begin() + 1, itend = seq.end();
410 while (it != itend) {
411 os << std::string(indent + delta_indent, ' ');
419 void indexed::printindices(std::ostream & os) const
421 if (seq.size() > 1) {
422 exvector::const_iterator it=seq.begin() + 1, itend = seq.end();
423 while (it != itend) {
430 /** Check whether all indices are of class idx. This function is used
431 * internally to make sure that all constructed indexed objects really
432 * carry indices and not some other classes. */
433 void indexed::assert_all_indices_of_type_idx(void) const
435 GINAC_ASSERT(seq.size() > 0);
436 exvector::const_iterator it = seq.begin() + 1, itend = seq.end();
437 while (it != itend) {
438 if (!is_ex_of_type(*it, idx))
439 throw(std::invalid_argument("indices of indexed object must be of type idx"));
448 /** Check whether two sorted index vectors are consistent (i.e. equal). */
449 static bool indices_consistent(const exvector & v1, const exvector & v2)
451 // Number of indices must be the same
452 if (v1.size() != v2.size())
455 // And also the indices themselves
456 exvector::const_iterator ait = v1.begin(), aitend = v1.end(),
457 bit = v2.begin(), bitend = v2.end();
458 while (ait != aitend) {
459 if (!ait->is_equal(*bit))
466 exvector indexed::get_indices(void) const
468 GINAC_ASSERT(seq.size() >= 1);
469 return exvector(seq.begin() + 1, seq.end());
472 exvector indexed::get_dummy_indices(void) const
474 exvector free_indices, dummy_indices;
475 find_free_and_dummy(seq.begin() + 1, seq.end(), free_indices, dummy_indices);
476 return dummy_indices;
479 exvector indexed::get_dummy_indices(const indexed & other) const
481 exvector indices = get_free_indices();
482 exvector other_indices = other.get_free_indices();
483 indices.insert(indices.end(), other_indices.begin(), other_indices.end());
484 exvector dummy_indices;
485 find_dummy_indices(indices, dummy_indices);
486 return dummy_indices;
489 exvector indexed::get_free_indices(void) const
491 exvector free_indices, dummy_indices;
492 find_free_and_dummy(seq.begin() + 1, seq.end(), free_indices, dummy_indices);
496 exvector add::get_free_indices(void) const
498 exvector free_indices;
499 for (unsigned i=0; i<nops(); i++) {
501 free_indices = op(i).get_free_indices();
503 exvector free_indices_of_term = op(i).get_free_indices();
504 if (!indices_consistent(free_indices, free_indices_of_term))
505 throw (std::runtime_error("add::get_free_indices: inconsistent indices in sum"));
511 exvector mul::get_free_indices(void) const
513 // Concatenate free indices of all factors
515 for (unsigned i=0; i<nops(); i++) {
516 exvector free_indices_of_factor = op(i).get_free_indices();
517 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
520 // And remove the dummy indices
521 exvector free_indices, dummy_indices;
522 find_free_and_dummy(un, free_indices, dummy_indices);
526 exvector ncmul::get_free_indices(void) const
528 // Concatenate free indices of all factors
530 for (unsigned i=0; i<nops(); i++) {
531 exvector free_indices_of_factor = op(i).get_free_indices();
532 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
535 // And remove the dummy indices
536 exvector free_indices, dummy_indices;
537 find_free_and_dummy(un, free_indices, dummy_indices);
541 exvector power::get_free_indices(void) const
543 // Return free indices of basis
544 return basis.get_free_indices();
547 /** Simplify product of indexed expressions (commutative, noncommutative and
548 * simple squares), return list of free indices. */
549 ex simplify_indexed_product(const ex & e, exvector & free_indices, const scalar_products & sp)
551 // Remember whether the product was commutative or noncommutative
552 // (because we chop it into factors and need to reassemble later)
553 bool non_commutative = is_ex_exactly_of_type(e, ncmul);
555 // Collect factors in an exvector, store squares twice
557 v.reserve(e.nops() * 2);
559 if (is_ex_exactly_of_type(e, power)) {
560 // We only get called for simple squares, split a^2 -> a*a
561 GINAC_ASSERT(e.op(1).is_equal(_ex2()));
562 v.push_back(e.op(0));
563 v.push_back(e.op(0));
565 for (int i=0; i<e.nops(); i++) {
567 if (is_ex_exactly_of_type(f, power) && f.op(1).is_equal(_ex2())) {
568 v.push_back(f.op(0));
569 v.push_back(f.op(0));
570 } else if (is_ex_exactly_of_type(f, ncmul)) {
571 // Noncommutative factor found, split it as well
572 non_commutative = true; // everything becomes noncommutative, ncmul will sort out the commutative factors later
573 for (int j=0; j<f.nops(); j++)
574 v.push_back(f.op(j));
580 // Perform contractions
581 bool something_changed = false;
582 GINAC_ASSERT(v.size() > 1);
583 exvector::iterator it1, itend = v.end(), next_to_last = itend - 1;
584 for (it1 = v.begin(); it1 != next_to_last; it1++) {
587 if (!is_ex_of_type(*it1, indexed))
590 // Indexed factor found, get free indices and look for contraction
592 exvector free1, dummy1;
593 find_free_and_dummy(ex_to_indexed(*it1).seq.begin() + 1, ex_to_indexed(*it1).seq.end(), free1, dummy1);
595 exvector::iterator it2;
596 for (it2 = it1 + 1; it2 != itend; it2++) {
598 if (!is_ex_of_type(*it2, indexed))
601 // Find free indices of second factor and merge them with free
602 // indices of first factor
604 find_free_and_dummy(ex_to_indexed(*it2).seq.begin() + 1, ex_to_indexed(*it2).seq.end(), un, dummy1);
605 un.insert(un.end(), free1.begin(), free1.end());
607 // Check whether the two factors share dummy indices
608 exvector free, dummy;
609 find_free_and_dummy(un, free, dummy);
610 if (dummy.size() == 0)
613 // At least one dummy index, is it a defined scalar product?
614 if (free.size() == 0) {
615 if (sp.is_defined(*it1, *it2)) {
616 *it1 = sp.evaluate(*it1, *it2);
618 something_changed = true;
623 // Contraction of symmetric with antisymmetric object is zero
624 if ((ex_to_indexed(*it1).symmetry == indexed::symmetric &&
625 ex_to_indexed(*it2).symmetry == indexed::antisymmetric
626 || ex_to_indexed(*it1).symmetry == indexed::antisymmetric &&
627 ex_to_indexed(*it2).symmetry == indexed::symmetric)
628 && dummy.size() > 1) {
629 free_indices.clear();
633 // Try to contract the first one with the second one
634 bool contracted = it1->op(0).bp->contract_with(it1, it2, v);
637 // That didn't work; maybe the second object knows how to
638 // contract itself with the first one
639 contracted = it2->op(0).bp->contract_with(it2, it1, v);
642 something_changed = true;
644 // Both objects may have new indices now or they might
645 // even not be indexed objects any more, so we have to
652 // Find free indices (concatenate them all and call find_free_and_dummy())
653 exvector un, dummy_indices;
654 it1 = v.begin(); itend = v.end();
655 while (it1 != itend) {
656 if (is_ex_of_type(*it1, indexed)) {
657 const indexed & o = ex_to_indexed(*it1);
658 un.insert(un.end(), o.seq.begin() + 1, o.seq.end());
662 find_free_and_dummy(un, free_indices, dummy_indices);
665 if (something_changed) {
673 // Product of indexed object with a scalar?
674 if (is_ex_exactly_of_type(r, mul) && r.nops() == 2
675 && is_ex_exactly_of_type(r.op(1), numeric) && is_ex_of_type(r.op(0), indexed))
676 return r.op(0).op(0).bp->scalar_mul_indexed(r.op(0), ex_to_numeric(r.op(1)));
681 /** Simplify indexed expression, return list of free indices. */
682 ex simplify_indexed(const ex & e, exvector & free_indices, const scalar_products & sp)
684 // Expand the expression
685 ex e_expanded = e.expand();
687 // Simplification of single indexed object: just find the free indices
688 if (is_ex_of_type(e_expanded, indexed)) {
689 const indexed &i = ex_to_indexed(e_expanded);
690 exvector dummy_indices;
691 find_free_and_dummy(i.seq.begin() + 1, i.seq.end(), free_indices, dummy_indices);
695 // Simplification of sum = sum of simplifications, check consistency of
696 // free indices in each term
697 if (is_ex_exactly_of_type(e_expanded, add)) {
700 free_indices.clear();
702 for (unsigned i=0; i<e_expanded.nops(); i++) {
703 exvector free_indices_of_term;
704 ex term = simplify_indexed(e_expanded.op(i), free_indices_of_term, sp);
705 if (!term.is_zero()) {
707 free_indices = free_indices_of_term;
711 if (!indices_consistent(free_indices, free_indices_of_term))
712 throw (std::runtime_error("simplify_indexed: inconsistent indices in sum"));
713 if (is_ex_of_type(sum, indexed) && is_ex_of_type(term, indexed))
714 sum = sum.op(0).bp->add_indexed(sum, term);
724 // Simplification of products
725 if (is_ex_exactly_of_type(e_expanded, mul)
726 || is_ex_exactly_of_type(e_expanded, ncmul)
727 || (is_ex_exactly_of_type(e_expanded, power) && is_ex_of_type(e_expanded.op(0), indexed) && e_expanded.op(1).is_equal(_ex2())))
728 return simplify_indexed_product(e_expanded, free_indices, sp);
730 // Cannot do anything
731 free_indices.clear();
735 ex simplify_indexed(const ex & e)
737 exvector free_indices;
739 return simplify_indexed(e, free_indices, sp);
742 ex simplify_indexed(const ex & e, const scalar_products & sp)
744 exvector free_indices;
745 return simplify_indexed(e, free_indices, sp);
752 void scalar_products::add(const ex & v1, const ex & v2, const ex & sp)
754 spm[make_key(v1, v2)] = sp;
757 void scalar_products::clear(void)
762 /** Check whether scalar product pair is defined. */
763 bool scalar_products::is_defined(const ex & v1, const ex & v2) const
765 return spm.find(make_key(v1, v2)) != spm.end();
768 /** Return value of defined scalar product pair. */
769 ex scalar_products::evaluate(const ex & v1, const ex & v2) const
771 return spm.find(make_key(v1, v2))->second;
774 void scalar_products::debugprint(void) const
776 std::cerr << "map size=" << spm.size() << std::endl;
777 for (spmap::const_iterator cit=spm.begin(); cit!=spm.end(); ++cit) {
778 const spmapkey & k = cit->first;
779 std::cerr << "item key=(" << k.first << "," << k.second;
780 std::cerr << "), value=" << cit->second << std::endl;
784 /** Make key from object pair. */
785 spmapkey scalar_products::make_key(const ex & v1, const ex & v2)
787 // If indexed, extract base objects
788 ex s1 = is_ex_of_type(v1, indexed) ? v1.op(0) : v1;
789 ex s2 = is_ex_of_type(v2, indexed) ? v2.op(0) : v2;
791 // Enforce canonical order in pair
792 if (s1.compare(s2) > 0)
793 return spmapkey(s2, s1);
795 return spmapkey(s1, s2);