- inserted a couple of missing namepace std:: resolutions.
[ginac.git] / ginac / indexed.cpp
1 /** @file indexed.cpp
2  *
3  *  Implementation of GiNaC's indexed expressions. */
4
5 /*
6  *  GiNaC Copyright (C) 1999-2001 Johannes Gutenberg University Mainz, Germany
7  *
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.
12  *
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.
17  *
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
21  */
22
23 #include <stdexcept>
24 #include <algorithm>
25
26 #include "indexed.h"
27 #include "idx.h"
28 #include "add.h"
29 #include "mul.h"
30 #include "ncmul.h"
31 #include "power.h"
32 #include "lst.h"
33 #include "inifcns.h" // for symmetrize()
34 #include "print.h"
35 #include "archive.h"
36 #include "utils.h"
37 #include "debugmsg.h"
38
39 namespace GiNaC {
40
41 GINAC_IMPLEMENT_REGISTERED_CLASS(indexed, exprseq)
42
43 //////////
44 // default constructor, destructor, copy constructor assignment operator and helpers
45 //////////
46
47 indexed::indexed() : symmetry(unknown)
48 {
49         debugmsg("indexed default constructor", LOGLEVEL_CONSTRUCT);
50         tinfo_key = TINFO_indexed;
51 }
52
53 void indexed::copy(const indexed & other)
54 {
55         inherited::copy(other);
56         symmetry = other.symmetry;
57 }
58
59 DEFAULT_DESTROY(indexed)
60
61 //////////
62 // other constructors
63 //////////
64
65 indexed::indexed(const ex & b) : inherited(b), symmetry(unknown)
66 {
67         debugmsg("indexed constructor from ex", LOGLEVEL_CONSTRUCT);
68         tinfo_key = TINFO_indexed;
69         assert_all_indices_of_type_idx();
70 }
71
72 indexed::indexed(const ex & b, const ex & i1) : inherited(b, i1), symmetry(unknown)
73 {
74         debugmsg("indexed constructor from ex,ex", LOGLEVEL_CONSTRUCT);
75         tinfo_key = TINFO_indexed;
76         assert_all_indices_of_type_idx();
77 }
78
79 indexed::indexed(const ex & b, const ex & i1, const ex & i2) : inherited(b, i1, i2), symmetry(unknown)
80 {
81         debugmsg("indexed constructor from ex,ex,ex", LOGLEVEL_CONSTRUCT);
82         tinfo_key = TINFO_indexed;
83         assert_all_indices_of_type_idx();
84 }
85
86 indexed::indexed(const ex & b, const ex & i1, const ex & i2, const ex & i3) : inherited(b, i1, i2, i3), symmetry(unknown)
87 {
88         debugmsg("indexed constructor from ex,ex,ex,ex", LOGLEVEL_CONSTRUCT);
89         tinfo_key = TINFO_indexed;
90         assert_all_indices_of_type_idx();
91 }
92
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)
94 {
95         debugmsg("indexed constructor from ex,ex,ex,ex,ex", LOGLEVEL_CONSTRUCT);
96         tinfo_key = TINFO_indexed;
97         assert_all_indices_of_type_idx();
98 }
99
100 indexed::indexed(const ex & b, symmetry_type symm, const ex & i1, const ex & i2) : inherited(b, i1, i2), symmetry(symm)
101 {
102         debugmsg("indexed constructor from ex,symmetry,ex,ex", LOGLEVEL_CONSTRUCT);
103         tinfo_key = TINFO_indexed;
104         assert_all_indices_of_type_idx();
105 }
106
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)
108 {
109         debugmsg("indexed constructor from ex,symmetry,ex,ex,ex", LOGLEVEL_CONSTRUCT);
110         tinfo_key = TINFO_indexed;
111         assert_all_indices_of_type_idx();
112 }
113
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)
115 {
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();
119 }
120
121 indexed::indexed(const ex & b, const exvector & v) : inherited(b), symmetry(unknown)
122 {
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();
127 }
128
129 indexed::indexed(const ex & b, symmetry_type symm, const exvector & v) : inherited(b), symmetry(symm)
130 {
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();
135 }
136
137 indexed::indexed(symmetry_type symm, const exprseq & es) : inherited(es), symmetry(symm)
138 {
139         debugmsg("indexed constructor from symmetry,exprseq", LOGLEVEL_CONSTRUCT);
140         tinfo_key = TINFO_indexed;
141         assert_all_indices_of_type_idx();
142 }
143
144 indexed::indexed(symmetry_type symm, const exvector & v, bool discardable) : inherited(v, discardable), symmetry(symm)
145 {
146         debugmsg("indexed constructor from symmetry,exvector", LOGLEVEL_CONSTRUCT);
147         tinfo_key = TINFO_indexed;
148         assert_all_indices_of_type_idx();
149 }
150
151 indexed::indexed(symmetry_type symm, exvector * vp) : inherited(vp), symmetry(symm)
152 {
153         debugmsg("indexed constructor from symmetry,exvector *", LOGLEVEL_CONSTRUCT);
154         tinfo_key = TINFO_indexed;
155         assert_all_indices_of_type_idx();
156 }
157
158 //////////
159 // archiving
160 //////////
161
162 indexed::indexed(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
163 {
164         debugmsg("indexed constructor from archive_node", LOGLEVEL_CONSTRUCT);
165         unsigned int symm;
166         if (!(n.find_unsigned("symmetry", symm)))
167                 throw (std::runtime_error("unknown indexed symmetry type in archive"));
168 }
169
170 void indexed::archive(archive_node &n) const
171 {
172         inherited::archive(n);
173         n.add_unsigned("symmetry", symmetry);
174 }
175
176 DEFAULT_UNARCHIVE(indexed)
177
178 //////////
179 // functions overriding virtual functions from bases classes
180 //////////
181
182 void indexed::print(const print_context & c, unsigned level) const
183 {
184         debugmsg("indexed print", LOGLEVEL_PRINT);
185         GINAC_ASSERT(seq.size() > 0);
186
187         if (is_of_type(c, print_tree)) {
188
189                 c.s << std::string(level, ' ') << class_name()
190                     << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
191                     << ", " << seq.size()-1 << " indices";
192                 switch (symmetry) {
193                         case symmetric: c.s << ", symmetric"; break;
194                         case antisymmetric: c.s << ", antisymmetric"; break;
195                         default: break;
196                 }
197                 c.s << std::endl;
198                 unsigned delta_indent = static_cast<const print_tree &>(c).delta_indent;
199                 seq[0].print(c, level + delta_indent);
200                 printindices(c, level + delta_indent);
201
202         } else {
203
204                 bool is_tex = is_of_type(c, print_latex);
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)
208                                 || is_ex_of_type(base, indexed);
209                 if (is_tex)
210                         c.s << "{";
211                 if (need_parens)
212                         c.s << "(";
213                 base.print(c);
214                 if (need_parens)
215                         c.s << ")";
216                 if (is_tex)
217                         c.s << "}";
218                 printindices(c, level);
219         }
220 }
221
222 bool indexed::info(unsigned inf) const
223 {
224         if (inf == info_flags::indexed) return true;
225         if (inf == info_flags::has_indices) return seq.size() > 1;
226         return inherited::info(inf);
227 }
228
229 struct idx_is_not : public std::binary_function<ex, unsigned, bool> {
230         bool operator() (const ex & e, unsigned inf) const {
231                 return !(ex_to_idx(e).get_value().info(inf));
232         }
233 };
234
235 bool indexed::all_index_values_are(unsigned inf) const
236 {
237         // No indices? Then no property can be fulfilled
238         if (seq.size() < 2)
239                 return false;
240
241         // Check all indices
242         return find_if(seq.begin() + 1, seq.end(), bind2nd(idx_is_not(), inf)) == seq.end();
243 }
244
245 int indexed::compare_same_type(const basic & other) const
246 {
247         GINAC_ASSERT(is_of_type(other, indexed));
248         return inherited::compare_same_type(other);
249 }
250
251 // The main difference between sort_index_vector() and canonicalize_indices()
252 // is that the latter takes the symmetry of the object into account. Once we
253 // implement mixed symmetries, canonicalize_indices() will only be able to
254 // reorder index pairs with known symmetry properties, while sort_index_vector()
255 // always sorts the whole vector.
256
257 /** Bring a vector of indices into a canonic order. This operation only makes
258  *  sense if the object carrying these indices is either symmetric or totally
259  *  antisymmetric with respect to the indices.
260  *
261  *  @param itbegin Start of index vector
262  *  @param itend End of index vector
263  *  @param antisymm Whether the object is antisymmetric
264  *  @return the sign introduced by the reordering of the indices if the object
265  *          is antisymmetric (or 0 if two equal indices are encountered). For
266  *          symmetric objects, this is always +1. If the index vector was
267  *          already in a canonic order this function returns INT_MAX. */
268 static int canonicalize_indices(exvector::iterator itbegin, exvector::iterator itend, bool antisymm)
269 {
270         bool something_changed = false;
271         int sig = 1;
272
273         // Simple bubble sort algorithm should be sufficient for the small
274         // number of indices expected
275         exvector::iterator it1 = itbegin, next_to_last_idx = itend - 1;
276         while (it1 != next_to_last_idx) {
277                 exvector::iterator it2 = it1 + 1;
278                 while (it2 != itend) {
279                         int cmpval = it1->compare(*it2);
280                         if (cmpval == 1) {
281                                 it1->swap(*it2);
282                                 something_changed = true;
283                                 if (antisymm)
284                                         sig = -sig;
285                         } else if (cmpval == 0 && antisymm) {
286                                 something_changed = true;
287                                 sig = 0;
288                         }
289                         it2++;
290                 }
291                 it1++;
292         }
293
294         return something_changed ? sig : INT_MAX;
295 }
296
297 ex indexed::eval(int level) const
298 {
299         // First evaluate children, then we will end up here again
300         if (level > 1)
301                 return indexed(symmetry, evalchildren(level));
302
303         const ex &base = seq[0];
304
305         // If the base object is 0, the whole object is 0
306         if (base.is_zero())
307                 return _ex0();
308
309         // If the base object is a product, pull out the numeric factor
310         if (is_ex_exactly_of_type(base, mul) && is_ex_exactly_of_type(base.op(base.nops() - 1), numeric)) {
311                 exvector v(seq);
312                 ex f = ex_to_numeric(base.op(base.nops() - 1));
313                 v[0] = seq[0] / f;
314                 return f * thisexprseq(v);
315         }
316
317         // Canonicalize indices according to the symmetry properties
318         if (seq.size() > 2 && (symmetry == symmetric || symmetry == antisymmetric)) {
319                 exvector v(seq);
320                 int sig = canonicalize_indices(v.begin() + 1, v.end(), symmetry == antisymmetric);
321                 if (sig != INT_MAX) {
322                         // Something has changed while sorting indices, more evaluations later
323                         if (sig == 0)
324                                 return _ex0();
325                         return ex(sig) * thisexprseq(v);
326                 }
327         }
328
329         // Let the class of the base object perform additional evaluations
330         return base.bp->eval_indexed(*this);
331 }
332
333 int indexed::degree(const ex & s) const
334 {
335         return is_equal(*s.bp) ? 1 : 0;
336 }
337
338 int indexed::ldegree(const ex & s) const
339 {
340         return is_equal(*s.bp) ? 1 : 0;
341 }
342
343 ex indexed::coeff(const ex & s, int n) const
344 {
345         if (is_equal(*s.bp))
346                 return n==1 ? _ex1() : _ex0();
347         else
348                 return n==0 ? ex(*this) : _ex0();
349 }
350
351 ex indexed::thisexprseq(const exvector & v) const
352 {
353         return indexed(symmetry, v);
354 }
355
356 ex indexed::thisexprseq(exvector * vp) const
357 {
358         return indexed(symmetry, vp);
359 }
360
361 ex indexed::expand(unsigned options) const
362 {
363         GINAC_ASSERT(seq.size() > 0);
364
365         if ((options & expand_options::expand_indexed) && is_ex_exactly_of_type(seq[0], add)) {
366
367                 // expand_indexed expands (a+b).i -> a.i + b.i
368                 const ex & base = seq[0];
369                 ex sum = _ex0();
370                 for (unsigned i=0; i<base.nops(); i++) {
371                         exvector s = seq;
372                         s[0] = base.op(i);
373                         sum += thisexprseq(s).expand();
374                 }
375                 return sum;
376
377         } else
378                 return inherited::expand(options);
379 }
380
381 //////////
382 // virtual functions which can be overridden by derived classes
383 //////////
384
385 // none
386
387 //////////
388 // non-virtual functions in this class
389 //////////
390
391 void indexed::printindices(const print_context & c, unsigned level) const
392 {
393         if (seq.size() > 1) {
394
395                 exvector::const_iterator it=seq.begin() + 1, itend = seq.end();
396
397                 if (is_of_type(c, print_latex)) {
398
399                         // TeX output: group by variance
400                         bool first = true;
401                         bool covariant = true;
402
403                         while (it != itend) {
404                                 bool cur_covariant = (is_ex_of_type(*it, varidx) ? ex_to_varidx(*it).is_covariant() : true);
405                                 if (first || cur_covariant != covariant) {
406                                         if (!first)
407                                                 c.s << "}";
408                                         covariant = cur_covariant;
409                                         if (covariant)
410                                                 c.s << "_{";
411                                         else
412                                                 c.s << "^{";
413                                 }
414                                 it->print(c, level);
415                                 c.s << " ";
416                                 first = false;
417                                 it++;
418                         }
419                         c.s << "}";
420
421                 } else {
422
423                         // Ordinary output
424                         while (it != itend) {
425                                 it->print(c, level);
426                                 it++;
427                         }
428                 }
429         }
430 }
431
432 /** Check whether all indices are of class idx. This function is used
433  *  internally to make sure that all constructed indexed objects really
434  *  carry indices and not some other classes. */
435 void indexed::assert_all_indices_of_type_idx(void) const
436 {
437         GINAC_ASSERT(seq.size() > 0);
438         exvector::const_iterator it = seq.begin() + 1, itend = seq.end();
439         while (it != itend) {
440                 if (!is_ex_of_type(*it, idx))
441                         throw(std::invalid_argument("indices of indexed object must be of type idx"));
442                 it++;
443         }
444 }
445
446 //////////
447 // global functions
448 //////////
449
450 /** Check whether two sorted index vectors are consistent (i.e. equal). */
451 static bool indices_consistent(const exvector & v1, const exvector & v2)
452 {
453         // Number of indices must be the same
454         if (v1.size() != v2.size())
455                 return false;
456
457         return equal(v1.begin(), v1.end(), v2.begin(), ex_is_equal());
458 }
459
460 exvector indexed::get_indices(void) const
461 {
462         GINAC_ASSERT(seq.size() >= 1);
463         return exvector(seq.begin() + 1, seq.end());
464 }
465
466 exvector indexed::get_dummy_indices(void) const
467 {
468         exvector free_indices, dummy_indices;
469         find_free_and_dummy(seq.begin() + 1, seq.end(), free_indices, dummy_indices);
470         return dummy_indices;
471 }
472
473 exvector indexed::get_dummy_indices(const indexed & other) const
474 {
475         exvector indices = get_free_indices();
476         exvector other_indices = other.get_free_indices();
477         indices.insert(indices.end(), other_indices.begin(), other_indices.end());
478         exvector dummy_indices;
479         find_dummy_indices(indices, dummy_indices);
480         return dummy_indices;
481 }
482
483 bool indexed::has_dummy_index_for(const ex & i) const
484 {
485         exvector::const_iterator it = seq.begin() + 1, itend = seq.end();
486         while (it != itend) {
487                 if (is_dummy_pair(*it, i))
488                         return true;
489                 it++;
490         }
491         return false;
492 }
493
494 exvector indexed::get_free_indices(void) const
495 {
496         exvector free_indices, dummy_indices;
497         find_free_and_dummy(seq.begin() + 1, seq.end(), free_indices, dummy_indices);
498         return free_indices;
499 }
500
501 exvector add::get_free_indices(void) const
502 {
503         exvector free_indices;
504         for (unsigned i=0; i<nops(); i++) {
505                 if (i == 0)
506                         free_indices = op(i).get_free_indices();
507                 else {
508                         exvector free_indices_of_term = op(i).get_free_indices();
509                         if (!indices_consistent(free_indices, free_indices_of_term))
510                                 throw (std::runtime_error("add::get_free_indices: inconsistent indices in sum"));
511                 }
512         }
513         return free_indices;
514 }
515
516 exvector mul::get_free_indices(void) const
517 {
518         // Concatenate free indices of all factors
519         exvector un;
520         for (unsigned i=0; i<nops(); i++) {
521                 exvector free_indices_of_factor = op(i).get_free_indices();
522                 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
523         }
524
525         // And remove the dummy indices
526         exvector free_indices, dummy_indices;
527         find_free_and_dummy(un, free_indices, dummy_indices);
528         return free_indices;
529 }
530
531 exvector ncmul::get_free_indices(void) const
532 {
533         // Concatenate free indices of all factors
534         exvector un;
535         for (unsigned i=0; i<nops(); i++) {
536                 exvector free_indices_of_factor = op(i).get_free_indices();
537                 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
538         }
539
540         // And remove the dummy indices
541         exvector free_indices, dummy_indices;
542         find_free_and_dummy(un, free_indices, dummy_indices);
543         return free_indices;
544 }
545
546 exvector power::get_free_indices(void) const
547 {
548         // Return free indices of basis
549         return basis.get_free_indices();
550 }
551
552 /** Rename dummy indices in an expression.
553  *
554  *  @param e Expression to be worked on
555  *  @param local_dummy_indices The set of dummy indices that appear in the
556  *    expression "e"
557  *  @param global_dummy_indices The set of dummy indices that have appeared
558  *    before and which we would like to use in "e", too. This gets updated
559  *    by the function */
560 static ex rename_dummy_indices(const ex & e, exvector & global_dummy_indices, exvector & local_dummy_indices)
561 {
562         int global_size = global_dummy_indices.size(),
563             local_size = local_dummy_indices.size();
564
565         // Any local dummy indices at all?
566         if (local_size == 0)
567                 return e;
568
569         if (global_size < local_size) {
570
571                 // More local indices than we encountered before, add the new ones
572                 // to the global set
573                 int remaining = local_size - global_size;
574                 exvector::const_iterator it = local_dummy_indices.begin(), itend = local_dummy_indices.end();
575                 while (it != itend && remaining > 0) {
576                         if (find_if(global_dummy_indices.begin(), global_dummy_indices.end(), bind2nd(ex_is_equal(), *it)) == global_dummy_indices.end()) {
577                                 global_dummy_indices.push_back(*it);
578                                 global_size++;
579                                 remaining--;
580                         }
581                         it++;
582                 }
583         }
584
585         // Replace index symbols in expression
586         GINAC_ASSERT(local_size <= global_size);
587         bool all_equal = true;
588         lst local_syms, global_syms;
589         for (unsigned i=0; i<local_size; i++) {
590                 ex loc_sym = local_dummy_indices[i].op(0);
591                 ex glob_sym = global_dummy_indices[i].op(0);
592                 if (!loc_sym.is_equal(glob_sym)) {
593                         all_equal = false;
594                         local_syms.append(loc_sym);
595                         global_syms.append(glob_sym);
596                 }
597         }
598         if (all_equal)
599                 return e;
600         else
601                 return e.subs(local_syms, global_syms);
602 }
603
604 /** Simplify product of indexed expressions (commutative, noncommutative and
605  *  simple squares), return list of free indices. */
606 ex simplify_indexed_product(const ex & e, exvector & free_indices, exvector & dummy_indices, const scalar_products & sp)
607 {
608         // Remember whether the product was commutative or noncommutative
609         // (because we chop it into factors and need to reassemble later)
610         bool non_commutative = is_ex_exactly_of_type(e, ncmul);
611
612         // Collect factors in an exvector, store squares twice
613         exvector v;
614         v.reserve(e.nops() * 2);
615
616         if (is_ex_exactly_of_type(e, power)) {
617                 // We only get called for simple squares, split a^2 -> a*a
618                 GINAC_ASSERT(e.op(1).is_equal(_ex2()));
619                 v.push_back(e.op(0));
620                 v.push_back(e.op(0));
621         } else {
622                 for (int i=0; i<e.nops(); i++) {
623                         ex f = e.op(i);
624                         if (is_ex_exactly_of_type(f, power) && f.op(1).is_equal(_ex2())) {
625                                 v.push_back(f.op(0));
626                     v.push_back(f.op(0));
627                         } else if (is_ex_exactly_of_type(f, ncmul)) {
628                                 // Noncommutative factor found, split it as well
629                                 non_commutative = true; // everything becomes noncommutative, ncmul will sort out the commutative factors later
630                                 for (int j=0; j<f.nops(); j++)
631                                         v.push_back(f.op(j));
632                         } else
633                                 v.push_back(f);
634                 }
635         }
636
637         // Perform contractions
638         bool something_changed = false;
639         GINAC_ASSERT(v.size() > 1);
640         exvector::iterator it1, itend = v.end(), next_to_last = itend - 1;
641         for (it1 = v.begin(); it1 != next_to_last; it1++) {
642
643 try_again:
644                 if (!is_ex_of_type(*it1, indexed))
645                         continue;
646
647                 bool first_noncommutative = (it1->return_type() != return_types::commutative);
648
649                 // Indexed factor found, get free indices and look for contraction
650                 // candidates
651                 exvector free1, dummy1;
652                 find_free_and_dummy(ex_to_indexed(*it1).seq.begin() + 1, ex_to_indexed(*it1).seq.end(), free1, dummy1);
653
654                 exvector::iterator it2;
655                 for (it2 = it1 + 1; it2 != itend; it2++) {
656
657                         if (!is_ex_of_type(*it2, indexed))
658                                 continue;
659
660                         bool second_noncommutative = (it2->return_type() != return_types::commutative);
661
662                         // Find free indices of second factor and merge them with free
663                         // indices of first factor
664                         exvector un;
665                         find_free_and_dummy(ex_to_indexed(*it2).seq.begin() + 1, ex_to_indexed(*it2).seq.end(), un, dummy1);
666                         un.insert(un.end(), free1.begin(), free1.end());
667
668                         // Check whether the two factors share dummy indices
669                         exvector free, dummy;
670                         find_free_and_dummy(un, free, dummy);
671                         if (dummy.size() == 0)
672                                 continue;
673
674                         // At least one dummy index, is it a defined scalar product?
675                         bool contracted = false;
676                         if (free.size() == 0) {
677                                 if (sp.is_defined(*it1, *it2)) {
678                                         *it1 = sp.evaluate(*it1, *it2);
679                                         *it2 = _ex1();
680                                         goto contraction_done;
681                                 }
682                         }
683
684                         // Contraction of symmetric with antisymmetric object is zero
685                         if ((ex_to_indexed(*it1).symmetry == indexed::symmetric &&
686                              ex_to_indexed(*it2).symmetry == indexed::antisymmetric
687                           || ex_to_indexed(*it1).symmetry == indexed::antisymmetric &&
688                              ex_to_indexed(*it2).symmetry == indexed::symmetric)
689                          && dummy.size() > 1) {
690                                 free_indices.clear();
691                                 return _ex0();
692                         }
693
694                         // Try to contract the first one with the second one
695                         contracted = it1->op(0).bp->contract_with(it1, it2, v);
696                         if (!contracted) {
697
698                                 // That didn't work; maybe the second object knows how to
699                                 // contract itself with the first one
700                                 contracted = it2->op(0).bp->contract_with(it2, it1, v);
701                         }
702                         if (contracted) {
703 contraction_done:
704                                 if (first_noncommutative || second_noncommutative
705                                  || is_ex_exactly_of_type(*it1, add) || is_ex_exactly_of_type(*it2, add)
706                                  || is_ex_exactly_of_type(*it1, mul) || is_ex_exactly_of_type(*it2, mul)
707                                  || is_ex_exactly_of_type(*it1, ncmul) || is_ex_exactly_of_type(*it2, ncmul)) {
708
709                                         // One of the factors became a sum or product:
710                                         // re-expand expression and run again
711                                         // Non-commutative products are always re-expanded to give
712                                         // simplify_ncmul() the chance to re-order and canonicalize
713                                         // the product
714                                         ex r = (non_commutative ? ex(ncmul(v, true)) : ex(mul(v)));
715                                         return simplify_indexed(r, free_indices, dummy_indices, sp);
716                                 }
717
718                                 // Both objects may have new indices now or they might
719                                 // even not be indexed objects any more, so we have to
720                                 // start over
721                                 something_changed = true;
722                                 goto try_again;
723                         }
724                 }
725         }
726
727         // Find free indices (concatenate them all and call find_free_and_dummy())
728         // and all dummy indices that appear
729         exvector un, individual_dummy_indices;
730         it1 = v.begin(); itend = v.end();
731         while (it1 != itend) {
732                 exvector free_indices_of_factor;
733                 if (is_ex_of_type(*it1, indexed)) {
734                         exvector dummy_indices_of_factor;
735                         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);
736                         individual_dummy_indices.insert(individual_dummy_indices.end(), dummy_indices_of_factor.begin(), dummy_indices_of_factor.end());
737                 } else
738                         free_indices_of_factor = it1->get_free_indices();
739                 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
740                 it1++;
741         }
742         exvector local_dummy_indices;
743         find_free_and_dummy(un, free_indices, local_dummy_indices);
744         local_dummy_indices.insert(local_dummy_indices.end(), individual_dummy_indices.begin(), individual_dummy_indices.end());
745
746         ex r;
747         if (something_changed)
748                 r = non_commutative ? ex(ncmul(v, true)) : ex(mul(v));
749         else
750                 r = e;
751
752         // Dummy index renaming
753         r = rename_dummy_indices(r, dummy_indices, local_dummy_indices);
754
755         // Product of indexed object with a scalar?
756         if (is_ex_exactly_of_type(r, mul) && r.nops() == 2
757          && is_ex_exactly_of_type(r.op(1), numeric) && is_ex_of_type(r.op(0), indexed))
758                 return r.op(0).op(0).bp->scalar_mul_indexed(r.op(0), ex_to_numeric(r.op(1)));
759         else
760                 return r;
761 }
762
763 /** Simplify indexed expression, return list of free indices. */
764 ex simplify_indexed(const ex & e, exvector & free_indices, exvector & dummy_indices, const scalar_products & sp)
765 {
766         // Expand the expression
767         ex e_expanded = e.expand();
768
769         // Simplification of single indexed object: just find the free indices
770         // and perform dummy index renaming
771         if (is_ex_of_type(e_expanded, indexed)) {
772                 const indexed &i = ex_to_indexed(e_expanded);
773                 exvector local_dummy_indices;
774                 find_free_and_dummy(i.seq.begin() + 1, i.seq.end(), free_indices, local_dummy_indices);
775                 return rename_dummy_indices(e_expanded, dummy_indices, local_dummy_indices);
776         }
777
778         // Simplification of sum = sum of simplifications, check consistency of
779         // free indices in each term
780         if (is_ex_exactly_of_type(e_expanded, add)) {
781                 bool first = true;
782                 ex sum = _ex0();
783                 free_indices.clear();
784
785                 for (unsigned i=0; i<e_expanded.nops(); i++) {
786                         exvector free_indices_of_term;
787                         ex term = simplify_indexed(e_expanded.op(i), free_indices_of_term, dummy_indices, sp);
788                         if (!term.is_zero()) {
789                                 if (first) {
790                                         free_indices = free_indices_of_term;
791                                         sum = term;
792                                         first = false;
793                                 } else {
794                                         if (!indices_consistent(free_indices, free_indices_of_term))
795                                                 throw (std::runtime_error("simplify_indexed: inconsistent indices in sum"));
796                                         if (is_ex_of_type(sum, indexed) && is_ex_of_type(term, indexed))
797                                                 sum = sum.op(0).bp->add_indexed(sum, term);
798                                         else
799                                                 sum += term;
800                                 }
801                         }
802                 }
803
804                 return sum;
805         }
806
807         // Simplification of products
808         if (is_ex_exactly_of_type(e_expanded, mul)
809          || is_ex_exactly_of_type(e_expanded, ncmul)
810          || (is_ex_exactly_of_type(e_expanded, power) && is_ex_of_type(e_expanded.op(0), indexed) && e_expanded.op(1).is_equal(_ex2())))
811                 return simplify_indexed_product(e_expanded, free_indices, dummy_indices, sp);
812
813         // Cannot do anything
814         free_indices.clear();
815         return e_expanded;
816 }
817
818 /** Simplify/canonicalize expression containing indexed objects. This
819  *  performs contraction of dummy indices where possible and checks whether
820  *  the free indices in sums are consistent.
821  *
822  *  @return simplified expression */
823 ex ex::simplify_indexed(void) const
824 {
825         exvector free_indices, dummy_indices;
826         scalar_products sp;
827         return GiNaC::simplify_indexed(*this, free_indices, dummy_indices, sp);
828 }
829
830 /** Simplify/canonicalize expression containing indexed objects. This
831  *  performs contraction of dummy indices where possible, checks whether
832  *  the free indices in sums are consistent, and automatically replaces
833  *  scalar products by known values if desired.
834  *
835  *  @param sp Scalar products to be replaced automatically
836  *  @return simplified expression */
837 ex ex::simplify_indexed(const scalar_products & sp) const
838 {
839         exvector free_indices, dummy_indices;
840         return GiNaC::simplify_indexed(*this, free_indices, dummy_indices, sp);
841 }
842
843 /** Symmetrize expression over its free indices. */
844 ex ex::symmetrize(void) const
845 {
846         return GiNaC::symmetrize(*this, get_free_indices());
847 }
848
849 /** Antisymmetrize expression over its free indices. */
850 ex ex::antisymmetrize(void) const
851 {
852         return GiNaC::antisymmetrize(*this, get_free_indices());
853 }
854
855 //////////
856 // helper classes
857 //////////
858
859 void scalar_products::add(const ex & v1, const ex & v2, const ex & sp)
860 {
861         spm[make_key(v1, v2)] = sp;
862 }
863
864 void scalar_products::add_vectors(const lst & l)
865 {
866         // Add all possible pairs of products
867         unsigned num = l.nops();
868         for (unsigned i=0; i<num; i++) {
869                 ex a = l.op(i);
870                 for (unsigned j=0; j<num; j++) {
871                         ex b = l.op(j);
872                         add(a, b, a*b);
873                 }
874         }
875 }
876
877 void scalar_products::clear(void)
878 {
879         spm.clear();
880 }
881
882 /** Check whether scalar product pair is defined. */
883 bool scalar_products::is_defined(const ex & v1, const ex & v2) const
884 {
885         return spm.find(make_key(v1, v2)) != spm.end();
886 }
887
888 /** Return value of defined scalar product pair. */
889 ex scalar_products::evaluate(const ex & v1, const ex & v2) const
890 {
891         return spm.find(make_key(v1, v2))->second;
892 }
893
894 void scalar_products::debugprint(void) const
895 {
896         std::cerr << "map size=" << spm.size() << std::endl;
897         for (spmap::const_iterator cit=spm.begin(); cit!=spm.end(); ++cit) {
898                 const spmapkey & k = cit->first;
899                 std::cerr << "item key=(" << k.first << "," << k.second;
900                 std::cerr << "), value=" << cit->second << std::endl;
901         }
902 }
903
904 /** Make key from object pair. */
905 spmapkey scalar_products::make_key(const ex & v1, const ex & v2)
906 {
907         // If indexed, extract base objects
908         ex s1 = is_ex_of_type(v1, indexed) ? v1.op(0) : v1;
909         ex s2 = is_ex_of_type(v2, indexed) ? v2.op(0) : v2;
910
911         // Enforce canonical order in pair
912         if (s1.compare(s2) > 0)
913                 return spmapkey(s2, s1);
914         else
915                 return spmapkey(s1, s2);
916 }
917
918 } // namespace GiNaC