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