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