]> www.ginac.de Git - ginac.git/blob - ginac/indexed.cpp
- color and clifford classes are quite functional now
[ginac.git] / ginac / indexed.cpp
1 /** @file indexed.cpp
2  *
3  *  Implementation of GiNaC's indexed expressions. */
4
5 /*
6  *  GiNaC Copyright (C) 1999-2001 Johannes Gutenberg University Mainz, Germany
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 2 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 #include <stdexcept>
24
25 #include "indexed.h"
26 #include "idx.h"
27 #include "add.h"
28 #include "mul.h"
29 #include "ncmul.h"
30 #include "power.h"
31 #include "lst.h"
32 #include "print.h"
33 #include "archive.h"
34 #include "utils.h"
35 #include "debugmsg.h"
36
37 namespace GiNaC {
38
39 GINAC_IMPLEMENT_REGISTERED_CLASS(indexed, exprseq)
40
41 //////////
42 // default constructor, destructor, copy constructor assignment operator and helpers
43 //////////
44
45 indexed::indexed() : symmetry(unknown)
46 {
47         debugmsg("indexed default constructor", LOGLEVEL_CONSTRUCT);
48         tinfo_key = TINFO_indexed;
49 }
50
51 void indexed::copy(const indexed & other)
52 {
53         inherited::copy(other);
54         symmetry = other.symmetry;
55 }
56
57 DEFAULT_DESTROY(indexed)
58
59 //////////
60 // other constructors
61 //////////
62
63 indexed::indexed(const ex & b) : inherited(b), symmetry(unknown)
64 {
65         debugmsg("indexed constructor from ex", LOGLEVEL_CONSTRUCT);
66         tinfo_key = TINFO_indexed;
67         assert_all_indices_of_type_idx();
68 }
69
70 indexed::indexed(const ex & b, const ex & i1) : inherited(b, i1), symmetry(unknown)
71 {
72         debugmsg("indexed constructor from ex,ex", LOGLEVEL_CONSTRUCT);
73         tinfo_key = TINFO_indexed;
74         assert_all_indices_of_type_idx();
75 }
76
77 indexed::indexed(const ex & b, const ex & i1, const ex & i2) : inherited(b, i1, i2), symmetry(unknown)
78 {
79         debugmsg("indexed constructor from ex,ex,ex", LOGLEVEL_CONSTRUCT);
80         tinfo_key = TINFO_indexed;
81         assert_all_indices_of_type_idx();
82 }
83
84 indexed::indexed(const ex & b, const ex & i1, const ex & i2, const ex & i3) : inherited(b, i1, i2, i3), symmetry(unknown)
85 {
86         debugmsg("indexed constructor from ex,ex,ex,ex", LOGLEVEL_CONSTRUCT);
87         tinfo_key = TINFO_indexed;
88         assert_all_indices_of_type_idx();
89 }
90
91 indexed::indexed(const ex & b, const ex & i1, const ex & i2, const ex & i3, const ex & i4) : inherited(b, i1, i2, i3, i4), symmetry(unknown)
92 {
93         debugmsg("indexed constructor from ex,ex,ex,ex,ex", LOGLEVEL_CONSTRUCT);
94         tinfo_key = TINFO_indexed;
95         assert_all_indices_of_type_idx();
96 }
97
98 indexed::indexed(const ex & b, symmetry_type symm, const ex & i1, const ex & i2) : inherited(b, i1, i2), symmetry(symm)
99 {
100         debugmsg("indexed constructor from ex,symmetry,ex,ex", LOGLEVEL_CONSTRUCT);
101         tinfo_key = TINFO_indexed;
102         assert_all_indices_of_type_idx();
103 }
104
105 indexed::indexed(const ex & b, symmetry_type symm, const ex & i1, const ex & i2, const ex & i3) : inherited(b, i1, i2, i3), symmetry(symm)
106 {
107         debugmsg("indexed constructor from ex,symmetry,ex,ex,ex", LOGLEVEL_CONSTRUCT);
108         tinfo_key = TINFO_indexed;
109         assert_all_indices_of_type_idx();
110 }
111
112 indexed::indexed(const ex & b, symmetry_type symm, const ex & i1, const ex & i2, const ex & i3, const ex & i4) : inherited(b, i1, i2, i3, i4), symmetry(symm)
113 {
114         debugmsg("indexed constructor from ex,symmetry,ex,ex,ex,ex", LOGLEVEL_CONSTRUCT);
115         tinfo_key = TINFO_indexed;
116         assert_all_indices_of_type_idx();
117 }
118
119 indexed::indexed(const ex & b, const exvector & v) : inherited(b), symmetry(unknown)
120 {
121         debugmsg("indexed constructor from ex,exvector", LOGLEVEL_CONSTRUCT);
122         seq.insert(seq.end(), v.begin(), v.end());
123         tinfo_key = TINFO_indexed;
124         assert_all_indices_of_type_idx();
125 }
126
127 indexed::indexed(const ex & b, symmetry_type symm, const exvector & v) : inherited(b), symmetry(symm)
128 {
129         debugmsg("indexed constructor from ex,symmetry,exvector", LOGLEVEL_CONSTRUCT);
130         seq.insert(seq.end(), v.begin(), v.end());
131         tinfo_key = TINFO_indexed;
132         assert_all_indices_of_type_idx();
133 }
134
135 indexed::indexed(symmetry_type symm, const exprseq & es) : inherited(es), symmetry(symm)
136 {
137         debugmsg("indexed constructor from symmetry,exprseq", LOGLEVEL_CONSTRUCT);
138         tinfo_key = TINFO_indexed;
139         assert_all_indices_of_type_idx();
140 }
141
142 indexed::indexed(symmetry_type symm, const exvector & v, bool discardable) : inherited(v, discardable), symmetry(symm)
143 {
144         debugmsg("indexed constructor from symmetry,exvector", LOGLEVEL_CONSTRUCT);
145         tinfo_key = TINFO_indexed;
146         assert_all_indices_of_type_idx();
147 }
148
149 indexed::indexed(symmetry_type symm, exvector * vp) : inherited(vp), symmetry(symm)
150 {
151         debugmsg("indexed constructor from symmetry,exvector *", LOGLEVEL_CONSTRUCT);
152         tinfo_key = TINFO_indexed;
153         assert_all_indices_of_type_idx();
154 }
155
156 //////////
157 // archiving
158 //////////
159
160 indexed::indexed(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
161 {
162         debugmsg("indexed constructor from archive_node", LOGLEVEL_CONSTRUCT);
163         unsigned int symm;
164         if (!(n.find_unsigned("symmetry", symm)))
165                 throw (std::runtime_error("unknown indexed symmetry type in archive"));
166 }
167
168 void indexed::archive(archive_node &n) const
169 {
170         inherited::archive(n);
171         n.add_unsigned("symmetry", symmetry);
172 }
173
174 DEFAULT_UNARCHIVE(indexed)
175
176 //////////
177 // functions overriding virtual functions from bases classes
178 //////////
179
180 void indexed::print(const print_context & c, unsigned level) const
181 {
182         debugmsg("indexed print", LOGLEVEL_PRINT);
183         GINAC_ASSERT(seq.size() > 0);
184
185         if (is_of_type(c, print_tree)) {
186
187                 c.s << std::string(level, ' ') << class_name()
188                     << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
189                     << ", " << seq.size()-1 << " indices";
190                 switch (symmetry) {
191                         case symmetric: c.s << ", symmetric"; break;
192                         case antisymmetric: c.s << ", antisymmetric"; break;
193                         default: break;
194                 }
195                 c.s << std::endl;
196                 unsigned delta_indent = static_cast<const print_tree &>(c).delta_indent;
197                 seq[0].print(c, level + delta_indent);
198                 printindices(c, level + delta_indent);
199
200         } else {
201
202                 bool is_tex = is_of_type(c, print_latex);
203                 const ex & base = seq[0];
204                 bool need_parens = is_ex_exactly_of_type(base, add) || is_ex_exactly_of_type(base, mul)
205                                 || is_ex_exactly_of_type(base, ncmul) || is_ex_exactly_of_type(base, power)
206                                 || is_ex_of_type(base, indexed);
207                 if (is_tex)
208                         c.s << "{";
209                 if (need_parens)
210                         c.s << "(";
211                 base.print(c);
212                 if (need_parens)
213                         c.s << ")";
214                 if (is_tex)
215                         c.s << "}";
216                 printindices(c, level);
217         }
218 }
219
220 bool indexed::info(unsigned inf) const
221 {
222         if (inf == info_flags::indexed) return true;
223         if (inf == info_flags::has_indices) return seq.size() > 1;
224         return inherited::info(inf);
225 }
226
227 bool indexed::all_index_values_are(unsigned inf) const
228 {
229         // No indices? Then no property can be fulfilled
230         if (seq.size() < 2)
231                 return false;
232
233         // Check all indices
234         exvector::const_iterator it = seq.begin() + 1, itend = seq.end();
235         while (it != itend) {
236                 GINAC_ASSERT(is_ex_of_type(*it, idx));
237                 if (!ex_to_idx(*it).get_value().info(inf))
238                         return false;
239                 it++;
240         }
241         return true;
242 }
243
244 int indexed::compare_same_type(const basic & other) const
245 {
246         GINAC_ASSERT(is_of_type(other, indexed));
247         return inherited::compare_same_type(other);
248 }
249
250 // The main difference between sort_index_vector() and canonicalize_indices()
251 // is that the latter takes the symmetry of the object into account. Once we
252 // implement mixed symmetries, canonicalize_indices() will only be able to
253 // reorder index pairs with known symmetry properties, while sort_index_vector()
254 // always sorts the whole vector.
255
256 /** Bring a vector of indices into a canonic order (don't care about the
257  *  symmetry of the objects carrying the indices). Dummy indices will lie
258  *  next to each other after the sorting.
259  *
260  *  @param v Index vector to be sorted */
261 static void sort_index_vector(exvector &v)
262 {
263         // Nothing to sort if less than 2 elements
264         if (v.size() < 2)
265                 return;
266
267         // Simple bubble sort algorithm should be sufficient for the small
268         // number of indices expected
269         exvector::iterator it1 = v.begin(), itend = v.end(), next_to_last_idx = itend - 1;
270         while (it1 != next_to_last_idx) {
271                 exvector::iterator it2 = it1 + 1;
272                 while (it2 != itend) {
273                         if (it1->compare(*it2) > 0)
274                                 it1->swap(*it2);
275                         it2++;
276                 }
277                 it1++;
278         }
279 }
280
281 /** Bring a vector of indices into a canonic order. This operation only makes
282  *  sense if the object carrying these indices is either symmetric or totally
283  *  antisymmetric with respect to the indices.
284  *
285  *  @param itbegin Start of index vector
286  *  @param itend End of index vector
287  *  @param antisymm Whether the object is antisymmetric
288  *  @return the sign introduced by the reordering of the indices if the object
289  *          is antisymmetric (or 0 if two equal indices are encountered). For
290  *          symmetric objects, this is always +1. If the index vector was
291  *          already in a canonic order this function returns INT_MAX. */
292 static int canonicalize_indices(exvector::iterator itbegin, exvector::iterator itend, bool antisymm)
293 {
294         bool something_changed = false;
295         int sig = 1;
296
297         // Simple bubble sort algorithm should be sufficient for the small
298         // number of indices expected
299         exvector::iterator it1 = itbegin, next_to_last_idx = itend - 1;
300         while (it1 != next_to_last_idx) {
301                 exvector::iterator it2 = it1 + 1;
302                 while (it2 != itend) {
303                         int cmpval = it1->compare(*it2);
304                         if (cmpval == 1) {
305                                 it1->swap(*it2);
306                                 something_changed = true;
307                                 if (antisymm)
308                                         sig = -sig;
309                         } else if (cmpval == 0 && antisymm) {
310                                 something_changed = true;
311                                 sig = 0;
312                         }
313                         it2++;
314                 }
315                 it1++;
316         }
317
318         return something_changed ? sig : INT_MAX;
319 }
320
321 ex indexed::eval(int level) const
322 {
323         // First evaluate children, then we will end up here again
324         if (level > 1)
325                 return indexed(symmetry, evalchildren(level));
326
327         const ex &base = seq[0];
328
329         // If the base object is 0, the whole object is 0
330         if (base.is_zero())
331                 return _ex0();
332
333         // If the base object is a product, pull out the numeric factor
334         if (is_ex_exactly_of_type(base, mul) && is_ex_exactly_of_type(base.op(base.nops() - 1), numeric)) {
335                 exvector v = seq;
336                 ex f = ex_to_numeric(base.op(base.nops() - 1));
337                 v[0] = seq[0] / f;
338                 return f * thisexprseq(v);
339         }
340
341         // Canonicalize indices according to the symmetry properties
342         if (seq.size() > 2 && (symmetry != unknown && symmetry != mixed)) {
343                 exvector v = seq;
344                 int sig = canonicalize_indices(v.begin() + 1, v.end(), symmetry == antisymmetric);
345                 if (sig != INT_MAX) {
346                         // Something has changed while sorting indices, more evaluations later
347                         if (sig == 0)
348                                 return _ex0();
349                         return ex(sig) * thisexprseq(v);
350                 }
351         }
352
353         // Let the class of the base object perform additional evaluations
354         return base.bp->eval_indexed(*this);
355 }
356
357 int indexed::degree(const ex & s) const
358 {
359         return is_equal(*s.bp) ? 1 : 0;
360 }
361
362 int indexed::ldegree(const ex & s) const
363 {
364         return is_equal(*s.bp) ? 1 : 0;
365 }
366
367 ex indexed::coeff(const ex & s, int n) const
368 {
369         if (is_equal(*s.bp))
370                 return n==1 ? _ex1() : _ex0();
371         else
372                 return n==0 ? ex(*this) : _ex0();
373 }
374
375 ex indexed::thisexprseq(const exvector & v) const
376 {
377         return indexed(symmetry, v);
378 }
379
380 ex indexed::thisexprseq(exvector * vp) const
381 {
382         return indexed(symmetry, vp);
383 }
384
385 ex indexed::expand(unsigned options) const
386 {
387         GINAC_ASSERT(seq.size() > 0);
388
389         if ((options & expand_options::expand_indexed) && is_ex_exactly_of_type(seq[0], add)) {
390
391                 // expand_indexed expands (a+b).i -> a.i + b.i
392                 const ex & base = seq[0];
393                 ex sum = _ex0();
394                 for (unsigned i=0; i<base.nops(); i++) {
395                         exvector s = seq;
396                         s[0] = base.op(i);
397                         sum += thisexprseq(s).expand();
398                 }
399                 return sum;
400
401         } else
402                 return inherited::expand(options);
403 }
404
405 //////////
406 // virtual functions which can be overridden by derived classes
407 //////////
408
409 // none
410
411 //////////
412 // non-virtual functions in this class
413 //////////
414
415 void indexed::printindices(const print_context & c, unsigned level) const
416 {
417         if (seq.size() > 1) {
418
419                 exvector::const_iterator it=seq.begin() + 1, itend = seq.end();
420
421                 if (is_of_type(c, print_latex)) {
422
423                         // TeX output: group by variance
424                         bool first = true;
425                         bool covariant = true;
426
427                         while (it != itend) {
428                                 bool cur_covariant = (is_ex_of_type(*it, varidx) ? ex_to_varidx(*it).is_covariant() : true);
429                                 if (first || cur_covariant != covariant) {
430                                         if (!first)
431                                                 c.s << "}";
432                                         covariant = cur_covariant;
433                                         if (covariant)
434                                                 c.s << "_{";
435                                         else
436                                                 c.s << "^{";
437                                 }
438                                 it->print(c, level);
439                                 c.s << " ";
440                                 first = false;
441                                 it++;
442                         }
443                         c.s << "}";
444
445                 } else {
446
447                         // Ordinary output
448                         while (it != itend) {
449                                 it->print(c, level);
450                                 it++;
451                         }
452                 }
453         }
454 }
455
456 /** Check whether all indices are of class idx. This function is used
457  *  internally to make sure that all constructed indexed objects really
458  *  carry indices and not some other classes. */
459 void indexed::assert_all_indices_of_type_idx(void) const
460 {
461         GINAC_ASSERT(seq.size() > 0);
462         exvector::const_iterator it = seq.begin() + 1, itend = seq.end();
463         while (it != itend) {
464                 if (!is_ex_of_type(*it, idx))
465                         throw(std::invalid_argument("indices of indexed object must be of type idx"));
466                 it++;
467         }
468 }
469
470 //////////
471 // global functions
472 //////////
473
474 /** Check whether two sorted index vectors are consistent (i.e. equal). */
475 static bool indices_consistent(const exvector & v1, const exvector & v2)
476 {
477         // Number of indices must be the same
478         if (v1.size() != v2.size())
479                 return false;
480
481         // And also the indices themselves
482         exvector::const_iterator ait = v1.begin(), aitend = v1.end(),
483                                  bit = v2.begin(), bitend = v2.end();
484         while (ait != aitend) {
485                 if (!ait->is_equal(*bit))
486                         return false;
487                 ait++; bit++;
488         }
489         return true;
490 }
491
492 exvector indexed::get_indices(void) const
493 {
494         GINAC_ASSERT(seq.size() >= 1);
495         return exvector(seq.begin() + 1, seq.end());
496 }
497
498 exvector indexed::get_dummy_indices(void) const
499 {
500         exvector free_indices, dummy_indices;
501         find_free_and_dummy(seq.begin() + 1, seq.end(), free_indices, dummy_indices);
502         return dummy_indices;
503 }
504
505 exvector indexed::get_dummy_indices(const indexed & other) const
506 {
507         exvector indices = get_free_indices();
508         exvector other_indices = other.get_free_indices();
509         indices.insert(indices.end(), other_indices.begin(), other_indices.end());
510         exvector dummy_indices;
511         find_dummy_indices(indices, dummy_indices);
512         return dummy_indices;
513 }
514
515 exvector indexed::get_free_indices(void) const
516 {
517         exvector free_indices, dummy_indices;
518         find_free_and_dummy(seq.begin() + 1, seq.end(), free_indices, dummy_indices);
519         return free_indices;
520 }
521
522 exvector add::get_free_indices(void) const
523 {
524         exvector free_indices;
525         for (unsigned i=0; i<nops(); i++) {
526                 if (i == 0)
527                         free_indices = op(i).get_free_indices();
528                 else {
529                         exvector free_indices_of_term = op(i).get_free_indices();
530                         if (!indices_consistent(free_indices, free_indices_of_term))
531                                 throw (std::runtime_error("add::get_free_indices: inconsistent indices in sum"));
532                 }
533         }
534         return free_indices;
535 }
536
537 exvector mul::get_free_indices(void) const
538 {
539         // Concatenate free indices of all factors
540         exvector un;
541         for (unsigned i=0; i<nops(); i++) {
542                 exvector free_indices_of_factor = op(i).get_free_indices();
543                 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
544         }
545
546         // And remove the dummy indices
547         exvector free_indices, dummy_indices;
548         find_free_and_dummy(un, free_indices, dummy_indices);
549         return free_indices;
550 }
551
552 exvector ncmul::get_free_indices(void) const
553 {
554         // Concatenate free indices of all factors
555         exvector un;
556         for (unsigned i=0; i<nops(); i++) {
557                 exvector free_indices_of_factor = op(i).get_free_indices();
558                 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
559         }
560
561         // And remove the dummy indices
562         exvector free_indices, dummy_indices;
563         find_free_and_dummy(un, free_indices, dummy_indices);
564         return free_indices;
565 }
566
567 exvector power::get_free_indices(void) const
568 {
569         // Return free indices of basis
570         return basis.get_free_indices();
571 }
572
573 /** Simplify product of indexed expressions (commutative, noncommutative and
574  *  simple squares), return list of free indices. */
575 ex simplify_indexed_product(const ex & e, exvector & free_indices, const scalar_products & sp)
576 {
577         // Remember whether the product was commutative or noncommutative
578         // (because we chop it into factors and need to reassemble later)
579         bool non_commutative = is_ex_exactly_of_type(e, ncmul);
580
581         // Collect factors in an exvector, store squares twice
582         exvector v;
583         v.reserve(e.nops() * 2);
584
585         if (is_ex_exactly_of_type(e, power)) {
586                 // We only get called for simple squares, split a^2 -> a*a
587                 GINAC_ASSERT(e.op(1).is_equal(_ex2()));
588                 v.push_back(e.op(0));
589                 v.push_back(e.op(0));
590         } else {
591                 for (int i=0; i<e.nops(); i++) {
592                         ex f = e.op(i);
593                         if (is_ex_exactly_of_type(f, power) && f.op(1).is_equal(_ex2())) {
594                                 v.push_back(f.op(0));
595                     v.push_back(f.op(0));
596                         } else if (is_ex_exactly_of_type(f, ncmul)) {
597                                 // Noncommutative factor found, split it as well
598                                 non_commutative = true; // everything becomes noncommutative, ncmul will sort out the commutative factors later
599                                 for (int j=0; j<f.nops(); j++)
600                                         v.push_back(f.op(j));
601                         } else
602                                 v.push_back(f);
603                 }
604         }
605
606         // Perform contractions
607         bool something_changed = false;
608         GINAC_ASSERT(v.size() > 1);
609         exvector::iterator it1, itend = v.end(), next_to_last = itend - 1;
610         for (it1 = v.begin(); it1 != next_to_last; it1++) {
611
612 try_again:
613                 if (!is_ex_of_type(*it1, indexed))
614                         continue;
615
616                 // Indexed factor found, get free indices and look for contraction
617                 // candidates
618                 exvector free1, dummy1;
619                 find_free_and_dummy(ex_to_indexed(*it1).seq.begin() + 1, ex_to_indexed(*it1).seq.end(), free1, dummy1);
620
621                 exvector::iterator it2;
622                 for (it2 = it1 + 1; it2 != itend; it2++) {
623
624                         if (!is_ex_of_type(*it2, indexed))
625                                 continue;
626
627                         // Find free indices of second factor and merge them with free
628                         // indices of first factor
629                         exvector un;
630                         find_free_and_dummy(ex_to_indexed(*it2).seq.begin() + 1, ex_to_indexed(*it2).seq.end(), un, dummy1);
631                         un.insert(un.end(), free1.begin(), free1.end());
632
633                         // Check whether the two factors share dummy indices
634                         exvector free, dummy;
635                         find_free_and_dummy(un, free, dummy);
636                         if (dummy.size() == 0)
637                                 continue;
638
639                         // At least one dummy index, is it a defined scalar product?
640                         bool contracted = false;
641                         if (free.size() == 0) {
642                                 if (sp.is_defined(*it1, *it2)) {
643                                         *it1 = sp.evaluate(*it1, *it2);
644                                         *it2 = _ex1();
645                                         goto contraction_done;
646                                 }
647                         }
648
649                         // Contraction of symmetric with antisymmetric object is zero
650                         if ((ex_to_indexed(*it1).symmetry == indexed::symmetric &&
651                              ex_to_indexed(*it2).symmetry == indexed::antisymmetric
652                           || ex_to_indexed(*it1).symmetry == indexed::antisymmetric &&
653                              ex_to_indexed(*it2).symmetry == indexed::symmetric)
654                          && dummy.size() > 1) {
655                                 free_indices.clear();
656                                 return _ex0();
657                         }
658
659                         // Try to contract the first one with the second one
660                         contracted = it1->op(0).bp->contract_with(it1, it2, v);
661                         if (!contracted) {
662
663                                 // That didn't work; maybe the second object knows how to
664                                 // contract itself with the first one
665                                 contracted = it2->op(0).bp->contract_with(it2, it1, v);
666                         }
667                         if (contracted) {
668 contraction_done:
669                                 if (non_commutative
670                                  || is_ex_exactly_of_type(*it1, add) || is_ex_exactly_of_type(*it2, add)
671                                  || is_ex_exactly_of_type(*it1, mul) || is_ex_exactly_of_type(*it2, mul)
672                                  || is_ex_exactly_of_type(*it1, ncmul) || is_ex_exactly_of_type(*it2, ncmul)) {
673
674                                         // One of the factors became a sum or product:
675                                         // re-expand expression and run again
676                                         // Non-commutative products are always re-expanded to give
677                                         // simplify_ncmul() the chance to re-order and canonicalize
678                                         // the product
679                                         ex r = (non_commutative ? ex(ncmul(v)) : ex(mul(v)));
680                                         return simplify_indexed(r, free_indices, sp);
681                                 }
682
683                                 // Both objects may have new indices now or they might
684                                 // even not be indexed objects any more, so we have to
685                                 // start over
686                                 something_changed = true;
687                                 goto try_again;
688                         }
689                 }
690         }
691
692         // Find free indices (concatenate them all and call find_free_and_dummy())
693         exvector un, dummy_indices;
694         it1 = v.begin(); itend = v.end();
695         while (it1 != itend) {
696                 exvector free_indices_of_factor = it1->get_free_indices();
697                 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
698                 it1++;
699         }
700         find_free_and_dummy(un, free_indices, dummy_indices);
701
702         ex r;
703         if (something_changed)
704                 r = non_commutative ? ex(ncmul(v)) : ex(mul(v));
705         else
706                 r = e;
707
708         // Product of indexed object with a scalar?
709         if (is_ex_exactly_of_type(r, mul) && r.nops() == 2
710          && is_ex_exactly_of_type(r.op(1), numeric) && is_ex_of_type(r.op(0), indexed))
711                 return r.op(0).op(0).bp->scalar_mul_indexed(r.op(0), ex_to_numeric(r.op(1)));
712         else
713                 return r;
714 }
715
716 /** Simplify indexed expression, return list of free indices. */
717 ex simplify_indexed(const ex & e, exvector & free_indices, const scalar_products & sp)
718 {
719         // Expand the expression
720         ex e_expanded = e.expand();
721
722         // Simplification of single indexed object: just find the free indices
723         if (is_ex_of_type(e_expanded, indexed)) {
724                 const indexed &i = ex_to_indexed(e_expanded);
725                 exvector dummy_indices;
726                 find_free_and_dummy(i.seq.begin() + 1, i.seq.end(), free_indices, dummy_indices);
727                 return e_expanded;
728         }
729
730         // Simplification of sum = sum of simplifications, check consistency of
731         // free indices in each term
732         if (is_ex_exactly_of_type(e_expanded, add)) {
733                 bool first = true;
734                 ex sum = _ex0();
735                 free_indices.clear();
736
737                 for (unsigned i=0; i<e_expanded.nops(); i++) {
738                         exvector free_indices_of_term;
739                         ex term = simplify_indexed(e_expanded.op(i), free_indices_of_term, sp);
740                         if (!term.is_zero()) {
741                                 if (first) {
742                                         free_indices = free_indices_of_term;
743                                         sum = term;
744                                         first = false;
745                                 } else {
746                                         if (!indices_consistent(free_indices, free_indices_of_term))
747                                                 throw (std::runtime_error("simplify_indexed: inconsistent indices in sum"));
748                                         if (is_ex_of_type(sum, indexed) && is_ex_of_type(term, indexed))
749                                                 sum = sum.op(0).bp->add_indexed(sum, term);
750                                         else
751                                                 sum += term;
752                                 }
753                         }
754                 }
755
756                 return sum;
757         }
758
759         // Simplification of products
760         if (is_ex_exactly_of_type(e_expanded, mul)
761          || is_ex_exactly_of_type(e_expanded, ncmul)
762          || (is_ex_exactly_of_type(e_expanded, power) && is_ex_of_type(e_expanded.op(0), indexed) && e_expanded.op(1).is_equal(_ex2())))
763                 return simplify_indexed_product(e_expanded, free_indices, sp);
764
765         // Cannot do anything
766         free_indices.clear();
767         return e_expanded;
768 }
769
770 ex simplify_indexed(const ex & e)
771 {
772         exvector free_indices;
773         scalar_products sp;
774         return simplify_indexed(e, free_indices, sp);
775 }
776
777 ex simplify_indexed(const ex & e, const scalar_products & sp)
778 {
779         exvector free_indices;
780         return simplify_indexed(e, free_indices, sp);
781 }
782
783 //////////
784 // helper classes
785 //////////
786
787 void scalar_products::add(const ex & v1, const ex & v2, const ex & sp)
788 {
789         spm[make_key(v1, v2)] = sp;
790 }
791
792 void scalar_products::add_vectors(const lst & l)
793 {
794         // Add all possible pairs of products
795         unsigned num = l.nops();
796         for (unsigned i=0; i<num; i++) {
797                 ex a = l.op(i);
798                 for (unsigned j=0; j<num; j++) {
799                         ex b = l.op(j);
800                         add(a, b, a*b);
801                 }
802         }
803 }
804
805 void scalar_products::clear(void)
806 {
807         spm.clear();
808 }
809
810 /** Check whether scalar product pair is defined. */
811 bool scalar_products::is_defined(const ex & v1, const ex & v2) const
812 {
813         return spm.find(make_key(v1, v2)) != spm.end();
814 }
815
816 /** Return value of defined scalar product pair. */
817 ex scalar_products::evaluate(const ex & v1, const ex & v2) const
818 {
819         return spm.find(make_key(v1, v2))->second;
820 }
821
822 void scalar_products::debugprint(void) const
823 {
824         std::cerr << "map size=" << spm.size() << std::endl;
825         for (spmap::const_iterator cit=spm.begin(); cit!=spm.end(); ++cit) {
826                 const spmapkey & k = cit->first;
827                 std::cerr << "item key=(" << k.first << "," << k.second;
828                 std::cerr << "), value=" << cit->second << std::endl;
829         }
830 }
831
832 /** Make key from object pair. */
833 spmapkey scalar_products::make_key(const ex & v1, const ex & v2)
834 {
835         // If indexed, extract base objects
836         ex s1 = is_ex_of_type(v1, indexed) ? v1.op(0) : v1;
837         ex s2 = is_ex_of_type(v2, indexed) ? v2.op(0) : v2;
838
839         // Enforce canonical order in pair
840         if (s1.compare(s2) > 0)
841                 return spmapkey(s2, s1);
842         else
843                 return spmapkey(s1, s2);
844 }
845
846 } // namespace GiNaC