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