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