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