]> www.ginac.de Git - ginac.git/blob - ginac/clifford.cpp
replaced non-ASCII character in exception msg
[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-2004 Johannes Gutenberg University Mainz, Germany
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 2 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 #include "clifford.h"
24
25 #include "ex.h"
26 #include "idx.h"
27 #include "ncmul.h"
28 #include "symbol.h"
29 #include "numeric.h" // for I
30 #include "symmetry.h"
31 #include "lst.h"
32 #include "relational.h"
33 #include "operators.h"
34 #include "add.h"
35 #include "mul.h"
36 #include "power.h"
37 #include "matrix.h"
38 #include "archive.h"
39 #include "utils.h"
40
41 namespace GiNaC {
42
43 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(clifford, indexed,
44   print_func<print_dflt>(&clifford::do_print_dflt).
45   print_func<print_latex>(&clifford::do_print_latex))
46
47 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(diracone, tensor,
48   print_func<print_dflt>(&diracone::do_print).
49   print_func<print_latex>(&diracone::do_print_latex))
50
51 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(cliffordunit, tensor,
52   print_func<print_dflt>(&cliffordunit::do_print).
53   print_func<print_latex>(&cliffordunit::do_print_latex))
54
55 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(diracgamma, cliffordunit,
56   print_func<print_dflt>(&diracgamma::do_print).
57   print_func<print_latex>(&diracgamma::do_print_latex))
58
59 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(diracgamma5, tensor,
60   print_func<print_dflt>(&diracgamma5::do_print).
61   print_func<print_latex>(&diracgamma5::do_print_latex))
62
63 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(diracgammaL, tensor,
64   print_func<print_context>(&diracgammaL::do_print).
65   print_func<print_latex>(&diracgammaL::do_print_latex))
66
67 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(diracgammaR, tensor,
68   print_func<print_context>(&diracgammaR::do_print).
69   print_func<print_latex>(&diracgammaR::do_print_latex))
70
71 //////////
72 // default constructors
73 //////////
74
75 static ex default_metric()
76 {
77         static ex m = (new minkmetric)->setflag(status_flags::dynallocated);
78         return m;
79 }
80
81 clifford::clifford() : representation_label(0), metric(default_metric())
82 {
83         tinfo_key = TINFO_clifford;
84 }
85
86 DEFAULT_CTOR(diracone)
87 DEFAULT_CTOR(cliffordunit)
88 DEFAULT_CTOR(diracgamma)
89 DEFAULT_CTOR(diracgamma5)
90 DEFAULT_CTOR(diracgammaL)
91 DEFAULT_CTOR(diracgammaR)
92
93 //////////
94 // other constructors
95 //////////
96
97 /** Construct object without any indices. This constructor is for internal
98  *  use only. Use the dirac_ONE() function instead.
99  *  @see dirac_ONE */
100 clifford::clifford(const ex & b, unsigned char rl) : inherited(b), representation_label(rl), metric(0)
101 {
102         tinfo_key = TINFO_clifford;
103 }
104
105 /** Construct object with one Lorentz index. This constructor is for internal
106  *  use only. Use the clifford_unit() or dirac_gamma() functions instead.
107  *  @see clifford_unit
108  *  @see dirac_gamma */
109 clifford::clifford(const ex & b, const ex & mu, const ex & metr, unsigned char rl) : inherited(b, mu), representation_label(rl), metric(metr)
110 {
111         GINAC_ASSERT(is_a<varidx>(mu));
112         tinfo_key = TINFO_clifford;
113 }
114
115 clifford::clifford(unsigned char rl, const ex & metr, const exvector & v, bool discardable) : inherited(not_symmetric(), v, discardable), representation_label(rl), metric(metr)
116 {
117         tinfo_key = TINFO_clifford;
118 }
119
120 clifford::clifford(unsigned char rl, const ex & metr, std::auto_ptr<exvector> vp) : inherited(not_symmetric(), vp), representation_label(rl), metric(metr)
121 {
122         tinfo_key = TINFO_clifford;
123 }
124
125 //////////
126 // archiving
127 //////////
128
129 clifford::clifford(const archive_node &n, lst &sym_lst) : inherited(n, sym_lst)
130 {
131         unsigned rl;
132         n.find_unsigned("label", rl);
133         representation_label = rl;
134         n.find_ex("metric", metric, sym_lst);
135 }
136
137 void clifford::archive(archive_node &n) const
138 {
139         inherited::archive(n);
140         n.add_unsigned("label", representation_label);
141         n.add_ex("metric", metric);
142 }
143
144 DEFAULT_UNARCHIVE(clifford)
145 DEFAULT_ARCHIVING(diracone)
146 DEFAULT_ARCHIVING(cliffordunit)
147 DEFAULT_ARCHIVING(diracgamma)
148 DEFAULT_ARCHIVING(diracgamma5)
149 DEFAULT_ARCHIVING(diracgammaL)
150 DEFAULT_ARCHIVING(diracgammaR)
151
152 //////////
153 // functions overriding virtual functions from base classes
154 //////////
155
156 ex clifford::get_metric(const ex & i, const ex & j) const
157 {
158         return indexed(metric, symmetric2(), i, j);
159 }
160
161 bool clifford::same_metric(const ex & other) const
162 {
163         if (is_a<clifford>(other)) {
164                 return get_metric().is_equal(ex_to<clifford>(other).get_metric());
165         } else if (is_a<indexed>(other)) {
166                 return get_metric(other.op(1), other.op(2)).is_equal(other);
167         } else
168                 return false;
169 }
170
171 int clifford::compare_same_type(const basic & other) const
172 {
173         GINAC_ASSERT(is_a<clifford>(other));
174         const clifford &o = static_cast<const clifford &>(other);
175
176         if (representation_label != o.representation_label) {
177                 // different representation label
178                 return representation_label < o.representation_label ? -1 : 1;
179         }
180
181         return inherited::compare_same_type(other);
182 }
183
184 bool clifford::match_same_type(const basic & other) const
185 {
186         GINAC_ASSERT(is_a<clifford>(other));
187         const clifford &o = static_cast<const clifford &>(other);
188
189         return (representation_label == o.representation_label) && same_metric(o);
190 }
191
192 static bool is_dirac_slash(const ex & seq0)
193 {
194         return !is_a<diracgamma5>(seq0) && !is_a<diracgammaL>(seq0) &&
195                !is_a<diracgammaR>(seq0) && !is_a<cliffordunit>(seq0) &&
196                !is_a<diracone>(seq0);
197 }
198
199 void clifford::do_print_dflt(const print_dflt & c, unsigned level) const
200 {
201         // dirac_slash() object is printed differently
202         if (is_dirac_slash(seq[0])) {
203                 seq[0].print(c, level);
204                 c.s << "\\";
205         } else
206                 this->print_dispatch<inherited>(c, level);
207 }
208
209 void clifford::do_print_latex(const print_latex & c, unsigned level) const
210 {
211         // dirac_slash() object is printed differently
212         if (is_dirac_slash(seq[0])) {
213                 c.s << "{";
214                 seq[0].print(c, level);
215                 c.s << "\\hspace{-1.0ex}/}";
216         } else
217                 this->print_dispatch<inherited>(c, level);
218 }
219
220 DEFAULT_COMPARE(diracone)
221 DEFAULT_COMPARE(cliffordunit)
222 DEFAULT_COMPARE(diracgamma)
223 DEFAULT_COMPARE(diracgamma5)
224 DEFAULT_COMPARE(diracgammaL)
225 DEFAULT_COMPARE(diracgammaR)
226
227 DEFAULT_PRINT_LATEX(diracone, "ONE", "\\mathbb{1}")
228 DEFAULT_PRINT_LATEX(cliffordunit, "e", "e")
229 DEFAULT_PRINT_LATEX(diracgamma, "gamma", "\\gamma")
230 DEFAULT_PRINT_LATEX(diracgamma5, "gamma5", "{\\gamma^5}")
231 DEFAULT_PRINT_LATEX(diracgammaL, "gammaL", "{\\gamma_L}")
232 DEFAULT_PRINT_LATEX(diracgammaR, "gammaR", "{\\gamma_R}")
233
234 /** This function decomposes gamma~mu -> (1, mu) and a\ -> (a.ix, ix) */
235 static void base_and_index(const ex & c, ex & b, ex & i)
236 {
237         GINAC_ASSERT(is_a<clifford>(c));
238         GINAC_ASSERT(c.nops() == 2);
239
240         if (is_a<cliffordunit>(c.op(0))) { // proper dirac gamma object or clifford unit
241                 i = c.op(1);
242                 b = _ex1;
243         } else if (is_a<diracgamma5>(c.op(0)) || is_a<diracgammaL>(c.op(0)) || is_a<diracgammaR>(c.op(0))) { // gamma5/L/R
244                 i = _ex0;
245                 b = _ex1;
246         } else { // slash object, generate new dummy index
247                 varidx ix((new symbol)->setflag(status_flags::dynallocated), ex_to<idx>(c.op(1)).get_dim());
248                 b = indexed(c.op(0), ix.toggle_variance());
249                 i = ix;
250         }
251 }
252
253 /** Predicate for finding non-clifford objects. */
254 struct is_not_a_clifford : public std::unary_function<ex, bool> {
255         bool operator()(const ex & e)
256         {
257                 return !is_a<clifford>(e);
258         }
259 };
260
261 /** Contraction of a gamma matrix with something else. */
262 bool diracgamma::contract_with(exvector::iterator self, exvector::iterator other, exvector & v) const
263 {
264         GINAC_ASSERT(is_a<clifford>(*self));
265         GINAC_ASSERT(is_a<indexed>(*other));
266         GINAC_ASSERT(is_a<diracgamma>(self->op(0)));
267         unsigned char rl = ex_to<clifford>(*self).get_representation_label();
268
269         ex dim = ex_to<idx>(self->op(1)).get_dim();
270         if (other->nops() > 1)
271                 dim = minimal_dim(dim, ex_to<idx>(other->op(1)).get_dim());
272
273         if (is_a<clifford>(*other)) {
274
275                 // Contraction only makes sense if the represenation labels are equal
276                 if (ex_to<clifford>(*other).get_representation_label() != rl)
277                         return false;
278
279                 size_t num = other - self;
280
281                 // gamma~mu gamma.mu = dim ONE
282                 if (num == 1) {
283                         *self = dim;
284                         *other = dirac_ONE(rl);
285                         return true;
286
287                 // gamma~mu gamma~alpha gamma.mu = (2-dim) gamma~alpha
288                 } else if (num == 2
289                         && is_a<clifford>(self[1])) {
290                         *self = 2 - dim;
291                         *other = _ex1;
292                         return true;
293
294                 // gamma~mu gamma~alpha gamma~beta gamma.mu = 4 g~alpha~beta + (dim-4) gamam~alpha gamma~beta
295                 } else if (num == 3
296                         && is_a<clifford>(self[1])
297                         && is_a<clifford>(self[2])) {
298                         ex b1, i1, b2, i2;
299                         base_and_index(self[1], b1, i1);
300                         base_and_index(self[2], b2, i2);
301                         *self = 4 * lorentz_g(i1, i2) * b1 * b2 * dirac_ONE(rl) + (dim - 4) * self[1] * self[2];
302                         self[1] = _ex1;
303                         self[2] = _ex1;
304                         *other = _ex1;
305                         return true;
306
307                 // 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
308                 } else if (num == 4
309                         && is_a<clifford>(self[1])
310                         && is_a<clifford>(self[2])
311                         && is_a<clifford>(self[3])) {
312                         *self = -2 * self[3] * self[2] * self[1] - (dim - 4) * self[1] * self[2] * self[3];
313                         self[1] = _ex1;
314                         self[2] = _ex1;
315                         self[3] = _ex1;
316                         *other = _ex1;
317                         return true;
318
319                 // gamma~mu Sodd gamma.mu = -2 Sodd_R
320                 // (Chisholm identity in 4 dimensions)
321                 } else if (!((other - self) & 1) && dim.is_equal(4)) {
322                         if (std::find_if(self + 1, other, is_not_a_clifford()) != other)
323                                 return false;
324
325                         *self = ncmul(exvector(std::reverse_iterator<exvector::const_iterator>(other), std::reverse_iterator<exvector::const_iterator>(self + 1)), true);
326                         std::fill(self + 1, other, _ex1);
327                         *other = _ex_2;
328                         return true;
329
330                 // gamma~mu Sodd gamma~alpha gamma.mu = 2 gamma~alpha Sodd + 2 Sodd_R gamma~alpha
331                 // (commutate contracted indices towards each other, then use
332                 // Chisholm identity in 4 dimensions)
333                 } else if (((other - self) & 1) && dim.is_equal(4)) {
334                         if (std::find_if(self + 1, other, is_not_a_clifford()) != other)
335                                 return false;
336
337                         exvector::iterator next_to_last = other - 1;
338                         ex S = ncmul(exvector(self + 1, next_to_last), true);
339                         ex SR = ncmul(exvector(std::reverse_iterator<exvector::const_iterator>(next_to_last), std::reverse_iterator<exvector::const_iterator>(self + 1)), true);
340
341                         *self = (*next_to_last) * S + SR * (*next_to_last);
342                         std::fill(self + 1, other, _ex1);
343                         *other = _ex2;
344                         return true;
345
346                 // gamma~mu S gamma~alpha gamma.mu = 2 gamma~alpha S - gamma~mu S gamma.mu gamma~alpha
347                 // (commutate contracted indices towards each other, simplify_indexed()
348                 // will re-expand and re-run the simplification)
349                 } else {
350                         if (std::find_if(self + 1, other, is_not_a_clifford()) != other)
351                                 return false;
352
353                         exvector::iterator next_to_last = other - 1;
354                         ex S = ncmul(exvector(self + 1, next_to_last), true);
355
356                         *self = 2 * (*next_to_last) * S - (*self) * S * (*other) * (*next_to_last);
357                         std::fill(self + 1, other + 1, _ex1);
358                         return true;
359                 }
360
361         } else if (is_a<symbol>(other->op(0)) && other->nops() == 2) {
362
363                 // x.mu gamma~mu -> x-slash
364                 *self = dirac_slash(other->op(0), dim, rl);
365                 *other = _ex1;
366                 return true;
367         }
368
369         return false;
370 }
371
372 /** An utility function looking for a given metric within an exvector,
373  *  used in cliffordunit::contract_with(). */
374 static int find_same_metric(exvector & v, ex & c)
375 {
376         for (int i=0; i<v.size();i++) {
377                 if (!is_a<clifford>(v[i]) && is_a<indexed>(v[i])
378                     && ex_to<clifford>(c).same_metric(v[i]) 
379                     && (ex_to<varidx>(c.op(1)) == ex_to<indexed>(v[i]).get_indices()[0]
380                         || ex_to<varidx>(c.op(1)).toggle_variance() == ex_to<indexed>(v[i]).get_indices()[0])) {
381                         return ++i; // next to found
382                 }
383         }
384         return 0; //nothing found
385 }
386
387 /** Contraction of a Clifford unit with something else. */
388 bool cliffordunit::contract_with(exvector::iterator self, exvector::iterator other, exvector & v) const
389 {
390         GINAC_ASSERT(is_a<clifford>(*self));
391         GINAC_ASSERT(is_a<indexed>(*other));
392         GINAC_ASSERT(is_a<cliffordunit>(self->op(0)));
393         clifford unit = ex_to<clifford>(*self);
394         unsigned char rl = unit.get_representation_label();
395
396         if (is_a<clifford>(*other)) {
397                 // Contraction only makes sense if the represenation labels are equal
398                 // and the metrics are the same
399                 if ((ex_to<clifford>(*other).get_representation_label() != rl) 
400                     && unit.same_metric(*other))
401                         return false;
402
403                 // Find if a previous contraction produces the square of self
404                 int prev_square = find_same_metric(v, self[0]);
405                 varidx d((new symbol)->setflag(status_flags::dynallocated), ex_to<idx>(ex_to<idx>(self->op(1)).get_dim()));
406                 ex squared_metric = unit.get_metric(self->op(1), d) * unit.get_metric(d.toggle_variance(), other->op(1));
407
408                 // e~mu e.mu = Tr ONE
409                 if (other - self == 1) {
410                         if (prev_square != 0) {
411                                 *self = squared_metric;
412                                 v[prev_square-1] = _ex1;
413                         } else
414                                 *self = unit.get_metric(self->op(1), other->op(1));
415                         *other = dirac_ONE(rl);
416                         return true;
417
418                 // e~mu e~alpha e.mu = (2e~alpha^2-Tr) e~alpha
419                 } else if (other - self == 2
420                         && is_a<clifford>(self[1])) {
421
422                         const ex & ia = self[1].op(1);
423                         const ex & ib = self[1].op(1);
424                         if (is_a<tensmetric>(unit.get_metric()))
425                                 *self = 2 - unit.get_metric(self->op(1), other->op(1));
426                         else if (prev_square != 0) {
427                                 *self = 2-squared_metric;
428                                 v[prev_square-1] = _ex1;
429                         } else 
430                                 *self = 2*unit.get_metric(ia, ib) - unit.get_metric(self->op(1), other->op(1));
431                         *other = _ex1;
432                         return true;
433
434                 // e~mu S e~alpha e.mu = 2 e~alpha^3 S - e~mu S e.mu e~alpha
435                 // (commutate contracted indices towards each other, simplify_indexed()
436                 // will re-expand and re-run the simplification)
437                 } else {
438                         exvector::iterator it = self + 1, next_to_last = other - 1;
439                         while (it != other) {
440                                 if (!is_a<clifford>(*it))
441                                         return false;
442                                 ++it;
443                         }
444
445                         it = self + 1;
446                         ex S = _ex1;
447                         while (it != next_to_last) {
448                                 S *= *it;
449                                 *it++ = _ex1;
450                         }
451
452                         const ex & ia = next_to_last->op(1);
453                         const ex & ib = next_to_last->op(1);
454                         if (is_a<tensmetric>(unit.get_metric()))
455                                 *self = 2 * (*next_to_last) * S - (*self) * S * (*other) * (*next_to_last);
456                         else if (prev_square != 0) {
457                                 *self = 2 * (*next_to_last) * S  - (*self) * S * (*other) * (*next_to_last)*unit.get_metric(self->op(1),self->op(1));
458                                 v[prev_square-1] = _ex1;
459                         } else 
460                                 *self = 2 * (*next_to_last) * S* unit.get_metric(ia,ib) - (*self) * S * (*other) * (*next_to_last);
461                         *next_to_last = _ex1;
462                         *other = _ex1;
463                         return true;
464                 }
465
466         } 
467
468         return false;
469 }
470
471 /** Perform automatic simplification on noncommutative product of clifford
472  *  objects. This removes superfluous ONEs, permutes gamma5/L/R's to the front
473  *  and removes squares of gamma objects. */
474 ex clifford::eval_ncmul(const exvector & v) const
475 {
476         exvector s;
477         s.reserve(v.size());
478
479         // Remove superfluous ONEs
480         exvector::const_iterator cit = v.begin(), citend = v.end();
481         while (cit != citend) {
482                 if (!is_a<clifford>(*cit) || !is_a<diracone>(cit->op(0)))
483                         s.push_back(*cit);
484                 cit++;
485         }
486
487         bool something_changed = false;
488         int sign = 1;
489
490         // Anticommutate gamma5/L/R's to the front
491         if (s.size() >= 2) {
492                 exvector::iterator first = s.begin(), next_to_last = s.end() - 2;
493                 while (true) {
494                         exvector::iterator it = next_to_last;
495                         while (true) {
496                                 exvector::iterator it2 = it + 1;
497                                 if (is_a<clifford>(*it) && is_a<clifford>(*it2)) {
498                                         ex e1 = it->op(0), e2 = it2->op(0);
499
500                                         if (is_a<diracgamma5>(e2)) {
501
502                                                 if (is_a<diracgammaL>(e1) || is_a<diracgammaR>(e1)) {
503
504                                                         // gammaL/R gamma5 -> gamma5 gammaL/R
505                                                         it->swap(*it2);
506                                                         something_changed = true;
507
508                                                 } else if (!is_a<diracgamma5>(e1)) {
509
510                                                         // gamma5 gamma5 -> gamma5 gamma5 (do nothing)
511                                                         // x gamma5 -> -gamma5 x
512                                                         it->swap(*it2);
513                                                         sign = -sign;
514                                                         something_changed = true;
515                                                 }
516
517                                         } else if (is_a<diracgammaL>(e2)) {
518
519                                                 if (is_a<diracgammaR>(e1)) {
520
521                                                         // gammaR gammaL -> 0
522                                                         return _ex0;
523
524                                                 } else if (!is_a<diracgammaL>(e1) && !is_a<diracgamma5>(e1)) {
525
526                                                         // gammaL gammaL -> gammaL gammaL (do nothing)
527                                                         // gamma5 gammaL -> gamma5 gammaL (do nothing)
528                                                         // x gammaL -> gammaR x
529                                                         it->swap(*it2);
530                                                         *it = clifford(diracgammaR(), ex_to<clifford>(*it).get_representation_label());
531                                                         something_changed = true;
532                                                 }
533
534                                         } else if (is_a<diracgammaR>(e2)) {
535
536                                                 if (is_a<diracgammaL>(e1)) {
537
538                                                         // gammaL gammaR -> 0
539                                                         return _ex0;
540
541                                                 } else if (!is_a<diracgammaR>(e1) && !is_a<diracgamma5>(e1)) {
542
543                                                         // gammaR gammaR -> gammaR gammaR (do nothing)
544                                                         // gamma5 gammaR -> gamma5 gammaR (do nothing)
545                                                         // x gammaR -> gammaL x
546                                                         it->swap(*it2);
547                                                         *it = clifford(diracgammaL(), ex_to<clifford>(*it).get_representation_label());
548                                                         something_changed = true;
549                                                 }
550                                         }
551                                 }
552                                 if (it == first)
553                                         break;
554                                 --it;
555                         }
556                         if (next_to_last == first)
557                                 break;
558                         --next_to_last;
559                 }
560         }
561
562         // Remove equal adjacent gammas
563         if (s.size() >= 2) {
564                 exvector::iterator it, itend = s.end() - 1;
565                 for (it = s.begin(); it != itend; ++it) {
566                         ex & a = it[0];
567                         ex & b = it[1];
568                         if (!is_a<clifford>(a) || !is_a<clifford>(b))
569                                 continue;
570
571                         const ex & ag = a.op(0);
572                         const ex & bg = b.op(0);
573                         bool a_is_cliffordunit = is_a<cliffordunit>(ag);
574                         bool b_is_cliffordunit =  is_a<cliffordunit>(bg);
575
576                         if (a_is_cliffordunit && b_is_cliffordunit && ex_to<clifford>(a).same_metric(b)) {
577
578                                 const ex & ia = a.op(1);
579                                 const ex & ib = b.op(1);
580                                 if (ia.is_equal(ib)) { // gamma~alpha gamma~alpha -> g~alpha~alpha
581                                         a = ex_to<clifford>(a).get_metric(ia, ib);
582                                         b = dirac_ONE(representation_label);
583                                         something_changed = true;
584                                 }
585
586                         } else if ((is_a<diracgamma5>(ag) && is_a<diracgamma5>(bg))) {
587
588                                 // Remove squares of gamma5
589                                 a = dirac_ONE(representation_label);
590                                 b = dirac_ONE(representation_label);
591                                 something_changed = true;
592
593                         } else if ((is_a<diracgammaL>(ag) && is_a<diracgammaL>(bg))
594                                 || (is_a<diracgammaR>(ag) && is_a<diracgammaR>(bg))) {
595
596                                 // Remove squares of gammaL/R
597                                 b = dirac_ONE(representation_label);
598                                 something_changed = true;
599
600                         } else if (is_a<diracgammaL>(ag) && is_a<diracgammaR>(bg)) {
601
602                                 // gammaL and gammaR are orthogonal
603                                 return _ex0;
604
605                         } else if (is_a<diracgamma5>(ag) && is_a<diracgammaL>(bg)) {
606
607                                 // gamma5 gammaL -> -gammaL
608                                 a = dirac_ONE(representation_label);
609                                 sign = -sign;
610                                 something_changed = true;
611
612                         } else if (is_a<diracgamma5>(ag) && is_a<diracgammaR>(bg)) {
613
614                                 // gamma5 gammaR -> gammaR
615                                 a = dirac_ONE(representation_label);
616                                 something_changed = true;
617
618                         } else if (!a_is_cliffordunit && !b_is_cliffordunit && ag.is_equal(bg)) {
619
620                                 // a\ a\ -> a^2
621                                 varidx ix((new symbol)->setflag(status_flags::dynallocated), ex_to<idx>(a.op(1)).minimal_dim(ex_to<idx>(b.op(1))));
622                                 
623                                 a = indexed(ag, ix) * indexed(ag, ix.toggle_variance());
624                                 b = dirac_ONE(representation_label);
625                                 something_changed = true;
626                         }
627                 }
628         }
629
630         if (s.empty())
631                 return clifford(diracone(), representation_label) * sign;
632         if (something_changed)
633                 return reeval_ncmul(s) * sign;
634         else
635                 return hold_ncmul(s) * sign;
636 }
637
638 ex clifford::thiscontainer(const exvector & v) const
639 {
640         return clifford(representation_label, get_metric(), v);
641 }
642
643 ex clifford::thiscontainer(std::auto_ptr<exvector> vp) const
644 {
645         return clifford(representation_label, get_metric(), vp);
646 }
647
648 ex diracgamma5::conjugate() const
649 {       
650         return _ex_1 * (*this);
651 }
652
653 ex diracgammaL::conjugate() const
654 {
655         return (new diracgammaR)->setflag(status_flags::dynallocated);
656 }
657
658 ex diracgammaR::conjugate() const
659 {
660         return (new diracgammaL)->setflag(status_flags::dynallocated);
661 }
662
663 //////////
664 // global functions
665 //////////
666
667 ex dirac_ONE(unsigned char rl)
668 {
669         static ex ONE = (new diracone)->setflag(status_flags::dynallocated);
670         return clifford(ONE, rl);
671 }
672
673 ex clifford_unit(const ex & mu, const ex & metr, unsigned char rl)
674 {
675         static ex unit = (new cliffordunit)->setflag(status_flags::dynallocated);
676
677         if (!is_a<varidx>(mu))
678                 throw(std::invalid_argument("index of Clifford unit must be of type varidx"));
679
680         return clifford(unit, mu, metr, rl);
681 }
682
683 ex dirac_gamma(const ex & mu, unsigned char rl)
684 {
685         static ex gamma = (new diracgamma)->setflag(status_flags::dynallocated);
686
687         if (!is_a<varidx>(mu))
688                 throw(std::invalid_argument("index of Dirac gamma must be of type varidx"));
689
690         return clifford(gamma, mu, default_metric(), rl);
691 }
692
693 ex dirac_gamma5(unsigned char rl)
694 {
695         static ex gamma5 = (new diracgamma5)->setflag(status_flags::dynallocated);
696         return clifford(gamma5, rl);
697 }
698
699 ex dirac_gammaL(unsigned char rl)
700 {
701         static ex gammaL = (new diracgammaL)->setflag(status_flags::dynallocated);
702         return clifford(gammaL, rl);
703 }
704
705 ex dirac_gammaR(unsigned char rl)
706 {
707         static ex gammaR = (new diracgammaR)->setflag(status_flags::dynallocated);
708         return clifford(gammaR, rl);
709 }
710
711 ex dirac_slash(const ex & e, const ex & dim, unsigned char rl)
712 {
713         // Slashed vectors are actually stored as a clifford object with the
714         // vector as its base expression and a (dummy) index that just serves
715         // for storing the space dimensionality
716         return clifford(e, varidx(0, dim), default_metric(), rl);
717 }
718
719 /** Check whether a given tinfo key (as returned by return_type_tinfo()
720  *  is that of a clifford object with the specified representation label. */
721 static bool is_clifford_tinfo(unsigned ti, unsigned char rl)
722 {
723         return ti == (TINFO_clifford + rl);
724 }
725
726 /** Check whether a given tinfo key (as returned by return_type_tinfo()
727  *  is that of a clifford object (with an arbitrary representation label). */
728 static bool is_clifford_tinfo(unsigned ti)
729 {
730         return (ti & ~0xff) == TINFO_clifford;
731 }
732
733 /** Extract representation label from tinfo key (as returned by
734  *  return_type_tinfo()). */
735 static unsigned char get_representation_label(unsigned ti)
736 {
737         return ti & 0xff;
738 }
739
740 /** Take trace of a string of an even number of Dirac gammas given a vector
741  *  of indices. */
742 static ex trace_string(exvector::const_iterator ix, size_t num)
743 {
744         // Tr gamma.mu gamma.nu = 4 g.mu.nu
745         if (num == 2)
746                 return lorentz_g(ix[0], ix[1]);
747
748         // 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 )
749         else if (num == 4)
750                 return lorentz_g(ix[0], ix[1]) * lorentz_g(ix[2], ix[3])
751                      + lorentz_g(ix[1], ix[2]) * lorentz_g(ix[0], ix[3])
752                      - lorentz_g(ix[0], ix[2]) * lorentz_g(ix[1], ix[3]);
753
754         // Traces of 6 or more gammas are computed recursively:
755         // Tr gamma.mu1 gamma.mu2 ... gamma.mun =
756         //   + g.mu1.mu2 * Tr gamma.mu3 ... gamma.mun
757         //   - g.mu1.mu3 * Tr gamma.mu2 gamma.mu4 ... gamma.mun
758         //   + g.mu1.mu4 * Tr gamma.mu3 gamma.mu3 gamma.mu5 ... gamma.mun
759         //   - ...
760         //   + g.mu1.mun * Tr gamma.mu2 ... gamma.mu(n-1)
761         exvector v(num - 2);
762         int sign = 1;
763         ex result;
764         for (size_t i=1; i<num; i++) {
765                 for (size_t n=1, j=0; n<num; n++) {
766                         if (n == i)
767                                 continue;
768                         v[j++] = ix[n];
769                 }
770                 result += sign * lorentz_g(ix[0], ix[i]) * trace_string(v.begin(), num-2);
771                 sign = -sign;
772         }
773         return result;
774 }
775
776 ex dirac_trace(const ex & e, const std::set<unsigned char> & rls, const ex & trONE)
777 {
778         if (is_a<clifford>(e)) {
779
780                 unsigned char rl = ex_to<clifford>(e).get_representation_label();
781
782                 // Are we taking the trace over this object's representation label?
783                 if (rls.find(rl) == rls.end())
784                         return e;
785
786                 // Yes, all elements are traceless, except for dirac_ONE and dirac_L/R
787                 const ex & g = e.op(0);
788                 if (is_a<diracone>(g))
789                         return trONE;
790                 else if (is_a<diracgammaL>(g) || is_a<diracgammaR>(g))
791                         return trONE/2;
792                 else
793                         return _ex0;
794
795         } else if (is_exactly_a<mul>(e)) {
796
797                 // Trace of product: pull out non-clifford factors
798                 ex prod = _ex1;
799                 for (size_t i=0; i<e.nops(); i++) {
800                         const ex &o = e.op(i);
801                         if (is_clifford_tinfo(o.return_type_tinfo()))
802                                 prod *= dirac_trace(o, rls, trONE);
803                         else
804                                 prod *= o;
805                 }
806                 return prod;
807
808         } else if (is_exactly_a<ncmul>(e)) {
809
810                 unsigned char rl = get_representation_label(e.return_type_tinfo());
811
812                 // Are we taking the trace over this string's representation label?
813                 if (rls.find(rl) == rls.end())
814                         return e;
815
816                 // Substitute gammaL/R and expand product, if necessary
817                 ex e_expanded = e.subs(lst(
818                         dirac_gammaL(rl) == (dirac_ONE(rl)-dirac_gamma5(rl))/2,
819                         dirac_gammaR(rl) == (dirac_ONE(rl)+dirac_gamma5(rl))/2
820                 ), subs_options::no_pattern).expand();
821                 if (!is_a<ncmul>(e_expanded))
822                         return dirac_trace(e_expanded, rls, trONE);
823
824                 // gamma5 gets moved to the front so this check is enough
825                 bool has_gamma5 = is_a<diracgamma5>(e.op(0).op(0));
826                 size_t num = e.nops();
827
828                 if (has_gamma5) {
829
830                         // Trace of gamma5 * odd number of gammas and trace of
831                         // gamma5 * gamma.mu * gamma.nu are zero
832                         if ((num & 1) == 0 || num == 3)
833                                 return _ex0;
834
835                         // Tr gamma5 gamma.mu gamma.nu gamma.rho gamma.sigma = 4I * epsilon(mu, nu, rho, sigma)
836                         // (the epsilon is always 4-dimensional)
837                         if (num == 5) {
838                                 ex b1, i1, b2, i2, b3, i3, b4, i4;
839                                 base_and_index(e.op(1), b1, i1);
840                                 base_and_index(e.op(2), b2, i2);
841                                 base_and_index(e.op(3), b3, i3);
842                                 base_and_index(e.op(4), b4, i4);
843                                 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();
844                         }
845
846                         // Tr gamma5 S_2k =
847                         //   I/4! * epsilon0123.mu1.mu2.mu3.mu4 * Tr gamma.mu1 gamma.mu2 gamma.mu3 gamma.mu4 S_2k
848                         // (the epsilon is always 4-dimensional)
849                         exvector ix(num-1), bv(num-1);
850                         for (size_t i=1; i<num; i++)
851                                 base_and_index(e.op(i), bv[i-1], ix[i-1]);
852                         num--;
853                         int *iv = new int[num];
854                         ex result;
855                         for (size_t i=0; i<num-3; i++) {
856                                 ex idx1 = ix[i];
857                                 for (size_t j=i+1; j<num-2; j++) {
858                                         ex idx2 = ix[j];
859                                         for (size_t k=j+1; k<num-1; k++) {
860                                                 ex idx3 = ix[k];
861                                                 for (size_t l=k+1; l<num; l++) {
862                                                         ex idx4 = ix[l];
863                                                         iv[0] = i; iv[1] = j; iv[2] = k; iv[3] = l;
864                                                         exvector v;
865                                                         v.reserve(num - 4);
866                                                         for (size_t n=0, t=4; n<num; n++) {
867                                                                 if (n == i || n == j || n == k || n == l)
868                                                                         continue;
869                                                                 iv[t++] = n;
870                                                                 v.push_back(ix[n]);
871                                                         }
872                                                         int sign = permutation_sign(iv, iv + num);
873                                                         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))
874                                                                 * trace_string(v.begin(), num - 4);
875                                                 }
876                                         }
877                                 }
878                         }
879                         delete[] iv;
880                         return trONE * I * result * mul(bv);
881
882                 } else { // no gamma5
883
884                         // Trace of odd number of gammas is zero
885                         if ((num & 1) == 1)
886                                 return _ex0;
887
888                         // Tr gamma.mu gamma.nu = 4 g.mu.nu
889                         if (num == 2) {
890                                 ex b1, i1, b2, i2;
891                                 base_and_index(e.op(0), b1, i1);
892                                 base_and_index(e.op(1), b2, i2);
893                                 return trONE * (lorentz_g(i1, i2) * b1 * b2).simplify_indexed();
894                         }
895
896                         exvector iv(num), bv(num);
897                         for (size_t i=0; i<num; i++)
898                                 base_and_index(e.op(i), bv[i], iv[i]);
899
900                         return trONE * (trace_string(iv.begin(), num) * mul(bv)).simplify_indexed();
901                 }
902
903         } else if (e.nops() > 0) {
904
905                 // Trace maps to all other container classes (this includes sums)
906                 pointer_to_map_function_2args<const std::set<unsigned char> &, const ex &> fcn(dirac_trace, rls, trONE);
907                 return e.map(fcn);
908
909         } else
910                 return _ex0;
911 }
912
913 ex dirac_trace(const ex & e, const lst & rll, const ex & trONE)
914 {
915         // Convert list to set
916         std::set<unsigned char> rls;
917         for (lst::const_iterator i = rll.begin(); i != rll.end(); ++i) {
918                 if (i->info(info_flags::nonnegint))
919                         rls.insert(ex_to<numeric>(*i).to_int());
920         }
921
922         return dirac_trace(e, rls, trONE);
923 }
924
925 ex dirac_trace(const ex & e, unsigned char rl, const ex & trONE)
926 {
927         // Convert label to set
928         std::set<unsigned char> rls;
929         rls.insert(rl);
930
931         return dirac_trace(e, rls, trONE);
932 }
933
934
935 ex canonicalize_clifford(const ex & e)
936 {
937         // Scan for any ncmul objects
938         exmap srl;
939         ex aux = e.to_rational(srl);
940         for (exmap::iterator i = srl.begin(); i != srl.end(); ++i) {
941
942                 ex lhs = i->first;
943                 ex rhs = i->second;
944
945                 if (is_exactly_a<ncmul>(rhs)
946                  && rhs.return_type() == return_types::noncommutative
947                  && is_clifford_tinfo(rhs.return_type_tinfo())) {
948
949                         // Expand product, if necessary
950                         ex rhs_expanded = rhs.expand();
951                         if (!is_a<ncmul>(rhs_expanded)) {
952                                 i->second = canonicalize_clifford(rhs_expanded);
953                                 continue;
954
955                         } else if (!is_a<clifford>(rhs.op(0)))
956                                 continue;
957
958                         exvector v;
959                         v.reserve(rhs.nops());
960                         for (size_t j=0; j<rhs.nops(); j++)
961                                 v.push_back(rhs.op(j));
962
963                         // Stupid recursive bubble sort because we only want to swap adjacent gammas
964                         exvector::iterator it = v.begin(), next_to_last = v.end() - 1;
965                         if (is_a<diracgamma5>(it->op(0)) || is_a<diracgammaL>(it->op(0)) || is_a<diracgammaR>(it->op(0)))
966                                 ++it;
967                         while (it != next_to_last) {
968                                 if (it[0].compare(it[1]) > 0) {
969                                         ex save0 = it[0], save1 = it[1];
970                                         ex b1, i1, b2, i2;
971                                         base_and_index(it[0], b1, i1);
972                                         base_and_index(it[1], b2, i2);
973                                         it[0] = (ex_to<clifford>(save0).get_metric(i1, i2) * b1 * b2).simplify_indexed();
974                                         it[1] = v.size() == 2 ? _ex2 * dirac_ONE(ex_to<clifford>(it[1]).get_representation_label()) : _ex2;
975                                         ex sum = ncmul(v);
976                                         it[0] = save1;
977                                         it[1] = save0;
978                                         sum -= ncmul(v, true);
979                                         i->second = canonicalize_clifford(sum);
980                                         goto next_sym;
981                                 }
982                                 ++it;
983                         }
984 next_sym:       ;
985                 }
986         }
987         return aux.subs(srl, subs_options::no_pattern).simplify_indexed();
988 }
989
990 ex clifford_prime(const ex &e)
991 {
992         pointer_to_map_function fcn(clifford_prime);
993         if (is_a<clifford>(e) && is_a<cliffordunit>(e.op(0))) {
994                 return -e;
995         } else if (is_a<add>(e)) {
996                 return e.map(fcn);
997         } else if (is_a<ncmul>(e)) {
998                 return e.map(fcn);
999         } else if (is_a<power>(e)) {
1000                 return pow(clifford_prime(e.op(0)), e.op(1));
1001         } else
1002                 return e;
1003 }
1004
1005 ex delete_ONE(const ex &e)
1006 {
1007         pointer_to_map_function fcn(delete_ONE);
1008         if (is_a<clifford>(e) && is_a<diracone>(e.op(0))) {
1009                 return 1;
1010         } else if (is_a<add>(e)) {
1011                 return e.map(fcn);
1012         } else if (is_a<ncmul>(e)) {
1013                 return e.map(fcn);
1014         } else if (is_a<mul>(e)) {
1015                 return e.map(fcn);
1016         } else if (is_a<power>(e)) {
1017                 return pow(delete_ONE(e.op(0)), e.op(1));
1018         } else
1019                 return e;
1020 }
1021
1022 ex clifford_norm(const ex &e)
1023 {
1024         return sqrt(delete_ONE((e * clifford_bar(e)).simplify_indexed()));
1025 }
1026
1027 ex clifford_inverse(const ex &e)
1028 {
1029         ex norm = clifford_norm(e);
1030         if (!norm.is_zero())
1031                 return clifford_bar(e) / pow(norm, 2);
1032 }
1033
1034 ex lst_to_clifford(const ex & v, const ex & mu, const ex & metr, unsigned char rl)
1035 {
1036         unsigned min, max;
1037         if (!ex_to<idx>(mu).is_dim_numeric())
1038                 throw(std::invalid_argument("Index should have a numeric dimension"));
1039         unsigned dim = (ex_to<numeric>(ex_to<idx>(mu).get_dim())).to_int();
1040         ex c = clifford_unit(mu, metr, rl);
1041
1042         if (is_a<matrix>(v)) {
1043                 if (ex_to<matrix>(v).cols() > ex_to<matrix>(v).rows()) {
1044                         min = ex_to<matrix>(v).rows();
1045                         max = ex_to<matrix>(v).cols();
1046                 } else {
1047                         min = ex_to<matrix>(v).cols();
1048                         max = ex_to<matrix>(v).rows();
1049                 }
1050                 if (min == 1) {
1051                         if (dim == max)
1052                                 if (is_a<varidx>(mu)) // need to swap variance
1053                                         return indexed(v, ex_to<varidx>(mu).toggle_variance()) * c;
1054                                 else
1055                                         return indexed(v, mu) * c;
1056                         else
1057                                 throw(std::invalid_argument("Dimensions of vector and clifford unit mismatch"));
1058                 } else
1059                         throw(std::invalid_argument("First argument should be a vector vector"));
1060         } else if (is_a<lst>(v)) {
1061                 if (dim == ex_to<lst>(v).nops())
1062                         return indexed(matrix(dim, 1, ex_to<lst>(v)), ex_to<varidx>(mu).toggle_variance()) * c;
1063                 else
1064                         throw(std::invalid_argument("List length and dimension of clifford unit mismatch"));
1065         } else
1066                 throw(std::invalid_argument("Cannot construct from anything but list or vector"));
1067 }
1068  
1069 } // namespace GiNaC