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