]> www.ginac.de Git - ginac.git/blob - ginac/indexed.cpp
dcd6d9510d6d0ac688802373f30f7d93e0f07362
[ginac.git] / ginac / indexed.cpp
1 /** @file indexed.cpp
2  *
3  *  Implementation of GiNaC's indexed expressions. */
4
5 /*
6  *  GiNaC Copyright (C) 1999-2002 Johannes Gutenberg University Mainz, Germany
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 2 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 #include <iostream>
24 #include <stdexcept>
25
26 #include "indexed.h"
27 #include "idx.h"
28 #include "add.h"
29 #include "mul.h"
30 #include "ncmul.h"
31 #include "power.h"
32 #include "relational.h"
33 #include "symmetry.h"
34 #include "lst.h"
35 #include "print.h"
36 #include "archive.h"
37 #include "utils.h"
38
39 namespace GiNaC {
40
41 GINAC_IMPLEMENT_REGISTERED_CLASS(indexed, exprseq)
42
43 //////////
44 // default ctor, dtor, copy ctor, assignment operator and helpers
45 //////////
46
47 indexed::indexed() : symtree(sy_none())
48 {
49         tinfo_key = TINFO_indexed;
50 }
51
52 void indexed::copy(const indexed & other)
53 {
54         inherited::copy(other);
55         symtree = other.symtree;
56 }
57
58 DEFAULT_DESTROY(indexed)
59
60 //////////
61 // other constructors
62 //////////
63
64 indexed::indexed(const ex & b) : inherited(b), symtree(sy_none())
65 {
66         tinfo_key = TINFO_indexed;
67         validate();
68 }
69
70 indexed::indexed(const ex & b, const ex & i1) : inherited(b, i1), symtree(sy_none())
71 {
72         tinfo_key = TINFO_indexed;
73         validate();
74 }
75
76 indexed::indexed(const ex & b, const ex & i1, const ex & i2) : inherited(b, i1, i2), symtree(sy_none())
77 {
78         tinfo_key = TINFO_indexed;
79         validate();
80 }
81
82 indexed::indexed(const ex & b, const ex & i1, const ex & i2, const ex & i3) : inherited(b, i1, i2, i3), symtree(sy_none())
83 {
84         tinfo_key = TINFO_indexed;
85         validate();
86 }
87
88 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())
89 {
90         tinfo_key = TINFO_indexed;
91         validate();
92 }
93
94 indexed::indexed(const ex & b, const symmetry & symm, const ex & i1, const ex & i2) : inherited(b, i1, i2), symtree(symm)
95 {
96         tinfo_key = TINFO_indexed;
97         validate();
98 }
99
100 indexed::indexed(const ex & b, const symmetry & symm, const ex & i1, const ex & i2, const ex & i3) : inherited(b, i1, i2, i3), symtree(symm)
101 {
102         tinfo_key = TINFO_indexed;
103         validate();
104 }
105
106 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)
107 {
108         tinfo_key = TINFO_indexed;
109         validate();
110 }
111
112 indexed::indexed(const ex & b, const exvector & v) : inherited(b), symtree(sy_none())
113 {
114         seq.insert(seq.end(), v.begin(), v.end());
115         tinfo_key = TINFO_indexed;
116         validate();
117 }
118
119 indexed::indexed(const ex & b, const symmetry & symm, const exvector & v) : inherited(b), symtree(symm)
120 {
121         seq.insert(seq.end(), v.begin(), v.end());
122         tinfo_key = TINFO_indexed;
123         validate();
124 }
125
126 indexed::indexed(const symmetry & symm, const exprseq & es) : inherited(es), symtree(symm)
127 {
128         tinfo_key = TINFO_indexed;
129 }
130
131 indexed::indexed(const symmetry & symm, const exvector & v, bool discardable) : inherited(v, discardable), symtree(symm)
132 {
133         tinfo_key = TINFO_indexed;
134 }
135
136 indexed::indexed(const symmetry & symm, exvector * vp) : inherited(vp), symtree(symm)
137 {
138         tinfo_key = TINFO_indexed;
139 }
140
141 //////////
142 // archiving
143 //////////
144
145 indexed::indexed(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
146 {
147         if (!n.find_ex("symmetry", symtree, sym_lst)) {
148                 // GiNaC versions <= 0.9.0 had an unsigned "symmetry" property
149                 unsigned symm = 0;
150                 n.find_unsigned("symmetry", symm);
151                 switch (symm) {
152                         case 1:
153                                 symtree = sy_symm();
154                                 break;
155                         case 2:
156                                 symtree = sy_anti();
157                                 break;
158                         default:
159                                 symtree = sy_none();
160                                 break;
161                 }
162                 const_cast<symmetry &>(ex_to<symmetry>(symtree)).validate(seq.size() - 1);
163         }
164 }
165
166 void indexed::archive(archive_node &n) const
167 {
168         inherited::archive(n);
169         n.add_ex("symmetry", symtree);
170 }
171
172 DEFAULT_UNARCHIVE(indexed)
173
174 //////////
175 // functions overriding virtual functions from base classes
176 //////////
177
178 void indexed::print(const print_context & c, unsigned level) const
179 {
180         GINAC_ASSERT(seq.size() > 0);
181
182         if (is_of_type(c, print_tree)) {
183
184                 c.s << std::string(level, ' ') << class_name()
185                     << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
186                     << ", " << seq.size()-1 << " indices"
187                     << ", symmetry=" << symtree << std::endl;
188                 unsigned delta_indent = static_cast<const print_tree &>(c).delta_indent;
189                 seq[0].print(c, level + delta_indent);
190                 printindices(c, level + delta_indent);
191
192         } else {
193
194                 bool is_tex = is_of_type(c, print_latex);
195                 const ex & base = seq[0];
196                 bool need_parens = is_ex_exactly_of_type(base, add) || is_ex_exactly_of_type(base, mul)
197                                 || is_ex_exactly_of_type(base, ncmul) || is_ex_exactly_of_type(base, power)
198                                 || is_ex_of_type(base, indexed);
199                 if (is_tex)
200                         c.s << "{";
201                 if (need_parens)
202                         c.s << "(";
203                 base.print(c);
204                 if (need_parens)
205                         c.s << ")";
206                 if (is_tex)
207                         c.s << "}";
208                 printindices(c, level);
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_ex_exactly_of_type(base, mul) && is_ex_exactly_of_type(base.op(base.nops() - 1), numeric)) {
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_ex_exactly_of_type(seq[0], add)) {
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_of_type(c, print_latex)) {
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_ex_of_type(*it, varidx) ? 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_ex_of_type(*it, idx))
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_ex_exactly_of_type(symtree, symmetry))
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 /** Check whether two sorted index vectors are consistent (i.e. equal). */
393 static bool indices_consistent(const exvector & v1, const exvector & v2)
394 {
395         // Number of indices must be the same
396         if (v1.size() != v2.size())
397                 return false;
398
399         return equal(v1.begin(), v1.end(), v2.begin(), ex_is_equal());
400 }
401
402 exvector indexed::get_indices(void) const
403 {
404         GINAC_ASSERT(seq.size() >= 1);
405         return exvector(seq.begin() + 1, seq.end());
406 }
407
408 exvector indexed::get_dummy_indices(void) const
409 {
410         exvector free_indices, dummy_indices;
411         find_free_and_dummy(seq.begin() + 1, seq.end(), free_indices, dummy_indices);
412         return dummy_indices;
413 }
414
415 exvector indexed::get_dummy_indices(const indexed & other) const
416 {
417         exvector indices = get_free_indices();
418         exvector other_indices = other.get_free_indices();
419         indices.insert(indices.end(), other_indices.begin(), other_indices.end());
420         exvector dummy_indices;
421         find_dummy_indices(indices, dummy_indices);
422         return dummy_indices;
423 }
424
425 bool indexed::has_dummy_index_for(const ex & i) const
426 {
427         exvector::const_iterator it = seq.begin() + 1, itend = seq.end();
428         while (it != itend) {
429                 if (is_dummy_pair(*it, i))
430                         return true;
431                 it++;
432         }
433         return false;
434 }
435
436 exvector indexed::get_free_indices(void) const
437 {
438         exvector free_indices, dummy_indices;
439         find_free_and_dummy(seq.begin() + 1, seq.end(), free_indices, dummy_indices);
440         return free_indices;
441 }
442
443 exvector add::get_free_indices(void) const
444 {
445         exvector free_indices;
446         for (unsigned i=0; i<nops(); i++) {
447                 if (i == 0)
448                         free_indices = op(i).get_free_indices();
449                 else {
450                         exvector free_indices_of_term = op(i).get_free_indices();
451                         if (!indices_consistent(free_indices, free_indices_of_term))
452                                 throw (std::runtime_error("add::get_free_indices: inconsistent indices in sum"));
453                 }
454         }
455         return free_indices;
456 }
457
458 exvector mul::get_free_indices(void) const
459 {
460         // Concatenate free indices of all factors
461         exvector un;
462         for (unsigned i=0; i<nops(); i++) {
463                 exvector free_indices_of_factor = op(i).get_free_indices();
464                 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
465         }
466
467         // And remove the dummy indices
468         exvector free_indices, dummy_indices;
469         find_free_and_dummy(un, free_indices, dummy_indices);
470         return free_indices;
471 }
472
473 exvector ncmul::get_free_indices(void) const
474 {
475         // Concatenate free indices of all factors
476         exvector un;
477         for (unsigned i=0; i<nops(); i++) {
478                 exvector free_indices_of_factor = op(i).get_free_indices();
479                 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
480         }
481
482         // And remove the dummy indices
483         exvector free_indices, dummy_indices;
484         find_free_and_dummy(un, free_indices, dummy_indices);
485         return free_indices;
486 }
487
488 exvector power::get_free_indices(void) const
489 {
490         // Return free indices of basis
491         return basis.get_free_indices();
492 }
493
494 /** Rename dummy indices in an expression.
495  *
496  *  @param e Expression to work on
497  *  @param local_dummy_indices The set of dummy indices that appear in the
498  *    expression "e"
499  *  @param global_dummy_indices The set of dummy indices that have appeared
500  *    before and which we would like to use in "e", too. This gets updated
501  *    by the function */
502 static ex rename_dummy_indices(const ex & e, exvector & global_dummy_indices, exvector & local_dummy_indices)
503 {
504         unsigned global_size = global_dummy_indices.size(),
505                  local_size = local_dummy_indices.size();
506
507         // Any local dummy indices at all?
508         if (local_size == 0)
509                 return e;
510
511         if (global_size < local_size) {
512
513                 // More local indices than we encountered before, add the new ones
514                 // to the global set
515                 int old_global_size = global_size;
516                 int remaining = local_size - global_size;
517                 exvector::const_iterator it = local_dummy_indices.begin(), itend = local_dummy_indices.end();
518                 while (it != itend && remaining > 0) {
519                         if (find_if(global_dummy_indices.begin(), global_dummy_indices.end(), bind2nd(ex_is_equal(), *it)) == global_dummy_indices.end()) {
520                                 global_dummy_indices.push_back(*it);
521                                 global_size++;
522                                 remaining--;
523                         }
524                         it++;
525                 }
526
527                 // If this is the first set of local indices, do nothing
528                 if (old_global_size == 0)
529                         return e;
530         }
531         GINAC_ASSERT(local_size <= global_size);
532
533         // Construct lists of index symbols
534         exlist local_syms, global_syms;
535         for (unsigned i=0; i<local_size; i++)
536                 local_syms.push_back(local_dummy_indices[i].op(0));
537         shaker_sort(local_syms.begin(), local_syms.end(), ex_is_less(), ex_swap());
538         for (unsigned i=0; i<global_size; i++)
539                 global_syms.push_back(global_dummy_indices[i].op(0));
540         shaker_sort(global_syms.begin(), global_syms.end(), ex_is_less(), ex_swap());
541
542         // Remove common indices
543         exlist local_uniq, global_uniq;
544         set_difference(local_syms.begin(), local_syms.end(), global_syms.begin(), global_syms.end(), std::back_insert_iterator<exlist>(local_uniq), ex_is_less());
545         set_difference(global_syms.begin(), global_syms.end(), local_syms.begin(), local_syms.end(), std::back_insert_iterator<exlist>(global_uniq), ex_is_less());
546
547         // Replace remaining non-common local index symbols by global ones
548         if (local_uniq.empty())
549                 return e;
550         else {
551                 while (global_uniq.size() > local_uniq.size())
552                         global_uniq.pop_back();
553                 return e.subs(lst(local_uniq), lst(global_uniq));
554         }
555 }
556
557 /** Given a set of indices, extract those of class varidx. */
558 static void find_variant_indices(const exvector & v, exvector & variant_indices)
559 {
560         exvector::const_iterator it1, itend;
561         for (it1 = v.begin(), itend = v.end(); it1 != itend; ++it1) {
562                 if (is_exactly_a<varidx>(*it1))
563                         variant_indices.push_back(*it1);
564         }
565 }
566
567 /** Raise/lower dummy indices in a single indexed objects to canonicalize their
568  *  variance.
569  *
570  *  @param e Object to work on
571  *  @param variant_dummy_indices The set of indices that might need repositioning (will be changed by this function)
572  *  @param moved_indices The set of indices that have been repositioned (will be changed by this function)
573  *  @return true if 'e' was changed */
574 bool reposition_dummy_indices(ex & e, exvector & variant_dummy_indices, exvector & moved_indices)
575 {
576         bool something_changed = false;
577
578         // If a dummy index is encountered for the first time in the
579         // product, pull it up, otherwise, pull it down
580         exvector::const_iterator it2, it2start, it2end;
581         for (it2start = ex_to<indexed>(e).seq.begin(), it2end = ex_to<indexed>(e).seq.end(), it2 = it2start + 1; it2 != it2end; ++it2) {
582                 if (!is_exactly_a<varidx>(*it2))
583                         continue;
584
585                 exvector::iterator vit, vitend;
586                 for (vit = variant_dummy_indices.begin(), vitend = variant_dummy_indices.end(); vit != vitend; ++vit) {
587                         if (it2->op(0).is_equal(vit->op(0))) {
588                                 if (ex_to<varidx>(*it2).is_covariant()) {
589                                         e = e.subs(lst(
590                                                 *it2 == ex_to<varidx>(*it2).toggle_variance(),
591                                                 ex_to<varidx>(*it2).toggle_variance() == *it2
592                                         ));
593                                         something_changed = true;
594                                         it2 = ex_to<indexed>(e).seq.begin() + (it2 - it2start);
595                                         it2start = ex_to<indexed>(e).seq.begin();
596                                         it2end = ex_to<indexed>(e).seq.end();
597                                 }
598                                 moved_indices.push_back(*vit);
599                                 variant_dummy_indices.erase(vit);
600                                 goto next_index;
601                         }
602                 }
603
604                 for (vit = moved_indices.begin(), vitend = moved_indices.end(); vit != vitend; ++vit) {
605                         if (it2->op(0).is_equal(vit->op(0))) {
606                                 if (ex_to<varidx>(*it2).is_contravariant()) {
607                                         e = e.subs(*it2 == ex_to<varidx>(*it2).toggle_variance());
608                                         something_changed = true;
609                                         it2 = ex_to<indexed>(e).seq.begin() + (it2 - it2start);
610                                         it2start = ex_to<indexed>(e).seq.begin();
611                                         it2end = ex_to<indexed>(e).seq.end();
612                                 }
613                                 goto next_index;
614                         }
615                 }
616
617 next_index: ;
618         }
619
620         return something_changed;
621 }
622
623 /* Ordering that only compares the base expressions of indexed objects. */
624 struct ex_base_is_less : public std::binary_function<ex, ex, bool> {
625         bool operator() (const ex &lh, const ex &rh) const
626         {
627                 return (is_a<indexed>(lh) ? lh.op(0) : lh).compare(is_a<indexed>(rh) ? rh.op(0) : rh) < 0;
628         }
629 };
630
631 /** Simplify product of indexed expressions (commutative, noncommutative and
632  *  simple squares), return list of free indices. */
633 ex simplify_indexed_product(const ex & e, exvector & free_indices, exvector & dummy_indices, const scalar_products & sp)
634 {
635         // Remember whether the product was commutative or noncommutative
636         // (because we chop it into factors and need to reassemble later)
637         bool non_commutative = is_ex_exactly_of_type(e, ncmul);
638
639         // Collect factors in an exvector, store squares twice
640         exvector v;
641         v.reserve(e.nops() * 2);
642
643         if (is_ex_exactly_of_type(e, power)) {
644                 // We only get called for simple squares, split a^2 -> a*a
645                 GINAC_ASSERT(e.op(1).is_equal(_ex2));
646                 v.push_back(e.op(0));
647                 v.push_back(e.op(0));
648         } else {
649                 for (unsigned i=0; i<e.nops(); i++) {
650                         ex f = e.op(i);
651                         if (is_ex_exactly_of_type(f, power) && f.op(1).is_equal(_ex2)) {
652                                 v.push_back(f.op(0));
653                     v.push_back(f.op(0));
654                         } else if (is_ex_exactly_of_type(f, ncmul)) {
655                                 // Noncommutative factor found, split it as well
656                                 non_commutative = true; // everything becomes noncommutative, ncmul will sort out the commutative factors later
657                                 for (unsigned j=0; j<f.nops(); j++)
658                                         v.push_back(f.op(j));
659                         } else
660                                 v.push_back(f);
661                 }
662         }
663
664         // Perform contractions
665         bool something_changed = false;
666         GINAC_ASSERT(v.size() > 1);
667         exvector::iterator it1, itend = v.end(), next_to_last = itend - 1;
668         for (it1 = v.begin(); it1 != next_to_last; it1++) {
669
670 try_again:
671                 if (!is_ex_of_type(*it1, indexed))
672                         continue;
673
674                 bool first_noncommutative = (it1->return_type() != return_types::commutative);
675
676                 // Indexed factor found, get free indices and look for contraction
677                 // candidates
678                 exvector free1, dummy1;
679                 find_free_and_dummy(ex_to<indexed>(*it1).seq.begin() + 1, ex_to<indexed>(*it1).seq.end(), free1, dummy1);
680
681                 exvector::iterator it2;
682                 for (it2 = it1 + 1; it2 != itend; it2++) {
683
684                         if (!is_ex_of_type(*it2, indexed))
685                                 continue;
686
687                         bool second_noncommutative = (it2->return_type() != return_types::commutative);
688
689                         // Find free indices of second factor and merge them with free
690                         // indices of first factor
691                         exvector un;
692                         find_free_and_dummy(ex_to<indexed>(*it2).seq.begin() + 1, ex_to<indexed>(*it2).seq.end(), un, dummy1);
693                         un.insert(un.end(), free1.begin(), free1.end());
694
695                         // Check whether the two factors share dummy indices
696                         exvector free, dummy;
697                         find_free_and_dummy(un, free, dummy);
698                         unsigned num_dummies = dummy.size();
699                         if (num_dummies == 0)
700                                 continue;
701
702                         // At least one dummy index, is it a defined scalar product?
703                         bool contracted = false;
704                         if (free.empty()) {
705                                 if (sp.is_defined(*it1, *it2)) {
706                                         *it1 = sp.evaluate(*it1, *it2);
707                                         *it2 = _ex1;
708                                         goto contraction_done;
709                                 }
710                         }
711
712                         // Try to contract the first one with the second one
713                         contracted = ex_to<basic>(it1->op(0)).contract_with(it1, it2, v);
714                         if (!contracted) {
715
716                                 // That didn't work; maybe the second object knows how to
717                                 // contract itself with the first one
718                                 contracted = ex_to<basic>(it2->op(0)).contract_with(it2, it1, v);
719                         }
720                         if (contracted) {
721 contraction_done:
722                                 if (first_noncommutative || second_noncommutative
723                                  || is_ex_exactly_of_type(*it1, add) || is_ex_exactly_of_type(*it2, add)
724                                  || is_ex_exactly_of_type(*it1, mul) || is_ex_exactly_of_type(*it2, mul)
725                                  || is_ex_exactly_of_type(*it1, ncmul) || is_ex_exactly_of_type(*it2, ncmul)) {
726
727                                         // One of the factors became a sum or product:
728                                         // re-expand expression and run again
729                                         // Non-commutative products are always re-expanded to give
730                                         // simplify_ncmul() the chance to re-order and canonicalize
731                                         // the product
732                                         ex r = (non_commutative ? ex(ncmul(v, true)) : ex(mul(v)));
733                                         return simplify_indexed(r, free_indices, dummy_indices, sp);
734                                 }
735
736                                 // Both objects may have new indices now or they might
737                                 // even not be indexed objects any more, so we have to
738                                 // start over
739                                 something_changed = true;
740                                 goto try_again;
741                         }
742                 }
743         }
744
745         // Find free indices (concatenate them all and call find_free_and_dummy())
746         // and all dummy indices that appear
747         exvector un, individual_dummy_indices;
748         for (it1 = v.begin(), itend = v.end(); it1 != itend; ++it1) {
749                 exvector free_indices_of_factor;
750                 if (is_ex_of_type(*it1, indexed)) {
751                         exvector dummy_indices_of_factor;
752                         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);
753                         individual_dummy_indices.insert(individual_dummy_indices.end(), dummy_indices_of_factor.begin(), dummy_indices_of_factor.end());
754                 } else
755                         free_indices_of_factor = it1->get_free_indices();
756                 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
757         }
758         exvector local_dummy_indices;
759         find_free_and_dummy(un, free_indices, local_dummy_indices);
760         local_dummy_indices.insert(local_dummy_indices.end(), individual_dummy_indices.begin(), individual_dummy_indices.end());
761
762         // Filter out the dummy indices with variance
763         exvector variant_dummy_indices;
764         find_variant_indices(local_dummy_indices, variant_dummy_indices);
765
766         // Any indices with variance present at all?
767         if (!variant_dummy_indices.empty()) {
768
769                 // Yes, bring the product into a canonical order that only depends on
770                 // the base expressions of indexed objects
771                 if (!non_commutative)
772                         std::sort(v.begin(), v.end(), ex_base_is_less());
773
774                 exvector moved_indices;
775
776                 // Iterate over all indexed objects in the product
777                 for (it1 = v.begin(), itend = v.end(); it1 != itend; ++it1) {
778                         if (!is_ex_of_type(*it1, indexed))
779                                 continue;
780
781                         if (reposition_dummy_indices(*it1, variant_dummy_indices, moved_indices))
782                                 something_changed = true;
783                 }
784         }
785
786         ex r;
787         if (something_changed)
788                 r = non_commutative ? ex(ncmul(v, true)) : ex(mul(v));
789         else
790                 r = e;
791
792         // The result should be symmetric with respect to exchange of dummy
793         // indices, so if the symmetrization vanishes, the whole expression is
794         // zero. This detects things like eps.i.j.k * p.j * p.k = 0.
795         if (local_dummy_indices.size() >= 2) {
796                 lst dummy_syms;
797                 for (int i=0; i<local_dummy_indices.size(); i++)
798                         dummy_syms.append(local_dummy_indices[i].op(0));
799                 if (r.symmetrize(dummy_syms).is_zero()) {
800                         free_indices.clear();
801                         return _ex0;
802                 }
803         }
804
805         // Dummy index renaming
806         r = rename_dummy_indices(r, dummy_indices, local_dummy_indices);
807
808         // Product of indexed object with a scalar?
809         if (is_ex_exactly_of_type(r, mul) && r.nops() == 2
810          && is_ex_exactly_of_type(r.op(1), numeric) && is_ex_of_type(r.op(0), indexed))
811                 return ex_to<basic>(r.op(0).op(0)).scalar_mul_indexed(r.op(0), ex_to<numeric>(r.op(1)));
812         else
813                 return r;
814 }
815
816 /** Simplify indexed expression, return list of free indices. */
817 ex simplify_indexed(const ex & e, exvector & free_indices, exvector & dummy_indices, const scalar_products & sp)
818 {
819         // Expand the expression
820         ex e_expanded = e.expand();
821
822         // Simplification of single indexed object: just find the free indices
823         // and perform dummy index renaming/repositioning
824         if (is_ex_of_type(e_expanded, indexed)) {
825
826                 // Find the dummy indices
827                 const indexed &i = ex_to<indexed>(e_expanded);
828                 exvector local_dummy_indices;
829                 find_free_and_dummy(i.seq.begin() + 1, i.seq.end(), free_indices, local_dummy_indices);
830
831                 // Filter out the dummy indices with variance
832                 exvector variant_dummy_indices;
833                 find_variant_indices(local_dummy_indices, variant_dummy_indices);
834
835                 // Any indices with variance present at all?
836                 if (!variant_dummy_indices.empty()) {
837
838                         // Yes, reposition them
839                         exvector moved_indices;
840                         reposition_dummy_indices(e_expanded, variant_dummy_indices, moved_indices);
841                 }
842
843                 // Rename the dummy indices
844                 return rename_dummy_indices(e_expanded, dummy_indices, local_dummy_indices);
845         }
846
847         // Simplification of sum = sum of simplifications, check consistency of
848         // free indices in each term
849         if (is_ex_exactly_of_type(e_expanded, add)) {
850                 bool first = true;
851                 ex sum = _ex0;
852                 free_indices.clear();
853
854                 for (unsigned i=0; i<e_expanded.nops(); i++) {
855                         exvector free_indices_of_term;
856                         ex term = simplify_indexed(e_expanded.op(i), free_indices_of_term, dummy_indices, sp);
857                         if (!term.is_zero()) {
858                                 if (first) {
859                                         free_indices = free_indices_of_term;
860                                         sum = term;
861                                         first = false;
862                                 } else {
863                                         if (!indices_consistent(free_indices, free_indices_of_term))
864                                                 throw (std::runtime_error("simplify_indexed: inconsistent indices in sum"));
865                                         if (is_ex_of_type(sum, indexed) && is_ex_of_type(term, indexed))
866                                                 sum = ex_to<basic>(sum.op(0)).add_indexed(sum, term);
867                                         else
868                                                 sum += term;
869                                 }
870                         }
871                 }
872
873                 return sum;
874         }
875
876         // Simplification of products
877         if (is_ex_exactly_of_type(e_expanded, mul)
878          || is_ex_exactly_of_type(e_expanded, ncmul)
879          || (is_ex_exactly_of_type(e_expanded, power) && is_ex_of_type(e_expanded.op(0), indexed) && e_expanded.op(1).is_equal(_ex2)))
880                 return simplify_indexed_product(e_expanded, free_indices, dummy_indices, sp);
881
882         // Cannot do anything
883         free_indices.clear();
884         return e_expanded;
885 }
886
887 /** Simplify/canonicalize expression containing indexed objects. This
888  *  performs contraction of dummy indices where possible and checks whether
889  *  the free indices in sums are consistent.
890  *
891  *  @return simplified expression */
892 ex ex::simplify_indexed(void) const
893 {
894         exvector free_indices, dummy_indices;
895         scalar_products sp;
896         return GiNaC::simplify_indexed(*this, free_indices, dummy_indices, sp);
897 }
898
899 /** Simplify/canonicalize expression containing indexed objects. This
900  *  performs contraction of dummy indices where possible, checks whether
901  *  the free indices in sums are consistent, and automatically replaces
902  *  scalar products by known values if desired.
903  *
904  *  @param sp Scalar products to be replaced automatically
905  *  @return simplified expression */
906 ex ex::simplify_indexed(const scalar_products & sp) const
907 {
908         exvector free_indices, dummy_indices;
909         return GiNaC::simplify_indexed(*this, free_indices, dummy_indices, sp);
910 }
911
912 /** Symmetrize expression over its free indices. */
913 ex ex::symmetrize(void) const
914 {
915         return GiNaC::symmetrize(*this, get_free_indices());
916 }
917
918 /** Antisymmetrize expression over its free indices. */
919 ex ex::antisymmetrize(void) const
920 {
921         return GiNaC::antisymmetrize(*this, get_free_indices());
922 }
923
924 /** Symmetrize expression by cyclic permutation over its free indices. */
925 ex ex::symmetrize_cyclic(void) const
926 {
927         return GiNaC::symmetrize_cyclic(*this, get_free_indices());
928 }
929
930 //////////
931 // helper classes
932 //////////
933
934 void scalar_products::add(const ex & v1, const ex & v2, const ex & sp)
935 {
936         spm[make_key(v1, v2)] = sp;
937 }
938
939 void scalar_products::add_vectors(const lst & l)
940 {
941         // Add all possible pairs of products
942         unsigned num = l.nops();
943         for (unsigned i=0; i<num; i++) {
944                 ex a = l.op(i);
945                 for (unsigned j=0; j<num; j++) {
946                         ex b = l.op(j);
947                         add(a, b, a*b);
948                 }
949         }
950 }
951
952 void scalar_products::clear(void)
953 {
954         spm.clear();
955 }
956
957 /** Check whether scalar product pair is defined. */
958 bool scalar_products::is_defined(const ex & v1, const ex & v2) const
959 {
960         return spm.find(make_key(v1, v2)) != spm.end();
961 }
962
963 /** Return value of defined scalar product pair. */
964 ex scalar_products::evaluate(const ex & v1, const ex & v2) const
965 {
966         return spm.find(make_key(v1, v2))->second;
967 }
968
969 void scalar_products::debugprint(void) const
970 {
971         std::cerr << "map size=" << spm.size() << std::endl;
972         spmap::const_iterator i = spm.begin(), end = spm.end();
973         while (i != end) {
974                 const spmapkey & k = i->first;
975                 std::cerr << "item key=(" << k.first << "," << k.second;
976                 std::cerr << "), value=" << i->second << std::endl;
977                 ++i;
978         }
979 }
980
981 /** Make key from object pair. */
982 spmapkey scalar_products::make_key(const ex & v1, const ex & v2)
983 {
984         // If indexed, extract base objects
985         ex s1 = is_ex_of_type(v1, indexed) ? v1.op(0) : v1;
986         ex s2 = is_ex_of_type(v2, indexed) ? v2.op(0) : v2;
987
988         // Enforce canonical order in pair
989         if (s1.compare(s2) > 0)
990                 return spmapkey(s2, s1);
991         else
992                 return spmapkey(s1, s2);
993 }
994
995 } // namespace GiNaC