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