]> www.ginac.de Git - ginac.git/blob - ginac/indexed.cpp
736c109b656ec26eeb658e2c9ccd3b133a76b2e3
[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                         unsigned num_dummies = dummy.size();
649                         if (num_dummies == 0)
650                                 continue;
651
652                         // At least one dummy index, is it a defined scalar product?
653                         bool contracted = false;
654                         if (free.empty()) {
655                                 if (sp.is_defined(*it1, *it2)) {
656                                         *it1 = sp.evaluate(*it1, *it2);
657                                         *it2 = _ex1();
658                                         goto contraction_done;
659                                 }
660                         }
661
662                         // Contraction of symmetric with antisymmetric object is zero
663                         if (num_dummies > 1
664                          && ex_to<symmetry>(ex_to<indexed>(*it1).symtree).has_symmetry()
665                          && ex_to<symmetry>(ex_to<indexed>(*it2).symtree).has_symmetry()) {
666
667                                 // Check all pairs of dummy indices
668                                 for (unsigned idx1=0; idx1<num_dummies-1; idx1++) {
669                                         for (unsigned idx2=idx1+1; idx2<num_dummies; idx2++) {
670
671                                                 // Try and swap the index pair and check whether the
672                                                 // relative sign changed
673                                                 lst subs_lst(dummy[idx1].op(0), dummy[idx2].op(0)), repl_lst(dummy[idx2].op(0), dummy[idx1].op(0));
674                                                 ex swapped1 = it1->subs(subs_lst, repl_lst);
675                                                 ex swapped2 = it2->subs(subs_lst, repl_lst);
676                                                 if (it1->is_equal(swapped1) && it2->is_equal(-swapped2)
677                                                  || it1->is_equal(-swapped1) && it2->is_equal(swapped2)) {
678                                                         free_indices.clear();
679                                                         return _ex0();
680                                                 }
681                                         }
682                                 }
683                         }
684
685                         // Try to contract the first one with the second one
686                         contracted = it1->op(0).bp->contract_with(it1, it2, v);
687                         if (!contracted) {
688
689                                 // That didn't work; maybe the second object knows how to
690                                 // contract itself with the first one
691                                 contracted = it2->op(0).bp->contract_with(it2, it1, v);
692                         }
693                         if (contracted) {
694 contraction_done:
695                                 if (first_noncommutative || second_noncommutative
696                                  || is_ex_exactly_of_type(*it1, add) || is_ex_exactly_of_type(*it2, add)
697                                  || is_ex_exactly_of_type(*it1, mul) || is_ex_exactly_of_type(*it2, mul)
698                                  || is_ex_exactly_of_type(*it1, ncmul) || is_ex_exactly_of_type(*it2, ncmul)) {
699
700                                         // One of the factors became a sum or product:
701                                         // re-expand expression and run again
702                                         // Non-commutative products are always re-expanded to give
703                                         // simplify_ncmul() the chance to re-order and canonicalize
704                                         // the product
705                                         ex r = (non_commutative ? ex(ncmul(v, true)) : ex(mul(v)));
706                                         return simplify_indexed(r, free_indices, dummy_indices, sp);
707                                 }
708
709                                 // Both objects may have new indices now or they might
710                                 // even not be indexed objects any more, so we have to
711                                 // start over
712                                 something_changed = true;
713                                 goto try_again;
714                         }
715                 }
716         }
717
718         // Find free indices (concatenate them all and call find_free_and_dummy())
719         // and all dummy indices that appear
720         exvector un, individual_dummy_indices;
721         it1 = v.begin(); itend = v.end();
722         while (it1 != itend) {
723                 exvector free_indices_of_factor;
724                 if (is_ex_of_type(*it1, indexed)) {
725                         exvector dummy_indices_of_factor;
726                         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);
727                         individual_dummy_indices.insert(individual_dummy_indices.end(), dummy_indices_of_factor.begin(), dummy_indices_of_factor.end());
728                 } else
729                         free_indices_of_factor = it1->get_free_indices();
730                 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
731                 it1++;
732         }
733         exvector local_dummy_indices;
734         find_free_and_dummy(un, free_indices, local_dummy_indices);
735         local_dummy_indices.insert(local_dummy_indices.end(), individual_dummy_indices.begin(), individual_dummy_indices.end());
736
737         ex r;
738         if (something_changed)
739                 r = non_commutative ? ex(ncmul(v, true)) : ex(mul(v));
740         else
741                 r = e;
742
743         // Dummy index renaming
744         r = rename_dummy_indices(r, dummy_indices, local_dummy_indices);
745
746         // Product of indexed object with a scalar?
747         if (is_ex_exactly_of_type(r, mul) && r.nops() == 2
748          && is_ex_exactly_of_type(r.op(1), numeric) && is_ex_of_type(r.op(0), indexed))
749                 return r.op(0).op(0).bp->scalar_mul_indexed(r.op(0), ex_to<numeric>(r.op(1)));
750         else
751                 return r;
752 }
753
754 /** Simplify indexed expression, return list of free indices. */
755 ex simplify_indexed(const ex & e, exvector & free_indices, exvector & dummy_indices, const scalar_products & sp)
756 {
757         // Expand the expression
758         ex e_expanded = e.expand();
759
760         // Simplification of single indexed object: just find the free indices
761         // and perform dummy index renaming
762         if (is_ex_of_type(e_expanded, indexed)) {
763                 const indexed &i = ex_to<indexed>(e_expanded);
764                 exvector local_dummy_indices;
765                 find_free_and_dummy(i.seq.begin() + 1, i.seq.end(), free_indices, local_dummy_indices);
766                 return rename_dummy_indices(e_expanded, dummy_indices, local_dummy_indices);
767         }
768
769         // Simplification of sum = sum of simplifications, check consistency of
770         // free indices in each term
771         if (is_ex_exactly_of_type(e_expanded, add)) {
772                 bool first = true;
773                 ex sum = _ex0();
774                 free_indices.clear();
775
776                 for (unsigned i=0; i<e_expanded.nops(); i++) {
777                         exvector free_indices_of_term;
778                         ex term = simplify_indexed(e_expanded.op(i), free_indices_of_term, dummy_indices, sp);
779                         if (!term.is_zero()) {
780                                 if (first) {
781                                         free_indices = free_indices_of_term;
782                                         sum = term;
783                                         first = false;
784                                 } else {
785                                         if (!indices_consistent(free_indices, free_indices_of_term))
786                                                 throw (std::runtime_error("simplify_indexed: inconsistent indices in sum"));
787                                         if (is_ex_of_type(sum, indexed) && is_ex_of_type(term, indexed))
788                                                 sum = sum.op(0).bp->add_indexed(sum, term);
789                                         else
790                                                 sum += term;
791                                 }
792                         }
793                 }
794
795                 return sum;
796         }
797
798         // Simplification of products
799         if (is_ex_exactly_of_type(e_expanded, mul)
800          || is_ex_exactly_of_type(e_expanded, ncmul)
801          || (is_ex_exactly_of_type(e_expanded, power) && is_ex_of_type(e_expanded.op(0), indexed) && e_expanded.op(1).is_equal(_ex2())))
802                 return simplify_indexed_product(e_expanded, free_indices, dummy_indices, sp);
803
804         // Cannot do anything
805         free_indices.clear();
806         return e_expanded;
807 }
808
809 /** Simplify/canonicalize expression containing indexed objects. This
810  *  performs contraction of dummy indices where possible and checks whether
811  *  the free indices in sums are consistent.
812  *
813  *  @return simplified expression */
814 ex ex::simplify_indexed(void) const
815 {
816         exvector free_indices, dummy_indices;
817         scalar_products sp;
818         return GiNaC::simplify_indexed(*this, free_indices, dummy_indices, sp);
819 }
820
821 /** Simplify/canonicalize expression containing indexed objects. This
822  *  performs contraction of dummy indices where possible, checks whether
823  *  the free indices in sums are consistent, and automatically replaces
824  *  scalar products by known values if desired.
825  *
826  *  @param sp Scalar products to be replaced automatically
827  *  @return simplified expression */
828 ex ex::simplify_indexed(const scalar_products & sp) const
829 {
830         exvector free_indices, dummy_indices;
831         return GiNaC::simplify_indexed(*this, free_indices, dummy_indices, sp);
832 }
833
834 /** Symmetrize expression over its free indices. */
835 ex ex::symmetrize(void) const
836 {
837         return GiNaC::symmetrize(*this, get_free_indices());
838 }
839
840 /** Antisymmetrize expression over its free indices. */
841 ex ex::antisymmetrize(void) const
842 {
843         return GiNaC::antisymmetrize(*this, get_free_indices());
844 }
845
846 /** Symmetrize expression by cyclic permutation over its free indices. */
847 ex ex::symmetrize_cyclic(void) const
848 {
849         return GiNaC::symmetrize_cyclic(*this, get_free_indices());
850 }
851
852 //////////
853 // helper classes
854 //////////
855
856 void scalar_products::add(const ex & v1, const ex & v2, const ex & sp)
857 {
858         spm[make_key(v1, v2)] = sp;
859 }
860
861 void scalar_products::add_vectors(const lst & l)
862 {
863         // Add all possible pairs of products
864         unsigned num = l.nops();
865         for (unsigned i=0; i<num; i++) {
866                 ex a = l.op(i);
867                 for (unsigned j=0; j<num; j++) {
868                         ex b = l.op(j);
869                         add(a, b, a*b);
870                 }
871         }
872 }
873
874 void scalar_products::clear(void)
875 {
876         spm.clear();
877 }
878
879 /** Check whether scalar product pair is defined. */
880 bool scalar_products::is_defined(const ex & v1, const ex & v2) const
881 {
882         return spm.find(make_key(v1, v2)) != spm.end();
883 }
884
885 /** Return value of defined scalar product pair. */
886 ex scalar_products::evaluate(const ex & v1, const ex & v2) const
887 {
888         return spm.find(make_key(v1, v2))->second;
889 }
890
891 void scalar_products::debugprint(void) const
892 {
893         std::cerr << "map size=" << spm.size() << std::endl;
894         spmap::const_iterator i = spm.begin(), end = spm.end();
895         while (i != end) {
896                 const spmapkey & k = i->first;
897                 std::cerr << "item key=(" << k.first << "," << k.second;
898                 std::cerr << "), value=" << i->second << std::endl;
899                 ++i;
900         }
901 }
902
903 /** Make key from object pair. */
904 spmapkey scalar_products::make_key(const ex & v1, const ex & v2)
905 {
906         // If indexed, extract base objects
907         ex s1 = is_ex_of_type(v1, indexed) ? v1.op(0) : v1;
908         ex s2 = is_ex_of_type(v2, indexed) ? v2.op(0) : v2;
909
910         // Enforce canonical order in pair
911         if (s1.compare(s2) > 0)
912                 return spmapkey(s2, s1);
913         else
914                 return spmapkey(s1, s2);
915 }
916
917 } // namespace GiNaC