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