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