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