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