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