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