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