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