48bb14217dd06a6bf7b18792ea87d31c7fc54452
[ginac.git] / ginac / indexed.cpp
1 /** @file indexed.cpp
2  *
3  *  Implementation of GiNaC's indexed expressions. */
4
5 /*
6  *  GiNaC Copyright (C) 1999-2003 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 <sstream>
25 #include <stdexcept>
26
27 #include "indexed.h"
28 #include "idx.h"
29 #include "add.h"
30 #include "mul.h"
31 #include "ncmul.h"
32 #include "power.h"
33 #include "relational.h"
34 #include "symmetry.h"
35 #include "operators.h"
36 #include "lst.h"
37 #include "print.h"
38 #include "archive.h"
39 #include "utils.h"
40
41 namespace GiNaC {
42
43 GINAC_IMPLEMENT_REGISTERED_CLASS(indexed, exprseq)
44
45 //////////
46 // default constructor
47 //////////
48
49 indexed::indexed() : symtree(sy_none())
50 {
51         tinfo_key = TINFO_indexed;
52 }
53
54 //////////
55 // other constructors
56 //////////
57
58 indexed::indexed(const ex & b) : inherited(b), symtree(sy_none())
59 {
60         tinfo_key = TINFO_indexed;
61         validate();
62 }
63
64 indexed::indexed(const ex & b, const ex & i1) : inherited(b, i1), symtree(sy_none())
65 {
66         tinfo_key = TINFO_indexed;
67         validate();
68 }
69
70 indexed::indexed(const ex & b, const ex & i1, const ex & i2) : inherited(b, i1, i2), symtree(sy_none())
71 {
72         tinfo_key = TINFO_indexed;
73         validate();
74 }
75
76 indexed::indexed(const ex & b, const ex & i1, const ex & i2, const ex & i3) : inherited(b, i1, i2, i3), symtree(sy_none())
77 {
78         tinfo_key = TINFO_indexed;
79         validate();
80 }
81
82 indexed::indexed(const ex & b, const ex & i1, const ex & i2, const ex & i3, const ex & i4) : inherited(b, i1, i2, i3, i4), symtree(sy_none())
83 {
84         tinfo_key = TINFO_indexed;
85         validate();
86 }
87
88 indexed::indexed(const ex & b, const symmetry & symm, const ex & i1, const ex & i2) : inherited(b, i1, i2), symtree(symm)
89 {
90         tinfo_key = TINFO_indexed;
91         validate();
92 }
93
94 indexed::indexed(const ex & b, const symmetry & symm, const ex & i1, const ex & i2, const ex & i3) : inherited(b, i1, i2, i3), symtree(symm)
95 {
96         tinfo_key = TINFO_indexed;
97         validate();
98 }
99
100 indexed::indexed(const ex & b, const symmetry & symm, const ex & i1, const ex & i2, const ex & i3, const ex & i4) : inherited(b, i1, i2, i3, i4), symtree(symm)
101 {
102         tinfo_key = TINFO_indexed;
103         validate();
104 }
105
106 indexed::indexed(const ex & b, const exvector & v) : inherited(b), symtree(sy_none())
107 {
108         seq.insert(seq.end(), v.begin(), v.end());
109         tinfo_key = TINFO_indexed;
110         validate();
111 }
112
113 indexed::indexed(const ex & b, const symmetry & symm, const exvector & v) : inherited(b), symtree(symm)
114 {
115         seq.insert(seq.end(), v.begin(), v.end());
116         tinfo_key = TINFO_indexed;
117         validate();
118 }
119
120 indexed::indexed(const symmetry & symm, const exprseq & es) : inherited(es), symtree(symm)
121 {
122         tinfo_key = TINFO_indexed;
123 }
124
125 indexed::indexed(const symmetry & symm, const exvector & v, bool discardable) : inherited(v, discardable), symtree(symm)
126 {
127         tinfo_key = TINFO_indexed;
128 }
129
130 indexed::indexed(const symmetry & symm, exvector * vp) : inherited(vp), symtree(symm)
131 {
132         tinfo_key = TINFO_indexed;
133 }
134
135 //////////
136 // archiving
137 //////////
138
139 indexed::indexed(const archive_node &n, lst &sym_lst) : inherited(n, sym_lst)
140 {
141         if (!n.find_ex("symmetry", symtree, sym_lst)) {
142                 // GiNaC versions <= 0.9.0 had an unsigned "symmetry" property
143                 unsigned symm = 0;
144                 n.find_unsigned("symmetry", symm);
145                 switch (symm) {
146                         case 1:
147                                 symtree = sy_symm();
148                                 break;
149                         case 2:
150                                 symtree = sy_anti();
151                                 break;
152                         default:
153                                 symtree = sy_none();
154                                 break;
155                 }
156                 const_cast<symmetry &>(ex_to<symmetry>(symtree)).validate(seq.size() - 1);
157         }
158 }
159
160 void indexed::archive(archive_node &n) const
161 {
162         inherited::archive(n);
163         n.add_ex("symmetry", symtree);
164 }
165
166 DEFAULT_UNARCHIVE(indexed)
167
168 //////////
169 // functions overriding virtual functions from base classes
170 //////////
171
172 void indexed::print(const print_context & c, unsigned level) const
173 {
174         GINAC_ASSERT(seq.size() > 0);
175
176         if (is_a<print_tree>(c)) {
177
178                 c.s << std::string(level, ' ') << class_name()
179                     << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
180                     << ", " << seq.size()-1 << " indices"
181                     << ", symmetry=" << symtree << std::endl;
182                 unsigned delta_indent = static_cast<const print_tree &>(c).delta_indent;
183                 seq[0].print(c, level + delta_indent);
184                 printindices(c, level + delta_indent);
185
186         } else {
187
188                 bool is_tex = is_a<print_latex>(c);
189                 const ex & base = seq[0];
190
191                 if (precedence() <= level)
192                         c.s << (is_tex ? "{(" : "(");
193                 if (is_tex)
194                         c.s << "{";
195                 base.print(c, precedence());
196                 if (is_tex)
197                         c.s << "}";
198                 printindices(c, level);
199                 if (precedence() <= level)
200                         c.s << (is_tex ? ")}" : ")");
201         }
202 }
203
204 bool indexed::info(unsigned inf) const
205 {
206         if (inf == info_flags::indexed) return true;
207         if (inf == info_flags::has_indices) return seq.size() > 1;
208         return inherited::info(inf);
209 }
210
211 struct idx_is_not : public std::binary_function<ex, unsigned, bool> {
212         bool operator() (const ex & e, unsigned inf) const {
213                 return !(ex_to<idx>(e).get_value().info(inf));
214         }
215 };
216
217 bool indexed::all_index_values_are(unsigned inf) const
218 {
219         // No indices? Then no property can be fulfilled
220         if (seq.size() < 2)
221                 return false;
222
223         // Check all indices
224         return find_if(seq.begin() + 1, seq.end(), bind2nd(idx_is_not(), inf)) == seq.end();
225 }
226
227 int indexed::compare_same_type(const basic & other) const
228 {
229         GINAC_ASSERT(is_a<indexed>(other));
230         return inherited::compare_same_type(other);
231 }
232
233 ex indexed::eval(int level) const
234 {
235         // First evaluate children, then we will end up here again
236         if (level > 1)
237                 return indexed(ex_to<symmetry>(symtree), evalchildren(level));
238
239         const ex &base = seq[0];
240
241         // If the base object is 0, the whole object is 0
242         if (base.is_zero())
243                 return _ex0;
244
245         // If the base object is a product, pull out the numeric factor
246         if (is_exactly_a<mul>(base) && is_exactly_a<numeric>(base.op(base.nops() - 1))) {
247                 exvector v(seq);
248                 ex f = ex_to<numeric>(base.op(base.nops() - 1));
249                 v[0] = seq[0] / f;
250                 return f * thiscontainer(v);
251         }
252
253         // Canonicalize indices according to the symmetry properties
254         if (seq.size() > 2) {
255                 exvector v = seq;
256                 GINAC_ASSERT(is_exactly_a<symmetry>(symtree));
257                 int sig = canonicalize(v.begin() + 1, ex_to<symmetry>(symtree));
258                 if (sig != INT_MAX) {
259                         // Something has changed while sorting indices, more evaluations later
260                         if (sig == 0)
261                                 return _ex0;
262                         return ex(sig) * thiscontainer(v);
263                 }
264         }
265
266         // Let the class of the base object perform additional evaluations
267         return ex_to<basic>(base).eval_indexed(*this);
268 }
269
270 ex indexed::thiscontainer(const exvector & v) const
271 {
272         return indexed(ex_to<symmetry>(symtree), v);
273 }
274
275 ex indexed::thiscontainer(exvector * vp) const
276 {
277         return indexed(ex_to<symmetry>(symtree), vp);
278 }
279
280 ex indexed::expand(unsigned options) const
281 {
282         GINAC_ASSERT(seq.size() > 0);
283
284         if ((options & expand_options::expand_indexed) && is_exactly_a<add>(seq[0])) {
285
286                 // expand_indexed expands (a+b).i -> a.i + b.i
287                 const ex & base = seq[0];
288                 ex sum = _ex0;
289                 for (size_t i=0; i<base.nops(); i++) {
290                         exvector s = seq;
291                         s[0] = base.op(i);
292                         sum += thiscontainer(s).expand();
293                 }
294                 return sum;
295
296         } else
297                 return inherited::expand(options);
298 }
299
300 //////////
301 // virtual functions which can be overridden by derived classes
302 //////////
303
304 // none
305
306 //////////
307 // non-virtual functions in this class
308 //////////
309
310 void indexed::printindices(const print_context & c, unsigned level) const
311 {
312         if (seq.size() > 1) {
313
314                 exvector::const_iterator it=seq.begin() + 1, itend = seq.end();
315
316                 if (is_a<print_latex>(c)) {
317
318                         // TeX output: group by variance
319                         bool first = true;
320                         bool covariant = true;
321
322                         while (it != itend) {
323                                 bool cur_covariant = (is_a<varidx>(*it) ? ex_to<varidx>(*it).is_covariant() : true);
324                                 if (first || cur_covariant != covariant) { // Variance changed
325                                         // The empty {} prevents indices from ending up on top of each other
326                                         if (!first)
327                                                 c.s << "}{}";
328                                         covariant = cur_covariant;
329                                         if (covariant)
330                                                 c.s << "_{";
331                                         else
332                                                 c.s << "^{";
333                                 }
334                                 it->print(c, level);
335                                 c.s << " ";
336                                 first = false;
337                                 it++;
338                         }
339                         c.s << "}";
340
341                 } else {
342
343                         // Ordinary output
344                         while (it != itend) {
345                                 it->print(c, level);
346                                 it++;
347                         }
348                 }
349         }
350 }
351
352 /** Check whether all indices are of class idx and validate the symmetry
353  *  tree. This function is used internally to make sure that all constructed
354  *  indexed objects really carry indices and not some other classes. */
355 void indexed::validate() const
356 {
357         GINAC_ASSERT(seq.size() > 0);
358         exvector::const_iterator it = seq.begin() + 1, itend = seq.end();
359         while (it != itend) {
360                 if (!is_a<idx>(*it))
361                         throw(std::invalid_argument("indices of indexed object must be of type idx"));
362                 it++;
363         }
364
365         if (!symtree.is_zero()) {
366                 if (!is_exactly_a<symmetry>(symtree))
367                         throw(std::invalid_argument("symmetry of indexed object must be of type symmetry"));
368                 const_cast<symmetry &>(ex_to<symmetry>(symtree)).validate(seq.size() - 1);
369         }
370 }
371
372 /** Implementation of ex::diff() for an indexed object always returns 0.
373  *
374  *  @see ex::diff */
375 ex indexed::derivative(const symbol & s) const
376 {
377         return _ex0;
378 }
379
380 //////////
381 // global functions
382 //////////
383
384 struct idx_is_equal_ignore_dim : public std::binary_function<ex, ex, bool> {
385         bool operator() (const ex &lh, const ex &rh) const
386         {
387                 if (lh.is_equal(rh))
388                         return true;
389                 else
390                         try {
391                                 // Replacing the dimension might cause an error (e.g. with
392                                 // index classes that only work in a fixed number of dimensions)
393                                 return lh.is_equal(ex_to<idx>(rh).replace_dim(ex_to<idx>(lh).get_dim()));
394                         } catch (...) {
395                                 return false;
396                         }
397         }
398 };
399
400 /** Check whether two sorted index vectors are consistent (i.e. equal). */
401 static bool indices_consistent(const exvector & v1, const exvector & v2)
402 {
403         // Number of indices must be the same
404         if (v1.size() != v2.size())
405                 return false;
406
407         return equal(v1.begin(), v1.end(), v2.begin(), idx_is_equal_ignore_dim());
408 }
409
410 exvector indexed::get_indices() const
411 {
412         GINAC_ASSERT(seq.size() >= 1);
413         return exvector(seq.begin() + 1, seq.end());
414 }
415
416 exvector indexed::get_dummy_indices() const
417 {
418         exvector free_indices, dummy_indices;
419         find_free_and_dummy(seq.begin() + 1, seq.end(), free_indices, dummy_indices);
420         return dummy_indices;
421 }
422
423 exvector indexed::get_dummy_indices(const indexed & other) const
424 {
425         exvector indices = get_free_indices();
426         exvector other_indices = other.get_free_indices();
427         indices.insert(indices.end(), other_indices.begin(), other_indices.end());
428         exvector dummy_indices;
429         find_dummy_indices(indices, dummy_indices);
430         return dummy_indices;
431 }
432
433 bool indexed::has_dummy_index_for(const ex & i) const
434 {
435         exvector::const_iterator it = seq.begin() + 1, itend = seq.end();
436         while (it != itend) {
437                 if (is_dummy_pair(*it, i))
438                         return true;
439                 it++;
440         }
441         return false;
442 }
443
444 exvector indexed::get_free_indices() const
445 {
446         exvector free_indices, dummy_indices;
447         find_free_and_dummy(seq.begin() + 1, seq.end(), free_indices, dummy_indices);
448         return free_indices;
449 }
450
451 exvector add::get_free_indices() const
452 {
453         exvector free_indices;
454         for (size_t i=0; i<nops(); i++) {
455                 if (i == 0)
456                         free_indices = op(i).get_free_indices();
457                 else {
458                         exvector free_indices_of_term = op(i).get_free_indices();
459                         if (!indices_consistent(free_indices, free_indices_of_term))
460                                 throw (std::runtime_error("add::get_free_indices: inconsistent indices in sum"));
461                 }
462         }
463         return free_indices;
464 }
465
466 exvector mul::get_free_indices() const
467 {
468         // Concatenate free indices of all factors
469         exvector un;
470         for (size_t i=0; i<nops(); i++) {
471                 exvector free_indices_of_factor = op(i).get_free_indices();
472                 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
473         }
474
475         // And remove the dummy indices
476         exvector free_indices, dummy_indices;
477         find_free_and_dummy(un, free_indices, dummy_indices);
478         return free_indices;
479 }
480
481 exvector ncmul::get_free_indices() const
482 {
483         // Concatenate free indices of all factors
484         exvector un;
485         for (size_t i=0; i<nops(); i++) {
486                 exvector free_indices_of_factor = op(i).get_free_indices();
487                 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
488         }
489
490         // And remove the dummy indices
491         exvector free_indices, dummy_indices;
492         find_free_and_dummy(un, free_indices, dummy_indices);
493         return free_indices;
494 }
495
496 exvector power::get_free_indices() const
497 {
498         // Return free indices of basis
499         return basis.get_free_indices();
500 }
501
502 /** Rename dummy indices in an expression.
503  *
504  *  @param e Expression to work on
505  *  @param local_dummy_indices The set of dummy indices that appear in the
506  *    expression "e"
507  *  @param global_dummy_indices The set of dummy indices that have appeared
508  *    before and which we would like to use in "e", too. This gets updated
509  *    by the function */
510 static ex rename_dummy_indices(const ex & e, exvector & global_dummy_indices, exvector & local_dummy_indices)
511 {
512         size_t global_size = global_dummy_indices.size(),
513                local_size = local_dummy_indices.size();
514
515         // Any local dummy indices at all?
516         if (local_size == 0)
517                 return e;
518
519         if (global_size < local_size) {
520
521                 // More local indices than we encountered before, add the new ones
522                 // to the global set
523                 size_t old_global_size = global_size;
524                 int remaining = local_size - global_size;
525                 exvector::const_iterator it = local_dummy_indices.begin(), itend = local_dummy_indices.end();
526                 while (it != itend && remaining > 0) {
527                         if (find_if(global_dummy_indices.begin(), global_dummy_indices.end(), bind2nd(op0_is_equal(), *it)) == global_dummy_indices.end()) {
528                                 global_dummy_indices.push_back(*it);
529                                 global_size++;
530                                 remaining--;
531                         }
532                         it++;
533                 }
534
535                 // If this is the first set of local indices, do nothing
536                 if (old_global_size == 0)
537                         return e;
538         }
539         GINAC_ASSERT(local_size <= global_size);
540
541         // Construct vectors of index symbols
542         exvector local_syms, global_syms;
543         local_syms.reserve(local_size);
544         global_syms.reserve(local_size);
545         for (size_t i=0; i<local_size; i++)
546                 local_syms.push_back(local_dummy_indices[i].op(0));
547         shaker_sort(local_syms.begin(), local_syms.end(), ex_is_less(), ex_swap());
548         for (size_t i=0; i<local_size; i++) // don't use more global symbols than necessary
549                 global_syms.push_back(global_dummy_indices[i].op(0));
550         shaker_sort(global_syms.begin(), global_syms.end(), ex_is_less(), ex_swap());
551
552         // Remove common indices
553         exvector local_uniq, global_uniq;
554         set_difference(local_syms.begin(), local_syms.end(), global_syms.begin(), global_syms.end(), std::back_insert_iterator<exvector>(local_uniq), ex_is_less());
555         set_difference(global_syms.begin(), global_syms.end(), local_syms.begin(), local_syms.end(), std::back_insert_iterator<exvector>(global_uniq), ex_is_less());
556
557         // Replace remaining non-common local index symbols by global ones
558         if (local_uniq.empty())
559                 return e;
560         else {
561                 while (global_uniq.size() > local_uniq.size())
562                         global_uniq.pop_back();
563                 return e.subs(lst(local_uniq.begin(), local_uniq.end()), lst(global_uniq.begin(), global_uniq.end()), subs_options::no_pattern);
564         }
565 }
566
567 /** Given a set of indices, extract those of class varidx. */
568 static void find_variant_indices(const exvector & v, exvector & variant_indices)
569 {
570         exvector::const_iterator it1, itend;
571         for (it1 = v.begin(), itend = v.end(); it1 != itend; ++it1) {
572                 if (is_exactly_a<varidx>(*it1))
573                         variant_indices.push_back(*it1);
574         }
575 }
576
577 /** Raise/lower dummy indices in a single indexed objects to canonicalize their
578  *  variance.
579  *
580  *  @param e Object to work on
581  *  @param variant_dummy_indices The set of indices that might need repositioning (will be changed by this function)
582  *  @param moved_indices The set of indices that have been repositioned (will be changed by this function)
583  *  @return true if 'e' was changed */
584 bool reposition_dummy_indices(ex & e, exvector & variant_dummy_indices, exvector & moved_indices)
585 {
586         bool something_changed = false;
587
588         // If a dummy index is encountered for the first time in the
589         // product, pull it up, otherwise, pull it down
590         exvector::const_iterator it2, it2start, it2end;
591         for (it2start = ex_to<indexed>(e).seq.begin(), it2end = ex_to<indexed>(e).seq.end(), it2 = it2start + 1; it2 != it2end; ++it2) {
592                 if (!is_exactly_a<varidx>(*it2))
593                         continue;
594
595                 exvector::iterator vit, vitend;
596                 for (vit = variant_dummy_indices.begin(), vitend = variant_dummy_indices.end(); vit != vitend; ++vit) {
597                         if (it2->op(0).is_equal(vit->op(0))) {
598                                 if (ex_to<varidx>(*it2).is_covariant()) {
599                                         e = e.subs(lst(
600                                                 *it2 == ex_to<varidx>(*it2).toggle_variance(),
601                                                 ex_to<varidx>(*it2).toggle_variance() == *it2
602                                         ), subs_options::no_pattern);
603                                         something_changed = true;
604                                         it2 = ex_to<indexed>(e).seq.begin() + (it2 - it2start);
605                                         it2start = ex_to<indexed>(e).seq.begin();
606                                         it2end = ex_to<indexed>(e).seq.end();
607                                 }
608                                 moved_indices.push_back(*vit);
609                                 variant_dummy_indices.erase(vit);
610                                 goto next_index;
611                         }
612                 }
613
614                 for (vit = moved_indices.begin(), vitend = moved_indices.end(); vit != vitend; ++vit) {
615                         if (it2->op(0).is_equal(vit->op(0))) {
616                                 if (ex_to<varidx>(*it2).is_contravariant()) {
617                                         e = e.subs(*it2 == ex_to<varidx>(*it2).toggle_variance(), subs_options::no_pattern);
618                                         something_changed = true;
619                                         it2 = ex_to<indexed>(e).seq.begin() + (it2 - it2start);
620                                         it2start = ex_to<indexed>(e).seq.begin();
621                                         it2end = ex_to<indexed>(e).seq.end();
622                                 }
623                                 goto next_index;
624                         }
625                 }
626
627 next_index: ;
628         }
629
630         return something_changed;
631 }
632
633 /* Ordering that only compares the base expressions of indexed objects. */
634 struct ex_base_is_less : public std::binary_function<ex, ex, bool> {
635         bool operator() (const ex &lh, const ex &rh) const
636         {
637                 return (is_a<indexed>(lh) ? lh.op(0) : lh).compare(is_a<indexed>(rh) ? rh.op(0) : rh) < 0;
638         }
639 };
640
641 /** Simplify product of indexed expressions (commutative, noncommutative and
642  *  simple squares), return list of free indices. */
643 ex simplify_indexed_product(const ex & e, exvector & free_indices, exvector & dummy_indices, const scalar_products & sp)
644 {
645         // Remember whether the product was commutative or noncommutative
646         // (because we chop it into factors and need to reassemble later)
647         bool non_commutative = is_exactly_a<ncmul>(e);
648
649         // Collect factors in an exvector, store squares twice
650         exvector v;
651         v.reserve(e.nops() * 2);
652
653         if (is_exactly_a<power>(e)) {
654                 // We only get called for simple squares, split a^2 -> a*a
655                 GINAC_ASSERT(e.op(1).is_equal(_ex2));
656                 v.push_back(e.op(0));
657                 v.push_back(e.op(0));
658         } else {
659                 for (size_t i=0; i<e.nops(); i++) {
660                         ex f = e.op(i);
661                         if (is_exactly_a<power>(f) && f.op(1).is_equal(_ex2)) {
662                                 v.push_back(f.op(0));
663                     v.push_back(f.op(0));
664                         } else if (is_exactly_a<ncmul>(f)) {
665                                 // Noncommutative factor found, split it as well
666                                 non_commutative = true; // everything becomes noncommutative, ncmul will sort out the commutative factors later
667                                 for (size_t j=0; j<f.nops(); j++)
668                                         v.push_back(f.op(j));
669                         } else
670                                 v.push_back(f);
671                 }
672         }
673
674         // Perform contractions
675         bool something_changed = false;
676         GINAC_ASSERT(v.size() > 1);
677         exvector::iterator it1, itend = v.end(), next_to_last = itend - 1;
678         for (it1 = v.begin(); it1 != next_to_last; it1++) {
679
680 try_again:
681                 if (!is_a<indexed>(*it1))
682                         continue;
683
684                 bool first_noncommutative = (it1->return_type() != return_types::commutative);
685
686                 // Indexed factor found, get free indices and look for contraction
687                 // candidates
688                 exvector free1, dummy1;
689                 find_free_and_dummy(ex_to<indexed>(*it1).seq.begin() + 1, ex_to<indexed>(*it1).seq.end(), free1, dummy1);
690
691                 exvector::iterator it2;
692                 for (it2 = it1 + 1; it2 != itend; it2++) {
693
694                         if (!is_a<indexed>(*it2))
695                                 continue;
696
697                         bool second_noncommutative = (it2->return_type() != return_types::commutative);
698
699                         // Find free indices of second factor and merge them with free
700                         // indices of first factor
701                         exvector un;
702                         find_free_and_dummy(ex_to<indexed>(*it2).seq.begin() + 1, ex_to<indexed>(*it2).seq.end(), un, dummy1);
703                         un.insert(un.end(), free1.begin(), free1.end());
704
705                         // Check whether the two factors share dummy indices
706                         exvector free, dummy;
707                         find_free_and_dummy(un, free, dummy);
708                         size_t num_dummies = dummy.size();
709                         if (num_dummies == 0)
710                                 continue;
711
712                         // At least one dummy index, is it a defined scalar product?
713                         bool contracted = false;
714                         if (free.empty()) {
715
716                                 // Find minimal dimension of all indices of both factors
717                                 exvector::const_iterator dit = ex_to<indexed>(*it1).seq.begin() + 1, ditend = ex_to<indexed>(*it1).seq.end();
718                                 ex dim = ex_to<idx>(*dit).get_dim();
719                                 ++dit;
720                                 for (; dit != ditend; ++dit) {
721                                         dim = minimal_dim(dim, ex_to<idx>(*dit).get_dim());
722                                 }
723                                 dit = ex_to<indexed>(*it2).seq.begin() + 1;
724                                 ditend = ex_to<indexed>(*it2).seq.end();
725                                 for (; dit != ditend; ++dit) {
726                                         dim = minimal_dim(dim, ex_to<idx>(*dit).get_dim());
727                                 }
728
729                                 // User-defined scalar product?
730                                 if (sp.is_defined(*it1, *it2, dim)) {
731
732                                         // Yes, substitute it
733                                         *it1 = sp.evaluate(*it1, *it2, dim);
734                                         *it2 = _ex1;
735                                         goto contraction_done;
736                                 }
737                         }
738
739                         // Try to contract the first one with the second one
740                         contracted = ex_to<basic>(it1->op(0)).contract_with(it1, it2, v);
741                         if (!contracted) {
742
743                                 // That didn't work; maybe the second object knows how to
744                                 // contract itself with the first one
745                                 contracted = ex_to<basic>(it2->op(0)).contract_with(it2, it1, v);
746                         }
747                         if (contracted) {
748 contraction_done:
749                                 if (first_noncommutative || second_noncommutative
750                                  || is_exactly_a<add>(*it1) || is_exactly_a<add>(*it2)
751                                  || is_exactly_a<mul>(*it1) || is_exactly_a<mul>(*it2)
752                                  || is_exactly_a<ncmul>(*it1) || is_exactly_a<ncmul>(*it2)) {
753
754                                         // One of the factors became a sum or product:
755                                         // re-expand expression and run again
756                                         // Non-commutative products are always re-expanded to give
757                                         // eval_ncmul() the chance to re-order and canonicalize
758                                         // the product
759                                         ex r = (non_commutative ? ex(ncmul(v, true)) : ex(mul(v)));
760                                         return simplify_indexed(r, free_indices, dummy_indices, sp);
761                                 }
762
763                                 // Both objects may have new indices now or they might
764                                 // even not be indexed objects any more, so we have to
765                                 // start over
766                                 something_changed = true;
767                                 goto try_again;
768                         }
769                 }
770         }
771
772         // Find free indices (concatenate them all and call find_free_and_dummy())
773         // and all dummy indices that appear
774         exvector un, individual_dummy_indices;
775         for (it1 = v.begin(), itend = v.end(); it1 != itend; ++it1) {
776                 exvector free_indices_of_factor;
777                 if (is_a<indexed>(*it1)) {
778                         exvector dummy_indices_of_factor;
779                         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);
780                         individual_dummy_indices.insert(individual_dummy_indices.end(), dummy_indices_of_factor.begin(), dummy_indices_of_factor.end());
781                 } else
782                         free_indices_of_factor = it1->get_free_indices();
783                 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
784         }
785         exvector local_dummy_indices;
786         find_free_and_dummy(un, free_indices, local_dummy_indices);
787         local_dummy_indices.insert(local_dummy_indices.end(), individual_dummy_indices.begin(), individual_dummy_indices.end());
788
789         // Filter out the dummy indices with variance
790         exvector variant_dummy_indices;
791         find_variant_indices(local_dummy_indices, variant_dummy_indices);
792
793         // Any indices with variance present at all?
794         if (!variant_dummy_indices.empty()) {
795
796                 // Yes, bring the product into a canonical order that only depends on
797                 // the base expressions of indexed objects
798                 if (!non_commutative)
799                         std::sort(v.begin(), v.end(), ex_base_is_less());
800
801                 exvector moved_indices;
802
803                 // Iterate over all indexed objects in the product
804                 for (it1 = v.begin(), itend = v.end(); it1 != itend; ++it1) {
805                         if (!is_a<indexed>(*it1))
806                                 continue;
807
808                         if (reposition_dummy_indices(*it1, variant_dummy_indices, moved_indices))
809                                 something_changed = true;
810                 }
811         }
812
813         ex r;
814         if (something_changed)
815                 r = non_commutative ? ex(ncmul(v, true)) : ex(mul(v));
816         else
817                 r = e;
818
819         // The result should be symmetric with respect to exchange of dummy
820         // indices, so if the symmetrization vanishes, the whole expression is
821         // zero. This detects things like eps.i.j.k * p.j * p.k = 0.
822         if (local_dummy_indices.size() >= 2) {
823                 exvector dummy_syms;
824                 dummy_syms.reserve(local_dummy_indices.size());
825                 for (exvector::const_iterator it = local_dummy_indices.begin(); it != local_dummy_indices.end(); ++it)
826                         dummy_syms.push_back(it->op(0));
827                 if (symmetrize(r, dummy_syms).is_zero()) {
828                         free_indices.clear();
829                         return _ex0;
830                 }
831         }
832
833         // Dummy index renaming
834         r = rename_dummy_indices(r, dummy_indices, local_dummy_indices);
835
836         // Product of indexed object with a scalar?
837         if (is_exactly_a<mul>(r) && r.nops() == 2
838          && is_exactly_a<numeric>(r.op(1)) && is_a<indexed>(r.op(0)))
839                 return ex_to<basic>(r.op(0).op(0)).scalar_mul_indexed(r.op(0), ex_to<numeric>(r.op(1)));
840         else
841                 return r;
842 }
843
844 /** This structure stores the original and symmetrized versions of terms
845  *  obtained during the simplification of sums. */
846 class terminfo {
847 public:
848         terminfo(const ex & orig_, const ex & symm_) : orig(orig_), symm(symm_) {}
849
850         ex orig; /**< original term */
851         ex symm; /**< symmtrized term */
852 };
853
854 class terminfo_is_less {
855 public:
856         bool operator() (const terminfo & ti1, const terminfo & ti2) const
857         {
858                 return (ti1.symm.compare(ti2.symm) < 0);
859         }
860 };
861
862 /** This structure stores the individual symmetrized terms obtained during
863  *  the simplification of sums. */
864 class symminfo {
865 public:
866         symminfo() : num(0) {}
867
868         symminfo(const ex & symmterm_, const ex & orig_, size_t num_) : orig(orig_), num(num_)
869         {
870                 if (is_exactly_a<mul>(symmterm_) && is_exactly_a<numeric>(symmterm_.op(symmterm_.nops()-1))) {
871                         coeff = symmterm_.op(symmterm_.nops()-1);
872                         symmterm = symmterm_ / coeff;
873                 } else {
874                         coeff = 1;
875                         symmterm = symmterm_;
876                 }
877         }
878
879         ex symmterm;  /**< symmetrized term */
880         ex coeff;     /**< coefficient of symmetrized term */
881         ex orig;      /**< original term */
882         size_t num; /**< how many symmetrized terms resulted from the original term */
883 };
884
885 class symminfo_is_less_by_symmterm {
886 public:
887         bool operator() (const symminfo & si1, const symminfo & si2) const
888         {
889                 return (si1.symmterm.compare(si2.symmterm) < 0);
890         }
891 };
892
893 class symminfo_is_less_by_orig {
894 public:
895         bool operator() (const symminfo & si1, const symminfo & si2) const
896         {
897                 return (si1.orig.compare(si2.orig) < 0);
898         }
899 };
900
901 /** Simplify indexed expression, return list of free indices. */
902 ex simplify_indexed(const ex & e, exvector & free_indices, exvector & dummy_indices, const scalar_products & sp)
903 {
904         // Expand the expression
905         ex e_expanded = e.expand();
906
907         // Simplification of single indexed object: just find the free indices
908         // and perform dummy index renaming/repositioning
909         if (is_a<indexed>(e_expanded)) {
910
911                 // Find the dummy indices
912                 const indexed &i = ex_to<indexed>(e_expanded);
913                 exvector local_dummy_indices;
914                 find_free_and_dummy(i.seq.begin() + 1, i.seq.end(), free_indices, local_dummy_indices);
915
916                 // Filter out the dummy indices with variance
917                 exvector variant_dummy_indices;
918                 find_variant_indices(local_dummy_indices, variant_dummy_indices);
919
920                 // Any indices with variance present at all?
921                 if (!variant_dummy_indices.empty()) {
922
923                         // Yes, reposition them
924                         exvector moved_indices;
925                         reposition_dummy_indices(e_expanded, variant_dummy_indices, moved_indices);
926                 }
927
928                 // Rename the dummy indices
929                 return rename_dummy_indices(e_expanded, dummy_indices, local_dummy_indices);
930         }
931
932         // Simplification of sum = sum of simplifications, check consistency of
933         // free indices in each term
934         if (is_exactly_a<add>(e_expanded)) {
935                 bool first = true;
936                 ex sum;
937                 free_indices.clear();
938
939                 for (size_t i=0; i<e_expanded.nops(); i++) {
940                         exvector free_indices_of_term;
941                         ex term = simplify_indexed(e_expanded.op(i), free_indices_of_term, dummy_indices, sp);
942                         if (!term.is_zero()) {
943                                 if (first) {
944                                         free_indices = free_indices_of_term;
945                                         sum = term;
946                                         first = false;
947                                 } else {
948                                         if (!indices_consistent(free_indices, free_indices_of_term)) {
949                                                 std::ostringstream s;
950                                                 s << "simplify_indexed: inconsistent indices in sum: ";
951                                                 s << exprseq(free_indices) << " vs. " << exprseq(free_indices_of_term);
952                                                 throw (std::runtime_error(s.str()));
953                                         }
954                                         if (is_a<indexed>(sum) && is_a<indexed>(term))
955                                                 sum = ex_to<basic>(sum.op(0)).add_indexed(sum, term);
956                                         else
957                                                 sum += term;
958                                 }
959                         }
960                 }
961
962                 // If the sum turns out to be zero, we are finished
963                 if (sum.is_zero()) {
964                         free_indices.clear();
965                         return sum;
966                 }
967
968                 // More than one term and more than one dummy index?
969                 size_t num_terms_orig = (is_exactly_a<add>(sum) ? sum.nops() : 1);
970                 if (num_terms_orig < 2 || dummy_indices.size() < 2)
971                         return sum;
972
973                 // Yes, construct vector of all dummy index symbols
974                 exvector dummy_syms;
975                 dummy_syms.reserve(dummy_indices.size());
976                 for (exvector::const_iterator it = dummy_indices.begin(); it != dummy_indices.end(); ++it)
977                         dummy_syms.push_back(it->op(0));
978
979                 // Chop the sum into terms and symmetrize each one over the dummy
980                 // indices
981                 std::vector<terminfo> terms;
982                 for (size_t i=0; i<sum.nops(); i++) {
983                         const ex & term = sum.op(i);
984                         ex term_symm = symmetrize(term, dummy_syms);
985                         if (term_symm.is_zero())
986                                 continue;
987                         terms.push_back(terminfo(term, term_symm));
988                 }
989
990                 // Sort by symmetrized terms
991                 std::sort(terms.begin(), terms.end(), terminfo_is_less());
992
993                 // Combine equal symmetrized terms
994                 std::vector<terminfo> terms_pass2;
995                 for (std::vector<terminfo>::const_iterator i=terms.begin(); i!=terms.end(); ) {
996                         size_t num = 1;
997                         std::vector<terminfo>::const_iterator j = i + 1;
998                         while (j != terms.end() && j->symm == i->symm) {
999                                 num++;
1000                                 j++;
1001                         }
1002                         terms_pass2.push_back(terminfo(i->orig * num, i->symm * num));
1003                         i = j;
1004                 }
1005
1006                 // If there is only one term left, we are finished
1007                 if (terms_pass2.size() == 1)
1008                         return terms_pass2[0].orig;
1009
1010                 // Chop the symmetrized terms into subterms
1011                 std::vector<symminfo> sy;
1012                 for (std::vector<terminfo>::const_iterator i=terms_pass2.begin(); i!=terms_pass2.end(); ++i) {
1013                         if (is_exactly_a<add>(i->symm)) {
1014                                 size_t num = i->symm.nops();
1015                                 for (size_t j=0; j<num; j++)
1016                                         sy.push_back(symminfo(i->symm.op(j), i->orig, num));
1017                         } else
1018                                 sy.push_back(symminfo(i->symm, i->orig, 1));
1019                 }
1020
1021                 // Sort by symmetrized subterms
1022                 std::sort(sy.begin(), sy.end(), symminfo_is_less_by_symmterm());
1023
1024                 // Combine equal symmetrized subterms
1025                 std::vector<symminfo> sy_pass2;
1026                 exvector result;
1027                 for (std::vector<symminfo>::const_iterator i=sy.begin(); i!=sy.end(); ) {
1028
1029                         // Combine equal terms
1030                         std::vector<symminfo>::const_iterator j = i + 1;
1031                         if (j != sy.end() && j->symmterm == i->symmterm) {
1032
1033                                 // More than one term, collect the coefficients
1034                                 ex coeff = i->coeff;
1035                                 while (j != sy.end() && j->symmterm == i->symmterm) {
1036                                         coeff += j->coeff;
1037                                         j++;
1038                                 }
1039
1040                                 // Add combined term to result
1041                                 if (!coeff.is_zero())
1042                                         result.push_back(coeff * i->symmterm);
1043
1044                         } else {
1045
1046                                 // Single term, store for second pass
1047                                 sy_pass2.push_back(*i);
1048                         }
1049
1050                         i = j;
1051                 }
1052
1053                 // Were there any remaining terms that didn't get combined?
1054                 if (sy_pass2.size() > 0) {
1055
1056                         // Yes, sort by their original terms
1057                         std::sort(sy_pass2.begin(), sy_pass2.end(), symminfo_is_less_by_orig());
1058
1059                         for (std::vector<symminfo>::const_iterator i=sy_pass2.begin(); i!=sy_pass2.end(); ) {
1060
1061                                 // How many symmetrized terms of this original term are left?
1062                                 size_t num = 1;
1063                                 std::vector<symminfo>::const_iterator j = i + 1;
1064                                 while (j != sy_pass2.end() && j->orig == i->orig) {
1065                                         num++;
1066                                         j++;
1067                                 }
1068
1069                                 if (num == i->num) {
1070
1071                                         // All terms left, then add the original term to the result
1072                                         result.push_back(i->orig);
1073
1074                                 } else {
1075
1076                                         // Some terms were combined with others, add up the remaining symmetrized terms
1077                                         std::vector<symminfo>::const_iterator k;
1078                                         for (k=i; k!=j; k++)
1079                                                 result.push_back(k->coeff * k->symmterm);
1080                                 }
1081
1082                                 i = j;
1083                         }
1084                 }
1085
1086                 // Add all resulting terms
1087                 ex sum_symm = (new add(result))->setflag(status_flags::dynallocated);
1088                 if (sum_symm.is_zero())
1089                         free_indices.clear();
1090                 return sum_symm;
1091         }
1092
1093         // Simplification of products
1094         if (is_exactly_a<mul>(e_expanded)
1095          || is_exactly_a<ncmul>(e_expanded)
1096          || (is_exactly_a<power>(e_expanded) && is_a<indexed>(e_expanded.op(0)) && e_expanded.op(1).is_equal(_ex2)))
1097                 return simplify_indexed_product(e_expanded, free_indices, dummy_indices, sp);
1098
1099         // Cannot do anything
1100         free_indices.clear();
1101         return e_expanded;
1102 }
1103
1104 /** Simplify/canonicalize expression containing indexed objects. This
1105  *  performs contraction of dummy indices where possible and checks whether
1106  *  the free indices in sums are consistent.
1107  *
1108  *  @return simplified expression */
1109 ex ex::simplify_indexed() const
1110 {
1111         exvector free_indices, dummy_indices;
1112         scalar_products sp;
1113         return GiNaC::simplify_indexed(*this, free_indices, dummy_indices, sp);
1114 }
1115
1116 /** Simplify/canonicalize expression containing indexed objects. This
1117  *  performs contraction of dummy indices where possible, checks whether
1118  *  the free indices in sums are consistent, and automatically replaces
1119  *  scalar products by known values if desired.
1120  *
1121  *  @param sp Scalar products to be replaced automatically
1122  *  @return simplified expression */
1123 ex ex::simplify_indexed(const scalar_products & sp) const
1124 {
1125         exvector free_indices, dummy_indices;
1126         return GiNaC::simplify_indexed(*this, free_indices, dummy_indices, sp);
1127 }
1128
1129 /** Symmetrize expression over its free indices. */
1130 ex ex::symmetrize() const
1131 {
1132         return GiNaC::symmetrize(*this, get_free_indices());
1133 }
1134
1135 /** Antisymmetrize expression over its free indices. */
1136 ex ex::antisymmetrize() const
1137 {
1138         return GiNaC::antisymmetrize(*this, get_free_indices());
1139 }
1140
1141 /** Symmetrize expression by cyclic permutation over its free indices. */
1142 ex ex::symmetrize_cyclic() const
1143 {
1144         return GiNaC::symmetrize_cyclic(*this, get_free_indices());
1145 }
1146
1147 //////////
1148 // helper classes
1149 //////////
1150
1151 spmapkey::spmapkey(const ex & v1_, const ex & v2_, const ex & dim_) : dim(dim_)
1152 {
1153         // If indexed, extract base objects
1154         ex s1 = is_a<indexed>(v1_) ? v1_.op(0) : v1_;
1155         ex s2 = is_a<indexed>(v2_) ? v2_.op(0) : v2_;
1156
1157         // Enforce canonical order in pair
1158         if (s1.compare(s2) > 0) {
1159                 v1 = s2;
1160                 v2 = s1;
1161         } else {
1162                 v1 = s1;
1163                 v2 = s2;
1164         }
1165 }
1166
1167 bool spmapkey::operator==(const spmapkey &other) const
1168 {
1169         if (!v1.is_equal(other.v1))
1170                 return false;
1171         if (!v2.is_equal(other.v2))
1172                 return false;
1173         if (is_a<wildcard>(dim) || is_a<wildcard>(other.dim))
1174                 return true;
1175         else
1176                 return dim.is_equal(other.dim);
1177 }
1178
1179 bool spmapkey::operator<(const spmapkey &other) const
1180 {
1181         int cmp = v1.compare(other.v1);
1182         if (cmp)
1183                 return cmp < 0;
1184         cmp = v2.compare(other.v2);
1185         if (cmp)
1186                 return cmp < 0;
1187
1188         // Objects are equal, now check dimensions
1189         if (is_a<wildcard>(dim) || is_a<wildcard>(other.dim))
1190                 return false;
1191         else
1192                 return dim.compare(other.dim) < 0;
1193 }
1194
1195 void spmapkey::debugprint() const
1196 {
1197         std::cerr << "(" << v1 << "," << v2 << "," << dim << ")";
1198 }
1199
1200 void scalar_products::add(const ex & v1, const ex & v2, const ex & sp)
1201 {
1202         spm[spmapkey(v1, v2)] = sp;
1203 }
1204
1205 void scalar_products::add(const ex & v1, const ex & v2, const ex & dim, const ex & sp)
1206 {
1207         spm[spmapkey(v1, v2, dim)] = sp;
1208 }
1209
1210 void scalar_products::add_vectors(const lst & l, const ex & dim)
1211 {
1212         // Add all possible pairs of products
1213         for (lst::const_iterator it1 = l.begin(); it1 != l.end(); ++it1)
1214                 for (lst::const_iterator it2 = l.begin(); it2 != l.end(); ++it2)
1215                         add(*it1, *it2, *it1 * *it2);
1216 }
1217
1218 void scalar_products::clear()
1219 {
1220         spm.clear();
1221 }
1222
1223 /** Check whether scalar product pair is defined. */
1224 bool scalar_products::is_defined(const ex & v1, const ex & v2, const ex & dim) const
1225 {
1226         return spm.find(spmapkey(v1, v2, dim)) != spm.end();
1227 }
1228
1229 /** Return value of defined scalar product pair. */
1230 ex scalar_products::evaluate(const ex & v1, const ex & v2, const ex & dim) const
1231 {
1232         return spm.find(spmapkey(v1, v2, dim))->second;
1233 }
1234
1235 void scalar_products::debugprint() const
1236 {
1237         std::cerr << "map size=" << spm.size() << std::endl;
1238         spmap::const_iterator i = spm.begin(), end = spm.end();
1239         while (i != end) {
1240                 const spmapkey & k = i->first;
1241                 std::cerr << "item key=";
1242                 k.debugprint();
1243                 std::cerr << ", value=" << i->second << std::endl;
1244                 ++i;
1245         }
1246 }
1247
1248 } // namespace GiNaC