]> www.ginac.de Git - ginac.git/blob - ginac/clifford.cpp
* Deleted bogus try -- catch block in the ex::series() [Sheplyakov].
[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-2007 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
21  */
22
23 #include <stdexcept>
24
25 #include "clifford.h"
26
27 #include "ex.h"
28 #include "idx.h"
29 #include "ncmul.h"
30 #include "symbol.h"
31 #include "numeric.h" // for I
32 #include "symmetry.h"
33 #include "lst.h"
34 #include "relational.h"
35 #include "operators.h"
36 #include "add.h"
37 #include "mul.h"
38 #include "power.h"
39 #include "matrix.h"
40 #include "archive.h"
41 #include "utils.h"
42
43 namespace GiNaC {
44
45 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(clifford, indexed,
46   print_func<print_dflt>(&clifford::do_print_dflt).
47   print_func<print_latex>(&clifford::do_print_latex))
48
49 const tinfo_static_t clifford::return_type_tinfo_static[256] = {{}};
50
51 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(diracone, tensor,
52   print_func<print_dflt>(&diracone::do_print).
53   print_func<print_latex>(&diracone::do_print_latex))
54
55 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(cliffordunit, tensor,
56   print_func<print_dflt>(&cliffordunit::do_print).
57   print_func<print_latex>(&cliffordunit::do_print_latex))
58
59 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(diracgamma, cliffordunit,
60   print_func<print_dflt>(&diracgamma::do_print).
61   print_func<print_latex>(&diracgamma::do_print_latex))
62
63 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(diracgamma5, tensor,
64   print_func<print_dflt>(&diracgamma5::do_print).
65   print_func<print_latex>(&diracgamma5::do_print_latex))
66
67 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(diracgammaL, tensor,
68   print_func<print_context>(&diracgammaL::do_print).
69   print_func<print_latex>(&diracgammaL::do_print_latex))
70
71 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(diracgammaR, tensor,
72   print_func<print_context>(&diracgammaR::do_print).
73   print_func<print_latex>(&diracgammaR::do_print_latex))
74
75 //////////
76 // default constructors
77 //////////
78
79 clifford::clifford() : representation_label(0), metric(0), commutator_sign(-1)
80 {
81         tinfo_key = &clifford::tinfo_static;
82 }
83
84 DEFAULT_CTOR(diracone)
85 DEFAULT_CTOR(cliffordunit)
86 DEFAULT_CTOR(diracgamma)
87 DEFAULT_CTOR(diracgamma5)
88 DEFAULT_CTOR(diracgammaL)
89 DEFAULT_CTOR(diracgammaR)
90
91 //////////
92 // other constructors
93 //////////
94
95 /** Construct object without any indices. This constructor is for internal
96  *  use only. Use the dirac_ONE() function instead.
97  *  @see dirac_ONE */
98 clifford::clifford(const ex & b, unsigned char rl) : inherited(b), representation_label(rl), metric(0), commutator_sign(-1)
99 {
100         tinfo_key = &clifford::tinfo_static;
101 }
102
103 /** Construct object with one Lorentz index. This constructor is for internal
104  *  use only. Use the clifford_unit() or dirac_gamma() functions instead.
105  *  @see clifford_unit
106  *  @see dirac_gamma */
107 clifford::clifford(const ex & b, const ex & mu, const ex & metr, unsigned char rl, int comm_sign) : inherited(b, mu), representation_label(rl), metric(metr), commutator_sign(comm_sign)
108 {
109         GINAC_ASSERT(is_a<varidx>(mu));
110         tinfo_key = &clifford::tinfo_static;
111 }
112
113 clifford::clifford(unsigned char rl, const ex & metr, int comm_sign, const exvector & v, bool discardable) : inherited(not_symmetric(), v, discardable), representation_label(rl), metric(metr), commutator_sign(comm_sign)
114 {
115         tinfo_key = &clifford::tinfo_static;
116 }
117
118 clifford::clifford(unsigned char rl, const ex & metr, int comm_sign, std::auto_ptr<exvector> vp) : inherited(not_symmetric(), vp), representation_label(rl), metric(metr), commutator_sign(comm_sign)
119 {
120         tinfo_key = &clifford::tinfo_static;
121 }
122
123 //////////
124 // archiving
125 //////////
126
127 clifford::clifford(const archive_node & n, lst & sym_lst) : inherited(n, sym_lst)
128 {
129         unsigned rl;
130         n.find_unsigned("label", rl);
131         representation_label = rl;
132         n.find_ex("metric", metric, sym_lst);
133         n.find_unsigned("commutator_sign+1", rl);
134         commutator_sign = rl - 1;
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         n.add_unsigned("commutator_sign+1", commutator_sign+1);
143 }
144
145 DEFAULT_UNARCHIVE(clifford)
146 DEFAULT_ARCHIVING(diracone)
147 DEFAULT_ARCHIVING(cliffordunit)
148 DEFAULT_ARCHIVING(diracgamma)
149 DEFAULT_ARCHIVING(diracgamma5)
150 DEFAULT_ARCHIVING(diracgammaL)
151 DEFAULT_ARCHIVING(diracgammaR)
152
153
154 ex clifford::get_metric(const ex & i, const ex & j, bool symmetrised) const
155 {
156         if (is_a<indexed>(metric)) {
157                 if (symmetrised && !(ex_to<symmetry>(ex_to<indexed>(metric).get_symmetry()).has_symmetry())) {
158                         if (is_a<matrix>(metric.op(0))) {
159                                 return indexed((ex_to<matrix>(metric.op(0)).add(ex_to<matrix>(metric.op(0)).transpose())).mul(numeric(1, 2)),
160                                                symmetric2(), i, j);
161                         } else {
162                                 return simplify_indexed(indexed(metric.op(0)*_ex1_2, i, j) + indexed(metric.op(0)*_ex1_2, j, i));
163                         }
164                 } else {
165                         return metric.subs(lst(metric.op(1) == i, metric.op(2) == j), subs_options::no_pattern);
166                 }
167         } else {
168                 exvector indices = metric.get_free_indices();
169                 if (symmetrised)
170                         return _ex1_2*simplify_indexed(metric.subs(lst(indices[0] == i, indices[1] == j), subs_options::no_pattern)
171                                                                         + metric.subs(lst(indices[0] == j, indices[1] == i), subs_options::no_pattern));
172                 else
173                         return metric.subs(lst(indices[0] == i, indices[1] == j), subs_options::no_pattern);
174         }
175 }
176
177 bool clifford::same_metric(const ex & other) const
178 {
179         ex metr;
180         if (is_a<clifford>(other)) 
181                 metr = ex_to<clifford>(other).get_metric();
182         else 
183                 metr = other;
184
185         if (is_a<indexed>(metr))
186                 return metr.op(0).is_equal(get_metric().op(0));
187         else {
188                 exvector indices = metr.get_free_indices();
189                 return  (indices.size() == 2) 
190                         && simplify_indexed(get_metric(indices[0], indices[1])-metr).is_zero();
191         }
192 }
193
194 //////////
195 // functions overriding virtual functions from base classes
196 //////////
197
198 ex clifford::op(size_t i) const
199 {
200         GINAC_ASSERT(i<nops());
201         if (nops()-i == 1)
202                 return representation_label;
203         else 
204                 return inherited::op(i);
205 }
206
207 ex & clifford::let_op(size_t i)
208 {
209         GINAC_ASSERT(i<nops());
210
211         static ex rl = numeric(representation_label);
212         ensure_if_modifiable();
213         if (nops()-i == 1)
214                 return rl;
215         else 
216                 return inherited::let_op(i);
217 }
218
219 ex clifford::subs(const exmap & m, unsigned options) const
220 {
221         ex subsed = inherited::subs(m, options);
222         if(is_a<clifford>(subsed)) {
223                 ex prevmetric = ex_to<clifford>(subsed).metric;
224                 ex newmetric = prevmetric.subs(m, options);
225                 if(!are_ex_trivially_equal(prevmetric, newmetric)) {
226                         clifford c = ex_to<clifford>(subsed);
227                         c.metric = newmetric;
228                         subsed = c;
229                 }
230         }
231         return subsed;
232 }
233
234 int clifford::compare_same_type(const basic & other) const
235 {
236         GINAC_ASSERT(is_a<clifford>(other));
237         const clifford &o = static_cast<const clifford &>(other);
238
239         if (representation_label != o.representation_label) {
240                 // different representation label
241                 return representation_label < o.representation_label ? -1 : 1;
242         }
243
244         return inherited::compare_same_type(other);
245 }
246
247 bool clifford::match_same_type(const basic & other) const
248 {
249         GINAC_ASSERT(is_a<clifford>(other));
250         const clifford &o = static_cast<const clifford &>(other);
251
252         return ((representation_label == o.representation_label) && (commutator_sign == o.get_commutator_sign()) && same_metric(o));
253 }
254
255 static bool is_dirac_slash(const ex & seq0)
256 {
257         return !is_a<diracgamma5>(seq0) && !is_a<diracgammaL>(seq0) &&
258                !is_a<diracgammaR>(seq0) && !is_a<cliffordunit>(seq0) &&
259                !is_a<diracone>(seq0);
260 }
261
262 void clifford::do_print_dflt(const print_dflt & c, unsigned level) const
263 {
264         // dirac_slash() object is printed differently
265         if (is_dirac_slash(seq[0])) {
266                 seq[0].print(c, precedence());
267                 c.s << "\\";
268         } else { // We do not print representation label if it is 0
269                 if (representation_label == 0) {
270                         this->print_dispatch<inherited>(c, level);
271                 } else { // otherwise we put it before indices in square brackets; the code is borrowed from indexed.cpp 
272                         if (precedence() <= level) {
273                                 c.s << '(';
274                         }
275                         seq[0].print(c, precedence());
276                         c.s << '[' << int(representation_label) << ']';
277                         printindices(c, level);
278                         if (precedence() <= level) {
279                                 c.s << ')';
280                         }
281                 }
282         }
283 }
284
285 void clifford::do_print_latex(const print_latex & c, unsigned level) const
286 {
287         // dirac_slash() object is printed differently
288         if (is_dirac_slash(seq[0])) {
289                 c.s << "{";
290                 seq[0].print(c, precedence());
291                 c.s << "\\hspace{-1.0ex}/}";
292         } else {
293                 c.s << "\\clifford[" << int(representation_label) << "]";
294                 this->print_dispatch<inherited>(c, level);
295         }
296 }
297
298 DEFAULT_COMPARE(diracone)
299 DEFAULT_COMPARE(cliffordunit)
300 DEFAULT_COMPARE(diracgamma)
301 DEFAULT_COMPARE(diracgamma5)
302 DEFAULT_COMPARE(diracgammaL)
303 DEFAULT_COMPARE(diracgammaR)
304
305 DEFAULT_PRINT_LATEX(diracone, "ONE", "\\mathbf{1}")
306 DEFAULT_PRINT_LATEX(cliffordunit, "e", "e")
307 DEFAULT_PRINT_LATEX(diracgamma, "gamma", "\\gamma")
308 DEFAULT_PRINT_LATEX(diracgamma5, "gamma5", "{\\gamma^5}")
309 DEFAULT_PRINT_LATEX(diracgammaL, "gammaL", "{\\gamma_L}")
310 DEFAULT_PRINT_LATEX(diracgammaR, "gammaR", "{\\gamma_R}")
311
312 /** This function decomposes gamma~mu -> (1, mu) and a\ -> (a.ix, ix) */
313 static void base_and_index(const ex & c, ex & b, ex & i)
314 {
315         GINAC_ASSERT(is_a<clifford>(c));
316         GINAC_ASSERT(c.nops() == 2+1);
317
318         if (is_a<cliffordunit>(c.op(0))) { // proper dirac gamma object or clifford unit
319                 i = c.op(1);
320                 b = _ex1;
321         } else if (is_a<diracgamma5>(c.op(0)) || is_a<diracgammaL>(c.op(0)) || is_a<diracgammaR>(c.op(0))) { // gamma5/L/R
322                 i = _ex0;
323                 b = _ex1;
324         } else { // slash object, generate new dummy index
325                 varidx ix((new symbol)->setflag(status_flags::dynallocated), ex_to<idx>(c.op(1)).get_dim());
326                 b = indexed(c.op(0), ix.toggle_variance());
327                 i = ix;
328         }
329 }
330
331 /** Predicate for finding non-clifford objects. */
332 struct is_not_a_clifford : public std::unary_function<ex, bool> {
333         bool operator()(const ex & e)
334         {
335                 return !is_a<clifford>(e);
336         }
337 };
338
339 /** Contraction of a gamma matrix with something else. */
340 bool diracgamma::contract_with(exvector::iterator self, exvector::iterator other, exvector & v) const
341 {
342         GINAC_ASSERT(is_a<clifford>(*self));
343         GINAC_ASSERT(is_a<indexed>(*other));
344         GINAC_ASSERT(is_a<diracgamma>(self->op(0)));
345         unsigned char rl = ex_to<clifford>(*self).get_representation_label();
346
347         ex dim = ex_to<idx>(self->op(1)).get_dim();
348         if (other->nops() > 1)
349                 dim = minimal_dim(dim, ex_to<idx>(other->op(1)).get_dim());
350
351         if (is_a<clifford>(*other)) {
352
353                 // Contraction only makes sense if the represenation labels are equal
354                 if (ex_to<clifford>(*other).get_representation_label() != rl)
355                         return false;
356
357                 size_t num = other - self;
358
359                 // gamma~mu gamma.mu = dim ONE
360                 if (num == 1) {
361                         *self = dim;
362                         *other = dirac_ONE(rl);
363                         return true;
364
365                 // gamma~mu gamma~alpha gamma.mu = (2-dim) gamma~alpha
366                 } else if (num == 2
367                         && is_a<clifford>(self[1])) {
368                         *self = 2 - dim;
369                         *other = _ex1;
370                         return true;
371
372                 // gamma~mu gamma~alpha gamma~beta gamma.mu = 4 g~alpha~beta + (dim-4) gamam~alpha gamma~beta
373                 } else if (num == 3
374                         && is_a<clifford>(self[1])
375                         && is_a<clifford>(self[2])) {
376                         ex b1, i1, b2, i2;
377                         base_and_index(self[1], b1, i1);
378                         base_and_index(self[2], b2, i2);
379                         *self = 4 * lorentz_g(i1, i2) * b1 * b2 * dirac_ONE(rl) + (dim - 4) * self[1] * self[2];
380                         self[1] = _ex1;
381                         self[2] = _ex1;
382                         *other = _ex1;
383                         return true;
384
385                 // 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
386                 } else if (num == 4
387                         && is_a<clifford>(self[1])
388                         && is_a<clifford>(self[2])
389                         && is_a<clifford>(self[3])) {
390                         *self = -2 * self[3] * self[2] * self[1] - (dim - 4) * self[1] * self[2] * self[3];
391                         self[1] = _ex1;
392                         self[2] = _ex1;
393                         self[3] = _ex1;
394                         *other = _ex1;
395                         return true;
396
397                 // gamma~mu Sodd gamma.mu = -2 Sodd_R
398                 // (Chisholm identity in 4 dimensions)
399                 } else if (!((other - self) & 1) && dim.is_equal(4)) {
400                         if (std::find_if(self + 1, other, is_not_a_clifford()) != other)
401                                 return false;
402
403                         *self = ncmul(exvector(std::reverse_iterator<exvector::const_iterator>(other), std::reverse_iterator<exvector::const_iterator>(self + 1)), true);
404                         std::fill(self + 1, other, _ex1);
405                         *other = _ex_2;
406                         return true;
407
408                 // gamma~mu Sodd gamma~alpha gamma.mu = 2 gamma~alpha Sodd + 2 Sodd_R gamma~alpha
409                 // (commutate contracted indices towards each other, then use
410                 // Chisholm identity in 4 dimensions)
411                 } else if (((other - self) & 1) && dim.is_equal(4)) {
412                         if (std::find_if(self + 1, other, is_not_a_clifford()) != other)
413                                 return false;
414
415                         exvector::iterator next_to_last = other - 1;
416                         ex S = ncmul(exvector(self + 1, next_to_last), true);
417                         ex SR = ncmul(exvector(std::reverse_iterator<exvector::const_iterator>(next_to_last), std::reverse_iterator<exvector::const_iterator>(self + 1)), true);
418
419                         *self = (*next_to_last) * S + SR * (*next_to_last);
420                         std::fill(self + 1, other, _ex1);
421                         *other = _ex2;
422                         return true;
423
424                 // gamma~mu S gamma~alpha gamma.mu = 2 gamma~alpha S - gamma~mu S gamma.mu gamma~alpha
425                 // (commutate contracted indices towards each other, simplify_indexed()
426                 // will re-expand and re-run the simplification)
427                 } else {
428                         if (std::find_if(self + 1, other, is_not_a_clifford()) != other)
429                                 return false;
430
431                         exvector::iterator next_to_last = other - 1;
432                         ex S = ncmul(exvector(self + 1, next_to_last), true);
433
434                         *self = 2 * (*next_to_last) * S - (*self) * S * (*other) * (*next_to_last);
435                         std::fill(self + 1, other + 1, _ex1);
436                         return true;
437                 }
438
439         } else if (is_a<symbol>(other->op(0)) && other->nops() == 2) {
440
441                 // x.mu gamma~mu -> x-slash
442                 *self = dirac_slash(other->op(0), dim, rl);
443                 *other = _ex1;
444                 return true;
445         }
446
447         return false;
448 }
449
450 /** Contraction of a Clifford unit with something else. */
451 bool cliffordunit::contract_with(exvector::iterator self, exvector::iterator other, exvector & v) const
452 {
453         GINAC_ASSERT(is_a<clifford>(*self));
454         GINAC_ASSERT(is_a<indexed>(*other));
455         GINAC_ASSERT(is_a<cliffordunit>(self->op(0)));
456         clifford unit = ex_to<clifford>(*self);
457         unsigned char rl = unit.get_representation_label();
458
459         if (is_a<clifford>(*other)) {
460                 // Contraction only makes sense if the represenation labels are equal
461                 // and the metrics are the same
462                 if ((ex_to<clifford>(*other).get_representation_label() != rl) 
463                     && unit.same_metric(*other))
464                         return false;
465
466                 exvector::iterator before_other = other - 1;
467                 ex mu = self->op(1);
468                 ex mu_toggle = other->op(1);
469                 ex alpha = before_other->op(1);
470
471                 // e~mu e.mu = Tr ONE
472                 if (other - self == 1) {
473                         *self = unit.get_metric(mu, mu_toggle, true);
474                         *other = dirac_ONE(rl);
475                         return true;
476
477                 } else if (other - self == 2) {
478                         if (is_a<clifford>(*before_other) && ex_to<clifford>(*before_other).get_representation_label() == rl) {
479                                 // e~mu e~alpha e.mu = 2*e~mu B(alpha, mu.toggle_variance())-Tr(B) e~alpha
480                                 *self = 2 * (*self) * unit.get_metric(alpha, mu_toggle, true) - unit.get_metric(mu, mu_toggle, true) * (*before_other);
481                                 *before_other = _ex1;
482                                 *other = _ex1;
483                                 return true;
484
485                         } else {
486                                 // e~mu S e.mu = Tr S ONE
487                                 *self = unit.get_metric(mu, mu_toggle, true);
488                                 *other = dirac_ONE(rl);
489                                 return true;
490                         }
491                 } else {
492                 // e~mu S e~alpha e.mu = 2 e~mu S B(alpha, mu.toggle_variance()) - e~mu S e.mu e~alpha
493                 // (commutate contracted indices towards each other, simplify_indexed()
494                 // will re-expand and re-run the simplification)
495                         if (std::find_if(self + 1, other, is_not_a_clifford()) != other) {
496                                 return false;
497                         }
498                         
499                         ex S = ncmul(exvector(self + 1, before_other), true);
500
501                         if (is_a<clifford>(*before_other) && ex_to<clifford>(*before_other).get_representation_label() == rl) {
502                                 *self = 2 * (*self) * S * unit.get_metric(alpha, mu_toggle, true) - (*self) * S * (*other) * (*before_other);
503                         } else {
504                                 // simply commutes
505                                 *self = (*self) * S * (*other) * (*before_other);
506                         }
507                                 
508                         std::fill(self + 1, other + 1, _ex1);
509                         return true;
510                 }
511         }
512         return false;
513 }
514
515 /** Perform automatic simplification on noncommutative product of clifford
516  *  objects. This removes superfluous ONEs, permutes gamma5/L/R's to the front
517  *  and removes squares of gamma objects. */
518 ex clifford::eval_ncmul(const exvector & v) const
519 {
520         exvector s;
521         s.reserve(v.size());
522
523         // Remove superfluous ONEs
524         exvector::const_iterator cit = v.begin(), citend = v.end();
525         while (cit != citend) {
526                 if (!is_a<clifford>(*cit) || !is_a<diracone>(cit->op(0)))
527                         s.push_back(*cit);
528                 cit++;
529         }
530
531         bool something_changed = false;
532         int sign = 1;
533
534         // Anticommutate gamma5/L/R's to the front
535         if (s.size() >= 2) {
536                 exvector::iterator first = s.begin(), next_to_last = s.end() - 2;
537                 while (true) {
538                         exvector::iterator it = next_to_last;
539                         while (true) {
540                                 exvector::iterator it2 = it + 1;
541                                 if (is_a<clifford>(*it) && is_a<clifford>(*it2)) {
542                                         ex e1 = it->op(0), e2 = it2->op(0);
543
544                                         if (is_a<diracgamma5>(e2)) {
545
546                                                 if (is_a<diracgammaL>(e1) || is_a<diracgammaR>(e1)) {
547
548                                                         // gammaL/R gamma5 -> gamma5 gammaL/R
549                                                         it->swap(*it2);
550                                                         something_changed = true;
551
552                                                 } else if (!is_a<diracgamma5>(e1)) {
553
554                                                         // gamma5 gamma5 -> gamma5 gamma5 (do nothing)
555                                                         // x gamma5 -> -gamma5 x
556                                                         it->swap(*it2);
557                                                         sign = -sign;
558                                                         something_changed = true;
559                                                 }
560
561                                         } else if (is_a<diracgammaL>(e2)) {
562
563                                                 if (is_a<diracgammaR>(e1)) {
564
565                                                         // gammaR gammaL -> 0
566                                                         return _ex0;
567
568                                                 } else if (!is_a<diracgammaL>(e1) && !is_a<diracgamma5>(e1)) {
569
570                                                         // gammaL gammaL -> gammaL gammaL (do nothing)
571                                                         // gamma5 gammaL -> gamma5 gammaL (do nothing)
572                                                         // x gammaL -> gammaR x
573                                                         it->swap(*it2);
574                                                         *it = clifford(diracgammaR(), ex_to<clifford>(*it).get_representation_label());
575                                                         something_changed = true;
576                                                 }
577
578                                         } else if (is_a<diracgammaR>(e2)) {
579
580                                                 if (is_a<diracgammaL>(e1)) {
581
582                                                         // gammaL gammaR -> 0
583                                                         return _ex0;
584
585                                                 } else if (!is_a<diracgammaR>(e1) && !is_a<diracgamma5>(e1)) {
586
587                                                         // gammaR gammaR -> gammaR gammaR (do nothing)
588                                                         // gamma5 gammaR -> gamma5 gammaR (do nothing)
589                                                         // x gammaR -> gammaL x
590                                                         it->swap(*it2);
591                                                         *it = clifford(diracgammaL(), ex_to<clifford>(*it).get_representation_label());
592                                                         something_changed = true;
593                                                 }
594                                         }
595                                 }
596                                 if (it == first)
597                                         break;
598                                 --it;
599                         }
600                         if (next_to_last == first)
601                                 break;
602                         --next_to_last;
603                 }
604         }
605
606         // Remove equal adjacent gammas
607         if (s.size() >= 2) {
608                 exvector::iterator it, itend = s.end() - 1;
609                 for (it = s.begin(); it != itend; ++it) {
610                         ex & a = it[0];
611                         ex & b = it[1];
612                         if (!is_a<clifford>(a) || !is_a<clifford>(b))
613                                 continue;
614
615                         const ex & ag = a.op(0);
616                         const ex & bg = b.op(0);
617                         bool a_is_cliffordunit = is_a<cliffordunit>(ag);
618                         bool b_is_cliffordunit =  is_a<cliffordunit>(bg);
619
620                         if (a_is_cliffordunit && b_is_cliffordunit && ex_to<clifford>(a).same_metric(b)
621                                 && (ex_to<clifford>(a).get_commutator_sign() == -1)) {
622                                 // This is done only for Clifford algebras 
623                                 
624                                 const ex & ia = a.op(1);
625                                 const ex & ib = b.op(1);
626                                 if (ia.is_equal(ib)) { // gamma~alpha gamma~alpha -> g~alpha~alpha
627                                         a = ex_to<clifford>(a).get_metric(ia, ib, true);
628                                         b = dirac_ONE(representation_label);
629                                         something_changed = true;
630                                 }
631
632                         } else if ((is_a<diracgamma5>(ag) && is_a<diracgamma5>(bg))) {
633
634                                 // Remove squares of gamma5
635                                 a = dirac_ONE(representation_label);
636                                 b = dirac_ONE(representation_label);
637                                 something_changed = true;
638
639                         } else if ((is_a<diracgammaL>(ag) && is_a<diracgammaL>(bg))
640                                 || (is_a<diracgammaR>(ag) && is_a<diracgammaR>(bg))) {
641
642                                 // Remove squares of gammaL/R
643                                 b = dirac_ONE(representation_label);
644                                 something_changed = true;
645
646                         } else if (is_a<diracgammaL>(ag) && is_a<diracgammaR>(bg)) {
647
648                                 // gammaL and gammaR are orthogonal
649                                 return _ex0;
650
651                         } else if (is_a<diracgamma5>(ag) && is_a<diracgammaL>(bg)) {
652
653                                 // gamma5 gammaL -> -gammaL
654                                 a = dirac_ONE(representation_label);
655                                 sign = -sign;
656                                 something_changed = true;
657
658                         } else if (is_a<diracgamma5>(ag) && is_a<diracgammaR>(bg)) {
659
660                                 // gamma5 gammaR -> gammaR
661                                 a = dirac_ONE(representation_label);
662                                 something_changed = true;
663
664                         } else if (!a_is_cliffordunit && !b_is_cliffordunit && ag.is_equal(bg)) {
665
666                                 // a\ a\ -> a^2
667                                 varidx ix((new symbol)->setflag(status_flags::dynallocated), ex_to<idx>(a.op(1)).minimal_dim(ex_to<idx>(b.op(1))));
668                                 
669                                 a = indexed(ag, ix) * indexed(ag, ix.toggle_variance());
670                                 b = dirac_ONE(representation_label);
671                                 something_changed = true;
672                         }
673                 }
674         }
675
676         if (s.empty())
677                 return dirac_ONE(representation_label) * sign;
678         if (something_changed)
679                 return reeval_ncmul(s) * sign;
680         else
681                 return hold_ncmul(s) * sign;
682 }
683
684 ex clifford::thiscontainer(const exvector & v) const
685 {
686         return clifford(representation_label, metric, commutator_sign, v);
687 }
688
689 ex clifford::thiscontainer(std::auto_ptr<exvector> vp) const
690 {
691         return clifford(representation_label, metric, commutator_sign, vp);
692 }
693
694 ex diracgamma5::conjugate() const
695 {       
696         return _ex_1 * (*this);
697 }
698
699 ex diracgammaL::conjugate() const
700 {
701         return (new diracgammaR)->setflag(status_flags::dynallocated);
702 }
703
704 ex diracgammaR::conjugate() const
705 {
706         return (new diracgammaL)->setflag(status_flags::dynallocated);
707 }
708
709 //////////
710 // global functions
711 //////////
712
713 ex dirac_ONE(unsigned char rl)
714 {
715         static ex ONE = (new diracone)->setflag(status_flags::dynallocated);
716         return clifford(ONE, rl);
717 }
718
719 ex clifford_unit(const ex & mu, const ex & metr, unsigned char rl)
720 {
721         static ex unit = (new cliffordunit)->setflag(status_flags::dynallocated);
722
723         if (!is_a<idx>(mu))
724                 throw(std::invalid_argument("clifford_unit(): index of Clifford unit must be of type idx or varidx"));
725
726         exvector indices = metr.get_free_indices();
727
728         if (indices.size() == 2) {
729                 return clifford(unit, mu, metr, rl);
730         } else if (is_a<matrix>(metr)) {
731                 matrix M = ex_to<matrix>(metr);
732                 unsigned n = M.rows();
733                 bool symmetric = true;
734
735                 static idx xi((new symbol)->setflag(status_flags::dynallocated), n),
736                         chi((new symbol)->setflag(status_flags::dynallocated), n);
737                 if ((n ==  M.cols()) && (n == ex_to<idx>(mu).get_dim())) {
738                         for (unsigned i = 0; i < n; i++) {
739                                 for (unsigned j = i+1; j < n; j++) {
740                                         if (M(i, j) != M(j, i)) {
741                                                 symmetric = false;
742                                         }
743                                 }
744                         }
745                         return clifford(unit, mu, indexed(metr, symmetric?symmetric2():not_symmetric(), xi, chi), rl);
746                 } else {
747                         throw(std::invalid_argument("clifford_unit(): metric for Clifford unit must be a square matrix with the same dimensions as index"));
748                 }
749         } else if (indices.size() == 0) { // a tensor or other expression without indices
750                 static varidx xi((new symbol)->setflag(status_flags::dynallocated), ex_to<idx>(mu).get_dim()),
751                         chi((new symbol)->setflag(status_flags::dynallocated), ex_to<idx>(mu).get_dim());
752                 return clifford(unit, mu, indexed(metr, xi, chi), rl);
753         }  else 
754                 throw(std::invalid_argument("clifford_unit(): metric for Clifford unit must be of type tensor, matrix or an expression with two free indices"));
755 }
756
757 ex dirac_gamma(const ex & mu, unsigned char rl)
758 {
759         static ex gamma = (new diracgamma)->setflag(status_flags::dynallocated);
760
761         if (!is_a<varidx>(mu))
762                 throw(std::invalid_argument("dirac_gamma(): index of Dirac gamma must be of type varidx"));
763
764         static varidx xi((new symbol)->setflag(status_flags::dynallocated), ex_to<varidx>(mu).get_dim()),
765                 chi((new symbol)->setflag(status_flags::dynallocated), ex_to<varidx>(mu).get_dim());
766         return clifford(gamma, mu, indexed((new minkmetric)->setflag(status_flags::dynallocated), symmetric2(), xi, chi), rl);
767 }
768
769 ex dirac_gamma5(unsigned char rl)
770 {
771         static ex gamma5 = (new diracgamma5)->setflag(status_flags::dynallocated);
772         return clifford(gamma5, rl);
773 }
774
775 ex dirac_gammaL(unsigned char rl)
776 {
777         static ex gammaL = (new diracgammaL)->setflag(status_flags::dynallocated);
778         return clifford(gammaL, rl);
779 }
780
781 ex dirac_gammaR(unsigned char rl)
782 {
783         static ex gammaR = (new diracgammaR)->setflag(status_flags::dynallocated);
784         return clifford(gammaR, rl);
785 }
786
787 ex dirac_slash(const ex & e, const ex & dim, unsigned char rl)
788 {
789         // Slashed vectors are actually stored as a clifford object with the
790         // vector as its base expression and a (dummy) index that just serves
791         // for storing the space dimensionality
792
793         static varidx xi((new symbol)->setflag(status_flags::dynallocated), dim),
794                 chi((new symbol)->setflag(status_flags::dynallocated), dim);
795    return clifford(e, varidx(0, dim), indexed((new minkmetric)->setflag(status_flags::dynallocated), symmetric2(), xi, chi), rl);
796 }
797
798 /** Check whether a given tinfo key (as returned by return_type_tinfo()
799  *  is that of a clifford object (with an arbitrary representation label). */
800 bool is_clifford_tinfo(tinfo_t ti)
801 {
802         p_int start_loc=(p_int)&clifford::return_type_tinfo_static;
803         return (p_int)ti>=start_loc && (p_int)ti<start_loc+256;
804 }
805
806 /** Extract representation label from tinfo key (as returned by
807  *  return_type_tinfo()). */
808 static unsigned char get_representation_label(tinfo_t ti)
809 {
810         return (unsigned char)((p_int)ti-(p_int)&clifford::return_type_tinfo_static);
811 }
812
813 /** Take trace of a string of an even number of Dirac gammas given a vector
814  *  of indices. */
815 static ex trace_string(exvector::const_iterator ix, size_t num)
816 {
817         // Tr gamma.mu gamma.nu = 4 g.mu.nu
818         if (num == 2)
819                 return lorentz_g(ix[0], ix[1]);
820
821         // 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 )
822         else if (num == 4)
823                 return lorentz_g(ix[0], ix[1]) * lorentz_g(ix[2], ix[3])
824                      + lorentz_g(ix[1], ix[2]) * lorentz_g(ix[0], ix[3])
825                      - lorentz_g(ix[0], ix[2]) * lorentz_g(ix[1], ix[3]);
826
827         // Traces of 6 or more gammas are computed recursively:
828         // Tr gamma.mu1 gamma.mu2 ... gamma.mun =
829         //   + g.mu1.mu2 * Tr gamma.mu3 ... gamma.mun
830         //   - g.mu1.mu3 * Tr gamma.mu2 gamma.mu4 ... gamma.mun
831         //   + g.mu1.mu4 * Tr gamma.mu3 gamma.mu3 gamma.mu5 ... gamma.mun
832         //   - ...
833         //   + g.mu1.mun * Tr gamma.mu2 ... gamma.mu(n-1)
834         exvector v(num - 2);
835         int sign = 1;
836         ex result;
837         for (size_t i=1; i<num; i++) {
838                 for (size_t n=1, j=0; n<num; n++) {
839                         if (n == i)
840                                 continue;
841                         v[j++] = ix[n];
842                 }
843                 result += sign * lorentz_g(ix[0], ix[i]) * trace_string(v.begin(), num-2);
844                 sign = -sign;
845         }
846         return result;
847 }
848
849 ex dirac_trace(const ex & e, const std::set<unsigned char> & rls, const ex & trONE)
850 {
851         if (is_a<clifford>(e)) {
852
853                 unsigned char rl = ex_to<clifford>(e).get_representation_label();
854
855                 // Are we taking the trace over this object's representation label?
856                 if (rls.find(rl) == rls.end())
857                         return e;
858
859                 // Yes, all elements are traceless, except for dirac_ONE and dirac_L/R
860                 const ex & g = e.op(0);
861                 if (is_a<diracone>(g))
862                         return trONE;
863                 else if (is_a<diracgammaL>(g) || is_a<diracgammaR>(g))
864                         return trONE/2;
865                 else
866                         return _ex0;
867
868         } else if (is_exactly_a<mul>(e)) {
869
870                 // Trace of product: pull out non-clifford factors
871                 ex prod = _ex1;
872                 for (size_t i=0; i<e.nops(); i++) {
873                         const ex &o = e.op(i);
874                         if (is_clifford_tinfo(o.return_type_tinfo()))
875                                 prod *= dirac_trace(o, rls, trONE);
876                         else
877                                 prod *= o;
878                 }
879                 return prod;
880
881         } else if (is_exactly_a<ncmul>(e)) {
882
883                 unsigned char rl = get_representation_label(e.return_type_tinfo());
884
885                 // Are we taking the trace over this string's representation label?
886                 if (rls.find(rl) == rls.end())
887                         return e;
888
889                 // Substitute gammaL/R and expand product, if necessary
890                 ex e_expanded = e.subs(lst(
891                         dirac_gammaL(rl) == (dirac_ONE(rl)-dirac_gamma5(rl))/2,
892                         dirac_gammaR(rl) == (dirac_ONE(rl)+dirac_gamma5(rl))/2
893                 ), subs_options::no_pattern).expand();
894                 if (!is_a<ncmul>(e_expanded))
895                         return dirac_trace(e_expanded, rls, trONE);
896
897                 // gamma5 gets moved to the front so this check is enough
898                 bool has_gamma5 = is_a<diracgamma5>(e.op(0).op(0));
899                 size_t num = e.nops();
900
901                 if (has_gamma5) {
902
903                         // Trace of gamma5 * odd number of gammas and trace of
904                         // gamma5 * gamma.mu * gamma.nu are zero
905                         if ((num & 1) == 0 || num == 3)
906                                 return _ex0;
907
908                         // Tr gamma5 gamma.mu gamma.nu gamma.rho gamma.sigma = 4I * epsilon(mu, nu, rho, sigma)
909                         // (the epsilon is always 4-dimensional)
910                         if (num == 5) {
911                                 ex b1, i1, b2, i2, b3, i3, b4, i4;
912                                 base_and_index(e.op(1), b1, i1);
913                                 base_and_index(e.op(2), b2, i2);
914                                 base_and_index(e.op(3), b3, i3);
915                                 base_and_index(e.op(4), b4, i4);
916                                 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();
917                         }
918
919                         // Tr gamma5 S_2k =
920                         //   I/4! * epsilon0123.mu1.mu2.mu3.mu4 * Tr gamma.mu1 gamma.mu2 gamma.mu3 gamma.mu4 S_2k
921                         // (the epsilon is always 4-dimensional)
922                         exvector ix(num-1), bv(num-1);
923                         for (size_t i=1; i<num; i++)
924                                 base_and_index(e.op(i), bv[i-1], ix[i-1]);
925                         num--;
926                         int *iv = new int[num];
927                         ex result;
928                         for (size_t i=0; i<num-3; i++) {
929                                 ex idx1 = ix[i];
930                                 for (size_t j=i+1; j<num-2; j++) {
931                                         ex idx2 = ix[j];
932                                         for (size_t k=j+1; k<num-1; k++) {
933                                                 ex idx3 = ix[k];
934                                                 for (size_t l=k+1; l<num; l++) {
935                                                         ex idx4 = ix[l];
936                                                         iv[0] = i; iv[1] = j; iv[2] = k; iv[3] = l;
937                                                         exvector v;
938                                                         v.reserve(num - 4);
939                                                         for (size_t n=0, t=4; n<num; n++) {
940                                                                 if (n == i || n == j || n == k || n == l)
941                                                                         continue;
942                                                                 iv[t++] = n;
943                                                                 v.push_back(ix[n]);
944                                                         }
945                                                         int sign = permutation_sign(iv, iv + num);
946                                                         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))
947                                                                 * trace_string(v.begin(), num - 4);
948                                                 }
949                                         }
950                                 }
951                         }
952                         delete[] iv;
953                         return trONE * I * result * mul(bv);
954
955                 } else { // no gamma5
956
957                         // Trace of odd number of gammas is zero
958                         if ((num & 1) == 1)
959                                 return _ex0;
960
961                         // Tr gamma.mu gamma.nu = 4 g.mu.nu
962                         if (num == 2) {
963                                 ex b1, i1, b2, i2;
964                                 base_and_index(e.op(0), b1, i1);
965                                 base_and_index(e.op(1), b2, i2);
966                                 return trONE * (lorentz_g(i1, i2) * b1 * b2).simplify_indexed();
967                         }
968
969                         exvector iv(num), bv(num);
970                         for (size_t i=0; i<num; i++)
971                                 base_and_index(e.op(i), bv[i], iv[i]);
972
973                         return trONE * (trace_string(iv.begin(), num) * mul(bv)).simplify_indexed();
974                 }
975
976         } else if (e.nops() > 0) {
977
978                 // Trace maps to all other container classes (this includes sums)
979                 pointer_to_map_function_2args<const std::set<unsigned char> &, const ex &> fcn(dirac_trace, rls, trONE);
980                 return e.map(fcn);
981
982         } else
983                 return _ex0;
984 }
985
986 ex dirac_trace(const ex & e, const lst & rll, const ex & trONE)
987 {
988         // Convert list to set
989         std::set<unsigned char> rls;
990         for (lst::const_iterator i = rll.begin(); i != rll.end(); ++i) {
991                 if (i->info(info_flags::nonnegint))
992                         rls.insert(ex_to<numeric>(*i).to_int());
993         }
994
995         return dirac_trace(e, rls, trONE);
996 }
997
998 ex dirac_trace(const ex & e, unsigned char rl, const ex & trONE)
999 {
1000         // Convert label to set
1001         std::set<unsigned char> rls;
1002         rls.insert(rl);
1003
1004         return dirac_trace(e, rls, trONE);
1005 }
1006
1007
1008 ex canonicalize_clifford(const ex & e_)
1009 {
1010         pointer_to_map_function fcn(canonicalize_clifford);
1011
1012         if (is_a<matrix>(e_)    // || is_a<pseries>(e) || is_a<integral>(e)
1013                 || e_.info(info_flags::list)) {
1014                 return e_.map(fcn);
1015         } else {
1016                 ex e=simplify_indexed(e_);
1017                 // Scan for any ncmul objects
1018                 exmap srl;
1019                 ex aux = e.to_rational(srl);
1020                 for (exmap::iterator i = srl.begin(); i != srl.end(); ++i) {
1021
1022                         ex lhs = i->first;
1023                         ex rhs = i->second;
1024
1025                         if (is_exactly_a<ncmul>(rhs)
1026                                         && rhs.return_type() == return_types::noncommutative
1027                                         && is_clifford_tinfo(rhs.return_type_tinfo())) {
1028
1029                                 // Expand product, if necessary
1030                                 ex rhs_expanded = rhs.expand();
1031                                 if (!is_a<ncmul>(rhs_expanded)) {
1032                                         i->second = canonicalize_clifford(rhs_expanded);
1033                                         continue;
1034
1035                                 } else if (!is_a<clifford>(rhs.op(0)))
1036                                         continue;
1037
1038                                 exvector v;
1039                                 v.reserve(rhs.nops());
1040                                 for (size_t j=0; j<rhs.nops(); j++)
1041                                         v.push_back(rhs.op(j));
1042
1043                                 // Stupid recursive bubble sort because we only want to swap adjacent gammas
1044                                 exvector::iterator it = v.begin(), next_to_last = v.end() - 1;
1045                                 if (is_a<diracgamma5>(it->op(0)) || is_a<diracgammaL>(it->op(0)) || is_a<diracgammaR>(it->op(0)))
1046                                         ++it;
1047
1048                                 while (it != next_to_last) {
1049                                         if (it[0].compare(it[1]) > 0) {
1050
1051                                                 ex save0 = it[0], save1 = it[1];
1052                                                 ex b1, i1, b2, i2;
1053                                                 base_and_index(it[0], b1, i1);
1054                                                 base_and_index(it[1], b2, i2);
1055                                                 // for Clifford algebras (commutator_sign == -1) metric should be symmetrised
1056                                                 it[0] = (ex_to<clifford>(save0).get_metric(i1, i2, ex_to<clifford>(save0).get_commutator_sign() == -1) * b1 * b2).simplify_indexed();
1057                                                 it[1] = v.size() ? _ex2 * dirac_ONE(ex_to<clifford>(save0).get_representation_label()) : _ex2;
1058                                                 ex sum = ncmul(v);
1059                                                 it[0] = save1;
1060                                                 it[1] = save0;
1061                                                 sum += ex_to<clifford>(save0).get_commutator_sign() * ncmul(v, true);
1062                                                 i->second = canonicalize_clifford(sum);
1063                                                 goto next_sym;
1064                                         }
1065                                         ++it;
1066                                 }
1067 next_sym:       ;
1068                         }
1069                 }
1070                 return aux.subs(srl, subs_options::no_pattern).simplify_indexed();
1071         }
1072 }
1073
1074 ex clifford_prime(const ex & e)
1075 {
1076         pointer_to_map_function fcn(clifford_prime);
1077         if (is_a<clifford>(e) && is_a<cliffordunit>(e.op(0))) {
1078                 return -e;
1079         } else if (is_a<add>(e) || is_a<ncmul>(e) || is_a<mul>(e) //|| is_a<pseries>(e) || is_a<integral>(e)
1080                            || is_a<matrix>(e) || e.info(info_flags::list)) {
1081                 return e.map(fcn);
1082         } else if (is_a<power>(e)) {
1083                 return pow(clifford_prime(e.op(0)), e.op(1));
1084         } else
1085                 return e;
1086 }
1087
1088 ex remove_dirac_ONE(const ex & e, unsigned char rl, unsigned options)
1089 {
1090         pointer_to_map_function_2args<unsigned char, unsigned> fcn(remove_dirac_ONE, rl, options | 1);
1091         bool need_reevaluation = false;
1092         ex e1 = e;
1093         if (! (options & 1) )  { // is not a child
1094                 if (options & 2)
1095                         e1 = expand_dummy_sum(e, true);
1096                 e1 = canonicalize_clifford(e1);
1097         }
1098         
1099         if (is_a<clifford>(e1) && ex_to<clifford>(e1).get_representation_label() >= rl) {
1100                 if (is_a<diracone>(e1.op(0)))
1101                         return 1;
1102                 else 
1103                         throw(std::invalid_argument("remove_dirac_ONE(): expression is a non-scalar Clifford number!"));
1104         } else if (is_a<add>(e1) || is_a<ncmul>(e1) || is_a<mul>(e1)  
1105                            || is_a<matrix>(e1) || e1.info(info_flags::list)) {
1106                 if (options & 3) // is a child or was already expanded
1107                         return e1.map(fcn);
1108                 else
1109                         try {
1110                                 return e1.map(fcn);
1111                         } catch (std::exception &p) {
1112                                 need_reevaluation = true;
1113                         }
1114         } else if (is_a<power>(e1)) {
1115                 if (options & 3) // is a child or was already expanded
1116                         return pow(remove_dirac_ONE(e1.op(0), rl, options | 1), e1.op(1));
1117                 else
1118                         try {
1119                                 return pow(remove_dirac_ONE(e1.op(0), rl, options | 1), e1.op(1));
1120                         } catch (std::exception &p) {
1121                                 need_reevaluation = true;
1122                         }
1123         } 
1124         if (need_reevaluation)
1125                 return remove_dirac_ONE(e, rl, options | 2);
1126         return e1;
1127 }
1128
1129 char clifford_max_label(const ex & e, bool ignore_ONE)
1130 {
1131         if (is_a<clifford>(e))
1132                 if (ignore_ONE && is_a<diracone>(e.op(0)))
1133                         return -1;
1134                 else
1135                         return ex_to<clifford>(e).get_representation_label();
1136         else {
1137                 char rl = -1;
1138                 for (size_t i=0; i < e.nops(); i++) 
1139                         rl = (rl > clifford_max_label(e.op(i), ignore_ONE)) ? rl : clifford_max_label(e.op(i), ignore_ONE);
1140                 return rl;
1141         }
1142 }
1143
1144 ex clifford_norm(const ex & e)
1145 {
1146         return sqrt(remove_dirac_ONE(e * clifford_bar(e)));
1147 }
1148         
1149 ex clifford_inverse(const ex & e)
1150 {
1151         ex norm = clifford_norm(e);
1152         if (!norm.is_zero())
1153                 return clifford_bar(e) / pow(norm, 2);
1154         else 
1155                 throw(std::invalid_argument("clifford_inverse(): cannot find inverse of Clifford number with zero norm!"));
1156 }
1157
1158 ex lst_to_clifford(const ex & v, const ex & mu, const ex & metr, unsigned char rl)
1159 {
1160         if (!ex_to<idx>(mu).is_dim_numeric())
1161                 throw(std::invalid_argument("lst_to_clifford(): Index should have a numeric dimension"));
1162         ex e = clifford_unit(mu, metr, rl);
1163         return lst_to_clifford(v, e);
1164 }
1165
1166 ex lst_to_clifford(const ex & v, const ex & e) {
1167         unsigned min, max;
1168
1169         if (is_a<clifford>(e)) {
1170                 ex mu = e.op(1);
1171                 ex mu_toggle
1172                         = is_a<varidx>(mu) ? ex_to<varidx>(mu).toggle_variance() : mu;
1173                 unsigned dim = (ex_to<numeric>(ex_to<idx>(mu).get_dim())).to_int();
1174
1175                 if (is_a<matrix>(v)) {
1176                         if (ex_to<matrix>(v).cols() > ex_to<matrix>(v).rows()) {
1177                                 min = ex_to<matrix>(v).rows();
1178                                 max = ex_to<matrix>(v).cols();
1179                         } else {
1180                                 min = ex_to<matrix>(v).cols();
1181                                 max = ex_to<matrix>(v).rows();
1182                         }
1183                         if (min == 1) {
1184                                 if (dim == max)
1185                                         return indexed(v, mu_toggle) * e;
1186                                 else if (max - dim == 1) {
1187                                         if (ex_to<matrix>(v).cols() > ex_to<matrix>(v).rows())
1188                                                 return v.op(0) * dirac_ONE(ex_to<clifford>(e).get_representation_label()) + indexed(sub_matrix(ex_to<matrix>(v), 0, 1, 1, dim), mu_toggle) * e;
1189                                         else 
1190                                                 return v.op(0) * dirac_ONE(ex_to<clifford>(e).get_representation_label()) + indexed(sub_matrix(ex_to<matrix>(v), 1, dim, 0, 1), mu_toggle) * e;
1191                                 } else
1192                                         throw(std::invalid_argument("lst_to_clifford(): dimensions of vector and clifford unit mismatch"));
1193                         } else
1194                                 throw(std::invalid_argument("lst_to_clifford(): first argument should be a vector (nx1 or 1xn matrix)"));
1195                 } else if (v.info(info_flags::list)) {
1196                         if (dim == ex_to<lst>(v).nops())
1197                                 return indexed(matrix(dim, 1, ex_to<lst>(v)), mu_toggle) * e;
1198                         else if (ex_to<lst>(v).nops() - dim == 1)
1199                                 return v.op(0) * dirac_ONE(ex_to<clifford>(e).get_representation_label()) + indexed(sub_matrix(matrix(dim+1, 1, ex_to<lst>(v)), 1, dim, 0, 1), mu_toggle) * e;
1200                         else
1201                                 throw(std::invalid_argument("lst_to_clifford(): list length and dimension of clifford unit mismatch"));
1202                 } else
1203                         throw(std::invalid_argument("lst_to_clifford(): cannot construct from anything but list or vector"));
1204         } else
1205                 throw(std::invalid_argument("lst_to_clifford(): the second argument should be a Clifford unit"));
1206 }
1207  
1208 /** Auxiliary structure to define a function for striping one Clifford unit
1209  * from vectors. Used in  clifford_to_lst(). */
1210 static ex get_clifford_comp(const ex & e, const ex & c) 
1211 {
1212         pointer_to_map_function_1arg<const ex &> fcn(get_clifford_comp, c);
1213         int ival = ex_to<numeric>(ex_to<idx>(c.op(1)).get_value()).to_int();
1214                 
1215         if (is_a<add>(e) || e.info(info_flags::list) // || is_a<pseries>(e) || is_a<integral>(e)
1216                 || is_a<matrix>(e)) 
1217                 return e.map(fcn);
1218         else if (is_a<ncmul>(e) || is_a<mul>(e)) {
1219                 // find a Clifford unit with the same metric, delete it and substitute its index
1220                 size_t ind = e.nops() + 1;
1221                 for (size_t j = 0; j < e.nops(); j++) 
1222                         if (is_a<clifford>(e.op(j)) && ex_to<clifford>(c).same_metric(e.op(j)))
1223                                 if (ind > e.nops()) 
1224                                         ind = j;
1225                                 else 
1226                                         throw(std::invalid_argument("get_clifford_comp(): expression is a Clifford multi-vector"));
1227                 if (ind < e.nops()) {
1228                         ex S = 1;
1229                         bool same_value_index, found_dummy;
1230                         same_value_index = ( ex_to<idx>(e.op(ind).op(1)).is_numeric()
1231                                                                  &&  (ival == ex_to<numeric>(ex_to<idx>(e.op(ind).op(1)).get_value()).to_int()) );
1232                         found_dummy = same_value_index;
1233                         for(size_t j=0; j < e.nops(); j++)
1234                                 if (j != ind) 
1235                                         if (same_value_index) 
1236                                                 S = S * e.op(j);
1237                                         else {
1238                                                 exvector ind_vec = ex_to<indexed>(e.op(j)).get_dummy_indices(ex_to<indexed>(e.op(ind)));
1239                                                 if (ind_vec.size() > 0) {
1240                                                         found_dummy = true;
1241                                                         exvector::const_iterator it = ind_vec.begin(), itend = ind_vec.end();
1242                                                         while (it != itend) {
1243                                                                 ex curridx = *it;
1244                                                                 ex curridx_toggle = is_a<varidx>(curridx)
1245                                                                         ? ex_to<varidx>(curridx).toggle_variance()
1246                                                                         : curridx;
1247                                                                 S = S * e.op(j).subs(lst(curridx == ival,
1248                                                                         curridx_toggle == ival), subs_options::no_pattern);
1249                                                                 ++it;
1250                                                         }
1251                                                 } else
1252                                                         S = S * e.op(j);
1253                                         }
1254                         return (found_dummy ? S : 0);
1255                 } else
1256                         throw(std::invalid_argument("get_clifford_comp(): expression is not a Clifford vector to the given units"));
1257         } else if (e.is_zero()) 
1258                 return e;
1259         else if (is_a<clifford>(e) && ex_to<clifford>(e).same_metric(c))
1260                 if ( ex_to<idx>(e.op(1)).is_numeric() &&
1261                          (ival != ex_to<numeric>(ex_to<idx>(e.op(1)).get_value()).to_int()) )
1262                         return 0;
1263                 else 
1264                         return 1;
1265         else
1266                 throw(std::invalid_argument("get_clifford_comp(): expression is not usable as a Clifford vector"));
1267 }
1268
1269
1270 lst clifford_to_lst(const ex & e, const ex & c, bool algebraic)
1271 {
1272         GINAC_ASSERT(is_a<clifford>(c));
1273         ex mu = c.op(1);
1274         if (! ex_to<idx>(mu).is_dim_numeric())
1275                 throw(std::invalid_argument("clifford_to_lst(): index should have a numeric dimension"));
1276         unsigned int D = ex_to<numeric>(ex_to<idx>(mu).get_dim()).to_int();
1277
1278         if (algebraic) // check if algebraic method is applicable
1279                 for (unsigned int i = 0; i < D; i++) 
1280                         if (pow(c.subs(mu == i, subs_options::no_pattern), 2).is_zero() 
1281                                 or (not is_a<numeric>(pow(c.subs(mu == i, subs_options::no_pattern), 2))))
1282                                 algebraic = false;
1283         lst V; 
1284         ex v0 = remove_dirac_ONE(canonicalize_clifford(e+clifford_prime(e)).normal())/2;
1285         if (not v0.is_zero())
1286                 V.append(v0);
1287         ex e1 = canonicalize_clifford(e - v0 * dirac_ONE(ex_to<clifford>(c).get_representation_label())); 
1288         if (algebraic) {
1289                 for (unsigned int i = 0; i < D; i++) 
1290                         V.append(remove_dirac_ONE(
1291                                                 simplify_indexed(canonicalize_clifford(e1 * c.subs(mu == i, subs_options::no_pattern) +  c.subs(mu == i, subs_options::no_pattern) * e1))
1292                                                 / (2*pow(c.subs(mu == i, subs_options::no_pattern), 2))));
1293         } else {
1294                 try {
1295                         for (unsigned int i = 0; i < D; i++) 
1296                                 V.append(get_clifford_comp(e1, c.subs(c.op(1) == i, subs_options::no_pattern)));
1297                 } catch  (std::exception &p) {
1298                         /* Try to expand dummy summations to simplify the expression*/
1299                         e1 = canonicalize_clifford(expand_dummy_sum(e, true));
1300                         V.remove_all();
1301                         v0 = remove_dirac_ONE(canonicalize_clifford(e1+clifford_prime(e1)).normal())/2;
1302                         if (not v0.is_zero()) {
1303                                 V.append(v0);
1304                                 e1 = canonicalize_clifford(e1 - v0 * dirac_ONE(ex_to<clifford>(c).get_representation_label())); 
1305                         }
1306                         for (unsigned int i = 0; i < D; i++) 
1307                                 V.append(get_clifford_comp(e1, c.subs(c.op(1) == i, subs_options::no_pattern)));
1308                 }
1309         }
1310         return V;
1311 }
1312
1313
1314 ex clifford_moebius_map(const ex & a, const ex & b, const ex & c, const ex & d, const ex & v, const ex & G, unsigned char rl)
1315 {
1316         ex x, D, cu;
1317         
1318         if (! is_a<matrix>(v) && ! v.info(info_flags::list))
1319                 throw(std::invalid_argument("clifford_moebius_map(): parameter v should be either vector or list"));
1320         
1321         if (is_a<clifford>(G)) {
1322                 cu = G;
1323         } else {
1324                 if (is_a<indexed>(G)) {
1325                         D = ex_to<idx>(G.op(1)).get_dim();
1326                         varidx mu((new symbol)->setflag(status_flags::dynallocated), D);
1327                         cu = clifford_unit(mu, G, rl);
1328                 } else if (is_a<matrix>(G)) {
1329                         D = ex_to<matrix>(G).rows(); 
1330                         idx mu((new symbol)->setflag(status_flags::dynallocated), D);
1331                         cu = clifford_unit(mu, G, rl);
1332                 } else throw(std::invalid_argument("clifford_moebius_map(): metric should be an indexed object, matrix, or a Clifford unit"));
1333                 
1334         }
1335         
1336         x = lst_to_clifford(v, cu); 
1337         ex e = clifford_to_lst(simplify_indexed(canonicalize_clifford((a * x + b) * clifford_inverse(c * x + d))), cu, false);
1338         return (is_a<matrix>(v) ? matrix(ex_to<matrix>(v).rows(), ex_to<matrix>(v).cols(), ex_to<lst>(e)) : e);
1339 }
1340
1341 ex clifford_moebius_map(const ex & M, const ex & v, const ex & G, unsigned char rl)
1342 {
1343         if (is_a<matrix>(M) && (ex_to<matrix>(M).rows() == 2) && (ex_to<matrix>(M).cols() == 2)) 
1344                 return clifford_moebius_map(M.op(0), M.op(1), M.op(2), M.op(3), v, G, rl);
1345         else
1346                 throw(std::invalid_argument("clifford_moebius_map(): parameter M should be a 2x2 matrix"));
1347 }
1348
1349 } // namespace GiNaC