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