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