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