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