]> www.ginac.de Git - ginac.git/blob - ginac/indexed.cpp
- simplify_indexed() renames dummy indices so, e.g., "a.i*a.i+a.j*a.j" gets
[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 bool indexed::all_index_values_are(unsigned inf) const
229 {
230         // No indices? Then no property can be fulfilled
231         if (seq.size() < 2)
232                 return false;
233
234         // Check all indices
235         exvector::const_iterator it = seq.begin() + 1, itend = seq.end();
236         while (it != itend) {
237                 GINAC_ASSERT(is_ex_of_type(*it, idx));
238                 if (!ex_to_idx(*it).get_value().info(inf))
239                         return false;
240                 it++;
241         }
242         return true;
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 != unknown && symmetry != mixed)) {
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         // And also the indices themselves
458         exvector::const_iterator ait = v1.begin(), aitend = v1.end(),
459                                  bit = v2.begin(), bitend = v2.end();
460         while (ait != aitend) {
461                 if (!ait->is_equal(*bit))
462                         return false;
463                 ait++; bit++;
464         }
465         return true;
466 }
467
468 exvector indexed::get_indices(void) const
469 {
470         GINAC_ASSERT(seq.size() >= 1);
471         return exvector(seq.begin() + 1, seq.end());
472 }
473
474 exvector indexed::get_dummy_indices(void) const
475 {
476         exvector free_indices, dummy_indices;
477         find_free_and_dummy(seq.begin() + 1, seq.end(), free_indices, dummy_indices);
478         return dummy_indices;
479 }
480
481 exvector indexed::get_dummy_indices(const indexed & other) const
482 {
483         exvector indices = get_free_indices();
484         exvector other_indices = other.get_free_indices();
485         indices.insert(indices.end(), other_indices.begin(), other_indices.end());
486         exvector dummy_indices;
487         find_dummy_indices(indices, dummy_indices);
488         return dummy_indices;
489 }
490
491 exvector indexed::get_free_indices(void) const
492 {
493         exvector free_indices, dummy_indices;
494         find_free_and_dummy(seq.begin() + 1, seq.end(), free_indices, dummy_indices);
495         return free_indices;
496 }
497
498 exvector add::get_free_indices(void) const
499 {
500         exvector free_indices;
501         for (unsigned i=0; i<nops(); i++) {
502                 if (i == 0)
503                         free_indices = op(i).get_free_indices();
504                 else {
505                         exvector free_indices_of_term = op(i).get_free_indices();
506                         if (!indices_consistent(free_indices, free_indices_of_term))
507                                 throw (std::runtime_error("add::get_free_indices: inconsistent indices in sum"));
508                 }
509         }
510         return free_indices;
511 }
512
513 exvector mul::get_free_indices(void) const
514 {
515         // Concatenate free indices of all factors
516         exvector un;
517         for (unsigned i=0; i<nops(); i++) {
518                 exvector free_indices_of_factor = op(i).get_free_indices();
519                 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
520         }
521
522         // And remove the dummy indices
523         exvector free_indices, dummy_indices;
524         find_free_and_dummy(un, free_indices, dummy_indices);
525         return free_indices;
526 }
527
528 exvector ncmul::get_free_indices(void) const
529 {
530         // Concatenate free indices of all factors
531         exvector un;
532         for (unsigned i=0; i<nops(); i++) {
533                 exvector free_indices_of_factor = op(i).get_free_indices();
534                 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
535         }
536
537         // And remove the dummy indices
538         exvector free_indices, dummy_indices;
539         find_free_and_dummy(un, free_indices, dummy_indices);
540         return free_indices;
541 }
542
543 exvector power::get_free_indices(void) const
544 {
545         // Return free indices of basis
546         return basis.get_free_indices();
547 }
548
549 /* Function object for STL sort() */
550 struct ex_is_less {
551         bool operator() (const ex &lh, const ex &rh) const
552         {
553                 return lh.compare(rh) < 0;
554         }
555 };
556
557 /** Rename dummy indices in an expression.
558  *
559  *  @param e Expression to be worked on
560  *  @param local_dummy_indices The set of dummy indices that appear in the
561  *    expression "e"
562  *  @param global_dummy_indices The set of dummy indices that have appeared
563  *    before and which we would like to use in "e", too. This gets updated
564  *    by the function */
565 static ex rename_dummy_indices(const ex & e, exvector & global_dummy_indices, exvector & local_dummy_indices)
566 {
567         int global_size = global_dummy_indices.size(),
568             local_size = local_dummy_indices.size();
569
570         // Any local dummy indices at all?
571         if (local_size == 0)
572                 return e;
573
574         sort(local_dummy_indices.begin(), local_dummy_indices.end(), ex_is_less());
575
576         if (global_size < local_size) {
577
578                 // More local indices than we encountered before, add the new ones
579                 // to the global set
580                 int remaining = local_size - global_size;
581                 exvector::const_iterator it = local_dummy_indices.begin(), itend = local_dummy_indices.end();
582                 while (it != itend && remaining > 0) {
583                         exvector::const_iterator git = global_dummy_indices.begin(), gitend = global_dummy_indices.end();
584                         while (git != gitend) {
585                                 if (it->is_equal(*git))
586                                         goto found;
587                                 git++;
588                         }
589                         global_dummy_indices.push_back(*it);
590                         global_size++;
591                         remaining--;
592 found:          it++;
593                 }
594                 sort(global_dummy_indices.begin(), global_dummy_indices.end(), ex_is_less());
595         }
596
597         // Replace index symbols in expression
598         GINAC_ASSERT(local_size <= global_size);
599         bool all_equal = true;
600         lst local_syms, global_syms;
601         for (unsigned i=0; i<local_size; i++) {
602                 ex loc_sym = local_dummy_indices[i].op(0);
603                 ex glob_sym = global_dummy_indices[i].op(0);
604                 if (!loc_sym.is_equal(glob_sym))
605                         all_equal = false;
606                 local_syms.append(loc_sym);
607                 global_syms.append(glob_sym);
608         }
609         if (all_equal)
610                 return e;
611         else
612                 return e.subs(local_syms, global_syms);
613 }
614
615 /** Simplify product of indexed expressions (commutative, noncommutative and
616  *  simple squares), return list of free indices. */
617 ex simplify_indexed_product(const ex & e, exvector & free_indices, exvector & dummy_indices, const scalar_products & sp)
618 {
619         // Remember whether the product was commutative or noncommutative
620         // (because we chop it into factors and need to reassemble later)
621         bool non_commutative = is_ex_exactly_of_type(e, ncmul);
622
623         // Collect factors in an exvector, store squares twice
624         exvector v;
625         v.reserve(e.nops() * 2);
626
627         if (is_ex_exactly_of_type(e, power)) {
628                 // We only get called for simple squares, split a^2 -> a*a
629                 GINAC_ASSERT(e.op(1).is_equal(_ex2()));
630                 v.push_back(e.op(0));
631                 v.push_back(e.op(0));
632         } else {
633                 for (int i=0; i<e.nops(); i++) {
634                         ex f = e.op(i);
635                         if (is_ex_exactly_of_type(f, power) && f.op(1).is_equal(_ex2())) {
636                                 v.push_back(f.op(0));
637                     v.push_back(f.op(0));
638                         } else if (is_ex_exactly_of_type(f, ncmul)) {
639                                 // Noncommutative factor found, split it as well
640                                 non_commutative = true; // everything becomes noncommutative, ncmul will sort out the commutative factors later
641                                 for (int j=0; j<f.nops(); j++)
642                                         v.push_back(f.op(j));
643                         } else
644                                 v.push_back(f);
645                 }
646         }
647
648         // Perform contractions
649         bool something_changed = false;
650         GINAC_ASSERT(v.size() > 1);
651         exvector::iterator it1, itend = v.end(), next_to_last = itend - 1;
652         for (it1 = v.begin(); it1 != next_to_last; it1++) {
653
654 try_again:
655                 if (!is_ex_of_type(*it1, indexed))
656                         continue;
657
658                 // Indexed factor found, get free indices and look for contraction
659                 // candidates
660                 exvector free1, dummy1;
661                 find_free_and_dummy(ex_to_indexed(*it1).seq.begin() + 1, ex_to_indexed(*it1).seq.end(), free1, dummy1);
662
663                 exvector::iterator it2;
664                 for (it2 = it1 + 1; it2 != itend; it2++) {
665
666                         if (!is_ex_of_type(*it2, indexed))
667                                 continue;
668
669                         // Find free indices of second factor and merge them with free
670                         // indices of first factor
671                         exvector un;
672                         find_free_and_dummy(ex_to_indexed(*it2).seq.begin() + 1, ex_to_indexed(*it2).seq.end(), un, dummy1);
673                         un.insert(un.end(), free1.begin(), free1.end());
674
675                         // Check whether the two factors share dummy indices
676                         exvector free, dummy;
677                         find_free_and_dummy(un, free, dummy);
678                         if (dummy.size() == 0)
679                                 continue;
680
681                         // At least one dummy index, is it a defined scalar product?
682                         bool contracted = false;
683                         if (free.size() == 0) {
684                                 if (sp.is_defined(*it1, *it2)) {
685                                         *it1 = sp.evaluate(*it1, *it2);
686                                         *it2 = _ex1();
687                                         goto contraction_done;
688                                 }
689                         }
690
691                         // Contraction of symmetric with antisymmetric object is zero
692                         if ((ex_to_indexed(*it1).symmetry == indexed::symmetric &&
693                              ex_to_indexed(*it2).symmetry == indexed::antisymmetric
694                           || ex_to_indexed(*it1).symmetry == indexed::antisymmetric &&
695                              ex_to_indexed(*it2).symmetry == indexed::symmetric)
696                          && dummy.size() > 1) {
697                                 free_indices.clear();
698                                 return _ex0();
699                         }
700
701                         // Try to contract the first one with the second one
702                         contracted = it1->op(0).bp->contract_with(it1, it2, v);
703                         if (!contracted) {
704
705                                 // That didn't work; maybe the second object knows how to
706                                 // contract itself with the first one
707                                 contracted = it2->op(0).bp->contract_with(it2, it1, v);
708                         }
709                         if (contracted) {
710 contraction_done:
711                                 if (non_commutative
712                                  || is_ex_exactly_of_type(*it1, add) || is_ex_exactly_of_type(*it2, add)
713                                  || is_ex_exactly_of_type(*it1, mul) || is_ex_exactly_of_type(*it2, mul)
714                                  || is_ex_exactly_of_type(*it1, ncmul) || is_ex_exactly_of_type(*it2, ncmul)) {
715
716                                         // One of the factors became a sum or product:
717                                         // re-expand expression and run again
718                                         // Non-commutative products are always re-expanded to give
719                                         // simplify_ncmul() the chance to re-order and canonicalize
720                                         // the product
721                                         ex r = (non_commutative ? ex(ncmul(v)) : ex(mul(v)));
722                                         return simplify_indexed(r, free_indices, dummy_indices, sp);
723                                 }
724
725                                 // Both objects may have new indices now or they might
726                                 // even not be indexed objects any more, so we have to
727                                 // start over
728                                 something_changed = true;
729                                 goto try_again;
730                         }
731                 }
732         }
733
734         // Find free indices (concatenate them all and call find_free_and_dummy())
735         exvector un, local_dummy_indices;
736         it1 = v.begin(); itend = v.end();
737         while (it1 != itend) {
738                 exvector 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         find_free_and_dummy(un, free_indices, local_dummy_indices);
743
744         ex r;
745         if (something_changed)
746                 r = non_commutative ? ex(ncmul(v)) : ex(mul(v));
747         else
748                 r = e;
749
750         // Dummy index renaming
751         r = rename_dummy_indices(r, dummy_indices, local_dummy_indices);
752
753         // Product of indexed object with a scalar?
754         if (is_ex_exactly_of_type(r, mul) && r.nops() == 2
755          && is_ex_exactly_of_type(r.op(1), numeric) && is_ex_of_type(r.op(0), indexed))
756                 return r.op(0).op(0).bp->scalar_mul_indexed(r.op(0), ex_to_numeric(r.op(1)));
757         else
758                 return r;
759 }
760
761 /** Simplify indexed expression, return list of free indices. */
762 ex simplify_indexed(const ex & e, exvector & free_indices, exvector & dummy_indices, const scalar_products & sp)
763 {
764         // Expand the expression
765         ex e_expanded = e.expand();
766
767         // Simplification of single indexed object: just find the free indices
768         // (and perform dummy index renaming if 
769         if (is_ex_of_type(e_expanded, indexed)) {
770                 const indexed &i = ex_to_indexed(e_expanded);
771                 exvector local_dummy_indices;
772                 find_free_and_dummy(i.seq.begin() + 1, i.seq.end(), free_indices, local_dummy_indices);
773                 return rename_dummy_indices(e_expanded, dummy_indices, local_dummy_indices);
774         }
775
776         // Simplification of sum = sum of simplifications, check consistency of
777         // free indices in each term
778         if (is_ex_exactly_of_type(e_expanded, add)) {
779                 bool first = true;
780                 ex sum = _ex0();
781                 free_indices.clear();
782
783                 for (unsigned i=0; i<e_expanded.nops(); i++) {
784                         exvector free_indices_of_term;
785                         ex term = simplify_indexed(e_expanded.op(i), free_indices_of_term, dummy_indices, sp);
786                         if (!term.is_zero()) {
787                                 if (first) {
788                                         free_indices = free_indices_of_term;
789                                         sum = term;
790                                         first = false;
791                                 } else {
792                                         if (!indices_consistent(free_indices, free_indices_of_term))
793                                                 throw (std::runtime_error("simplify_indexed: inconsistent indices in sum"));
794                                         if (is_ex_of_type(sum, indexed) && is_ex_of_type(term, indexed))
795                                                 sum = sum.op(0).bp->add_indexed(sum, term);
796                                         else
797                                                 sum += term;
798                                 }
799                         }
800                 }
801
802                 return sum;
803         }
804
805         // Simplification of products
806         if (is_ex_exactly_of_type(e_expanded, mul)
807          || is_ex_exactly_of_type(e_expanded, ncmul)
808          || (is_ex_exactly_of_type(e_expanded, power) && is_ex_of_type(e_expanded.op(0), indexed) && e_expanded.op(1).is_equal(_ex2())))
809                 return simplify_indexed_product(e_expanded, free_indices, dummy_indices, sp);
810
811         // Cannot do anything
812         free_indices.clear();
813         return e_expanded;
814 }
815
816 ex simplify_indexed(const ex & e)
817 {
818         exvector free_indices, dummy_indices;
819         scalar_products sp;
820         return simplify_indexed(e, free_indices, dummy_indices, sp);
821 }
822
823 ex simplify_indexed(const ex & e, const scalar_products & sp)
824 {
825         exvector free_indices, dummy_indices;
826         return simplify_indexed(e, free_indices, dummy_indices, sp);
827 }
828
829 //////////
830 // helper classes
831 //////////
832
833 void scalar_products::add(const ex & v1, const ex & v2, const ex & sp)
834 {
835         spm[make_key(v1, v2)] = sp;
836 }
837
838 void scalar_products::add_vectors(const lst & l)
839 {
840         // Add all possible pairs of products
841         unsigned num = l.nops();
842         for (unsigned i=0; i<num; i++) {
843                 ex a = l.op(i);
844                 for (unsigned j=0; j<num; j++) {
845                         ex b = l.op(j);
846                         add(a, b, a*b);
847                 }
848         }
849 }
850
851 void scalar_products::clear(void)
852 {
853         spm.clear();
854 }
855
856 /** Check whether scalar product pair is defined. */
857 bool scalar_products::is_defined(const ex & v1, const ex & v2) const
858 {
859         return spm.find(make_key(v1, v2)) != spm.end();
860 }
861
862 /** Return value of defined scalar product pair. */
863 ex scalar_products::evaluate(const ex & v1, const ex & v2) const
864 {
865         return spm.find(make_key(v1, v2))->second;
866 }
867
868 void scalar_products::debugprint(void) const
869 {
870         std::cerr << "map size=" << spm.size() << std::endl;
871         for (spmap::const_iterator cit=spm.begin(); cit!=spm.end(); ++cit) {
872                 const spmapkey & k = cit->first;
873                 std::cerr << "item key=(" << k.first << "," << k.second;
874                 std::cerr << "), value=" << cit->second << std::endl;
875         }
876 }
877
878 /** Make key from object pair. */
879 spmapkey scalar_products::make_key(const ex & v1, const ex & v2)
880 {
881         // If indexed, extract base objects
882         ex s1 = is_ex_of_type(v1, indexed) ? v1.op(0) : v1;
883         ex s2 = is_ex_of_type(v2, indexed) ? v2.op(0) : v2;
884
885         // Enforce canonical order in pair
886         if (s1.compare(s2) > 0)
887                 return spmapkey(s2, s1);
888         else
889                 return spmapkey(s1, s2);
890 }
891
892 } // namespace GiNaC