* Happy New Year(s)!
[ginac.git] / ginac / clifford.cpp
1 /** @file clifford.cpp
2  *
3  *  Implementation of GiNaC's clifford algebra (Dirac gamma) objects. */
4
5 /*
6  *  GiNaC Copyright (C) 1999-2007 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
21  */
22
23 #include <stdexcept>
24
25 #include "clifford.h"
26
27 #include "ex.h"
28 #include "idx.h"
29 #include "ncmul.h"
30 #include "symbol.h"
31 #include "numeric.h" // for I
32 #include "symmetry.h"
33 #include "lst.h"
34 #include "relational.h"
35 #include "operators.h"
36 #include "add.h"
37 #include "mul.h"
38 #include "power.h"
39 #include "matrix.h"
40 #include "archive.h"
41 #include "utils.h"
42
43 namespace GiNaC {
44
45 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(clifford, indexed,
46   print_func<print_dflt>(&clifford::do_print_dflt).
47   print_func<print_latex>(&clifford::do_print_latex))
48
49 const tinfo_static_t clifford::return_type_tinfo_static[256] = {{}};
50
51 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(diracone, tensor,
52   print_func<print_dflt>(&diracone::do_print).
53   print_func<print_latex>(&diracone::do_print_latex))
54
55 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(cliffordunit, tensor,
56   print_func<print_dflt>(&cliffordunit::do_print).
57   print_func<print_latex>(&cliffordunit::do_print_latex))
58
59 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(diracgamma, cliffordunit,
60   print_func<print_dflt>(&diracgamma::do_print).
61   print_func<print_latex>(&diracgamma::do_print_latex))
62
63 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(diracgamma5, tensor,
64   print_func<print_dflt>(&diracgamma5::do_print).
65   print_func<print_latex>(&diracgamma5::do_print_latex))
66
67 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(diracgammaL, tensor,
68   print_func<print_context>(&diracgammaL::do_print).
69   print_func<print_latex>(&diracgammaL::do_print_latex))
70
71 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(diracgammaR, tensor,
72   print_func<print_context>(&diracgammaR::do_print).
73   print_func<print_latex>(&diracgammaR::do_print_latex))
74
75 //////////
76 // default constructors
77 //////////
78
79 clifford::clifford() : representation_label(0), metric(0), commutator_sign(-1)
80 {
81         tinfo_key = &clifford::tinfo_static;
82 }
83
84 DEFAULT_CTOR(diracone)
85 DEFAULT_CTOR(cliffordunit)
86 DEFAULT_CTOR(diracgamma)
87 DEFAULT_CTOR(diracgamma5)
88 DEFAULT_CTOR(diracgammaL)
89 DEFAULT_CTOR(diracgammaR)
90
91 //////////
92 // other constructors
93 //////////
94
95 /** Construct object without any indices. This constructor is for internal
96  *  use only. Use the dirac_ONE() function instead.
97  *  @see dirac_ONE */
98 clifford::clifford(const ex & b, unsigned char rl) : inherited(b), representation_label(rl), metric(0), commutator_sign(-1)
99 {
100         tinfo_key = &clifford::tinfo_static;
101 }
102
103 /** Construct object with one Lorentz index. This constructor is for internal
104  *  use only. Use the clifford_unit() or dirac_gamma() functions instead.
105  *  @see clifford_unit
106  *  @see dirac_gamma */
107 clifford::clifford(const ex & b, const ex & mu, const ex & metr, unsigned char rl, int comm_sign) : inherited(b, mu), representation_label(rl), metric(metr), commutator_sign(comm_sign)
108 {
109         GINAC_ASSERT(is_a<varidx>(mu));
110         tinfo_key = &clifford::tinfo_static;
111 }
112
113 clifford::clifford(unsigned char rl, const ex & metr, int comm_sign, const exvector & v, bool discardable) : inherited(not_symmetric(), v, discardable), representation_label(rl), metric(metr), commutator_sign(comm_sign)
114 {
115         tinfo_key = &clifford::tinfo_static;
116 }
117
118 clifford::clifford(unsigned char rl, const ex & metr, int comm_sign, std::auto_ptr<exvector> vp) : inherited(not_symmetric(), vp), representation_label(rl), metric(metr), commutator_sign(comm_sign)
119 {
120         tinfo_key = &clifford::tinfo_static;
121 }
122
123 //////////
124 // archiving
125 //////////
126
127 clifford::clifford(const archive_node & n, lst & sym_lst) : inherited(n, sym_lst)
128 {
129         unsigned rl;
130         n.find_unsigned("label", rl);
131         representation_label = rl;
132         n.find_ex("metric", metric, sym_lst);
133         n.find_unsigned("commutator_sign+1", rl);
134         commutator_sign = rl - 1;
135 }
136
137 void clifford::archive(archive_node & n) const
138 {
139         inherited::archive(n);
140         n.add_unsigned("label", representation_label);
141         n.add_ex("metric", metric);
142         n.add_unsigned("commutator_sign+1", commutator_sign+1);
143 }
144
145 DEFAULT_UNARCHIVE(clifford)
146 DEFAULT_ARCHIVING(diracone)
147 DEFAULT_ARCHIVING(cliffordunit)
148 DEFAULT_ARCHIVING(diracgamma)
149 DEFAULT_ARCHIVING(diracgamma5)
150 DEFAULT_ARCHIVING(diracgammaL)
151 DEFAULT_ARCHIVING(diracgammaR)
152
153
154 ex clifford::get_metric(const ex & i, const ex & j, bool symmetrised) const
155 {
156         if (is_a<indexed>(metric)) {
157                 if (symmetrised && !(ex_to<symmetry>(ex_to<indexed>(metric).get_symmetry()).has_symmetry())) {
158                         if (is_a<matrix>(metric.op(0))) {
159                                 return indexed((ex_to<matrix>(metric.op(0)).add(ex_to<matrix>(metric.op(0)).transpose())).mul(numeric(1, 2)),
160                                                symmetric2(), i, j);
161                         } else {
162                                 return simplify_indexed(indexed(metric.op(0)*_ex1_2, i, j) + indexed(metric.op(0)*_ex1_2, j, i));
163                         }
164                 } else {
165                         return metric.subs(lst(metric.op(1) == i, metric.op(2) == j), subs_options::no_pattern);
166                 }
167         } else {
168                 exvector indices = metric.get_free_indices();
169                 if (symmetrised)
170                         return _ex1_2*simplify_indexed(metric.subs(lst(indices[0] == i, indices[1] == j), subs_options::no_pattern)
171                                                                         + metric.subs(lst(indices[0] == j, indices[1] == i), subs_options::no_pattern));
172                 else
173                         return metric.subs(lst(indices[0] == i, indices[1] == j), subs_options::no_pattern);
174         }
175 }
176
177 bool clifford::same_metric(const ex & other) const
178 {
179         ex metr;
180         if (is_a<clifford>(other)) 
181                 metr = ex_to<clifford>(other).get_metric();
182         else 
183                 metr = other;
184
185         if (is_a<indexed>(metr))
186                 return metr.op(0).is_equal(get_metric().op(0));
187         else {
188                 exvector indices = metr.get_free_indices();
189                 return  (indices.size() == 2) 
190                         && simplify_indexed(get_metric(indices[0], indices[1])-metr).is_zero();
191         }
192 }
193
194 //////////
195 // functions overriding virtual functions from base classes
196 //////////
197
198 ex clifford::op(size_t i) const
199 {
200         GINAC_ASSERT(i<nops());
201         if (nops()-i == 1)
202                 return representation_label;
203         else 
204                 return inherited::op(i);
205 }
206
207 ex & clifford::let_op(size_t i)
208 {
209         GINAC_ASSERT(i<nops());
210
211         static ex rl = numeric(representation_label);
212         ensure_if_modifiable();
213         if (nops()-i == 1)
214                 return rl;
215         else 
216                 return inherited::let_op(i);
217 }
218
219 ex clifford::subs(const exmap & m, unsigned options) const
220 {
221         ex subsed = inherited::subs(m, options);
222         if(is_a<clifford>(subsed)) {
223                 ex prevmetric = ex_to<clifford>(subsed).metric;
224                 ex newmetric = prevmetric.subs(m, options);
225                 if(!are_ex_trivially_equal(prevmetric, newmetric)) {
226                         clifford c = ex_to<clifford>(subsed);
227                         c.metric = newmetric;
228                         subsed = c;
229                 }
230         }
231         return subsed;
232 }
233
234 int clifford::compare_same_type(const basic & other) const
235 {
236         GINAC_ASSERT(is_a<clifford>(other));
237         const clifford &o = static_cast<const clifford &>(other);
238
239         if (representation_label != o.representation_label) {
240                 // different representation label
241                 return representation_label < o.representation_label ? -1 : 1;
242         }
243
244         return inherited::compare_same_type(other);
245 }
246
247 bool clifford::match_same_type(const basic & other) const
248 {
249         GINAC_ASSERT(is_a<clifford>(other));
250         const clifford &o = static_cast<const clifford &>(other);
251
252         return ((representation_label == o.representation_label) && (commutator_sign == o.get_commutator_sign()) && same_metric(o));
253 }
254
255 static bool is_dirac_slash(const ex & seq0)
256 {
257         return !is_a<diracgamma5>(seq0) && !is_a<diracgammaL>(seq0) &&
258                !is_a<diracgammaR>(seq0) && !is_a<cliffordunit>(seq0) &&
259                !is_a<diracone>(seq0);
260 }
261
262 void clifford::do_print_dflt(const print_dflt & c, unsigned level) const
263 {
264         // dirac_slash() object is printed differently
265         if (is_dirac_slash(seq[0])) {
266                 seq[0].print(c, precedence());
267                 c.s << "\\";
268         } else
269                 this->print_dispatch<inherited>(c, level);
270 }
271
272 void clifford::do_print_latex(const print_latex & c, unsigned level) const
273 {
274         // dirac_slash() object is printed differently
275         if (is_dirac_slash(seq[0])) {
276                 c.s << "{";
277                 seq[0].print(c, precedence());
278                 c.s << "\\hspace{-1.0ex}/}";
279         } else {
280                 c.s << "\\clifford[" << int(representation_label) << "]";
281                 this->print_dispatch<inherited>(c, level);
282         }
283 }
284
285 DEFAULT_COMPARE(diracone)
286 DEFAULT_COMPARE(cliffordunit)
287 DEFAULT_COMPARE(diracgamma)
288 DEFAULT_COMPARE(diracgamma5)
289 DEFAULT_COMPARE(diracgammaL)
290 DEFAULT_COMPARE(diracgammaR)
291
292 DEFAULT_PRINT_LATEX(diracone, "ONE", "\\mathbf{1}")
293 DEFAULT_PRINT_LATEX(cliffordunit, "e", "e")
294 DEFAULT_PRINT_LATEX(diracgamma, "gamma", "\\gamma")
295 DEFAULT_PRINT_LATEX(diracgamma5, "gamma5", "{\\gamma^5}")
296 DEFAULT_PRINT_LATEX(diracgammaL, "gammaL", "{\\gamma_L}")
297 DEFAULT_PRINT_LATEX(diracgammaR, "gammaR", "{\\gamma_R}")
298
299 /** This function decomposes gamma~mu -> (1, mu) and a\ -> (a.ix, ix) */
300 static void base_and_index(const ex & c, ex & b, ex & i)
301 {
302         GINAC_ASSERT(is_a<clifford>(c));
303         GINAC_ASSERT(c.nops() == 2+1);
304
305         if (is_a<cliffordunit>(c.op(0))) { // proper dirac gamma object or clifford unit
306                 i = c.op(1);
307                 b = _ex1;
308         } else if (is_a<diracgamma5>(c.op(0)) || is_a<diracgammaL>(c.op(0)) || is_a<diracgammaR>(c.op(0))) { // gamma5/L/R
309                 i = _ex0;
310                 b = _ex1;
311         } else { // slash object, generate new dummy index
312                 varidx ix((new symbol)->setflag(status_flags::dynallocated), ex_to<idx>(c.op(1)).get_dim());
313                 b = indexed(c.op(0), ix.toggle_variance());
314                 i = ix;
315         }
316 }
317
318 /** Predicate for finding non-clifford objects. */
319 struct is_not_a_clifford : public std::unary_function<ex, bool> {
320         bool operator()(const ex & e)
321         {
322                 return !is_a<clifford>(e);
323         }
324 };
325
326 /** Contraction of a gamma matrix with something else. */
327 bool diracgamma::contract_with(exvector::iterator self, exvector::iterator other, exvector & v) const
328 {
329         GINAC_ASSERT(is_a<clifford>(*self));
330         GINAC_ASSERT(is_a<indexed>(*other));
331         GINAC_ASSERT(is_a<diracgamma>(self->op(0)));
332         unsigned char rl = ex_to<clifford>(*self).get_representation_label();
333
334         ex dim = ex_to<idx>(self->op(1)).get_dim();
335         if (other->nops() > 1)
336                 dim = minimal_dim(dim, ex_to<idx>(other->op(1)).get_dim());
337
338         if (is_a<clifford>(*other)) {
339
340                 // Contraction only makes sense if the represenation labels are equal
341                 if (ex_to<clifford>(*other).get_representation_label() != rl)
342                         return false;
343
344                 size_t num = other - self;
345
346                 // gamma~mu gamma.mu = dim ONE
347                 if (num == 1) {
348                         *self = dim;
349                         *other = dirac_ONE(rl);
350                         return true;
351
352                 // gamma~mu gamma~alpha gamma.mu = (2-dim) gamma~alpha
353                 } else if (num == 2
354                         && is_a<clifford>(self[1])) {
355                         *self = 2 - dim;
356                         *other = _ex1;
357                         return true;
358
359                 // gamma~mu gamma~alpha gamma~beta gamma.mu = 4 g~alpha~beta + (dim-4) gamam~alpha gamma~beta
360                 } else if (num == 3
361                         && is_a<clifford>(self[1])
362                         && is_a<clifford>(self[2])) {
363                         ex b1, i1, b2, i2;
364                         base_and_index(self[1], b1, i1);
365                         base_and_index(self[2], b2, i2);
366                         *self = 4 * lorentz_g(i1, i2) * b1 * b2 * dirac_ONE(rl) + (dim - 4) * self[1] * self[2];
367                         self[1] = _ex1;
368                         self[2] = _ex1;
369                         *other = _ex1;
370                         return true;
371
372                 // gamma~mu gamma~alpha gamma~beta gamma~delta gamma.mu = -2 gamma~delta gamma~beta gamma~alpha - (dim-4) gamam~alpha gamma~beta gamma~delta
373                 } else if (num == 4
374                         && is_a<clifford>(self[1])
375                         && is_a<clifford>(self[2])
376                         && is_a<clifford>(self[3])) {
377                         *self = -2 * self[3] * self[2] * self[1] - (dim - 4) * self[1] * self[2] * self[3];
378                         self[1] = _ex1;
379                         self[2] = _ex1;
380                         self[3] = _ex1;
381                         *other = _ex1;
382                         return true;
383
384                 // gamma~mu Sodd gamma.mu = -2 Sodd_R
385                 // (Chisholm identity in 4 dimensions)
386                 } else if (!((other - self) & 1) && dim.is_equal(4)) {
387                         if (std::find_if(self + 1, other, is_not_a_clifford()) != other)
388                                 return false;
389
390                         *self = ncmul(exvector(std::reverse_iterator<exvector::const_iterator>(other), std::reverse_iterator<exvector::const_iterator>(self + 1)), true);
391                         std::fill(self + 1, other, _ex1);
392                         *other = _ex_2;
393                         return true;
394
395                 // gamma~mu Sodd gamma~alpha gamma.mu = 2 gamma~alpha Sodd + 2 Sodd_R gamma~alpha
396                 // (commutate contracted indices towards each other, then use
397                 // Chisholm identity in 4 dimensions)
398                 } else if (((other - self) & 1) && dim.is_equal(4)) {
399                         if (std::find_if(self + 1, other, is_not_a_clifford()) != other)
400                                 return false;
401
402                         exvector::iterator next_to_last = other - 1;
403                         ex S = ncmul(exvector(self + 1, next_to_last), true);
404                         ex SR = ncmul(exvector(std::reverse_iterator<exvector::const_iterator>(next_to_last), std::reverse_iterator<exvector::const_iterator>(self + 1)), true);
405
406                         *self = (*next_to_last) * S + SR * (*next_to_last);
407                         std::fill(self + 1, other, _ex1);
408                         *other = _ex2;
409                         return true;
410
411                 // gamma~mu S gamma~alpha gamma.mu = 2 gamma~alpha S - gamma~mu S gamma.mu gamma~alpha
412                 // (commutate contracted indices towards each other, simplify_indexed()
413                 // will re-expand and re-run the simplification)
414                 } else {
415                         if (std::find_if(self + 1, other, is_not_a_clifford()) != other)
416                                 return false;
417
418                         exvector::iterator next_to_last = other - 1;
419                         ex S = ncmul(exvector(self + 1, next_to_last), true);
420
421                         *self = 2 * (*next_to_last) * S - (*self) * S * (*other) * (*next_to_last);
422                         std::fill(self + 1, other + 1, _ex1);
423                         return true;
424                 }
425
426         } else if (is_a<symbol>(other->op(0)) && other->nops() == 2) {
427
428                 // x.mu gamma~mu -> x-slash
429                 *self = dirac_slash(other->op(0), dim, rl);
430                 *other = _ex1;
431                 return true;
432         }
433
434         return false;
435 }
436
437 /** Contraction of a Clifford unit with something else. */
438 bool cliffordunit::contract_with(exvector::iterator self, exvector::iterator other, exvector & v) const
439 {
440         GINAC_ASSERT(is_a<clifford>(*self));
441         GINAC_ASSERT(is_a<indexed>(*other));
442         GINAC_ASSERT(is_a<cliffordunit>(self->op(0)));
443         clifford unit = ex_to<clifford>(*self);
444         unsigned char rl = unit.get_representation_label();
445
446         if (is_a<clifford>(*other)) {
447                 // Contraction only makes sense if the represenation labels are equal
448                 // and the metrics are the same
449                 if ((ex_to<clifford>(*other).get_representation_label() != rl) 
450                     && unit.same_metric(*other))
451                         return false;
452
453                 exvector::iterator before_other = other - 1;
454                 ex mu = self->op(1);
455                 ex mu_toggle = other->op(1);
456                 ex alpha = before_other->op(1);
457
458                 // e~mu e.mu = Tr ONE
459                 if (other - self == 1) {
460                         *self = unit.get_metric(mu, mu_toggle, true);
461                         *other = dirac_ONE(rl);
462                         return true;
463
464                 } else if (other - self == 2) {
465                         if (is_a<clifford>(*before_other) && ex_to<clifford>(*before_other).get_representation_label() == rl) {
466                                 // e~mu e~alpha e.mu = 2*e~mu B(alpha, mu.toggle_variance())-Tr(B) e~alpha
467                                 *self = 2 * (*self) * unit.get_metric(alpha, mu_toggle, true) - unit.get_metric(mu, mu_toggle, true) * (*before_other);
468                                 *before_other = _ex1;
469                                 *other = _ex1;
470                                 return true;
471
472                         } else {
473                                 // e~mu S e.mu = Tr S ONE
474                                 *self = unit.get_metric(mu, mu_toggle, true);
475                                 *other = dirac_ONE(rl);
476                                 return true;
477                         }
478                 } else {
479                 // e~mu S e~alpha e.mu = 2 e~mu S B(alpha, mu.toggle_variance()) - e~mu S e.mu e~alpha
480                 // (commutate contracted indices towards each other, simplify_indexed()
481                 // will re-expand and re-run the simplification)
482                         if (std::find_if(self + 1, other, is_not_a_clifford()) != other) {
483                                 return false;
484                         }
485                         
486                         ex S = ncmul(exvector(self + 1, before_other), true);
487
488                         if (is_a<clifford>(*before_other) && ex_to<clifford>(*before_other).get_representation_label() == rl) {
489                                 *self = 2 * (*self) * S * unit.get_metric(alpha, mu_toggle, true) - (*self) * S * (*other) * (*before_other);
490                         } else {
491                                 // simply commutes
492                                 *self = (*self) * S * (*other) * (*before_other);
493                         }
494                                 
495                         std::fill(self + 1, other + 1, _ex1);
496                         return true;
497                 }
498         }
499         return false;
500 }
501
502 /** Perform automatic simplification on noncommutative product of clifford
503  *  objects. This removes superfluous ONEs, permutes gamma5/L/R's to the front
504  *  and removes squares of gamma objects. */
505 ex clifford::eval_ncmul(const exvector & v) const
506 {
507         exvector s;
508         s.reserve(v.size());
509
510         // Remove superfluous ONEs
511         exvector::const_iterator cit = v.begin(), citend = v.end();
512         while (cit != citend) {
513                 if (!is_a<clifford>(*cit) || !is_a<diracone>(cit->op(0)))
514                         s.push_back(*cit);
515                 cit++;
516         }
517
518         bool something_changed = false;
519         int sign = 1;
520
521         // Anticommutate gamma5/L/R's to the front
522         if (s.size() >= 2) {
523                 exvector::iterator first = s.begin(), next_to_last = s.end() - 2;
524                 while (true) {
525                         exvector::iterator it = next_to_last;
526                         while (true) {
527                                 exvector::iterator it2 = it + 1;
528                                 if (is_a<clifford>(*it) && is_a<clifford>(*it2)) {
529                                         ex e1 = it->op(0), e2 = it2->op(0);
530
531                                         if (is_a<diracgamma5>(e2)) {
532
533                                                 if (is_a<diracgammaL>(e1) || is_a<diracgammaR>(e1)) {
534
535                                                         // gammaL/R gamma5 -> gamma5 gammaL/R
536                                                         it->swap(*it2);
537                                                         something_changed = true;
538
539                                                 } else if (!is_a<diracgamma5>(e1)) {
540
541                                                         // gamma5 gamma5 -> gamma5 gamma5 (do nothing)
542                                                         // x gamma5 -> -gamma5 x
543                                                         it->swap(*it2);
544                                                         sign = -sign;
545                                                         something_changed = true;
546                                                 }
547
548                                         } else if (is_a<diracgammaL>(e2)) {
549
550                                                 if (is_a<diracgammaR>(e1)) {
551
552                                                         // gammaR gammaL -> 0
553                                                         return _ex0;
554
555                                                 } else if (!is_a<diracgammaL>(e1) && !is_a<diracgamma5>(e1)) {
556
557                                                         // gammaL gammaL -> gammaL gammaL (do nothing)
558                                                         // gamma5 gammaL -> gamma5 gammaL (do nothing)
559                                                         // x gammaL -> gammaR x
560                                                         it->swap(*it2);
561                                                         *it = clifford(diracgammaR(), ex_to<clifford>(*it).get_representation_label());
562                                                         something_changed = true;
563                                                 }
564
565                                         } else if (is_a<diracgammaR>(e2)) {
566
567                                                 if (is_a<diracgammaL>(e1)) {
568
569                                                         // gammaL gammaR -> 0
570                                                         return _ex0;
571
572                                                 } else if (!is_a<diracgammaR>(e1) && !is_a<diracgamma5>(e1)) {
573
574                                                         // gammaR gammaR -> gammaR gammaR (do nothing)
575                                                         // gamma5 gammaR -> gamma5 gammaR (do nothing)
576                                                         // x gammaR -> gammaL x
577                                                         it->swap(*it2);
578                                                         *it = clifford(diracgammaL(), ex_to<clifford>(*it).get_representation_label());
579                                                         something_changed = true;
580                                                 }
581                                         }
582                                 }
583                                 if (it == first)
584                                         break;
585                                 --it;
586                         }
587                         if (next_to_last == first)
588                                 break;
589                         --next_to_last;
590                 }
591         }
592
593         // Remove equal adjacent gammas
594         if (s.size() >= 2) {
595                 exvector::iterator it, itend = s.end() - 1;
596                 for (it = s.begin(); it != itend; ++it) {
597                         ex & a = it[0];
598                         ex & b = it[1];
599                         if (!is_a<clifford>(a) || !is_a<clifford>(b))
600                                 continue;
601
602                         const ex & ag = a.op(0);
603                         const ex & bg = b.op(0);
604                         bool a_is_cliffordunit = is_a<cliffordunit>(ag);
605                         bool b_is_cliffordunit =  is_a<cliffordunit>(bg);
606
607                         if (a_is_cliffordunit && b_is_cliffordunit && ex_to<clifford>(a).same_metric(b)
608                                 && (ex_to<clifford>(a).get_commutator_sign() == -1)) {
609                                 // This is done only for Clifford algebras 
610                                 
611                                 const ex & ia = a.op(1);
612                                 const ex & ib = b.op(1);
613                                 if (ia.is_equal(ib)) { // gamma~alpha gamma~alpha -> g~alpha~alpha
614                                         a = ex_to<clifford>(a).get_metric(ia, ib, true);
615                                         b = dirac_ONE(representation_label);
616                                         something_changed = true;
617                                 }
618
619                         } else if ((is_a<diracgamma5>(ag) && is_a<diracgamma5>(bg))) {
620
621                                 // Remove squares of gamma5
622                                 a = dirac_ONE(representation_label);
623                                 b = dirac_ONE(representation_label);
624                                 something_changed = true;
625
626                         } else if ((is_a<diracgammaL>(ag) && is_a<diracgammaL>(bg))
627                                 || (is_a<diracgammaR>(ag) && is_a<diracgammaR>(bg))) {
628
629                                 // Remove squares of gammaL/R
630                                 b = dirac_ONE(representation_label);
631                                 something_changed = true;
632
633                         } else if (is_a<diracgammaL>(ag) && is_a<diracgammaR>(bg)) {
634
635                                 // gammaL and gammaR are orthogonal
636                                 return _ex0;
637
638                         } else if (is_a<diracgamma5>(ag) && is_a<diracgammaL>(bg)) {
639
640                                 // gamma5 gammaL -> -gammaL
641                                 a = dirac_ONE(representation_label);
642                                 sign = -sign;
643                                 something_changed = true;
644
645                         } else if (is_a<diracgamma5>(ag) && is_a<diracgammaR>(bg)) {
646
647                                 // gamma5 gammaR -> gammaR
648                                 a = dirac_ONE(representation_label);
649                                 something_changed = true;
650
651                         } else if (!a_is_cliffordunit && !b_is_cliffordunit && ag.is_equal(bg)) {
652
653                                 // a\ a\ -> a^2
654                                 varidx ix((new symbol)->setflag(status_flags::dynallocated), ex_to<idx>(a.op(1)).minimal_dim(ex_to<idx>(b.op(1))));
655                                 
656                                 a = indexed(ag, ix) * indexed(ag, ix.toggle_variance());
657                                 b = dirac_ONE(representation_label);
658                                 something_changed = true;
659                         }
660                 }
661         }
662
663         if (s.empty())
664                 return dirac_ONE(representation_label) * sign;
665         if (something_changed)
666                 return reeval_ncmul(s) * sign;
667         else
668                 return hold_ncmul(s) * sign;
669 }
670
671 ex clifford::thiscontainer(const exvector & v) const
672 {
673         return clifford(representation_label, metric, commutator_sign, v);
674 }
675
676 ex clifford::thiscontainer(std::auto_ptr<exvector> vp) const
677 {
678         return clifford(representation_label, metric, commutator_sign, vp);
679 }
680
681 ex diracgamma5::conjugate() const
682 {       
683         return _ex_1 * (*this);
684 }
685
686 ex diracgammaL::conjugate() const
687 {
688         return (new diracgammaR)->setflag(status_flags::dynallocated);
689 }
690
691 ex diracgammaR::conjugate() const
692 {
693         return (new diracgammaL)->setflag(status_flags::dynallocated);
694 }
695
696 //////////
697 // global functions
698 //////////
699
700 ex dirac_ONE(unsigned char rl)
701 {
702         static ex ONE = (new diracone)->setflag(status_flags::dynallocated);
703         return clifford(ONE, rl);
704 }
705
706 ex clifford_unit(const ex & mu, const ex & metr, unsigned char rl)
707 {
708         static ex unit = (new cliffordunit)->setflag(status_flags::dynallocated);
709
710         if (!is_a<idx>(mu))
711                 throw(std::invalid_argument("clifford_unit(): index of Clifford unit must be of type idx or varidx"));
712
713         exvector indices = metr.get_free_indices();
714
715         if (indices.size() == 2) {
716                 return clifford(unit, mu, metr, rl);
717         } else if (is_a<matrix>(metr)) {
718                 matrix M = ex_to<matrix>(metr);
719                 unsigned n = M.rows();
720                 bool symmetric = true;
721
722                 static idx xi((new symbol)->setflag(status_flags::dynallocated), n),
723                         chi((new symbol)->setflag(status_flags::dynallocated), n);
724                 if ((n ==  M.cols()) && (n == ex_to<idx>(mu).get_dim())) {
725                         for (unsigned i = 0; i < n; i++) {
726                                 for (unsigned j = i+1; j < n; j++) {
727                                         if (M(i, j) != M(j, i)) {
728                                                 symmetric = false;
729                                         }
730                                 }
731                         }
732                         return clifford(unit, mu, indexed(metr, symmetric?symmetric2():not_symmetric(), xi, chi), rl);
733                 } else {
734                         throw(std::invalid_argument("clifford_unit(): metric for Clifford unit must be a square matrix with the same dimensions as index"));
735                 }
736         } else if (indices.size() == 0) { // a tensor or other expression without indices
737                 static varidx xi((new symbol)->setflag(status_flags::dynallocated), ex_to<idx>(mu).get_dim()),
738                         chi((new symbol)->setflag(status_flags::dynallocated), ex_to<idx>(mu).get_dim());
739                 return clifford(unit, mu, indexed(metr, xi, chi), rl);
740         }  else 
741                 throw(std::invalid_argument("clifford_unit(): metric for Clifford unit must be of type tensor, matrix or an expression with two free indices"));
742 }
743
744 ex dirac_gamma(const ex & mu, unsigned char rl)
745 {
746         static ex gamma = (new diracgamma)->setflag(status_flags::dynallocated);
747
748         if (!is_a<varidx>(mu))
749                 throw(std::invalid_argument("dirac_gamma(): index of Dirac gamma must be of type varidx"));
750
751         static varidx xi((new symbol)->setflag(status_flags::dynallocated), ex_to<varidx>(mu).get_dim()),
752                 chi((new symbol)->setflag(status_flags::dynallocated), ex_to<varidx>(mu).get_dim());
753         return clifford(gamma, mu, indexed((new minkmetric)->setflag(status_flags::dynallocated), symmetric2(), xi, chi), rl);
754 }
755
756 ex dirac_gamma5(unsigned char rl)
757 {
758         static ex gamma5 = (new diracgamma5)->setflag(status_flags::dynallocated);
759         return clifford(gamma5, rl);
760 }
761
762 ex dirac_gammaL(unsigned char rl)
763 {
764         static ex gammaL = (new diracgammaL)->setflag(status_flags::dynallocated);
765         return clifford(gammaL, rl);
766 }
767
768 ex dirac_gammaR(unsigned char rl)
769 {
770         static ex gammaR = (new diracgammaR)->setflag(status_flags::dynallocated);
771         return clifford(gammaR, rl);
772 }
773
774 ex dirac_slash(const ex & e, const ex & dim, unsigned char rl)
775 {
776         // Slashed vectors are actually stored as a clifford object with the
777         // vector as its base expression and a (dummy) index that just serves
778         // for storing the space dimensionality
779
780         static varidx xi((new symbol)->setflag(status_flags::dynallocated), dim),
781                 chi((new symbol)->setflag(status_flags::dynallocated), dim);
782    return clifford(e, varidx(0, dim), indexed((new minkmetric)->setflag(status_flags::dynallocated), symmetric2(), xi, chi), rl);
783 }
784
785 /** Check whether a given tinfo key (as returned by return_type_tinfo()
786  *  is that of a clifford object (with an arbitrary representation label). */
787 bool is_clifford_tinfo(tinfo_t ti)
788 {
789         p_int start_loc=(p_int)&clifford::return_type_tinfo_static;
790         return (p_int)ti>=start_loc && (p_int)ti<start_loc+256;
791 }
792
793 /** Extract representation label from tinfo key (as returned by
794  *  return_type_tinfo()). */
795 static unsigned char get_representation_label(tinfo_t ti)
796 {
797         return (unsigned char)((p_int)ti-(p_int)&clifford::return_type_tinfo_static);
798 }
799
800 /** Take trace of a string of an even number of Dirac gammas given a vector
801  *  of indices. */
802 static ex trace_string(exvector::const_iterator ix, size_t num)
803 {
804         // Tr gamma.mu gamma.nu = 4 g.mu.nu
805         if (num == 2)
806                 return lorentz_g(ix[0], ix[1]);
807
808         // Tr gamma.mu gamma.nu gamma.rho gamma.sig = 4 (g.mu.nu g.rho.sig + g.nu.rho g.mu.sig - g.mu.rho g.nu.sig )
809         else if (num == 4)
810                 return lorentz_g(ix[0], ix[1]) * lorentz_g(ix[2], ix[3])
811                      + lorentz_g(ix[1], ix[2]) * lorentz_g(ix[0], ix[3])
812                      - lorentz_g(ix[0], ix[2]) * lorentz_g(ix[1], ix[3]);
813
814         // Traces of 6 or more gammas are computed recursively:
815         // Tr gamma.mu1 gamma.mu2 ... gamma.mun =
816         //   + g.mu1.mu2 * Tr gamma.mu3 ... gamma.mun
817         //   - g.mu1.mu3 * Tr gamma.mu2 gamma.mu4 ... gamma.mun
818         //   + g.mu1.mu4 * Tr gamma.mu3 gamma.mu3 gamma.mu5 ... gamma.mun
819         //   - ...
820         //   + g.mu1.mun * Tr gamma.mu2 ... gamma.mu(n-1)
821         exvector v(num - 2);
822         int sign = 1;
823         ex result;
824         for (size_t i=1; i<num; i++) {
825                 for (size_t n=1, j=0; n<num; n++) {
826                         if (n == i)
827                                 continue;
828                         v[j++] = ix[n];
829                 }
830                 result += sign * lorentz_g(ix[0], ix[i]) * trace_string(v.begin(), num-2);
831                 sign = -sign;
832         }
833         return result;
834 }
835
836 ex dirac_trace(const ex & e, const std::set<unsigned char> & rls, const ex & trONE)
837 {
838         if (is_a<clifford>(e)) {
839
840                 unsigned char rl = ex_to<clifford>(e).get_representation_label();
841
842                 // Are we taking the trace over this object's representation label?
843                 if (rls.find(rl) == rls.end())
844                         return e;
845
846                 // Yes, all elements are traceless, except for dirac_ONE and dirac_L/R
847                 const ex & g = e.op(0);
848                 if (is_a<diracone>(g))
849                         return trONE;
850                 else if (is_a<diracgammaL>(g) || is_a<diracgammaR>(g))
851                         return trONE/2;
852                 else
853                         return _ex0;
854
855         } else if (is_exactly_a<mul>(e)) {
856
857                 // Trace of product: pull out non-clifford factors
858                 ex prod = _ex1;
859                 for (size_t i=0; i<e.nops(); i++) {
860                         const ex &o = e.op(i);
861                         if (is_clifford_tinfo(o.return_type_tinfo()))
862                                 prod *= dirac_trace(o, rls, trONE);
863                         else
864                                 prod *= o;
865                 }
866                 return prod;
867
868         } else if (is_exactly_a<ncmul>(e)) {
869
870                 unsigned char rl = get_representation_label(e.return_type_tinfo());
871
872                 // Are we taking the trace over this string's representation label?
873                 if (rls.find(rl) == rls.end())
874                         return e;
875
876                 // Substitute gammaL/R and expand product, if necessary
877                 ex e_expanded = e.subs(lst(
878                         dirac_gammaL(rl) == (dirac_ONE(rl)-dirac_gamma5(rl))/2,
879                         dirac_gammaR(rl) == (dirac_ONE(rl)+dirac_gamma5(rl))/2
880                 ), subs_options::no_pattern).expand();
881                 if (!is_a<ncmul>(e_expanded))
882                         return dirac_trace(e_expanded, rls, trONE);
883
884                 // gamma5 gets moved to the front so this check is enough
885                 bool has_gamma5 = is_a<diracgamma5>(e.op(0).op(0));
886                 size_t num = e.nops();
887
888                 if (has_gamma5) {
889
890                         // Trace of gamma5 * odd number of gammas and trace of
891                         // gamma5 * gamma.mu * gamma.nu are zero
892                         if ((num & 1) == 0 || num == 3)
893                                 return _ex0;
894
895                         // Tr gamma5 gamma.mu gamma.nu gamma.rho gamma.sigma = 4I * epsilon(mu, nu, rho, sigma)
896                         // (the epsilon is always 4-dimensional)
897                         if (num == 5) {
898                                 ex b1, i1, b2, i2, b3, i3, b4, i4;
899                                 base_and_index(e.op(1), b1, i1);
900                                 base_and_index(e.op(2), b2, i2);
901                                 base_and_index(e.op(3), b3, i3);
902                                 base_and_index(e.op(4), b4, i4);
903                                 return trONE * I * (lorentz_eps(ex_to<idx>(i1).replace_dim(_ex4), ex_to<idx>(i2).replace_dim(_ex4), ex_to<idx>(i3).replace_dim(_ex4), ex_to<idx>(i4).replace_dim(_ex4)) * b1 * b2 * b3 * b4).simplify_indexed();
904                         }
905
906                         // Tr gamma5 S_2k =
907                         //   I/4! * epsilon0123.mu1.mu2.mu3.mu4 * Tr gamma.mu1 gamma.mu2 gamma.mu3 gamma.mu4 S_2k
908                         // (the epsilon is always 4-dimensional)
909                         exvector ix(num-1), bv(num-1);
910                         for (size_t i=1; i<num; i++)
911                                 base_and_index(e.op(i), bv[i-1], ix[i-1]);
912                         num--;
913                         int *iv = new int[num];
914                         ex result;
915                         for (size_t i=0; i<num-3; i++) {
916                                 ex idx1 = ix[i];
917                                 for (size_t j=i+1; j<num-2; j++) {
918                                         ex idx2 = ix[j];
919                                         for (size_t k=j+1; k<num-1; k++) {
920                                                 ex idx3 = ix[k];
921                                                 for (size_t l=k+1; l<num; l++) {
922                                                         ex idx4 = ix[l];
923                                                         iv[0] = i; iv[1] = j; iv[2] = k; iv[3] = l;
924                                                         exvector v;
925                                                         v.reserve(num - 4);
926                                                         for (size_t n=0, t=4; n<num; n++) {
927                                                                 if (n == i || n == j || n == k || n == l)
928                                                                         continue;
929                                                                 iv[t++] = n;
930                                                                 v.push_back(ix[n]);
931                                                         }
932                                                         int sign = permutation_sign(iv, iv + num);
933                                                         result += sign * lorentz_eps(ex_to<idx>(idx1).replace_dim(_ex4), ex_to<idx>(idx2).replace_dim(_ex4), ex_to<idx>(idx3).replace_dim(_ex4), ex_to<idx>(idx4).replace_dim(_ex4))
934                                                                 * trace_string(v.begin(), num - 4);
935                                                 }
936                                         }
937                                 }
938                         }
939                         delete[] iv;
940                         return trONE * I * result * mul(bv);
941
942                 } else { // no gamma5
943
944                         // Trace of odd number of gammas is zero
945                         if ((num & 1) == 1)
946                                 return _ex0;
947
948                         // Tr gamma.mu gamma.nu = 4 g.mu.nu
949                         if (num == 2) {
950                                 ex b1, i1, b2, i2;
951                                 base_and_index(e.op(0), b1, i1);
952                                 base_and_index(e.op(1), b2, i2);
953                                 return trONE * (lorentz_g(i1, i2) * b1 * b2).simplify_indexed();
954                         }
955
956                         exvector iv(num), bv(num);
957                         for (size_t i=0; i<num; i++)
958                                 base_and_index(e.op(i), bv[i], iv[i]);
959
960                         return trONE * (trace_string(iv.begin(), num) * mul(bv)).simplify_indexed();
961                 }
962
963         } else if (e.nops() > 0) {
964
965                 // Trace maps to all other container classes (this includes sums)
966                 pointer_to_map_function_2args<const std::set<unsigned char> &, const ex &> fcn(dirac_trace, rls, trONE);
967                 return e.map(fcn);
968
969         } else
970                 return _ex0;
971 }
972
973 ex dirac_trace(const ex & e, const lst & rll, const ex & trONE)
974 {
975         // Convert list to set
976         std::set<unsigned char> rls;
977         for (lst::const_iterator i = rll.begin(); i != rll.end(); ++i) {
978                 if (i->info(info_flags::nonnegint))
979                         rls.insert(ex_to<numeric>(*i).to_int());
980         }
981
982         return dirac_trace(e, rls, trONE);
983 }
984
985 ex dirac_trace(const ex & e, unsigned char rl, const ex & trONE)
986 {
987         // Convert label to set
988         std::set<unsigned char> rls;
989         rls.insert(rl);
990
991         return dirac_trace(e, rls, trONE);
992 }
993
994
995 ex canonicalize_clifford(const ex & e_)
996 {
997         pointer_to_map_function fcn(canonicalize_clifford);
998
999         if (is_a<matrix>(e_)    // || is_a<pseries>(e) || is_a<integral>(e)
1000                 || e_.info(info_flags::list)) {
1001                 return e_.map(fcn);
1002         } else {
1003                 ex e=simplify_indexed(e_);
1004                 // Scan for any ncmul objects
1005                 exmap srl;
1006                 ex aux = e.to_rational(srl);
1007                 for (exmap::iterator i = srl.begin(); i != srl.end(); ++i) {
1008
1009                         ex lhs = i->first;
1010                         ex rhs = i->second;
1011
1012                         if (is_exactly_a<ncmul>(rhs)
1013                                         && rhs.return_type() == return_types::noncommutative
1014                                         && is_clifford_tinfo(rhs.return_type_tinfo())) {
1015
1016                                 // Expand product, if necessary
1017                                 ex rhs_expanded = rhs.expand();
1018                                 if (!is_a<ncmul>(rhs_expanded)) {
1019                                         i->second = canonicalize_clifford(rhs_expanded);
1020                                         continue;
1021
1022                                 } else if (!is_a<clifford>(rhs.op(0)))
1023                                         continue;
1024
1025                                 exvector v;
1026                                 v.reserve(rhs.nops());
1027                                 for (size_t j=0; j<rhs.nops(); j++)
1028                                         v.push_back(rhs.op(j));
1029
1030                                 // Stupid recursive bubble sort because we only want to swap adjacent gammas
1031                                 exvector::iterator it = v.begin(), next_to_last = v.end() - 1;
1032                                 if (is_a<diracgamma5>(it->op(0)) || is_a<diracgammaL>(it->op(0)) || is_a<diracgammaR>(it->op(0)))
1033                                         ++it;
1034
1035                                 while (it != next_to_last) {
1036                                         if (it[0].compare(it[1]) > 0) {
1037
1038                                                 ex save0 = it[0], save1 = it[1];
1039                                                 ex b1, i1, b2, i2;
1040                                                 base_and_index(it[0], b1, i1);
1041                                                 base_and_index(it[1], b2, i2);
1042                                                 // for Clifford algebras (commutator_sign == -1) metric should be symmetrised
1043                                                 it[0] = (ex_to<clifford>(save0).get_metric(i1, i2, ex_to<clifford>(save0).get_commutator_sign() == -1) * b1 * b2).simplify_indexed();
1044                                                 it[1] = v.size() ? _ex2 * dirac_ONE(ex_to<clifford>(save0).get_representation_label()) : _ex2;
1045                                                 ex sum = ncmul(v);
1046                                                 it[0] = save1;
1047                                                 it[1] = save0;
1048                                                 sum += ex_to<clifford>(save0).get_commutator_sign() * ncmul(v, true);
1049                                                 i->second = canonicalize_clifford(sum);
1050                                                 goto next_sym;
1051                                         }
1052                                         ++it;
1053                                 }
1054 next_sym:       ;
1055                         }
1056                 }
1057                 return aux.subs(srl, subs_options::no_pattern).simplify_indexed();
1058         }
1059 }
1060
1061 ex clifford_prime(const ex & e)
1062 {
1063         pointer_to_map_function fcn(clifford_prime);
1064         if (is_a<clifford>(e) && is_a<cliffordunit>(e.op(0))) {
1065                 return -e;
1066         } else if (is_a<add>(e) || is_a<ncmul>(e) || is_a<mul>(e) //|| is_a<pseries>(e) || is_a<integral>(e)
1067                            || is_a<matrix>(e) || e.info(info_flags::list)) {
1068                 return e.map(fcn);
1069         } else if (is_a<power>(e)) {
1070                 return pow(clifford_prime(e.op(0)), e.op(1));
1071         } else
1072                 return e;
1073 }
1074
1075 ex remove_dirac_ONE(const ex & e, unsigned char rl, unsigned options)
1076 {
1077         pointer_to_map_function_2args<unsigned char, unsigned> fcn(remove_dirac_ONE, rl, options | 1);
1078         bool need_reevaluation = false;
1079         ex e1 = e;
1080         if (! (options & 1) )  { // is not a child
1081                 if (options & 2)
1082                         e1 = expand_dummy_sum(e, true);
1083                 e1 = canonicalize_clifford(e1);
1084         }
1085         
1086         if (is_a<clifford>(e1) && ex_to<clifford>(e1).get_representation_label() >= rl) {
1087                 if (is_a<diracone>(e1.op(0)))
1088                         return 1;
1089                 else 
1090                         throw(std::invalid_argument("remove_dirac_ONE(): expression is a non-scalar Clifford number!"));
1091         } else if (is_a<add>(e1) || is_a<ncmul>(e1) || is_a<mul>(e1)  
1092                            || is_a<matrix>(e1) || e1.info(info_flags::list)) {
1093                 if (options & 3) // is a child or was already expanded
1094                         return e1.map(fcn);
1095                 else
1096                         try {
1097                                 return e1.map(fcn);
1098                         } catch (std::exception &p) {
1099                                 need_reevaluation = true;
1100                         }
1101         } else if (is_a<power>(e1)) {
1102                 if (options & 3) // is a child or was already expanded
1103                         return pow(remove_dirac_ONE(e1.op(0), rl, options | 1), e1.op(1));
1104                 else
1105                         try {
1106                                 return pow(remove_dirac_ONE(e1.op(0), rl, options | 1), e1.op(1));
1107                         } catch (std::exception &p) {
1108                                 need_reevaluation = true;
1109                         }
1110         } 
1111         if (need_reevaluation)
1112                 return remove_dirac_ONE(e, rl, options | 2);
1113         return e1;
1114 }
1115
1116 char clifford_max_label(const ex & e, bool ignore_ONE)
1117 {
1118         if (is_a<clifford>(e))
1119                 if (ignore_ONE && is_a<diracone>(e.op(0)))
1120                         return -1;
1121                 else
1122                         return ex_to<clifford>(e).get_representation_label();
1123         else {
1124                 char rl = -1;
1125                 for (size_t i=0; i < e.nops(); i++) 
1126                         rl = (rl > clifford_max_label(e.op(i), ignore_ONE)) ? rl : clifford_max_label(e.op(i), ignore_ONE);
1127                 return rl;
1128         }
1129 }
1130
1131 ex clifford_norm(const ex & e)
1132 {
1133         return sqrt(remove_dirac_ONE(e * clifford_bar(e)));
1134 }
1135         
1136 ex clifford_inverse(const ex & e)
1137 {
1138         ex norm = clifford_norm(e);
1139         if (!norm.is_zero())
1140                 return clifford_bar(e) / pow(norm, 2);
1141         else 
1142                 throw(std::invalid_argument("clifford_inverse(): cannot find inverse of Clifford number with zero norm!"));
1143 }
1144
1145 ex lst_to_clifford(const ex & v, const ex & mu, const ex & metr, unsigned char rl)
1146 {
1147         if (!ex_to<idx>(mu).is_dim_numeric())
1148                 throw(std::invalid_argument("lst_to_clifford(): Index should have a numeric dimension"));
1149         ex e = clifford_unit(mu, metr, rl);
1150         return lst_to_clifford(v, e);
1151 }
1152
1153 ex lst_to_clifford(const ex & v, const ex & e) {
1154         unsigned min, max;
1155
1156         if (is_a<clifford>(e)) {
1157                 ex mu = e.op(1);
1158                 ex mu_toggle
1159                         = is_a<varidx>(mu) ? ex_to<varidx>(mu).toggle_variance() : mu;
1160                 unsigned dim = (ex_to<numeric>(ex_to<idx>(mu).get_dim())).to_int();
1161
1162                 if (is_a<matrix>(v)) {
1163                         if (ex_to<matrix>(v).cols() > ex_to<matrix>(v).rows()) {
1164                                 min = ex_to<matrix>(v).rows();
1165                                 max = ex_to<matrix>(v).cols();
1166                         } else {
1167                                 min = ex_to<matrix>(v).cols();
1168                                 max = ex_to<matrix>(v).rows();
1169                         }
1170                         if (min == 1) {
1171                                 if (dim == max)
1172                                         return indexed(v, mu_toggle) * e;
1173                                 else
1174                                         throw(std::invalid_argument("lst_to_clifford(): dimensions of vector and clifford unit mismatch"));
1175                         } else
1176                                 throw(std::invalid_argument("lst_to_clifford(): first argument should be a vector (nx1 or 1xn matrix)"));
1177                 } else if (v.info(info_flags::list)) {
1178                         if (dim == ex_to<lst>(v).nops())
1179                                 return indexed(matrix(dim, 1, ex_to<lst>(v)), mu_toggle) * e;
1180                         else
1181                                 throw(std::invalid_argument("lst_to_clifford(): list length and dimension of clifford unit mismatch"));
1182                 } else
1183                         throw(std::invalid_argument("lst_to_clifford(): cannot construct from anything but list or vector"));
1184         } else
1185                 throw(std::invalid_argument("lst_to_clifford(): the second argument should be a Clifford unit"));
1186 }
1187  
1188 /** Auxiliary structure to define a function for striping one Clifford unit
1189  * from vectors. Used in  clifford_to_lst(). */
1190 static ex get_clifford_comp(const ex & e, const ex & c) 
1191 {
1192         pointer_to_map_function_1arg<const ex &> fcn(get_clifford_comp, c);
1193         int ival = ex_to<numeric>(ex_to<idx>(c.op(1)).get_value()).to_int();
1194                 
1195         if (is_a<add>(e) || e.info(info_flags::list) // || is_a<pseries>(e) || is_a<integral>(e)
1196                 || is_a<matrix>(e)) 
1197                 return e.map(fcn);
1198         else if (is_a<ncmul>(e) || is_a<mul>(e)) {
1199                 // find a Clifford unit with the same metric, delete it and substitute its index
1200                 size_t ind = e.nops() + 1;
1201                 for (size_t j = 0; j < e.nops(); j++) 
1202                         if (is_a<clifford>(e.op(j)) && ex_to<clifford>(c).same_metric(e.op(j)))
1203                                 if (ind > e.nops()) 
1204                                         ind = j;
1205                                 else 
1206                                         throw(std::invalid_argument("get_clifford_comp(): expression is a Clifford multi-vector"));
1207                 if (ind < e.nops()) {
1208                         ex S = 1;
1209                         bool same_value_index, found_dummy;
1210                         same_value_index = ( ex_to<idx>(e.op(ind).op(1)).is_numeric()
1211                                                                  &&  (ival == ex_to<numeric>(ex_to<idx>(e.op(ind).op(1)).get_value()).to_int()) );
1212                         found_dummy = same_value_index;
1213                         for(size_t j=0; j < e.nops(); j++)
1214                                 if (j != ind) 
1215                                         if (same_value_index) 
1216                                                 S = S * e.op(j);
1217                                         else {
1218                                                 exvector ind_vec = ex_to<indexed>(e.op(j)).get_dummy_indices(ex_to<indexed>(e.op(ind)));
1219                                                 if (ind_vec.size() > 0) {
1220                                                         found_dummy = true;
1221                                                         exvector::const_iterator it = ind_vec.begin(), itend = ind_vec.end();
1222                                                         while (it != itend) {
1223                                                                 ex curridx = *it;
1224                                                                 ex curridx_toggle = is_a<varidx>(curridx)
1225                                                                         ? ex_to<varidx>(curridx).toggle_variance()
1226                                                                         : curridx;
1227                                                                 S = S * e.op(j).subs(lst(curridx == ival,
1228                                                                         curridx_toggle == ival), subs_options::no_pattern);
1229                                                                 ++it;
1230                                                         }
1231                                                 } else
1232                                                         S = S * e.op(j);
1233                                         }
1234                         return (found_dummy ? S : 0);
1235                 } else
1236                         throw(std::invalid_argument("get_clifford_comp(): expression is not a Clifford vector to the given units"));
1237         } else if (e.is_zero()) 
1238                 return e;
1239         else if (is_a<clifford>(e) && ex_to<clifford>(e).same_metric(c))
1240                 if ( ex_to<idx>(e.op(1)).is_numeric() &&
1241                          (ival != ex_to<numeric>(ex_to<idx>(e.op(1)).get_value()).to_int()) )
1242                         return 0;
1243                 else 
1244                         return 1;
1245         else
1246                 throw(std::invalid_argument("get_clifford_comp(): expression is not usable as a Clifford vector"));
1247 }
1248
1249
1250 lst clifford_to_lst(const ex & e, const ex & c, bool algebraic)
1251 {
1252         GINAC_ASSERT(is_a<clifford>(c));
1253         ex mu = c.op(1);
1254         if (! ex_to<idx>(mu).is_dim_numeric())
1255                 throw(std::invalid_argument("clifford_to_lst(): index should have a numeric dimension"));
1256         unsigned int D = ex_to<numeric>(ex_to<idx>(mu).get_dim()).to_int();
1257
1258         if (algebraic) // check if algebraic method is applicable
1259                 for (unsigned int i = 0; i < D; i++) 
1260                         if (pow(c.subs(mu == i, subs_options::no_pattern), 2).is_zero() 
1261                                 or (not is_a<numeric>(pow(c.subs(mu == i, subs_options::no_pattern), 2))))
1262                                 algebraic = false;
1263         lst V; 
1264         if (algebraic) {
1265                 for (unsigned int i = 0; i < D; i++) 
1266                         V.append(remove_dirac_ONE(
1267                                                 simplify_indexed(canonicalize_clifford(e * c.subs(mu == i, subs_options::no_pattern) +  c.subs(mu == i, subs_options::no_pattern) * e))
1268                                                 / (2*pow(c.subs(mu == i, subs_options::no_pattern), 2))));
1269         } else {
1270                 ex e1 = canonicalize_clifford(e);
1271                 try {
1272                         for (unsigned int i = 0; i < D; i++) 
1273                                 V.append(get_clifford_comp(e1, c.subs(c.op(1) == i, subs_options::no_pattern)));
1274                 } catch  (std::exception &p) {
1275                         /* Try to expand dummy summations to simplify the expression*/
1276                         e1 = canonicalize_clifford(expand_dummy_sum(e1, true));
1277                         for (unsigned int i = 0; i < D; i++) 
1278                                 V.append(get_clifford_comp(e1, c.subs(c.op(1) == i, subs_options::no_pattern)));
1279                 }
1280         }
1281         return V;
1282 }
1283
1284
1285 ex clifford_moebius_map(const ex & a, const ex & b, const ex & c, const ex & d, const ex & v, const ex & G, unsigned char rl)
1286 {
1287         ex x, D, cu;
1288         
1289         if (! is_a<matrix>(v) && ! v.info(info_flags::list))
1290                 throw(std::invalid_argument("clifford_moebius_map(): parameter v should be either vector or list"));
1291         
1292         if (is_a<clifford>(G)) {
1293                 cu = G;
1294         } else {
1295                 if (is_a<indexed>(G)) {
1296                         D = ex_to<idx>(G.op(1)).get_dim();
1297                         varidx mu((new symbol)->setflag(status_flags::dynallocated), D);
1298                         cu = clifford_unit(mu, G, rl);
1299                 } else if (is_a<matrix>(G)) {
1300                         D = ex_to<matrix>(G).rows(); 
1301                         idx mu((new symbol)->setflag(status_flags::dynallocated), D);
1302                         cu = clifford_unit(mu, G, rl);
1303                 } else throw(std::invalid_argument("clifford_moebius_map(): metric should be an indexed object, matrix, or a Clifford unit"));
1304                 
1305         }
1306         
1307         x = lst_to_clifford(v, cu); 
1308         ex e = clifford_to_lst(simplify_indexed(canonicalize_clifford((a * x + b) * clifford_inverse(c * x + d))), cu, false);
1309         return (is_a<matrix>(v) ? matrix(ex_to<matrix>(v).rows(), ex_to<matrix>(v).cols(), ex_to<lst>(e)) : e);
1310 }
1311
1312 ex clifford_moebius_map(const ex & M, const ex & v, const ex & G, unsigned char rl)
1313 {
1314         if (is_a<matrix>(M)) 
1315                 return clifford_moebius_map(ex_to<matrix>(M)(0,0), ex_to<matrix>(M)(0,1),
1316                                             ex_to<matrix>(M)(1,0), ex_to<matrix>(M)(1,1), v, G, rl);
1317         else
1318                 throw(std::invalid_argument("clifford_moebius_map(): parameter M should be a matrix"));
1319 }
1320
1321 } // namespace GiNaC