Added integral class.
[ginac.git] / ginac / indexed.cpp
1 /** @file indexed.cpp
2  *
3  *  Implementation of GiNaC's indexed expressions. */
4
5 /*
6  *  GiNaC Copyright (C) 1999-2004 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 <iostream>
24 #include <sstream>
25 #include <stdexcept>
26
27 #include "indexed.h"
28 #include "idx.h"
29 #include "add.h"
30 #include "mul.h"
31 #include "ncmul.h"
32 #include "power.h"
33 #include "relational.h"
34 #include "symmetry.h"
35 #include "operators.h"
36 #include "lst.h"
37 #include "archive.h"
38 #include "utils.h"
39 #include "integral.h"
40
41 namespace GiNaC {
42
43 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(indexed, exprseq,
44   print_func<print_context>(&indexed::do_print).
45   print_func<print_latex>(&indexed::do_print_latex).
46   print_func<print_tree>(&indexed::do_print_tree))
47
48 //////////
49 // default constructor
50 //////////
51
52 indexed::indexed() : symtree(not_symmetric())
53 {
54         tinfo_key = TINFO_indexed;
55 }
56
57 //////////
58 // other constructors
59 //////////
60
61 indexed::indexed(const ex & b) : inherited(b), symtree(not_symmetric())
62 {
63         tinfo_key = TINFO_indexed;
64         validate();
65 }
66
67 indexed::indexed(const ex & b, const ex & i1) : inherited(b, i1), symtree(not_symmetric())
68 {
69         tinfo_key = TINFO_indexed;
70         validate();
71 }
72
73 indexed::indexed(const ex & b, const ex & i1, const ex & i2) : inherited(b, i1, i2), symtree(not_symmetric())
74 {
75         tinfo_key = TINFO_indexed;
76         validate();
77 }
78
79 indexed::indexed(const ex & b, const ex & i1, const ex & i2, const ex & i3) : inherited(b, i1, i2, i3), symtree(not_symmetric())
80 {
81         tinfo_key = TINFO_indexed;
82         validate();
83 }
84
85 indexed::indexed(const ex & b, const ex & i1, const ex & i2, const ex & i3, const ex & i4) : inherited(b, i1, i2, i3, i4), symtree(not_symmetric())
86 {
87         tinfo_key = TINFO_indexed;
88         validate();
89 }
90
91 indexed::indexed(const ex & b, const symmetry & symm, const ex & i1, const ex & i2) : inherited(b, i1, i2), symtree(symm)
92 {
93         tinfo_key = TINFO_indexed;
94         validate();
95 }
96
97 indexed::indexed(const ex & b, const symmetry & symm, const ex & i1, const ex & i2, const ex & i3) : inherited(b, i1, i2, i3), symtree(symm)
98 {
99         tinfo_key = TINFO_indexed;
100         validate();
101 }
102
103 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)
104 {
105         tinfo_key = TINFO_indexed;
106         validate();
107 }
108
109 indexed::indexed(const ex & b, const exvector & v) : inherited(b), symtree(not_symmetric())
110 {
111         seq.insert(seq.end(), v.begin(), v.end());
112         tinfo_key = TINFO_indexed;
113         validate();
114 }
115
116 indexed::indexed(const ex & b, const symmetry & symm, const exvector & v) : inherited(b), symtree(symm)
117 {
118         seq.insert(seq.end(), v.begin(), v.end());
119         tinfo_key = TINFO_indexed;
120         validate();
121 }
122
123 indexed::indexed(const symmetry & symm, const exprseq & es) : inherited(es), symtree(symm)
124 {
125         tinfo_key = TINFO_indexed;
126 }
127
128 indexed::indexed(const symmetry & symm, const exvector & v, bool discardable) : inherited(v, discardable), symtree(symm)
129 {
130         tinfo_key = TINFO_indexed;
131 }
132
133 indexed::indexed(const symmetry & symm, std::auto_ptr<exvector> vp) : inherited(vp), symtree(symm)
134 {
135         tinfo_key = TINFO_indexed;
136 }
137
138 //////////
139 // archiving
140 //////////
141
142 indexed::indexed(const archive_node &n, lst &sym_lst) : inherited(n, sym_lst)
143 {
144         if (!n.find_ex("symmetry", symtree, sym_lst)) {
145                 // GiNaC versions <= 0.9.0 had an unsigned "symmetry" property
146                 unsigned symm = 0;
147                 n.find_unsigned("symmetry", symm);
148                 switch (symm) {
149                         case 1:
150                                 symtree = sy_symm();
151                                 break;
152                         case 2:
153                                 symtree = sy_anti();
154                                 break;
155                         default:
156                                 symtree = not_symmetric();
157                                 break;
158                 }
159                 const_cast<symmetry &>(ex_to<symmetry>(symtree)).validate(seq.size() - 1);
160         }
161 }
162
163 void indexed::archive(archive_node &n) const
164 {
165         inherited::archive(n);
166         n.add_ex("symmetry", symtree);
167 }
168
169 DEFAULT_UNARCHIVE(indexed)
170
171 //////////
172 // functions overriding virtual functions from base classes
173 //////////
174
175 void indexed::printindices(const print_context & c, unsigned level) const
176 {
177         if (seq.size() > 1) {
178
179                 exvector::const_iterator it=seq.begin() + 1, itend = seq.end();
180
181                 if (is_a<print_latex>(c)) {
182
183                         // TeX output: group by variance
184                         bool first = true;
185                         bool covariant = true;
186
187                         while (it != itend) {
188                                 bool cur_covariant = (is_a<varidx>(*it) ? ex_to<varidx>(*it).is_covariant() : true);
189                                 if (first || cur_covariant != covariant) { // Variance changed
190                                         // The empty {} prevents indices from ending up on top of each other
191                                         if (!first)
192                                                 c.s << "}{}";
193                                         covariant = cur_covariant;
194                                         if (covariant)
195                                                 c.s << "_{";
196                                         else
197                                                 c.s << "^{";
198                                 }
199                                 it->print(c, level);
200                                 c.s << " ";
201                                 first = false;
202                                 it++;
203                         }
204                         c.s << "}";
205
206                 } else {
207
208                         // Ordinary output
209                         while (it != itend) {
210                                 it->print(c, level);
211                                 it++;
212                         }
213                 }
214         }
215 }
216
217 void indexed::print_indexed(const print_context & c, const char *openbrace, const char *closebrace, unsigned level) const
218 {
219         if (precedence() <= level)
220                 c.s << openbrace << '(';
221         c.s << openbrace;
222         seq[0].print(c, precedence());
223         c.s << closebrace;
224         printindices(c, level);
225         if (precedence() <= level)
226                 c.s << ')' << closebrace;
227 }
228
229 void indexed::do_print(const print_context & c, unsigned level) const
230 {
231         print_indexed(c, "", "", level);
232 }
233
234 void indexed::do_print_latex(const print_latex & c, unsigned level) const
235 {
236         print_indexed(c, "{", "}", level);
237 }
238
239 void indexed::do_print_tree(const print_tree & c, unsigned level) const
240 {
241         c.s << std::string(level, ' ') << class_name() << " @" << this
242             << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
243             << ", " << seq.size()-1 << " indices"
244             << ", symmetry=" << symtree << std::endl;
245         seq[0].print(c, level + c.delta_indent);
246         printindices(c, level + c.delta_indent);
247 }
248
249 bool indexed::info(unsigned inf) const
250 {
251         if (inf == info_flags::indexed) return true;
252         if (inf == info_flags::has_indices) return seq.size() > 1;
253         return inherited::info(inf);
254 }
255
256 struct idx_is_not : public std::binary_function<ex, unsigned, bool> {
257         bool operator() (const ex & e, unsigned inf) const {
258                 return !(ex_to<idx>(e).get_value().info(inf));
259         }
260 };
261
262 bool indexed::all_index_values_are(unsigned inf) const
263 {
264         // No indices? Then no property can be fulfilled
265         if (seq.size() < 2)
266                 return false;
267
268         // Check all indices
269         return find_if(seq.begin() + 1, seq.end(), bind2nd(idx_is_not(), inf)) == seq.end();
270 }
271
272 int indexed::compare_same_type(const basic & other) const
273 {
274         GINAC_ASSERT(is_a<indexed>(other));
275         return inherited::compare_same_type(other);
276 }
277
278 ex indexed::eval(int level) const
279 {
280         // First evaluate children, then we will end up here again
281         if (level > 1)
282                 return indexed(ex_to<symmetry>(symtree), evalchildren(level));
283
284         const ex &base = seq[0];
285
286         // If the base object is 0, the whole object is 0
287         if (base.is_zero())
288                 return _ex0;
289
290         // If the base object is a product, pull out the numeric factor
291         if (is_exactly_a<mul>(base) && is_exactly_a<numeric>(base.op(base.nops() - 1))) {
292                 exvector v(seq);
293                 ex f = ex_to<numeric>(base.op(base.nops() - 1));
294                 v[0] = seq[0] / f;
295                 return f * thiscontainer(v);
296         }
297
298         // Canonicalize indices according to the symmetry properties
299         if (seq.size() > 2) {
300                 exvector v = seq;
301                 GINAC_ASSERT(is_exactly_a<symmetry>(symtree));
302                 int sig = canonicalize(v.begin() + 1, ex_to<symmetry>(symtree));
303                 if (sig != INT_MAX) {
304                         // Something has changed while sorting indices, more evaluations later
305                         if (sig == 0)
306                                 return _ex0;
307                         return ex(sig) * thiscontainer(v);
308                 }
309         }
310
311         // Let the class of the base object perform additional evaluations
312         return ex_to<basic>(base).eval_indexed(*this);
313 }
314
315 ex indexed::thiscontainer(const exvector & v) const
316 {
317         return indexed(ex_to<symmetry>(symtree), v);
318 }
319
320 ex indexed::thiscontainer(std::auto_ptr<exvector> vp) const
321 {
322         return indexed(ex_to<symmetry>(symtree), vp);
323 }
324
325 ex indexed::expand(unsigned options) const
326 {
327         GINAC_ASSERT(seq.size() > 0);
328
329         if (options & expand_options::expand_indexed) {
330                 ex newbase = seq[0].expand(options);
331                 if (is_exactly_a<add>(newbase)) {
332                         ex sum = _ex0;
333                         for (size_t i=0; i<newbase.nops(); i++) {
334                                 exvector s = seq;
335                                 s[0] = newbase.op(i);
336                                 sum += thiscontainer(s).expand(options);
337                         }
338                         return sum;
339                 }
340                 if (!are_ex_trivially_equal(newbase, seq[0])) {
341                         exvector s = seq;
342                         s[0] = newbase;
343                         return ex_to<indexed>(thiscontainer(s)).inherited::expand(options);
344                 }
345         }
346         return inherited::expand(options);
347 }
348
349 //////////
350 // virtual functions which can be overridden by derived classes
351 //////////
352
353 // none
354
355 //////////
356 // non-virtual functions in this class
357 //////////
358
359 /** Check whether all indices are of class idx and validate the symmetry
360  *  tree. This function is used internally to make sure that all constructed
361  *  indexed objects really carry indices and not some other classes. */
362 void indexed::validate() const
363 {
364         GINAC_ASSERT(seq.size() > 0);
365         exvector::const_iterator it = seq.begin() + 1, itend = seq.end();
366         while (it != itend) {
367                 if (!is_a<idx>(*it))
368                         throw(std::invalid_argument("indices of indexed object must be of type idx"));
369                 it++;
370         }
371
372         if (!symtree.is_zero()) {
373                 if (!is_exactly_a<symmetry>(symtree))
374                         throw(std::invalid_argument("symmetry of indexed object must be of type symmetry"));
375                 const_cast<symmetry &>(ex_to<symmetry>(symtree)).validate(seq.size() - 1);
376         }
377 }
378
379 /** Implementation of ex::diff() for an indexed object always returns 0.
380  *
381  *  @see ex::diff */
382 ex indexed::derivative(const symbol & s) const
383 {
384         return _ex0;
385 }
386
387 //////////
388 // global functions
389 //////////
390
391 struct idx_is_equal_ignore_dim : public std::binary_function<ex, ex, bool> {
392         bool operator() (const ex &lh, const ex &rh) const
393         {
394                 if (lh.is_equal(rh))
395                         return true;
396                 else
397                         try {
398                                 // Replacing the dimension might cause an error (e.g. with
399                                 // index classes that only work in a fixed number of dimensions)
400                                 return lh.is_equal(ex_to<idx>(rh).replace_dim(ex_to<idx>(lh).get_dim()));
401                         } catch (...) {
402                                 return false;
403                         }
404         }
405 };
406
407 /** Check whether two sorted index vectors are consistent (i.e. equal). */
408 static bool indices_consistent(const exvector & v1, const exvector & v2)
409 {
410         // Number of indices must be the same
411         if (v1.size() != v2.size())
412                 return false;
413
414         return equal(v1.begin(), v1.end(), v2.begin(), idx_is_equal_ignore_dim());
415 }
416
417 exvector indexed::get_indices() const
418 {
419         GINAC_ASSERT(seq.size() >= 1);
420         return exvector(seq.begin() + 1, seq.end());
421 }
422
423 exvector indexed::get_dummy_indices() const
424 {
425         exvector free_indices, dummy_indices;
426         find_free_and_dummy(seq.begin() + 1, seq.end(), free_indices, dummy_indices);
427         return dummy_indices;
428 }
429
430 exvector indexed::get_dummy_indices(const indexed & other) const
431 {
432         exvector indices = get_free_indices();
433         exvector other_indices = other.get_free_indices();
434         indices.insert(indices.end(), other_indices.begin(), other_indices.end());
435         exvector dummy_indices;
436         find_dummy_indices(indices, dummy_indices);
437         return dummy_indices;
438 }
439
440 bool indexed::has_dummy_index_for(const ex & i) const
441 {
442         exvector::const_iterator it = seq.begin() + 1, itend = seq.end();
443         while (it != itend) {
444                 if (is_dummy_pair(*it, i))
445                         return true;
446                 it++;
447         }
448         return false;
449 }
450
451 exvector indexed::get_free_indices() const
452 {
453         exvector free_indices, dummy_indices;
454         find_free_and_dummy(seq.begin() + 1, seq.end(), free_indices, dummy_indices);
455         return free_indices;
456 }
457
458 exvector add::get_free_indices() const
459 {
460         exvector free_indices;
461         for (size_t i=0; i<nops(); i++) {
462                 if (i == 0)
463                         free_indices = op(i).get_free_indices();
464                 else {
465                         exvector free_indices_of_term = op(i).get_free_indices();
466                         if (!indices_consistent(free_indices, free_indices_of_term))
467                                 throw (std::runtime_error("add::get_free_indices: inconsistent indices in sum"));
468                 }
469         }
470         return free_indices;
471 }
472
473 exvector mul::get_free_indices() const
474 {
475         // Concatenate free indices of all factors
476         exvector un;
477         for (size_t i=0; i<nops(); i++) {
478                 exvector free_indices_of_factor = op(i).get_free_indices();
479                 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
480         }
481
482         // And remove the dummy indices
483         exvector free_indices, dummy_indices;
484         find_free_and_dummy(un, free_indices, dummy_indices);
485         return free_indices;
486 }
487
488 exvector ncmul::get_free_indices() const
489 {
490         // Concatenate free indices of all factors
491         exvector un;
492         for (size_t i=0; i<nops(); i++) {
493                 exvector free_indices_of_factor = op(i).get_free_indices();
494                 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
495         }
496
497         // And remove the dummy indices
498         exvector free_indices, dummy_indices;
499         find_free_and_dummy(un, free_indices, dummy_indices);
500         return free_indices;
501 }
502
503 struct is_summation_idx : public std::unary_function<ex, bool> {
504         bool operator()(const ex & e)
505         {
506                 return is_dummy_pair(e, e);
507         }
508 };
509
510 exvector power::get_free_indices() const
511 {
512         // Get free indices of basis
513         exvector basis_indices = basis.get_free_indices();
514
515         if (exponent.info(info_flags::even)) {
516                 // If the exponent is an even number, then any "free" index that
517                 // forms a dummy pair with itself is actually a summation index
518                 exvector really_free;
519                 std::remove_copy_if(basis_indices.begin(), basis_indices.end(),
520                                     std::back_inserter(really_free), is_summation_idx());
521                 return really_free;
522         } else
523                 return basis_indices;
524 }
525
526 exvector integral::get_free_indices() const
527 {
528         if (a.get_free_indices().size() || b.get_free_indices().size())
529                 throw (std::runtime_error("integral::get_free_indices: boundary values should not have free indices"));
530         return f.get_free_indices();
531 }
532
533 /** Rename dummy indices in an expression.
534  *
535  *  @param e Expression to work on
536  *  @param local_dummy_indices The set of dummy indices that appear in the
537  *    expression "e"
538  *  @param global_dummy_indices The set of dummy indices that have appeared
539  *    before and which we would like to use in "e", too. This gets updated
540  *    by the function */
541 static ex rename_dummy_indices(const ex & e, exvector & global_dummy_indices, exvector & local_dummy_indices)
542 {
543         size_t global_size = global_dummy_indices.size(),
544                local_size = local_dummy_indices.size();
545
546         // Any local dummy indices at all?
547         if (local_size == 0)
548                 return e;
549
550         if (global_size < local_size) {
551
552                 // More local indices than we encountered before, add the new ones
553                 // to the global set
554                 size_t old_global_size = global_size;
555                 int remaining = local_size - global_size;
556                 exvector::const_iterator it = local_dummy_indices.begin(), itend = local_dummy_indices.end();
557                 while (it != itend && remaining > 0) {
558                         if (find_if(global_dummy_indices.begin(), global_dummy_indices.end(), bind2nd(op0_is_equal(), *it)) == global_dummy_indices.end()) {
559                                 global_dummy_indices.push_back(*it);
560                                 global_size++;
561                                 remaining--;
562                         }
563                         it++;
564                 }
565
566                 // If this is the first set of local indices, do nothing
567                 if (old_global_size == 0)
568                         return e;
569         }
570         GINAC_ASSERT(local_size <= global_size);
571
572         // Construct vectors of index symbols
573         exvector local_syms, global_syms;
574         local_syms.reserve(local_size);
575         global_syms.reserve(local_size);
576         for (size_t i=0; i<local_size; i++)
577                 local_syms.push_back(local_dummy_indices[i].op(0));
578         shaker_sort(local_syms.begin(), local_syms.end(), ex_is_less(), ex_swap());
579         for (size_t i=0; i<local_size; i++) // don't use more global symbols than necessary
580                 global_syms.push_back(global_dummy_indices[i].op(0));
581         shaker_sort(global_syms.begin(), global_syms.end(), ex_is_less(), ex_swap());
582
583         // Remove common indices
584         exvector local_uniq, global_uniq;
585         set_difference(local_syms.begin(), local_syms.end(), global_syms.begin(), global_syms.end(), std::back_insert_iterator<exvector>(local_uniq), ex_is_less());
586         set_difference(global_syms.begin(), global_syms.end(), local_syms.begin(), local_syms.end(), std::back_insert_iterator<exvector>(global_uniq), ex_is_less());
587
588         // Replace remaining non-common local index symbols by global ones
589         if (local_uniq.empty())
590                 return e;
591         else {
592                 while (global_uniq.size() > local_uniq.size())
593                         global_uniq.pop_back();
594                 return e.subs(lst(local_uniq.begin(), local_uniq.end()), lst(global_uniq.begin(), global_uniq.end()), subs_options::no_pattern);
595         }
596 }
597
598 /** Given a set of indices, extract those of class varidx. */
599 static void find_variant_indices(const exvector & v, exvector & variant_indices)
600 {
601         exvector::const_iterator it1, itend;
602         for (it1 = v.begin(), itend = v.end(); it1 != itend; ++it1) {
603                 if (is_exactly_a<varidx>(*it1))
604                         variant_indices.push_back(*it1);
605         }
606 }
607
608 /** Raise/lower dummy indices in a single indexed objects to canonicalize their
609  *  variance.
610  *
611  *  @param e Object to work on
612  *  @param variant_dummy_indices The set of indices that might need repositioning (will be changed by this function)
613  *  @param moved_indices The set of indices that have been repositioned (will be changed by this function)
614  *  @return true if 'e' was changed */
615 bool reposition_dummy_indices(ex & e, exvector & variant_dummy_indices, exvector & moved_indices)
616 {
617         bool something_changed = false;
618
619         // If a dummy index is encountered for the first time in the
620         // product, pull it up, otherwise, pull it down
621         exvector::const_iterator it2, it2start, it2end;
622         for (it2start = ex_to<indexed>(e).seq.begin(), it2end = ex_to<indexed>(e).seq.end(), it2 = it2start + 1; it2 != it2end; ++it2) {
623                 if (!is_exactly_a<varidx>(*it2))
624                         continue;
625
626                 exvector::iterator vit, vitend;
627                 for (vit = variant_dummy_indices.begin(), vitend = variant_dummy_indices.end(); vit != vitend; ++vit) {
628                         if (it2->op(0).is_equal(vit->op(0))) {
629                                 if (ex_to<varidx>(*it2).is_covariant()) {
630                                         e = e.subs(lst(
631                                                 *it2 == ex_to<varidx>(*it2).toggle_variance(),
632                                                 ex_to<varidx>(*it2).toggle_variance() == *it2
633                                         ), subs_options::no_pattern);
634                                         something_changed = true;
635                                         it2 = ex_to<indexed>(e).seq.begin() + (it2 - it2start);
636                                         it2start = ex_to<indexed>(e).seq.begin();
637                                         it2end = ex_to<indexed>(e).seq.end();
638                                 }
639                                 moved_indices.push_back(*vit);
640                                 variant_dummy_indices.erase(vit);
641                                 goto next_index;
642                         }
643                 }
644
645                 for (vit = moved_indices.begin(), vitend = moved_indices.end(); vit != vitend; ++vit) {
646                         if (it2->op(0).is_equal(vit->op(0))) {
647                                 if (ex_to<varidx>(*it2).is_contravariant()) {
648                                         e = e.subs(*it2 == ex_to<varidx>(*it2).toggle_variance(), subs_options::no_pattern);
649                                         something_changed = true;
650                                         it2 = ex_to<indexed>(e).seq.begin() + (it2 - it2start);
651                                         it2start = ex_to<indexed>(e).seq.begin();
652                                         it2end = ex_to<indexed>(e).seq.end();
653                                 }
654                                 goto next_index;
655                         }
656                 }
657
658 next_index: ;
659         }
660
661         return something_changed;
662 }
663
664 /* Ordering that only compares the base expressions of indexed objects. */
665 struct ex_base_is_less : public std::binary_function<ex, ex, bool> {
666         bool operator() (const ex &lh, const ex &rh) const
667         {
668                 return (is_a<indexed>(lh) ? lh.op(0) : lh).compare(is_a<indexed>(rh) ? rh.op(0) : rh) < 0;
669         }
670 };
671
672 /** Simplify product of indexed expressions (commutative, noncommutative and
673  *  simple squares), return list of free indices. */
674 ex simplify_indexed_product(const ex & e, exvector & free_indices, exvector & dummy_indices, const scalar_products & sp)
675 {
676         // Remember whether the product was commutative or noncommutative
677         // (because we chop it into factors and need to reassemble later)
678         bool non_commutative = is_exactly_a<ncmul>(e);
679
680         // Collect factors in an exvector, store squares twice
681         exvector v;
682         v.reserve(e.nops() * 2);
683
684         if (is_exactly_a<power>(e)) {
685                 // We only get called for simple squares, split a^2 -> a*a
686                 GINAC_ASSERT(e.op(1).is_equal(_ex2));
687                 v.push_back(e.op(0));
688                 v.push_back(e.op(0));
689         } else {
690                 for (size_t i=0; i<e.nops(); i++) {
691                         ex f = e.op(i);
692                         if (is_exactly_a<power>(f) && f.op(1).is_equal(_ex2)) {
693                                 v.push_back(f.op(0));
694                     v.push_back(f.op(0));
695                         } else if (is_exactly_a<ncmul>(f)) {
696                                 // Noncommutative factor found, split it as well
697                                 non_commutative = true; // everything becomes noncommutative, ncmul will sort out the commutative factors later
698                                 for (size_t j=0; j<f.nops(); j++)
699                                         v.push_back(f.op(j));
700                         } else
701                                 v.push_back(f);
702                 }
703         }
704
705         // Perform contractions
706         bool something_changed = false;
707         GINAC_ASSERT(v.size() > 1);
708         exvector::iterator it1, itend = v.end(), next_to_last = itend - 1;
709         for (it1 = v.begin(); it1 != next_to_last; it1++) {
710
711 try_again:
712                 if (!is_a<indexed>(*it1))
713                         continue;
714
715                 bool first_noncommutative = (it1->return_type() != return_types::commutative);
716
717                 // Indexed factor found, get free indices and look for contraction
718                 // candidates
719                 exvector free1, dummy1;
720                 find_free_and_dummy(ex_to<indexed>(*it1).seq.begin() + 1, ex_to<indexed>(*it1).seq.end(), free1, dummy1);
721
722                 exvector::iterator it2;
723                 for (it2 = it1 + 1; it2 != itend; it2++) {
724
725                         if (!is_a<indexed>(*it2))
726                                 continue;
727
728                         bool second_noncommutative = (it2->return_type() != return_types::commutative);
729
730                         // Find free indices of second factor and merge them with free
731                         // indices of first factor
732                         exvector un;
733                         find_free_and_dummy(ex_to<indexed>(*it2).seq.begin() + 1, ex_to<indexed>(*it2).seq.end(), un, dummy1);
734                         un.insert(un.end(), free1.begin(), free1.end());
735
736                         // Check whether the two factors share dummy indices
737                         exvector free, dummy;
738                         find_free_and_dummy(un, free, dummy);
739                         size_t num_dummies = dummy.size();
740                         if (num_dummies == 0)
741                                 continue;
742
743                         // At least one dummy index, is it a defined scalar product?
744                         bool contracted = false;
745                         if (free.empty()) {
746
747                                 // Find minimal dimension of all indices of both factors
748                                 exvector::const_iterator dit = ex_to<indexed>(*it1).seq.begin() + 1, ditend = ex_to<indexed>(*it1).seq.end();
749                                 ex dim = ex_to<idx>(*dit).get_dim();
750                                 ++dit;
751                                 for (; dit != ditend; ++dit) {
752                                         dim = minimal_dim(dim, ex_to<idx>(*dit).get_dim());
753                                 }
754                                 dit = ex_to<indexed>(*it2).seq.begin() + 1;
755                                 ditend = ex_to<indexed>(*it2).seq.end();
756                                 for (; dit != ditend; ++dit) {
757                                         dim = minimal_dim(dim, ex_to<idx>(*dit).get_dim());
758                                 }
759
760                                 // User-defined scalar product?
761                                 if (sp.is_defined(*it1, *it2, dim)) {
762
763                                         // Yes, substitute it
764                                         *it1 = sp.evaluate(*it1, *it2, dim);
765                                         *it2 = _ex1;
766                                         goto contraction_done;
767                                 }
768                         }
769
770                         // Try to contract the first one with the second one
771                         contracted = ex_to<basic>(it1->op(0)).contract_with(it1, it2, v);
772                         if (!contracted) {
773
774                                 // That didn't work; maybe the second object knows how to
775                                 // contract itself with the first one
776                                 contracted = ex_to<basic>(it2->op(0)).contract_with(it2, it1, v);
777                         }
778                         if (contracted) {
779 contraction_done:
780                                 if (first_noncommutative || second_noncommutative
781                                  || is_exactly_a<add>(*it1) || is_exactly_a<add>(*it2)
782                                  || is_exactly_a<mul>(*it1) || is_exactly_a<mul>(*it2)
783                                  || is_exactly_a<ncmul>(*it1) || is_exactly_a<ncmul>(*it2)) {
784
785                                         // One of the factors became a sum or product:
786                                         // re-expand expression and run again
787                                         // Non-commutative products are always re-expanded to give
788                                         // eval_ncmul() the chance to re-order and canonicalize
789                                         // the product
790                                         ex r = (non_commutative ? ex(ncmul(v, true)) : ex(mul(v)));
791                                         return simplify_indexed(r, free_indices, dummy_indices, sp);
792                                 }
793
794                                 // Both objects may have new indices now or they might
795                                 // even not be indexed objects any more, so we have to
796                                 // start over
797                                 something_changed = true;
798                                 goto try_again;
799                         }
800                 }
801         }
802
803         // Find free indices (concatenate them all and call find_free_and_dummy())
804         // and all dummy indices that appear
805         exvector un, individual_dummy_indices;
806         for (it1 = v.begin(), itend = v.end(); it1 != itend; ++it1) {
807                 exvector free_indices_of_factor;
808                 if (is_a<indexed>(*it1)) {
809                         exvector dummy_indices_of_factor;
810                         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);
811                         individual_dummy_indices.insert(individual_dummy_indices.end(), dummy_indices_of_factor.begin(), dummy_indices_of_factor.end());
812                 } else
813                         free_indices_of_factor = it1->get_free_indices();
814                 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
815         }
816         exvector local_dummy_indices;
817         find_free_and_dummy(un, free_indices, local_dummy_indices);
818         local_dummy_indices.insert(local_dummy_indices.end(), individual_dummy_indices.begin(), individual_dummy_indices.end());
819
820         // Filter out the dummy indices with variance
821         exvector variant_dummy_indices;
822         find_variant_indices(local_dummy_indices, variant_dummy_indices);
823
824         // Any indices with variance present at all?
825         if (!variant_dummy_indices.empty()) {
826
827                 // Yes, bring the product into a canonical order that only depends on
828                 // the base expressions of indexed objects
829                 if (!non_commutative)
830                         std::sort(v.begin(), v.end(), ex_base_is_less());
831
832                 exvector moved_indices;
833
834                 // Iterate over all indexed objects in the product
835                 for (it1 = v.begin(), itend = v.end(); it1 != itend; ++it1) {
836                         if (!is_a<indexed>(*it1))
837                                 continue;
838
839                         if (reposition_dummy_indices(*it1, variant_dummy_indices, moved_indices))
840                                 something_changed = true;
841                 }
842         }
843
844         ex r;
845         if (something_changed)
846                 r = non_commutative ? ex(ncmul(v, true)) : ex(mul(v));
847         else
848                 r = e;
849
850         // The result should be symmetric with respect to exchange of dummy
851         // indices, so if the symmetrization vanishes, the whole expression is
852         // zero. This detects things like eps.i.j.k * p.j * p.k = 0.
853         if (local_dummy_indices.size() >= 2) {
854                 exvector dummy_syms;
855                 dummy_syms.reserve(local_dummy_indices.size());
856                 for (exvector::const_iterator it = local_dummy_indices.begin(); it != local_dummy_indices.end(); ++it)
857                         dummy_syms.push_back(it->op(0));
858                 if (symmetrize(r, dummy_syms).is_zero()) {
859                         free_indices.clear();
860                         return _ex0;
861                 }
862         }
863
864         // Dummy index renaming
865         r = rename_dummy_indices(r, dummy_indices, local_dummy_indices);
866
867         // Product of indexed object with a scalar?
868         if (is_exactly_a<mul>(r) && r.nops() == 2
869          && is_exactly_a<numeric>(r.op(1)) && is_a<indexed>(r.op(0)))
870                 return ex_to<basic>(r.op(0).op(0)).scalar_mul_indexed(r.op(0), ex_to<numeric>(r.op(1)));
871         else
872                 return r;
873 }
874
875 /** This structure stores the original and symmetrized versions of terms
876  *  obtained during the simplification of sums. */
877 class terminfo {
878 public:
879         terminfo(const ex & orig_, const ex & symm_) : orig(orig_), symm(symm_) {}
880
881         ex orig; /**< original term */
882         ex symm; /**< symmtrized term */
883 };
884
885 class terminfo_is_less {
886 public:
887         bool operator() (const terminfo & ti1, const terminfo & ti2) const
888         {
889                 return (ti1.symm.compare(ti2.symm) < 0);
890         }
891 };
892
893 /** This structure stores the individual symmetrized terms obtained during
894  *  the simplification of sums. */
895 class symminfo {
896 public:
897         symminfo() : num(0) {}
898
899         symminfo(const ex & symmterm_, const ex & orig_, size_t num_) : orig(orig_), num(num_)
900         {
901                 if (is_exactly_a<mul>(symmterm_) && is_exactly_a<numeric>(symmterm_.op(symmterm_.nops()-1))) {
902                         coeff = symmterm_.op(symmterm_.nops()-1);
903                         symmterm = symmterm_ / coeff;
904                 } else {
905                         coeff = 1;
906                         symmterm = symmterm_;
907                 }
908         }
909
910         ex symmterm;  /**< symmetrized term */
911         ex coeff;     /**< coefficient of symmetrized term */
912         ex orig;      /**< original term */
913         size_t num; /**< how many symmetrized terms resulted from the original term */
914 };
915
916 class symminfo_is_less_by_symmterm {
917 public:
918         bool operator() (const symminfo & si1, const symminfo & si2) const
919         {
920                 return (si1.symmterm.compare(si2.symmterm) < 0);
921         }
922 };
923
924 class symminfo_is_less_by_orig {
925 public:
926         bool operator() (const symminfo & si1, const symminfo & si2) const
927         {
928                 return (si1.orig.compare(si2.orig) < 0);
929         }
930 };
931
932 /** Simplify indexed expression, return list of free indices. */
933 ex simplify_indexed(const ex & e, exvector & free_indices, exvector & dummy_indices, const scalar_products & sp)
934 {
935         // Expand the expression
936         ex e_expanded = e.expand();
937
938         // Simplification of single indexed object: just find the free indices
939         // and perform dummy index renaming/repositioning
940         if (is_a<indexed>(e_expanded)) {
941
942                 // Find the dummy indices
943                 const indexed &i = ex_to<indexed>(e_expanded);
944                 exvector local_dummy_indices;
945                 find_free_and_dummy(i.seq.begin() + 1, i.seq.end(), free_indices, local_dummy_indices);
946
947                 // Filter out the dummy indices with variance
948                 exvector variant_dummy_indices;
949                 find_variant_indices(local_dummy_indices, variant_dummy_indices);
950
951                 // Any indices with variance present at all?
952                 if (!variant_dummy_indices.empty()) {
953
954                         // Yes, reposition them
955                         exvector moved_indices;
956                         reposition_dummy_indices(e_expanded, variant_dummy_indices, moved_indices);
957                 }
958
959                 // Rename the dummy indices
960                 return rename_dummy_indices(e_expanded, dummy_indices, local_dummy_indices);
961         }
962
963         // Simplification of sum = sum of simplifications, check consistency of
964         // free indices in each term
965         if (is_exactly_a<add>(e_expanded)) {
966                 bool first = true;
967                 ex sum;
968                 free_indices.clear();
969
970                 for (size_t i=0; i<e_expanded.nops(); i++) {
971                         exvector free_indices_of_term;
972                         ex term = simplify_indexed(e_expanded.op(i), free_indices_of_term, dummy_indices, sp);
973                         if (!term.is_zero()) {
974                                 if (first) {
975                                         free_indices = free_indices_of_term;
976                                         sum = term;
977                                         first = false;
978                                 } else {
979                                         if (!indices_consistent(free_indices, free_indices_of_term)) {
980                                                 std::ostringstream s;
981                                                 s << "simplify_indexed: inconsistent indices in sum: ";
982                                                 s << exprseq(free_indices) << " vs. " << exprseq(free_indices_of_term);
983                                                 throw (std::runtime_error(s.str()));
984                                         }
985                                         if (is_a<indexed>(sum) && is_a<indexed>(term))
986                                                 sum = ex_to<basic>(sum.op(0)).add_indexed(sum, term);
987                                         else
988                                                 sum += term;
989                                 }
990                         }
991                 }
992
993                 // If the sum turns out to be zero, we are finished
994                 if (sum.is_zero()) {
995                         free_indices.clear();
996                         return sum;
997                 }
998
999                 // More than one term and more than one dummy index?
1000                 size_t num_terms_orig = (is_exactly_a<add>(sum) ? sum.nops() : 1);
1001                 if (num_terms_orig < 2 || dummy_indices.size() < 2)
1002                         return sum;
1003
1004                 // Yes, construct vector of all dummy index symbols
1005                 exvector dummy_syms;
1006                 dummy_syms.reserve(dummy_indices.size());
1007                 for (exvector::const_iterator it = dummy_indices.begin(); it != dummy_indices.end(); ++it)
1008                         dummy_syms.push_back(it->op(0));
1009
1010                 // Chop the sum into terms and symmetrize each one over the dummy
1011                 // indices
1012                 std::vector<terminfo> terms;
1013                 for (size_t i=0; i<sum.nops(); i++) {
1014                         const ex & term = sum.op(i);
1015                         ex term_symm = symmetrize(term, dummy_syms);
1016                         if (term_symm.is_zero())
1017                                 continue;
1018                         terms.push_back(terminfo(term, term_symm));
1019                 }
1020
1021                 // Sort by symmetrized terms
1022                 std::sort(terms.begin(), terms.end(), terminfo_is_less());
1023
1024                 // Combine equal symmetrized terms
1025                 std::vector<terminfo> terms_pass2;
1026                 for (std::vector<terminfo>::const_iterator i=terms.begin(); i!=terms.end(); ) {
1027                         size_t num = 1;
1028                         std::vector<terminfo>::const_iterator j = i + 1;
1029                         while (j != terms.end() && j->symm == i->symm) {
1030                                 num++;
1031                                 j++;
1032                         }
1033                         terms_pass2.push_back(terminfo(i->orig * num, i->symm * num));
1034                         i = j;
1035                 }
1036
1037                 // If there is only one term left, we are finished
1038                 if (terms_pass2.size() == 1)
1039                         return terms_pass2[0].orig;
1040
1041                 // Chop the symmetrized terms into subterms
1042                 std::vector<symminfo> sy;
1043                 for (std::vector<terminfo>::const_iterator i=terms_pass2.begin(); i!=terms_pass2.end(); ++i) {
1044                         if (is_exactly_a<add>(i->symm)) {
1045                                 size_t num = i->symm.nops();
1046                                 for (size_t j=0; j<num; j++)
1047                                         sy.push_back(symminfo(i->symm.op(j), i->orig, num));
1048                         } else
1049                                 sy.push_back(symminfo(i->symm, i->orig, 1));
1050                 }
1051
1052                 // Sort by symmetrized subterms
1053                 std::sort(sy.begin(), sy.end(), symminfo_is_less_by_symmterm());
1054
1055                 // Combine equal symmetrized subterms
1056                 std::vector<symminfo> sy_pass2;
1057                 exvector result;
1058                 for (std::vector<symminfo>::const_iterator i=sy.begin(); i!=sy.end(); ) {
1059
1060                         // Combine equal terms
1061                         std::vector<symminfo>::const_iterator j = i + 1;
1062                         if (j != sy.end() && j->symmterm == i->symmterm) {
1063
1064                                 // More than one term, collect the coefficients
1065                                 ex coeff = i->coeff;
1066                                 while (j != sy.end() && j->symmterm == i->symmterm) {
1067                                         coeff += j->coeff;
1068                                         j++;
1069                                 }
1070
1071                                 // Add combined term to result
1072                                 if (!coeff.is_zero())
1073                                         result.push_back(coeff * i->symmterm);
1074
1075                         } else {
1076
1077                                 // Single term, store for second pass
1078                                 sy_pass2.push_back(*i);
1079                         }
1080
1081                         i = j;
1082                 }
1083
1084                 // Were there any remaining terms that didn't get combined?
1085                 if (sy_pass2.size() > 0) {
1086
1087                         // Yes, sort by their original terms
1088                         std::sort(sy_pass2.begin(), sy_pass2.end(), symminfo_is_less_by_orig());
1089
1090                         for (std::vector<symminfo>::const_iterator i=sy_pass2.begin(); i!=sy_pass2.end(); ) {
1091
1092                                 // How many symmetrized terms of this original term are left?
1093                                 size_t num = 1;
1094                                 std::vector<symminfo>::const_iterator j = i + 1;
1095                                 while (j != sy_pass2.end() && j->orig == i->orig) {
1096                                         num++;
1097                                         j++;
1098                                 }
1099
1100                                 if (num == i->num) {
1101
1102                                         // All terms left, then add the original term to the result
1103                                         result.push_back(i->orig);
1104
1105                                 } else {
1106
1107                                         // Some terms were combined with others, add up the remaining symmetrized terms
1108                                         std::vector<symminfo>::const_iterator k;
1109                                         for (k=i; k!=j; k++)
1110                                                 result.push_back(k->coeff * k->symmterm);
1111                                 }
1112
1113                                 i = j;
1114                         }
1115                 }
1116
1117                 // Add all resulting terms
1118                 ex sum_symm = (new add(result))->setflag(status_flags::dynallocated);
1119                 if (sum_symm.is_zero())
1120                         free_indices.clear();
1121                 return sum_symm;
1122         }
1123
1124         // Simplification of products
1125         if (is_exactly_a<mul>(e_expanded)
1126          || is_exactly_a<ncmul>(e_expanded)
1127          || (is_exactly_a<power>(e_expanded) && is_a<indexed>(e_expanded.op(0)) && e_expanded.op(1).is_equal(_ex2)))
1128                 return simplify_indexed_product(e_expanded, free_indices, dummy_indices, sp);
1129
1130         // Cannot do anything
1131         free_indices.clear();
1132         return e_expanded;
1133 }
1134
1135 /** Simplify/canonicalize expression containing indexed objects. This
1136  *  performs contraction of dummy indices where possible and checks whether
1137  *  the free indices in sums are consistent.
1138  *
1139  *  @param options Simplification options (currently unused)
1140  *  @return simplified expression */
1141 ex ex::simplify_indexed(unsigned options) const
1142 {
1143         exvector free_indices, dummy_indices;
1144         scalar_products sp;
1145         return GiNaC::simplify_indexed(*this, free_indices, dummy_indices, sp);
1146 }
1147
1148 /** Simplify/canonicalize expression containing indexed objects. This
1149  *  performs contraction of dummy indices where possible, checks whether
1150  *  the free indices in sums are consistent, and automatically replaces
1151  *  scalar products by known values if desired.
1152  *
1153  *  @param sp Scalar products to be replaced automatically
1154  *  @param options Simplification options (currently unused)
1155  *  @return simplified expression */
1156 ex ex::simplify_indexed(const scalar_products & sp, unsigned options) const
1157 {
1158         exvector free_indices, dummy_indices;
1159         return GiNaC::simplify_indexed(*this, free_indices, dummy_indices, sp);
1160 }
1161
1162 /** Symmetrize expression over its free indices. */
1163 ex ex::symmetrize() const
1164 {
1165         return GiNaC::symmetrize(*this, get_free_indices());
1166 }
1167
1168 /** Antisymmetrize expression over its free indices. */
1169 ex ex::antisymmetrize() const
1170 {
1171         return GiNaC::antisymmetrize(*this, get_free_indices());
1172 }
1173
1174 /** Symmetrize expression by cyclic permutation over its free indices. */
1175 ex ex::symmetrize_cyclic() const
1176 {
1177         return GiNaC::symmetrize_cyclic(*this, get_free_indices());
1178 }
1179
1180 //////////
1181 // helper classes
1182 //////////
1183
1184 spmapkey::spmapkey(const ex & v1_, const ex & v2_, const ex & dim_) : dim(dim_)
1185 {
1186         // If indexed, extract base objects
1187         ex s1 = is_a<indexed>(v1_) ? v1_.op(0) : v1_;
1188         ex s2 = is_a<indexed>(v2_) ? v2_.op(0) : v2_;
1189
1190         // Enforce canonical order in pair
1191         if (s1.compare(s2) > 0) {
1192                 v1 = s2;
1193                 v2 = s1;
1194         } else {
1195                 v1 = s1;
1196                 v2 = s2;
1197         }
1198 }
1199
1200 bool spmapkey::operator==(const spmapkey &other) const
1201 {
1202         if (!v1.is_equal(other.v1))
1203                 return false;
1204         if (!v2.is_equal(other.v2))
1205                 return false;
1206         if (is_a<wildcard>(dim) || is_a<wildcard>(other.dim))
1207                 return true;
1208         else
1209                 return dim.is_equal(other.dim);
1210 }
1211
1212 bool spmapkey::operator<(const spmapkey &other) const
1213 {
1214         int cmp = v1.compare(other.v1);
1215         if (cmp)
1216                 return cmp < 0;
1217         cmp = v2.compare(other.v2);
1218         if (cmp)
1219                 return cmp < 0;
1220
1221         // Objects are equal, now check dimensions
1222         if (is_a<wildcard>(dim) || is_a<wildcard>(other.dim))
1223                 return false;
1224         else
1225                 return dim.compare(other.dim) < 0;
1226 }
1227
1228 void spmapkey::debugprint() const
1229 {
1230         std::cerr << "(" << v1 << "," << v2 << "," << dim << ")";
1231 }
1232
1233 void scalar_products::add(const ex & v1, const ex & v2, const ex & sp)
1234 {
1235         spm[spmapkey(v1, v2)] = sp;
1236 }
1237
1238 void scalar_products::add(const ex & v1, const ex & v2, const ex & dim, const ex & sp)
1239 {
1240         spm[spmapkey(v1, v2, dim)] = sp;
1241 }
1242
1243 void scalar_products::add_vectors(const lst & l, const ex & dim)
1244 {
1245         // Add all possible pairs of products
1246         for (lst::const_iterator it1 = l.begin(); it1 != l.end(); ++it1)
1247                 for (lst::const_iterator it2 = l.begin(); it2 != l.end(); ++it2)
1248                         add(*it1, *it2, *it1 * *it2);
1249 }
1250
1251 void scalar_products::clear()
1252 {
1253         spm.clear();
1254 }
1255
1256 /** Check whether scalar product pair is defined. */
1257 bool scalar_products::is_defined(const ex & v1, const ex & v2, const ex & dim) const
1258 {
1259         return spm.find(spmapkey(v1, v2, dim)) != spm.end();
1260 }
1261
1262 /** Return value of defined scalar product pair. */
1263 ex scalar_products::evaluate(const ex & v1, const ex & v2, const ex & dim) const
1264 {
1265         return spm.find(spmapkey(v1, v2, dim))->second;
1266 }
1267
1268 void scalar_products::debugprint() const
1269 {
1270         std::cerr << "map size=" << spm.size() << std::endl;
1271         spmap::const_iterator i = spm.begin(), end = spm.end();
1272         while (i != end) {
1273                 const spmapkey & k = i->first;
1274                 std::cerr << "item key=";
1275                 k.debugprint();
1276                 std::cerr << ", value=" << i->second << std::endl;
1277                 ++i;
1278         }
1279 }
1280
1281 } // namespace GiNaC