]> www.ginac.de Git - ginac.git/blob - ginac/indexed.cpp
* Supplement some (now deprecated) macros by inlined template functions:
[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 #include <algorithm>
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 "symmetry.h"
33 #include "lst.h"
34 #include "print.h"
35 #include "archive.h"
36 #include "utils.h"
37 #include "debugmsg.h"
38
39 namespace GiNaC {
40
41 GINAC_IMPLEMENT_REGISTERED_CLASS(indexed, exprseq)
42
43 //////////
44 // default constructor, destructor, copy constructor assignment operator and helpers
45 //////////
46
47 indexed::indexed() : symtree(sy_none())
48 {
49         debugmsg("indexed default constructor", LOGLEVEL_CONSTRUCT);
50         tinfo_key = TINFO_indexed;
51 }
52
53 void indexed::copy(const indexed & other)
54 {
55         inherited::copy(other);
56         symtree = other.symtree;
57 }
58
59 DEFAULT_DESTROY(indexed)
60
61 //////////
62 // other constructors
63 //////////
64
65 indexed::indexed(const ex & b) : inherited(b), symtree(sy_none())
66 {
67         debugmsg("indexed constructor from ex", LOGLEVEL_CONSTRUCT);
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         debugmsg("indexed constructor from ex,ex", LOGLEVEL_CONSTRUCT);
75         tinfo_key = TINFO_indexed;
76         validate();
77 }
78
79 indexed::indexed(const ex & b, const ex & i1, const ex & i2) : inherited(b, i1, i2), symtree(sy_none())
80 {
81         debugmsg("indexed constructor from ex,ex,ex", LOGLEVEL_CONSTRUCT);
82         tinfo_key = TINFO_indexed;
83         validate();
84 }
85
86 indexed::indexed(const ex & b, const ex & i1, const ex & i2, const ex & i3) : inherited(b, i1, i2, i3), symtree(sy_none())
87 {
88         debugmsg("indexed constructor from ex,ex,ex,ex", LOGLEVEL_CONSTRUCT);
89         tinfo_key = TINFO_indexed;
90         validate();
91 }
92
93 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())
94 {
95         debugmsg("indexed constructor from ex,ex,ex,ex,ex", LOGLEVEL_CONSTRUCT);
96         tinfo_key = TINFO_indexed;
97         validate();
98 }
99
100 indexed::indexed(const ex & b, const symmetry & symm, const ex & i1, const ex & i2) : inherited(b, i1, i2), symtree(symm)
101 {
102         debugmsg("indexed constructor from ex,symmetry,ex,ex", LOGLEVEL_CONSTRUCT);
103         tinfo_key = TINFO_indexed;
104         validate();
105 }
106
107 indexed::indexed(const ex & b, const symmetry & symm, const ex & i1, const ex & i2, const ex & i3) : inherited(b, i1, i2, i3), symtree(symm)
108 {
109         debugmsg("indexed constructor from ex,symmetry,ex,ex,ex", LOGLEVEL_CONSTRUCT);
110         tinfo_key = TINFO_indexed;
111         validate();
112 }
113
114 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)
115 {
116         debugmsg("indexed constructor from ex,symmetry,ex,ex,ex,ex", LOGLEVEL_CONSTRUCT);
117         tinfo_key = TINFO_indexed;
118         validate();
119 }
120
121 indexed::indexed(const ex & b, const exvector & v) : inherited(b), symtree(sy_none())
122 {
123         debugmsg("indexed constructor from ex,exvector", LOGLEVEL_CONSTRUCT);
124         seq.insert(seq.end(), v.begin(), v.end());
125         tinfo_key = TINFO_indexed;
126         validate();
127 }
128
129 indexed::indexed(const ex & b, const symmetry & symm, const exvector & v) : inherited(b), symtree(symm)
130 {
131         debugmsg("indexed constructor from ex,symmetry,exvector", LOGLEVEL_CONSTRUCT);
132         seq.insert(seq.end(), v.begin(), v.end());
133         tinfo_key = TINFO_indexed;
134         validate();
135 }
136
137 indexed::indexed(const symmetry & symm, const exprseq & es) : inherited(es), symtree(symm)
138 {
139         debugmsg("indexed constructor from symmetry,exprseq", LOGLEVEL_CONSTRUCT);
140         tinfo_key = TINFO_indexed;
141 }
142
143 indexed::indexed(const symmetry & symm, const exvector & v, bool discardable) : inherited(v, discardable), symtree(symm)
144 {
145         debugmsg("indexed constructor from symmetry,exvector", LOGLEVEL_CONSTRUCT);
146         tinfo_key = TINFO_indexed;
147 }
148
149 indexed::indexed(const symmetry & symm, exvector * vp) : inherited(vp), symtree(symm)
150 {
151         debugmsg("indexed constructor from symmetry,exvector *", LOGLEVEL_CONSTRUCT);
152         tinfo_key = TINFO_indexed;
153 }
154
155 //////////
156 // archiving
157 //////////
158
159 indexed::indexed(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
160 {
161         debugmsg("indexed constructor from archive_node", LOGLEVEL_CONSTRUCT);
162         if (!n.find_ex("symmetry", symtree, sym_lst)) {
163                 // GiNaC versions <= 0.9.0 had an unsigned "symmetry" property
164                 unsigned symm = 0;
165                 n.find_unsigned("symmetry", symm);
166                 switch (symm) {
167                         case 1:
168                                 symtree = sy_symm();
169                                 break;
170                         case 2:
171                                 symtree = sy_anti();
172                                 break;
173                         default:
174                                 symtree = sy_none();
175                                 break;
176                 }
177                 ex_to_nonconst_symmetry(symtree).validate(seq.size() - 1);
178         }
179 }
180
181 void indexed::archive(archive_node &n) const
182 {
183         inherited::archive(n);
184         n.add_ex("symmetry", symtree);
185 }
186
187 DEFAULT_UNARCHIVE(indexed)
188
189 //////////
190 // functions overriding virtual functions from bases classes
191 //////////
192
193 void indexed::print(const print_context & c, unsigned level) const
194 {
195         debugmsg("indexed print", LOGLEVEL_PRINT);
196         GINAC_ASSERT(seq.size() > 0);
197
198         if (is_of_type(c, print_tree)) {
199
200                 c.s << std::string(level, ' ') << class_name()
201                     << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
202                     << ", " << seq.size()-1 << " indices"
203                     << ", symmetry=" << symtree << std::endl;
204                 c.s << std::endl;
205                 unsigned delta_indent = static_cast<const print_tree &>(c).delta_indent;
206                 seq[0].print(c, level + delta_indent);
207                 printindices(c, level + delta_indent);
208
209         } else {
210
211                 bool is_tex = is_of_type(c, print_latex);
212                 const ex & base = seq[0];
213                 bool need_parens = is_ex_exactly_of_type(base, add) || is_ex_exactly_of_type(base, mul)
214                                 || is_ex_exactly_of_type(base, ncmul) || is_ex_exactly_of_type(base, power)
215                                 || is_ex_of_type(base, indexed);
216                 if (is_tex)
217                         c.s << "{";
218                 if (need_parens)
219                         c.s << "(";
220                 base.print(c);
221                 if (need_parens)
222                         c.s << ")";
223                 if (is_tex)
224                         c.s << "}";
225                 printindices(c, level);
226         }
227 }
228
229 bool indexed::info(unsigned inf) const
230 {
231         if (inf == info_flags::indexed) return true;
232         if (inf == info_flags::has_indices) return seq.size() > 1;
233         return inherited::info(inf);
234 }
235
236 struct idx_is_not : public std::binary_function<ex, unsigned, bool> {
237         bool operator() (const ex & e, unsigned inf) const {
238                 return !(ex_to<idx>(e).get_value().info(inf));
239         }
240 };
241
242 bool indexed::all_index_values_are(unsigned inf) const
243 {
244         // No indices? Then no property can be fulfilled
245         if (seq.size() < 2)
246                 return false;
247
248         // Check all indices
249         return find_if(seq.begin() + 1, seq.end(), bind2nd(idx_is_not(), inf)) == seq.end();
250 }
251
252 int indexed::compare_same_type(const basic & other) const
253 {
254         GINAC_ASSERT(is_of_type(other, indexed));
255         return inherited::compare_same_type(other);
256 }
257
258 ex indexed::eval(int level) const
259 {
260         // First evaluate children, then we will end up here again
261         if (level > 1)
262                 return indexed(ex_to<symmetry>(symtree), evalchildren(level));
263
264         const ex &base = seq[0];
265
266         // If the base object is 0, the whole object is 0
267         if (base.is_zero())
268                 return _ex0();
269
270         // If the base object is a product, pull out the numeric factor
271         if (is_ex_exactly_of_type(base, mul) && is_ex_exactly_of_type(base.op(base.nops() - 1), numeric)) {
272                 exvector v(seq);
273                 ex f = ex_to<numeric>(base.op(base.nops() - 1));
274                 v[0] = seq[0] / f;
275                 return f * thisexprseq(v);
276         }
277
278         // Canonicalize indices according to the symmetry properties
279         if (seq.size() > 2) {
280                 exvector v = seq;
281                 GINAC_ASSERT(is_ex_exactly_of_type(symtree, symmetry));
282                 int sig = canonicalize(v.begin() + 1, ex_to<symmetry>(symtree));
283                 if (sig != INT_MAX) {
284                         // Something has changed while sorting indices, more evaluations later
285                         if (sig == 0)
286                                 return _ex0();
287                         return ex(sig) * thisexprseq(v);
288                 }
289         }
290
291         // Let the class of the base object perform additional evaluations
292         return base.bp->eval_indexed(*this);
293 }
294
295 int indexed::degree(const ex & s) const
296 {
297         return is_equal(*s.bp) ? 1 : 0;
298 }
299
300 int indexed::ldegree(const ex & s) const
301 {
302         return is_equal(*s.bp) ? 1 : 0;
303 }
304
305 ex indexed::coeff(const ex & s, int n) const
306 {
307         if (is_equal(*s.bp))
308                 return n==1 ? _ex1() : _ex0();
309         else
310                 return n==0 ? ex(*this) : _ex0();
311 }
312
313 ex indexed::thisexprseq(const exvector & v) const
314 {
315         return indexed(ex_to<symmetry>(symtree), v);
316 }
317
318 ex indexed::thisexprseq(exvector * vp) const
319 {
320         return indexed(ex_to<symmetry>(symtree), vp);
321 }
322
323 ex indexed::expand(unsigned options) const
324 {
325         GINAC_ASSERT(seq.size() > 0);
326
327         if ((options & expand_options::expand_indexed) && is_ex_exactly_of_type(seq[0], add)) {
328
329                 // expand_indexed expands (a+b).i -> a.i + b.i
330                 const ex & base = seq[0];
331                 ex sum = _ex0();
332                 for (unsigned i=0; i<base.nops(); i++) {
333                         exvector s = seq;
334                         s[0] = base.op(i);
335                         sum += thisexprseq(s).expand();
336                 }
337                 return sum;
338
339         } else
340                 return inherited::expand(options);
341 }
342
343 //////////
344 // virtual functions which can be overridden by derived classes
345 //////////
346
347 // none
348
349 //////////
350 // non-virtual functions in this class
351 //////////
352
353 void indexed::printindices(const print_context & c, unsigned level) const
354 {
355         if (seq.size() > 1) {
356
357                 exvector::const_iterator it=seq.begin() + 1, itend = seq.end();
358
359                 if (is_of_type(c, print_latex)) {
360
361                         // TeX output: group by variance
362                         bool first = true;
363                         bool covariant = true;
364
365                         while (it != itend) {
366                                 bool cur_covariant = (is_ex_of_type(*it, varidx) ? ex_to<varidx>(*it).is_covariant() : true);
367                                 if (first || cur_covariant != covariant) {
368                                         if (!first)
369                                                 c.s << "}";
370                                         covariant = cur_covariant;
371                                         if (covariant)
372                                                 c.s << "_{";
373                                         else
374                                                 c.s << "^{";
375                                 }
376                                 it->print(c, level);
377                                 c.s << " ";
378                                 first = false;
379                                 it++;
380                         }
381                         c.s << "}";
382
383                 } else {
384
385                         // Ordinary output
386                         while (it != itend) {
387                                 it->print(c, level);
388                                 it++;
389                         }
390                 }
391         }
392 }
393
394 /** Check whether all indices are of class idx and validate the symmetry
395  *  tree. This function is used internally to make sure that all constructed
396  *  indexed objects really carry indices and not some other classes. */
397 void indexed::validate(void) const
398 {
399         GINAC_ASSERT(seq.size() > 0);
400         exvector::const_iterator it = seq.begin() + 1, itend = seq.end();
401         while (it != itend) {
402                 if (!is_ex_of_type(*it, idx))
403                         throw(std::invalid_argument("indices of indexed object must be of type idx"));
404                 it++;
405         }
406
407         if (!symtree.is_zero()) {
408                 if (!is_ex_exactly_of_type(symtree, symmetry))
409                         throw(std::invalid_argument("symmetry of indexed object must be of type symmetry"));
410                 ex_to_nonconst_symmetry(symtree).validate(seq.size() - 1);
411         }
412 }
413
414 //////////
415 // global functions
416 //////////
417
418 /** Check whether two sorted index vectors are consistent (i.e. equal). */
419 static bool indices_consistent(const exvector & v1, const exvector & v2)
420 {
421         // Number of indices must be the same
422         if (v1.size() != v2.size())
423                 return false;
424
425         return equal(v1.begin(), v1.end(), v2.begin(), ex_is_equal());
426 }
427
428 exvector indexed::get_indices(void) const
429 {
430         GINAC_ASSERT(seq.size() >= 1);
431         return exvector(seq.begin() + 1, seq.end());
432 }
433
434 exvector indexed::get_dummy_indices(void) const
435 {
436         exvector free_indices, dummy_indices;
437         find_free_and_dummy(seq.begin() + 1, seq.end(), free_indices, dummy_indices);
438         return dummy_indices;
439 }
440
441 exvector indexed::get_dummy_indices(const indexed & other) const
442 {
443         exvector indices = get_free_indices();
444         exvector other_indices = other.get_free_indices();
445         indices.insert(indices.end(), other_indices.begin(), other_indices.end());
446         exvector dummy_indices;
447         find_dummy_indices(indices, dummy_indices);
448         return dummy_indices;
449 }
450
451 bool indexed::has_dummy_index_for(const ex & i) const
452 {
453         exvector::const_iterator it = seq.begin() + 1, itend = seq.end();
454         while (it != itend) {
455                 if (is_dummy_pair(*it, i))
456                         return true;
457                 it++;
458         }
459         return false;
460 }
461
462 exvector indexed::get_free_indices(void) const
463 {
464         exvector free_indices, dummy_indices;
465         find_free_and_dummy(seq.begin() + 1, seq.end(), free_indices, dummy_indices);
466         return free_indices;
467 }
468
469 exvector add::get_free_indices(void) const
470 {
471         exvector free_indices;
472         for (unsigned i=0; i<nops(); i++) {
473                 if (i == 0)
474                         free_indices = op(i).get_free_indices();
475                 else {
476                         exvector free_indices_of_term = op(i).get_free_indices();
477                         if (!indices_consistent(free_indices, free_indices_of_term))
478                                 throw (std::runtime_error("add::get_free_indices: inconsistent indices in sum"));
479                 }
480         }
481         return free_indices;
482 }
483
484 exvector mul::get_free_indices(void) const
485 {
486         // Concatenate free indices of all factors
487         exvector un;
488         for (unsigned i=0; i<nops(); i++) {
489                 exvector free_indices_of_factor = op(i).get_free_indices();
490                 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
491         }
492
493         // And remove the dummy indices
494         exvector free_indices, dummy_indices;
495         find_free_and_dummy(un, free_indices, dummy_indices);
496         return free_indices;
497 }
498
499 exvector ncmul::get_free_indices(void) const
500 {
501         // Concatenate free indices of all factors
502         exvector un;
503         for (unsigned i=0; i<nops(); i++) {
504                 exvector free_indices_of_factor = op(i).get_free_indices();
505                 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
506         }
507
508         // And remove the dummy indices
509         exvector free_indices, dummy_indices;
510         find_free_and_dummy(un, free_indices, dummy_indices);
511         return free_indices;
512 }
513
514 exvector power::get_free_indices(void) const
515 {
516         // Return free indices of basis
517         return basis.get_free_indices();
518 }
519
520 /** Rename dummy indices in an expression.
521  *
522  *  @param e Expression to be worked on
523  *  @param local_dummy_indices The set of dummy indices that appear in the
524  *    expression "e"
525  *  @param global_dummy_indices The set of dummy indices that have appeared
526  *    before and which we would like to use in "e", too. This gets updated
527  *    by the function */
528 static ex rename_dummy_indices(const ex & e, exvector & global_dummy_indices, exvector & local_dummy_indices)
529 {
530         int global_size = global_dummy_indices.size(),
531             local_size = local_dummy_indices.size();
532
533         // Any local dummy indices at all?
534         if (local_size == 0)
535                 return e;
536
537         if (global_size < local_size) {
538
539                 // More local indices than we encountered before, add the new ones
540                 // to the global set
541                 int remaining = local_size - global_size;
542                 exvector::const_iterator it = local_dummy_indices.begin(), itend = local_dummy_indices.end();
543                 while (it != itend && remaining > 0) {
544                         if (find_if(global_dummy_indices.begin(), global_dummy_indices.end(), bind2nd(ex_is_equal(), *it)) == global_dummy_indices.end()) {
545                                 global_dummy_indices.push_back(*it);
546                                 global_size++;
547                                 remaining--;
548                         }
549                         it++;
550                 }
551         }
552
553         // Replace index symbols in expression
554         GINAC_ASSERT(local_size <= global_size);
555         bool all_equal = true;
556         lst local_syms, global_syms;
557         for (unsigned i=0; i<local_size; i++) {
558                 ex loc_sym = local_dummy_indices[i].op(0);
559                 ex glob_sym = global_dummy_indices[i].op(0);
560                 if (!loc_sym.is_equal(glob_sym)) {
561                         all_equal = false;
562                         local_syms.append(loc_sym);
563                         global_syms.append(glob_sym);
564                 }
565         }
566         if (all_equal)
567                 return e;
568         else
569                 return e.subs(local_syms, global_syms);
570 }
571
572 /** Simplify product of indexed expressions (commutative, noncommutative and
573  *  simple squares), return list of free indices. */
574 ex simplify_indexed_product(const ex & e, exvector & free_indices, exvector & dummy_indices, const scalar_products & sp)
575 {
576         // Remember whether the product was commutative or noncommutative
577         // (because we chop it into factors and need to reassemble later)
578         bool non_commutative = is_ex_exactly_of_type(e, ncmul);
579
580         // Collect factors in an exvector, store squares twice
581         exvector v;
582         v.reserve(e.nops() * 2);
583
584         if (is_ex_exactly_of_type(e, power)) {
585                 // We only get called for simple squares, split a^2 -> a*a
586                 GINAC_ASSERT(e.op(1).is_equal(_ex2()));
587                 v.push_back(e.op(0));
588                 v.push_back(e.op(0));
589         } else {
590                 for (int i=0; i<e.nops(); i++) {
591                         ex f = e.op(i);
592                         if (is_ex_exactly_of_type(f, power) && f.op(1).is_equal(_ex2())) {
593                                 v.push_back(f.op(0));
594                     v.push_back(f.op(0));
595                         } else if (is_ex_exactly_of_type(f, ncmul)) {
596                                 // Noncommutative factor found, split it as well
597                                 non_commutative = true; // everything becomes noncommutative, ncmul will sort out the commutative factors later
598                                 for (int j=0; j<f.nops(); j++)
599                                         v.push_back(f.op(j));
600                         } else
601                                 v.push_back(f);
602                 }
603         }
604
605         // Perform contractions
606         bool something_changed = false;
607         GINAC_ASSERT(v.size() > 1);
608         exvector::iterator it1, itend = v.end(), next_to_last = itend - 1;
609         for (it1 = v.begin(); it1 != next_to_last; it1++) {
610
611 try_again:
612                 if (!is_ex_of_type(*it1, indexed))
613                         continue;
614
615                 bool first_noncommutative = (it1->return_type() != return_types::commutative);
616
617                 // Indexed factor found, get free indices and look for contraction
618                 // candidates
619                 exvector free1, dummy1;
620                 find_free_and_dummy(ex_to<indexed>(*it1).seq.begin() + 1, ex_to<indexed>(*it1).seq.end(), free1, dummy1);
621
622                 exvector::iterator it2;
623                 for (it2 = it1 + 1; it2 != itend; it2++) {
624
625                         if (!is_ex_of_type(*it2, indexed))
626                                 continue;
627
628                         bool second_noncommutative = (it2->return_type() != return_types::commutative);
629
630                         // Find free indices of second factor and merge them with free
631                         // indices of first factor
632                         exvector un;
633                         find_free_and_dummy(ex_to<indexed>(*it2).seq.begin() + 1, ex_to<indexed>(*it2).seq.end(), un, dummy1);
634                         un.insert(un.end(), free1.begin(), free1.end());
635
636                         // Check whether the two factors share dummy indices
637                         exvector free, dummy;
638                         find_free_and_dummy(un, free, dummy);
639                         if (dummy.size() == 0)
640                                 continue;
641
642                         // At least one dummy index, is it a defined scalar product?
643                         bool contracted = false;
644                         if (free.size() == 0) {
645                                 if (sp.is_defined(*it1, *it2)) {
646                                         *it1 = sp.evaluate(*it1, *it2);
647                                         *it2 = _ex1();
648                                         goto contraction_done;
649                                 }
650                         }
651
652                         // Contraction of symmetric with antisymmetric object is zero
653                         if (dummy.size() > 1
654                          && ex_to<symmetry>(ex_to<indexed>(*it1).symtree).has_symmetry()
655                          && ex_to<symmetry>(ex_to<indexed>(*it2).symtree).has_symmetry()) {
656
657                                 // Check all pairs of dummy indices
658                                 for (unsigned idx1=0; idx1<dummy.size()-1; idx1++) {
659                                         for (unsigned idx2=idx1+1; idx2<dummy.size(); idx2++) {
660
661                                                 // Try and swap the index pair and check whether the
662                                                 // relative sign changed
663                                                 lst subs_lst(dummy[idx1].op(0), dummy[idx2].op(0)), repl_lst(dummy[idx2].op(0), dummy[idx1].op(0));
664                                                 ex swapped1 = it1->subs(subs_lst, repl_lst);
665                                                 ex swapped2 = it2->subs(subs_lst, repl_lst);
666                                                 if (it1->is_equal(swapped1) && it2->is_equal(-swapped2)
667                                                  || it1->is_equal(-swapped1) && it2->is_equal(swapped2)) {
668                                                         free_indices.clear();
669                                                         return _ex0();
670                                                 }
671                                         }
672                                 }
673                         }
674
675                         // Try to contract the first one with the second one
676                         contracted = it1->op(0).bp->contract_with(it1, it2, v);
677                         if (!contracted) {
678
679                                 // That didn't work; maybe the second object knows how to
680                                 // contract itself with the first one
681                                 contracted = it2->op(0).bp->contract_with(it2, it1, v);
682                         }
683                         if (contracted) {
684 contraction_done:
685                                 if (first_noncommutative || second_noncommutative
686                                  || is_ex_exactly_of_type(*it1, add) || is_ex_exactly_of_type(*it2, add)
687                                  || is_ex_exactly_of_type(*it1, mul) || is_ex_exactly_of_type(*it2, mul)
688                                  || is_ex_exactly_of_type(*it1, ncmul) || is_ex_exactly_of_type(*it2, ncmul)) {
689
690                                         // One of the factors became a sum or product:
691                                         // re-expand expression and run again
692                                         // Non-commutative products are always re-expanded to give
693                                         // simplify_ncmul() the chance to re-order and canonicalize
694                                         // the product
695                                         ex r = (non_commutative ? ex(ncmul(v, true)) : ex(mul(v)));
696                                         return simplify_indexed(r, free_indices, dummy_indices, sp);
697                                 }
698
699                                 // Both objects may have new indices now or they might
700                                 // even not be indexed objects any more, so we have to
701                                 // start over
702                                 something_changed = true;
703                                 goto try_again;
704                         }
705                 }
706         }
707
708         // Find free indices (concatenate them all and call find_free_and_dummy())
709         // and all dummy indices that appear
710         exvector un, individual_dummy_indices;
711         it1 = v.begin(); itend = v.end();
712         while (it1 != itend) {
713                 exvector free_indices_of_factor;
714                 if (is_ex_of_type(*it1, indexed)) {
715                         exvector dummy_indices_of_factor;
716                         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);
717                         individual_dummy_indices.insert(individual_dummy_indices.end(), dummy_indices_of_factor.begin(), dummy_indices_of_factor.end());
718                 } else
719                         free_indices_of_factor = it1->get_free_indices();
720                 un.insert(un.end(), free_indices_of_factor.begin(), free_indices_of_factor.end());
721                 it1++;
722         }
723         exvector local_dummy_indices;
724         find_free_and_dummy(un, free_indices, local_dummy_indices);
725         local_dummy_indices.insert(local_dummy_indices.end(), individual_dummy_indices.begin(), individual_dummy_indices.end());
726
727         ex r;
728         if (something_changed)
729                 r = non_commutative ? ex(ncmul(v, true)) : ex(mul(v));
730         else
731                 r = e;
732
733         // Dummy index renaming
734         r = rename_dummy_indices(r, dummy_indices, local_dummy_indices);
735
736         // Product of indexed object with a scalar?
737         if (is_ex_exactly_of_type(r, mul) && r.nops() == 2
738          && is_ex_exactly_of_type(r.op(1), numeric) && is_ex_of_type(r.op(0), indexed))
739                 return r.op(0).op(0).bp->scalar_mul_indexed(r.op(0), ex_to<numeric>(r.op(1)));
740         else
741                 return r;
742 }
743
744 /** Simplify indexed expression, return list of free indices. */
745 ex simplify_indexed(const ex & e, exvector & free_indices, exvector & dummy_indices, const scalar_products & sp)
746 {
747         // Expand the expression
748         ex e_expanded = e.expand();
749
750         // Simplification of single indexed object: just find the free indices
751         // and perform dummy index renaming
752         if (is_ex_of_type(e_expanded, indexed)) {
753                 const indexed &i = ex_to<indexed>(e_expanded);
754                 exvector local_dummy_indices;
755                 find_free_and_dummy(i.seq.begin() + 1, i.seq.end(), free_indices, local_dummy_indices);
756                 return rename_dummy_indices(e_expanded, dummy_indices, local_dummy_indices);
757         }
758
759         // Simplification of sum = sum of simplifications, check consistency of
760         // free indices in each term
761         if (is_ex_exactly_of_type(e_expanded, add)) {
762                 bool first = true;
763                 ex sum = _ex0();
764                 free_indices.clear();
765
766                 for (unsigned i=0; i<e_expanded.nops(); i++) {
767                         exvector free_indices_of_term;
768                         ex term = simplify_indexed(e_expanded.op(i), free_indices_of_term, dummy_indices, sp);
769                         if (!term.is_zero()) {
770                                 if (first) {
771                                         free_indices = free_indices_of_term;
772                                         sum = term;
773                                         first = false;
774                                 } else {
775                                         if (!indices_consistent(free_indices, free_indices_of_term))
776                                                 throw (std::runtime_error("simplify_indexed: inconsistent indices in sum"));
777                                         if (is_ex_of_type(sum, indexed) && is_ex_of_type(term, indexed))
778                                                 sum = sum.op(0).bp->add_indexed(sum, term);
779                                         else
780                                                 sum += term;
781                                 }
782                         }
783                 }
784
785                 return sum;
786         }
787
788         // Simplification of products
789         if (is_ex_exactly_of_type(e_expanded, mul)
790          || is_ex_exactly_of_type(e_expanded, ncmul)
791          || (is_ex_exactly_of_type(e_expanded, power) && is_ex_of_type(e_expanded.op(0), indexed) && e_expanded.op(1).is_equal(_ex2())))
792                 return simplify_indexed_product(e_expanded, free_indices, dummy_indices, sp);
793
794         // Cannot do anything
795         free_indices.clear();
796         return e_expanded;
797 }
798
799 /** Simplify/canonicalize expression containing indexed objects. This
800  *  performs contraction of dummy indices where possible and checks whether
801  *  the free indices in sums are consistent.
802  *
803  *  @return simplified expression */
804 ex ex::simplify_indexed(void) const
805 {
806         exvector free_indices, dummy_indices;
807         scalar_products sp;
808         return GiNaC::simplify_indexed(*this, free_indices, dummy_indices, sp);
809 }
810
811 /** Simplify/canonicalize expression containing indexed objects. This
812  *  performs contraction of dummy indices where possible, checks whether
813  *  the free indices in sums are consistent, and automatically replaces
814  *  scalar products by known values if desired.
815  *
816  *  @param sp Scalar products to be replaced automatically
817  *  @return simplified expression */
818 ex ex::simplify_indexed(const scalar_products & sp) const
819 {
820         exvector free_indices, dummy_indices;
821         return GiNaC::simplify_indexed(*this, free_indices, dummy_indices, sp);
822 }
823
824 /** Symmetrize expression over its free indices. */
825 ex ex::symmetrize(void) const
826 {
827         return GiNaC::symmetrize(*this, get_free_indices());
828 }
829
830 /** Antisymmetrize expression over its free indices. */
831 ex ex::antisymmetrize(void) const
832 {
833         return GiNaC::antisymmetrize(*this, get_free_indices());
834 }
835
836 /** Symmetrize expression by cyclic permutation over its free indices. */
837 ex ex::symmetrize_cyclic(void) const
838 {
839         return GiNaC::symmetrize_cyclic(*this, get_free_indices());
840 }
841
842 //////////
843 // helper classes
844 //////////
845
846 void scalar_products::add(const ex & v1, const ex & v2, const ex & sp)
847 {
848         spm[make_key(v1, v2)] = sp;
849 }
850
851 void scalar_products::add_vectors(const lst & l)
852 {
853         // Add all possible pairs of products
854         unsigned num = l.nops();
855         for (unsigned i=0; i<num; i++) {
856                 ex a = l.op(i);
857                 for (unsigned j=0; j<num; j++) {
858                         ex b = l.op(j);
859                         add(a, b, a*b);
860                 }
861         }
862 }
863
864 void scalar_products::clear(void)
865 {
866         spm.clear();
867 }
868
869 /** Check whether scalar product pair is defined. */
870 bool scalar_products::is_defined(const ex & v1, const ex & v2) const
871 {
872         return spm.find(make_key(v1, v2)) != spm.end();
873 }
874
875 /** Return value of defined scalar product pair. */
876 ex scalar_products::evaluate(const ex & v1, const ex & v2) const
877 {
878         return spm.find(make_key(v1, v2))->second;
879 }
880
881 void scalar_products::debugprint(void) const
882 {
883         std::cerr << "map size=" << spm.size() << std::endl;
884         for (spmap::const_iterator cit=spm.begin(); cit!=spm.end(); ++cit) {
885                 const spmapkey & k = cit->first;
886                 std::cerr << "item key=(" << k.first << "," << k.second;
887                 std::cerr << "), value=" << cit->second << std::endl;
888         }
889 }
890
891 /** Make key from object pair. */
892 spmapkey scalar_products::make_key(const ex & v1, const ex & v2)
893 {
894         // If indexed, extract base objects
895         ex s1 = is_ex_of_type(v1, indexed) ? v1.op(0) : v1;
896         ex s2 = is_ex_of_type(v2, indexed) ? v2.op(0) : v2;
897
898         // Enforce canonical order in pair
899         if (s1.compare(s2) > 0)
900                 return spmapkey(s2, s1);
901         else
902                 return spmapkey(s1, s2);
903 }
904
905 } // namespace GiNaC