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