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 void indexed::destroy(bool call_parent)
58 inherited::destroy(call_parent);
65 indexed::indexed(const ex & b) : inherited(b), symmetry(unknown)
67 debugmsg("indexed constructor from ex", LOGLEVEL_CONSTRUCT);
68 tinfo_key = TINFO_indexed;
69 assert_all_indices_of_type_idx();
72 indexed::indexed(const ex & b, const ex & i1) : inherited(b, i1), symmetry(unknown)
74 debugmsg("indexed constructor from ex,ex", LOGLEVEL_CONSTRUCT);
75 tinfo_key = TINFO_indexed;
76 assert_all_indices_of_type_idx();
79 indexed::indexed(const ex & b, const ex & i1, const ex & i2) : inherited(b, i1, i2), symmetry(unknown)
81 debugmsg("indexed constructor from ex,ex,ex", LOGLEVEL_CONSTRUCT);
82 tinfo_key = TINFO_indexed;
83 assert_all_indices_of_type_idx();
86 indexed::indexed(const ex & b, const ex & i1, const ex & i2, const ex & i3) : inherited(b, i1, i2, i3), symmetry(unknown)
88 debugmsg("indexed constructor from ex,ex,ex,ex", LOGLEVEL_CONSTRUCT);
89 tinfo_key = TINFO_indexed;
90 assert_all_indices_of_type_idx();
93 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)
95 debugmsg("indexed constructor from ex,ex,ex,ex,ex", LOGLEVEL_CONSTRUCT);
96 tinfo_key = TINFO_indexed;
97 assert_all_indices_of_type_idx();
100 indexed::indexed(const ex & b, symmetry_type symm, const ex & i1, const ex & i2) : inherited(b, i1, i2), symmetry(symm)
102 debugmsg("indexed constructor from ex,symmetry,ex,ex", LOGLEVEL_CONSTRUCT);
103 tinfo_key = TINFO_indexed;
104 assert_all_indices_of_type_idx();
107 indexed::indexed(const ex & b, symmetry_type symm, const ex & i1, const ex & i2, const ex & i3) : inherited(b, i1, i2, i3), symmetry(symm)
109 debugmsg("indexed constructor from ex,symmetry,ex,ex,ex", LOGLEVEL_CONSTRUCT);
110 tinfo_key = TINFO_indexed;
111 assert_all_indices_of_type_idx();
114 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)
116 debugmsg("indexed constructor from ex,symmetry,ex,ex,ex,ex", LOGLEVEL_CONSTRUCT);
117 tinfo_key = TINFO_indexed;
118 assert_all_indices_of_type_idx();
121 indexed::indexed(const ex & b, const exvector & v) : inherited(b), symmetry(unknown)
123 debugmsg("indexed constructor from ex,exvector", LOGLEVEL_CONSTRUCT);
124 seq.insert(seq.end(), v.begin(), v.end());
125 tinfo_key = TINFO_indexed;
126 assert_all_indices_of_type_idx();
129 indexed::indexed(const ex & b, symmetry_type symm, const exvector & v) : inherited(b), symmetry(symm)
131 debugmsg("indexed constructor from ex,symmetry,exvector", LOGLEVEL_CONSTRUCT);
132 seq.insert(seq.end(), v.begin(), v.end());
133 tinfo_key = TINFO_indexed;
134 assert_all_indices_of_type_idx();
137 indexed::indexed(symmetry_type symm, const exprseq & es) : inherited(es), symmetry(symm)
139 debugmsg("indexed constructor from symmetry,exprseq", LOGLEVEL_CONSTRUCT);
140 tinfo_key = TINFO_indexed;
141 assert_all_indices_of_type_idx();
144 indexed::indexed(symmetry_type symm, const exvector & v, bool discardable) : inherited(v, discardable), symmetry(symm)
146 debugmsg("indexed constructor from symmetry,exvector", LOGLEVEL_CONSTRUCT);
147 tinfo_key = TINFO_indexed;
148 assert_all_indices_of_type_idx();
151 indexed::indexed(symmetry_type symm, exvector * vp) : inherited(vp), symmetry(symm)
153 debugmsg("indexed constructor from symmetry,exvector *", LOGLEVEL_CONSTRUCT);
154 tinfo_key = TINFO_indexed;
155 assert_all_indices_of_type_idx();
162 /** Construct object from archive_node. */
163 indexed::indexed(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
165 debugmsg("indexed constructor from archive_node", LOGLEVEL_CONSTRUCT);
167 if (!(n.find_unsigned("symmetry", symm)))
168 throw (std::runtime_error("unknown indexed symmetry type in archive"));
171 /** Unarchive the object. */
172 ex indexed::unarchive(const archive_node &n, const lst &sym_lst)
174 return (new indexed(n, sym_lst))->setflag(status_flags::dynallocated);
177 /** Archive the object. */
178 void indexed::archive(archive_node &n) const
180 inherited::archive(n);
181 n.add_unsigned("symmetry", symmetry);
185 // functions overriding virtual functions from bases classes
188 void indexed::printraw(std::ostream & os) const
190 debugmsg("indexed printraw", LOGLEVEL_PRINT);
191 GINAC_ASSERT(seq.size() > 0);
193 os << class_name() << "(";
197 os << ",hash=" << hashvalue << ",flags=" << flags << ")";
200 void indexed::printtree(std::ostream & os, unsigned indent) const
202 debugmsg("indexed printtree", LOGLEVEL_PRINT);
203 GINAC_ASSERT(seq.size() > 0);
205 os << std::string(indent, ' ') << class_name() << ", " << seq.size()-1 << " indices";
206 os << ",hash=" << hashvalue << ",flags=" << flags << std::endl;
207 printtreeindices(os, indent);
210 void indexed::print(std::ostream & os, unsigned upper_precedence) const
212 debugmsg("indexed print", LOGLEVEL_PRINT);
213 GINAC_ASSERT(seq.size() > 0);
215 const ex & base = seq[0];
216 bool need_parens = is_ex_exactly_of_type(base, add) || is_ex_exactly_of_type(base, mul)
217 || is_ex_exactly_of_type(base, ncmul) || is_ex_exactly_of_type(base, power);
226 bool indexed::info(unsigned inf) const
228 if (inf == info_flags::indexed) return true;
229 if (inf == info_flags::has_indices) return seq.size() > 1;
230 return inherited::info(inf);
233 bool indexed::all_index_values_are(unsigned inf) const
235 // No indices? Then no property can be fulfilled
240 exvector::const_iterator it = seq.begin() + 1, itend = seq.end();
241 while (it != itend) {
242 GINAC_ASSERT(is_ex_of_type(*it, idx));
243 if (!ex_to_idx(*it).get_value().info(inf))
250 int indexed::compare_same_type(const basic & other) const
252 GINAC_ASSERT(is_of_type(other, indexed));
253 return inherited::compare_same_type(other);
256 // The main difference between sort_index_vector() and canonicalize_indices()
257 // is that the latter takes the symmetry of the object into account. Once we
258 // implement mixed symmetries, canonicalize_indices() will only be able to
259 // reorder index pairs with known symmetry properties, while sort_index_vector()
260 // always sorts the whole vector.
262 /** Bring a vector of indices into a canonic order (don't care about the
263 * symmetry of the objects carrying the indices). Dummy indices will lie
264 * next to each other after the sorting.
266 * @param v Index vector to be sorted */
267 static void sort_index_vector(exvector &v)
269 // Nothing to sort if less than 2 elements
273 // Simple bubble sort algorithm should be sufficient for the small
274 // number of indices expected
275 exvector::iterator it1 = v.begin(), itend = v.end(), next_to_last_idx = itend - 1;
276 while (it1 != next_to_last_idx) {
277 exvector::iterator it2 = it1 + 1;
278 while (it2 != itend) {
279 if (it1->compare(*it2) > 0)
287 /** Bring a vector of indices into a canonic order. This operation only makes
288 * sense if the object carrying these indices is either symmetric or totally
289 * antisymmetric with respect to the indices.
291 * @param itbegin Start of index vector
292 * @param itend End of index vector
293 * @param antisymm Whether the object is antisymmetric
294 * @return the sign introduced by the reordering of the indices if the object
295 * is antisymmetric (or 0 if two equal indices are encountered). For
296 * symmetric objects, this is always +1. If the index vector was
297 * already in a canonic order this function returns INT_MAX. */
298 static int canonicalize_indices(exvector::iterator itbegin, exvector::iterator itend, bool antisymm)
300 bool something_changed = false;
303 // Simple bubble sort algorithm should be sufficient for the small
304 // number of indices expected
305 exvector::iterator it1 = itbegin, next_to_last_idx = itend - 1;
306 while (it1 != next_to_last_idx) {
307 exvector::iterator it2 = it1 + 1;
308 while (it2 != itend) {
309 int cmpval = it1->compare(*it2);
312 something_changed = true;
315 } else if (cmpval == 0 && antisymm) {
316 something_changed = true;
324 return something_changed ? sig : INT_MAX;
327 ex indexed::eval(int level) const
329 // First evaluate children, then we will end up here again
331 return indexed(symmetry, evalchildren(level));
333 // If the base object is 0, the whole object is 0
334 if (seq[0].is_zero())
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 seq[0].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 /** Given a vector of indices, split them into two vectors, one containing
449 * the free indices, the other containing the dummy indices. */
450 static void find_free_and_dummy(exvector::const_iterator it, exvector::const_iterator itend, exvector & out_free, exvector & out_dummy)
455 // No indices? Then do nothing
459 // Only one index? Then it is a free one if it's not numeric
460 if (itend - it == 1) {
461 if (ex_to_idx(*it).is_symbolic())
462 out_free.push_back(*it);
466 // Sort index vector. This will cause dummy indices come to lie next
467 // to each other (because the sort order is defined to guarantee this).
468 exvector v(it, itend);
469 sort_index_vector(v);
471 // Find dummy pairs and free indices
472 it = v.begin(); itend = v.end();
473 exvector::const_iterator last = it++;
474 while (it != itend) {
475 if (is_dummy_pair(*it, *last)) {
476 out_dummy.push_back(*last);
481 if (!it->is_equal(*last) && ex_to_idx(*last).is_symbolic())
482 out_free.push_back(*last);
486 if (ex_to_idx(*last).is_symbolic())
487 out_free.push_back(*last);
490 /** Check whether two sorted index vectors are consistent (i.e. equal). */
491 static bool indices_consistent(const exvector & v1, const exvector & v2)
493 // Number of indices must be the same
494 if (v1.size() != v2.size())
497 // And also the indices themselves
498 exvector::const_iterator ait = v1.begin(), aitend = v1.end(),
499 bit = v2.begin(), bitend = v2.end();
500 while (ait != aitend) {
501 if (!ait->is_equal(*bit))
508 exvector indexed::get_dummy_indices(void) const
510 exvector free_indices, dummy_indices;
511 find_free_and_dummy(seq.begin() + 1, seq.end(), free_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.begin(), un.end(), 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.begin(), un.end(), 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(); i++)
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, look for contraction candidates
617 exvector::iterator it2;
618 for (it2 = it1 + 1; it2 != itend; it2++) {
620 if (!is_ex_of_type(*it2, indexed))
623 // Check whether the two factors share dummy indices
624 exvector un(ex_to_indexed(*it1).seq.begin() + 1, ex_to_indexed(*it1).seq.end());
625 un.insert(un.end(), ex_to_indexed(*it2).seq.begin() + 1, ex_to_indexed(*it2).seq.end());
626 exvector free, dummy;
627 find_free_and_dummy(un.begin(), un.end(), free, dummy);
628 if (dummy.size() == 0)
631 // At least one dummy index, is it a defined scalar product?
632 if (free.size() == 0) {
633 if (sp.is_defined(*it1, *it2)) {
634 *it1 = sp.evaluate(*it1, *it2);
636 something_changed = true;
641 // Try to contract the first one with the second one
642 bool contracted = it1->op(0).bp->contract_with(it1, it2, v);
645 // That didn't work; maybe the second object knows how to
646 // contract itself with the first one
647 contracted = it2->op(0).bp->contract_with(it2, it1, v);
650 something_changed = true;
652 // Both objects may have new indices now or they might
653 // even not be indexed objects any more, so we have to
660 // Find free indices (concatenate them all and call find_free_and_dummy())
661 exvector un, dummy_indices;
662 it1 = v.begin(); itend = v.end();
663 while (it1 != itend) {
664 if (is_ex_of_type(*it1, indexed)) {
665 const indexed & o = ex_to_indexed(*it1);
666 un.insert(un.end(), o.seq.begin() + 1, o.seq.end());
670 find_free_and_dummy(un.begin(), un.end(), free_indices, dummy_indices);
672 if (something_changed) {
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 for (unsigned i=0; i<e_expanded.nops(); i++) {
701 exvector free_indices_of_term;
702 sum += simplify_indexed(e_expanded.op(i), free_indices_of_term, sp);
704 free_indices = free_indices_of_term;
705 else if (!indices_consistent(free_indices, free_indices_of_term))
706 throw (std::runtime_error("simplify_indexed: inconsistent indices in sum"));
712 // Simplification of products
713 if (is_ex_exactly_of_type(e_expanded, mul)
714 || is_ex_exactly_of_type(e_expanded, ncmul)
715 || (is_ex_exactly_of_type(e_expanded, power) && is_ex_of_type(e_expanded.op(0), indexed) && e_expanded.op(1).is_equal(_ex2())))
716 return simplify_indexed_product(e_expanded, free_indices, sp);
718 // Cannot do anything
719 free_indices.clear();
723 ex simplify_indexed(const ex & e)
725 exvector free_indices;
727 return simplify_indexed(e, free_indices, sp);
730 ex simplify_indexed(const ex & e, const scalar_products & sp)
732 exvector free_indices;
733 return simplify_indexed(e, free_indices, sp);
740 void scalar_products::add(const ex & v1, const ex & v2, const ex & sp)
742 spm[make_key(v1, v2)] = sp;
745 void scalar_products::clear(void)
750 /** Check whether scalar product pair is defined. */
751 bool scalar_products::is_defined(const ex & v1, const ex & v2) const
753 return spm.find(make_key(v1, v2)) != spm.end();
756 /** Return value of defined scalar product pair. */
757 ex scalar_products::evaluate(const ex & v1, const ex & v2) const
759 return spm.find(make_key(v1, v2))->second;
762 void scalar_products::debugprint(void) const
764 std::cerr << "map size=" << spm.size() << std::endl;
765 for (spmap::const_iterator cit=spm.begin(); cit!=spm.end(); ++cit) {
766 const spmapkey & k = cit->first;
767 std::cerr << "item key=(" << k.first << "," << k.second;
768 std::cerr << "), value=" << cit->second << std::endl;
772 /** Make key from object pair. */
773 spmapkey scalar_products::make_key(const ex & v1, const ex & v2)
775 // If indexed, extract base objects
776 ex s1 = is_ex_of_type(v1, indexed) ? v1.op(0) : v1;
777 ex s2 = is_ex_of_type(v2, indexed) ? v2.op(0) : v2;
779 // Enforce canonical order in pair
780 if (s1.compare(s2) > 0)
781 return spmapkey(s2, s1);
783 return spmapkey(s1, s2);