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