fixed coding style and stuff...
[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(sy_none(), 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(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         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         return clifford(diracone(), rl);
638 }
639
640 ex clifford_unit(const ex & mu, const ex & metr, unsigned char rl)
641 {
642         if (!is_a<varidx>(mu))
643                 throw(std::invalid_argument("index of Clifford unit must be of type varidx"));
644         if (!is_a<indexed>(metr))
645                 throw(std::invalid_argument("metric for Clifford unit must be of type indexed"));
646         exvector d = ex_to<indexed>(metr).get_indices();
647         if (d.size() > 2 || ex_to<idx>(d[0]).get_dim() != ex_to<idx>(d[1]).get_dim())
648           //|| ex_to<idx>(d[0]).get_dim() != ex_to<idx>(mu).get_dim())
649                 throw(std::invalid_argument("metric is not square"));
650         else
651                 ex_to<idx>(mu).replace_dim(ex_to<idx>(d[0]).get_dim());
652         return clifford(cliffordunit(), mu, metr, rl);
653 }
654
655 ex dirac_gamma(const ex & mu, unsigned char rl)
656 {
657         if (!is_a<varidx>(mu))
658                 throw(std::invalid_argument("index of Dirac gamma must be of type varidx"));
659
660         ex dim = ex_to<idx>(mu).get_dim();
661         return clifford(diracgamma(), mu, lorentz_g(varidx((new symbol)->setflag(status_flags::dynallocated), dim),varidx((new symbol)->setflag(status_flags::dynallocated), dim)), rl);
662 }
663
664 ex dirac_gamma5(unsigned char rl)
665 {
666         return clifford(diracgamma5(), rl);
667 }
668
669 ex dirac_gammaL(unsigned char rl)
670 {
671         return clifford(diracgammaL(), rl);
672 }
673
674 ex dirac_gammaR(unsigned char rl)
675 {
676         return clifford(diracgammaR(), rl);
677 }
678
679 ex dirac_slash(const ex & e, const ex & dim, unsigned char rl)
680 {
681         // Slashed vectors are actually stored as a clifford object with the
682         // vector as its base expression and a (dummy) index that just serves
683         // for storing the space dimensionality
684         return clifford(e, varidx(0, dim), rl);
685 }
686
687 /** Check whether a given tinfo key (as returned by return_type_tinfo()
688  *  is that of a clifford object with the specified representation label. */
689 static bool is_clifford_tinfo(unsigned ti, unsigned char rl)
690 {
691         return ti == (TINFO_clifford + rl);
692 }
693
694 /** Check whether a given tinfo key (as returned by return_type_tinfo()
695  *  is that of a clifford object (with an arbitrary representation label). */
696 static bool is_clifford_tinfo(unsigned ti)
697 {
698         return (ti & ~0xff) == TINFO_clifford;
699 }
700
701 /** Take trace of a string of an even number of Dirac gammas given a vector
702  *  of indices. */
703 static ex trace_string(exvector::const_iterator ix, size_t num)
704 {
705         // Tr gamma.mu gamma.nu = 4 g.mu.nu
706         if (num == 2)
707                 return lorentz_g(ix[0], ix[1]);
708
709         // 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 )
710         else if (num == 4)
711                 return lorentz_g(ix[0], ix[1]) * lorentz_g(ix[2], ix[3])
712                      + lorentz_g(ix[1], ix[2]) * lorentz_g(ix[0], ix[3])
713                      - lorentz_g(ix[0], ix[2]) * lorentz_g(ix[1], ix[3]);
714
715         // Traces of 6 or more gammas are computed recursively:
716         // Tr gamma.mu1 gamma.mu2 ... gamma.mun =
717         //   + g.mu1.mu2 * Tr gamma.mu3 ... gamma.mun
718         //   - g.mu1.mu3 * Tr gamma.mu2 gamma.mu4 ... gamma.mun
719         //   + g.mu1.mu4 * Tr gamma.mu3 gamma.mu3 gamma.mu5 ... gamma.mun
720         //   - ...
721         //   + g.mu1.mun * Tr gamma.mu2 ... gamma.mu(n-1)
722         exvector v(num - 2);
723         int sign = 1;
724         ex result;
725         for (size_t i=1; i<num; i++) {
726                 for (size_t n=1, j=0; n<num; n++) {
727                         if (n == i)
728                                 continue;
729                         v[j++] = ix[n];
730                 }
731                 result += sign * lorentz_g(ix[0], ix[i]) * trace_string(v.begin(), num-2);
732                 sign = -sign;
733         }
734         return result;
735 }
736
737 ex dirac_trace(const ex & e, unsigned char rl, const ex & trONE)
738 {
739         if (is_a<clifford>(e)) {
740
741                 if (!ex_to<clifford>(e).get_representation_label() == rl)
742                         return _ex0;
743                 const ex & g = e.op(0);
744                 if (is_a<diracone>(g))
745                         return trONE;
746                 else if (is_a<diracgammaL>(g) || is_a<diracgammaR>(g))
747                         return trONE/2;
748                 else
749                         return _ex0;
750
751         } else if (is_exactly_a<mul>(e)) {
752
753                 // Trace of product: pull out non-clifford factors
754                 ex prod = _ex1;
755                 for (size_t i=0; i<e.nops(); i++) {
756                         const ex &o = e.op(i);
757                         if (is_clifford_tinfo(o.return_type_tinfo(), rl))
758                                 prod *= dirac_trace(o, rl, trONE);
759                         else
760                                 prod *= o;
761                 }
762                 return prod;
763
764         } else if (is_exactly_a<ncmul>(e)) {
765
766                 if (!is_clifford_tinfo(e.return_type_tinfo(), rl))
767                         return _ex0;
768
769                 // Substitute gammaL/R and expand product, if necessary
770                 ex e_expanded = e.subs(lst(
771                         dirac_gammaL(rl) == (dirac_ONE(rl)-dirac_gamma5(rl))/2,
772                         dirac_gammaR(rl) == (dirac_ONE(rl)+dirac_gamma5(rl))/2
773                 ), subs_options::no_pattern).expand();
774                 if (!is_a<ncmul>(e_expanded))
775                         return dirac_trace(e_expanded, rl, trONE);
776
777                 // gamma5 gets moved to the front so this check is enough
778                 bool has_gamma5 = is_a<diracgamma5>(e.op(0).op(0));
779                 size_t num = e.nops();
780
781                 if (has_gamma5) {
782
783                         // Trace of gamma5 * odd number of gammas and trace of
784                         // gamma5 * gamma.mu * gamma.nu are zero
785                         if ((num & 1) == 0 || num == 3)
786                                 return _ex0;
787
788                         // Tr gamma5 gamma.mu gamma.nu gamma.rho gamma.sigma = 4I * epsilon(mu, nu, rho, sigma)
789                         // (the epsilon is always 4-dimensional)
790                         if (num == 5) {
791                                 ex b1, i1, b2, i2, b3, i3, b4, i4;
792                                 base_and_index(e.op(1), b1, i1);
793                                 base_and_index(e.op(2), b2, i2);
794                                 base_and_index(e.op(3), b3, i3);
795                                 base_and_index(e.op(4), b4, i4);
796                                 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();
797                         }
798
799                         // Tr gamma5 S_2k =
800                         //   I/4! * epsilon0123.mu1.mu2.mu3.mu4 * Tr gamma.mu1 gamma.mu2 gamma.mu3 gamma.mu4 S_2k
801                         // (the epsilon is always 4-dimensional)
802                         exvector ix(num-1), bv(num-1);
803                         for (size_t i=1; i<num; i++)
804                                 base_and_index(e.op(i), bv[i-1], ix[i-1]);
805                         num--;
806                         int *iv = new int[num];
807                         ex result;
808                         for (size_t i=0; i<num-3; i++) {
809                                 ex idx1 = ix[i];
810                                 for (size_t j=i+1; j<num-2; j++) {
811                                         ex idx2 = ix[j];
812                                         for (size_t k=j+1; k<num-1; k++) {
813                                                 ex idx3 = ix[k];
814                                                 for (size_t l=k+1; l<num; l++) {
815                                                         ex idx4 = ix[l];
816                                                         iv[0] = i; iv[1] = j; iv[2] = k; iv[3] = l;
817                                                         exvector v;
818                                                         v.reserve(num - 4);
819                                                         for (size_t n=0, t=4; n<num; n++) {
820                                                                 if (n == i || n == j || n == k || n == l)
821                                                                         continue;
822                                                                 iv[t++] = n;
823                                                                 v.push_back(ix[n]);
824                                                         }
825                                                         int sign = permutation_sign(iv, iv + num);
826                                                         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))
827                                                                 * trace_string(v.begin(), num - 4);
828                                                 }
829                                         }
830                                 }
831                         }
832                         delete[] iv;
833                         return trONE * I * result * mul(bv);
834
835                 } else { // no gamma5
836
837                         // Trace of odd number of gammas is zero
838                         if ((num & 1) == 1)
839                                 return _ex0;
840
841                         // Tr gamma.mu gamma.nu = 4 g.mu.nu
842                         if (num == 2) {
843                                 ex b1, i1, b2, i2;
844                                 base_and_index(e.op(0), b1, i1);
845                                 base_and_index(e.op(1), b2, i2);
846                                 return trONE * (lorentz_g(i1, i2) * b1 * b2).simplify_indexed();
847                         }
848
849                         exvector iv(num), bv(num);
850                         for (size_t i=0; i<num; i++)
851                                 base_and_index(e.op(i), bv[i], iv[i]);
852
853                         return trONE * (trace_string(iv.begin(), num) * mul(bv)).simplify_indexed();
854                 }
855
856         } else if (e.nops() > 0) {
857
858                 // Trace maps to all other container classes (this includes sums)
859                 pointer_to_map_function_2args<unsigned char, const ex &> fcn(dirac_trace, rl, trONE);
860                 return e.map(fcn);
861
862         } else
863                 return _ex0;
864 }
865
866 ex canonicalize_clifford(const ex & e)
867 {
868         // Scan for any ncmul objects
869         exmap srl;
870         ex aux = e.to_rational(srl);
871         for (exmap::iterator i = srl.begin(); i != srl.end(); ++i) {
872
873                 ex lhs = i->first;
874                 ex rhs = i->second;
875
876                 if (is_exactly_a<ncmul>(rhs)
877                  && rhs.return_type() == return_types::noncommutative
878                  && is_clifford_tinfo(rhs.return_type_tinfo())) {
879
880                         // Expand product, if necessary
881                         ex rhs_expanded = rhs.expand();
882                         if (!is_a<ncmul>(rhs_expanded)) {
883                                 i->second = canonicalize_clifford(rhs_expanded);
884                                 continue;
885
886                         } else if (!is_a<clifford>(rhs.op(0)))
887                                 continue;
888
889                         exvector v;
890                         v.reserve(rhs.nops());
891                         for (size_t j=0; j<rhs.nops(); j++)
892                                 v.push_back(rhs.op(j));
893
894                         // Stupid recursive bubble sort because we only want to swap adjacent gammas
895                         exvector::iterator it = v.begin(), next_to_last = v.end() - 1;
896                         if (is_a<diracgamma5>(it->op(0)) || is_a<diracgammaL>(it->op(0)) || is_a<diracgammaR>(it->op(0)))
897                                 ++it;
898                         while (it != next_to_last) {
899                                 if (it[0].compare(it[1]) > 0) {
900                                         ex save0 = it[0], save1 = it[1];
901                                         ex b1, i1, b2, i2;
902                                         base_and_index(it[0], b1, i1);
903                                         base_and_index(it[1], b2, i2);
904                                         it[0] = (ex_to<clifford>(save0).get_metric(i1, i2) * b1 * b2).simplify_indexed();
905                                         it[1] = v.size() == 2 ? _ex2 * dirac_ONE(ex_to<clifford>(it[1]).get_representation_label()) : _ex2;
906                                         ex sum = ncmul(v);
907                                         it[0] = save1;
908                                         it[1] = save0;
909                                         sum -= ncmul(v, true);
910                                         i->second = canonicalize_clifford(sum);
911                                         goto next_sym;
912                                 }
913                                 ++it;
914                         }
915 next_sym:       ;
916                 }
917         }
918         return aux.subs(srl, subs_options::no_pattern).simplify_indexed();
919 }
920
921 ex clifford_prime(const ex &e)
922 {
923         pointer_to_map_function fcn(clifford_prime);
924         if (is_a<clifford>(e) && is_a<cliffordunit>(e.op(0))) {
925                 return -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         } else
933                 return e;
934 }
935
936 ex delete_ONE(const ex &e)
937 {
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         } else
950                 return e;
951 }
952
953 ex clifford_norm(const ex &e)
954 {
955         return sqrt(delete_ONE((e * clifford_bar(e)).simplify_indexed()));
956 }
957
958 ex clifford_inverse(const ex &e)
959 {
960         ex norm = clifford_norm(e);
961         if (!norm.is_zero())
962                 return clifford_bar(e) / pow(norm, 2);
963 }
964
965 ex lst_to_clifford(const ex & v, const ex & mu, const ex & metr, unsigned char rl)
966 {
967         unsigned min, max;
968         if (!ex_to<idx>(mu).is_dim_numeric())
969                 throw(std::invalid_argument("Index should have a numeric dimension"));
970         unsigned dim = (ex_to<numeric>(ex_to<idx>(mu).get_dim())).to_int();
971         ex c = clifford_unit(mu, metr, rl);
972
973         if (is_a<matrix>(v)) {
974                 if (ex_to<matrix>(v).cols() > ex_to<matrix>(v).rows()) {
975                         min = ex_to<matrix>(v).rows();
976                         max = ex_to<matrix>(v).cols();
977                 } else {
978                         min = ex_to<matrix>(v).cols();
979                         max = ex_to<matrix>(v).rows();
980                 }
981                 if (min == 1) {
982                         if (dim == max)
983                                 if (is_a<varidx>(mu)) // need to swap variance
984                                         return indexed(v, ex_to<varidx>(mu).toggle_variance()) * c;
985                                 else
986                                         return indexed(v, mu) * c;
987                         else
988                                 throw(std::invalid_argument("Dimensions of vector and clifford unit mismatch"));
989                 } else
990                         throw(std::invalid_argument("First argument should be a vector vector"));
991         } else if (is_a<lst>(v)) {
992                 if (dim == ex_to<lst>(v).nops())
993                         return indexed(matrix(dim, 1, ex_to<lst>(v)), ex_to<varidx>(mu).toggle_variance()) * c;
994                 else
995                         throw(std::invalid_argument("List length and dimension of clifford unit mismatch"));
996         } else
997                 throw(std::invalid_argument("Cannot construct from anything but list or vector"));
998 }
999  
1000 } // namespace GiNaC