subs() and normal() use maps instead of lists, resulting in a huge performance
[ginac.git] / ginac / tensor.cpp
1 /** @file tensor.cpp
2  *
3  *  Implementation of GiNaC's special tensors. */
4
5 /*
6  *  GiNaC Copyright (C) 1999-2003 Johannes Gutenberg University Mainz, Germany
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 2 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 #include <iostream>
24 #include <stdexcept>
25 #include <vector>
26
27 #include "tensor.h"
28 #include "idx.h"
29 #include "indexed.h"
30 #include "symmetry.h"
31 #include "relational.h"
32 #include "operators.h"
33 #include "lst.h"
34 #include "numeric.h"
35 #include "matrix.h"
36 #include "print.h"
37 #include "archive.h"
38 #include "utils.h"
39
40 namespace GiNaC {
41
42 GINAC_IMPLEMENT_REGISTERED_CLASS(tensor, basic)
43 GINAC_IMPLEMENT_REGISTERED_CLASS(tensdelta, tensor)
44 GINAC_IMPLEMENT_REGISTERED_CLASS(tensmetric, tensor)
45 GINAC_IMPLEMENT_REGISTERED_CLASS(minkmetric, tensmetric)
46 GINAC_IMPLEMENT_REGISTERED_CLASS(spinmetric, tensmetric)
47 GINAC_IMPLEMENT_REGISTERED_CLASS(tensepsilon, tensor)
48
49 //////////
50 // constructors
51 //////////
52
53 tensor::tensor() : inherited(TINFO_tensor)
54 {
55         setflag(status_flags::evaluated | status_flags::expanded);
56 }
57
58 DEFAULT_CTOR(tensdelta)
59 DEFAULT_CTOR(tensmetric)
60
61 minkmetric::minkmetric() : pos_sig(false)
62 {
63         tinfo_key = TINFO_minkmetric;
64 }
65
66 spinmetric::spinmetric()
67 {
68         tinfo_key = TINFO_spinmetric;
69 }
70
71 minkmetric::minkmetric(bool ps) : pos_sig(ps)
72 {
73         tinfo_key = TINFO_minkmetric;
74 }
75
76 tensepsilon::tensepsilon() : minkowski(false), pos_sig(false)
77 {
78         tinfo_key = TINFO_tensepsilon;
79 }
80
81 tensepsilon::tensepsilon(bool mink, bool ps) : minkowski(mink), pos_sig(ps)
82 {
83         tinfo_key = TINFO_tensepsilon;
84 }
85
86 //////////
87 // archiving
88 //////////
89
90 DEFAULT_ARCHIVING(tensor)
91 DEFAULT_ARCHIVING(tensdelta)
92 DEFAULT_ARCHIVING(tensmetric)
93 DEFAULT_ARCHIVING(spinmetric)
94 DEFAULT_UNARCHIVE(minkmetric)
95 DEFAULT_UNARCHIVE(tensepsilon)
96
97 minkmetric::minkmetric(const archive_node &n, lst &sym_lst) : inherited(n, sym_lst)
98 {
99         n.find_bool("pos_sig", pos_sig);
100 }
101
102 void minkmetric::archive(archive_node &n) const
103 {
104         inherited::archive(n);
105         n.add_bool("pos_sig", pos_sig);
106 }
107
108 tensepsilon::tensepsilon(const archive_node &n, lst &sym_lst) : inherited(n, sym_lst)
109 {
110         n.find_bool("minkowski", minkowski);
111         n.find_bool("pos_sig", pos_sig);
112 }
113
114 void tensepsilon::archive(archive_node &n) const
115 {
116         inherited::archive(n);
117         n.add_bool("minkowski", minkowski);
118         n.add_bool("pos_sig", pos_sig);
119 }
120
121 //////////
122 // functions overriding virtual functions from base classes
123 //////////
124
125 DEFAULT_COMPARE(tensor)
126 DEFAULT_COMPARE(tensdelta)
127 DEFAULT_COMPARE(tensmetric)
128 DEFAULT_COMPARE(spinmetric)
129
130 int minkmetric::compare_same_type(const basic & other) const
131 {
132         GINAC_ASSERT(is_a<minkmetric>(other));
133         const minkmetric &o = static_cast<const minkmetric &>(other);
134
135         if (pos_sig != o.pos_sig)
136                 return pos_sig ? -1 : 1;
137         else
138                 return inherited::compare_same_type(other);
139 }
140
141 int tensepsilon::compare_same_type(const basic & other) const
142 {
143         GINAC_ASSERT(is_a<tensepsilon>(other));
144         const tensepsilon &o = static_cast<const tensepsilon &>(other);
145
146         if (minkowski != o.minkowski)
147                 return minkowski ? -1 : 1;
148         else if (pos_sig != o.pos_sig)
149                 return pos_sig ? -1 : 1;
150         else
151                 return inherited::compare_same_type(other);
152 }
153
154 DEFAULT_PRINT_LATEX(tensdelta, "delta", "\\delta")
155 DEFAULT_PRINT(tensmetric, "g")
156 DEFAULT_PRINT_LATEX(minkmetric, "eta", "\\eta")
157 DEFAULT_PRINT_LATEX(spinmetric, "eps", "\\varepsilon")
158 DEFAULT_PRINT_LATEX(tensepsilon, "eps", "\\varepsilon")
159
160 /** Automatic symbolic evaluation of an indexed delta tensor. */
161 ex tensdelta::eval_indexed(const basic & i) const
162 {
163         GINAC_ASSERT(is_a<indexed>(i));
164         GINAC_ASSERT(i.nops() == 3);
165         GINAC_ASSERT(is_a<tensdelta>(i.op(0)));
166
167         const idx & i1 = ex_to<idx>(i.op(1));
168         const idx & i2 = ex_to<idx>(i.op(2));
169
170         // The dimension of the indices must be equal, otherwise we use the minimal
171         // dimension
172         if (!i1.get_dim().is_equal(i2.get_dim())) {
173                 ex min_dim = i1.minimal_dim(i2);
174                 exmap m;
175                 m[i1] = i1.replace_dim(min_dim);
176                 m[i2] = i2.replace_dim(min_dim);
177                 return i.subs(m);
178         }
179
180         // Trace of delta tensor is the (effective) dimension of the space
181         if (is_dummy_pair(i1, i2)) {
182                 try {
183                         return i1.minimal_dim(i2);
184                 } catch (std::exception &e) {
185                         return i.hold();
186                 }
187         }
188
189         // Numeric evaluation
190         if (static_cast<const indexed &>(i).all_index_values_are(info_flags::integer)) {
191                 int n1 = ex_to<numeric>(i1.get_value()).to_int(), n2 = ex_to<numeric>(i2.get_value()).to_int();
192                 if (n1 == n2)
193                         return _ex1;
194                 else
195                         return _ex0;
196         }
197
198         // No further simplifications
199         return i.hold();
200 }
201
202 /** Automatic symbolic evaluation of an indexed metric tensor. */
203 ex tensmetric::eval_indexed(const basic & i) const
204 {
205         GINAC_ASSERT(is_a<indexed>(i));
206         GINAC_ASSERT(i.nops() == 3);
207         GINAC_ASSERT(is_a<tensmetric>(i.op(0)));
208         GINAC_ASSERT(is_a<varidx>(i.op(1)));
209         GINAC_ASSERT(is_a<varidx>(i.op(2)));
210
211         const varidx & i1 = ex_to<varidx>(i.op(1));
212         const varidx & i2 = ex_to<varidx>(i.op(2));
213
214         // The dimension of the indices must be equal, otherwise we use the minimal
215         // dimension
216         if (!i1.get_dim().is_equal(i2.get_dim())) {
217                 ex min_dim = i1.minimal_dim(i2);
218                 exmap m;
219                 m[i1] = i1.replace_dim(min_dim);
220                 m[i2] = i2.replace_dim(min_dim);
221                 return i.subs(m);
222         }
223
224         // A metric tensor with one covariant and one contravariant index gets
225         // replaced by a delta tensor
226         if (i1.is_covariant() != i2.is_covariant())
227                 return delta_tensor(i1, i2);
228
229         // No further simplifications
230         return i.hold();
231 }
232
233 /** Automatic symbolic evaluation of an indexed Lorentz metric tensor. */
234 ex minkmetric::eval_indexed(const basic & i) const
235 {
236         GINAC_ASSERT(is_a<indexed>(i));
237         GINAC_ASSERT(i.nops() == 3);
238         GINAC_ASSERT(is_a<minkmetric>(i.op(0)));
239         GINAC_ASSERT(is_a<varidx>(i.op(1)));
240         GINAC_ASSERT(is_a<varidx>(i.op(2)));
241
242         const varidx & i1 = ex_to<varidx>(i.op(1));
243         const varidx & i2 = ex_to<varidx>(i.op(2));
244
245         // Numeric evaluation
246         if (static_cast<const indexed &>(i).all_index_values_are(info_flags::nonnegint)) {
247                 int n1 = ex_to<numeric>(i1.get_value()).to_int(), n2 = ex_to<numeric>(i2.get_value()).to_int();
248                 if (n1 != n2)
249                         return _ex0;
250                 else if (n1 == 0)
251                         return pos_sig ? _ex_1 : _ex1;
252                 else
253                         return pos_sig ? _ex1 : _ex_1;
254         }
255
256         // Perform the usual evaluations of a metric tensor
257         return inherited::eval_indexed(i);
258 }
259
260 /** Automatic symbolic evaluation of an indexed metric tensor. */
261 ex spinmetric::eval_indexed(const basic & i) const
262 {
263         GINAC_ASSERT(is_a<indexed>(i));
264         GINAC_ASSERT(i.nops() == 3);
265         GINAC_ASSERT(is_a<spinmetric>(i.op(0)));
266         GINAC_ASSERT(is_a<spinidx>(i.op(1)));
267         GINAC_ASSERT(is_a<spinidx>(i.op(2)));
268
269         const spinidx & i1 = ex_to<spinidx>(i.op(1));
270         const spinidx & i2 = ex_to<spinidx>(i.op(2));
271
272         // Convolutions are zero
273         if (!(static_cast<const indexed &>(i).get_dummy_indices().empty()))
274                 return _ex0;
275
276         // Numeric evaluation
277         if (static_cast<const indexed &>(i).all_index_values_are(info_flags::nonnegint)) {
278                 int n1 = ex_to<numeric>(i1.get_value()).to_int(), n2 = ex_to<numeric>(i2.get_value()).to_int();
279                 if (n1 == n2)
280                         return _ex0;
281                 else if (n1 < n2)
282                         return _ex1;
283                 else
284                         return _ex_1;
285         }
286
287         // No further simplifications
288         return i.hold();
289 }
290
291 /** Automatic symbolic evaluation of an indexed epsilon tensor. */
292 ex tensepsilon::eval_indexed(const basic & i) const
293 {
294         GINAC_ASSERT(is_a<indexed>(i));
295         GINAC_ASSERT(i.nops() > 1);
296         GINAC_ASSERT(is_a<tensepsilon>(i.op(0)));
297
298         // Convolutions are zero
299         if (!(static_cast<const indexed &>(i).get_dummy_indices().empty()))
300                 return _ex0;
301
302         // Numeric evaluation
303         if (static_cast<const indexed &>(i).all_index_values_are(info_flags::nonnegint)) {
304
305                 // Get sign of index permutation (the indices should already be in
306                 // a canonic order but we can't assume what exactly that order is)
307                 std::vector<int> v;
308                 v.reserve(i.nops() - 1);
309                 for (size_t j=1; j<i.nops(); j++)
310                         v.push_back(ex_to<numeric>(ex_to<idx>(i.op(j)).get_value()).to_int());
311                 int sign = permutation_sign(v.begin(), v.end());
312
313                 // In a Minkowski space, check for covariant indices
314                 if (minkowski) {
315                         for (size_t j=1; j<i.nops(); j++) {
316                                 const ex & x = i.op(j);
317                                 if (!is_a<varidx>(x))
318                                         throw(std::runtime_error("indices of epsilon tensor in Minkowski space must be of type varidx"));
319                                 if (ex_to<varidx>(x).is_covariant())
320                                         if (ex_to<idx>(x).get_value().is_zero())
321                                                 sign = (pos_sig ? -sign : sign);
322                                         else
323                                                 sign = (pos_sig ? sign : -sign);
324                         }
325                 }
326
327                 return sign;
328         }
329
330         // No further simplifications
331         return i.hold();
332 }
333
334 bool tensor::replace_contr_index(exvector::iterator self, exvector::iterator other) const
335 {
336         // Try to contract the first index
337         const idx *self_idx = &ex_to<idx>(self->op(1));
338         const idx *free_idx = &ex_to<idx>(self->op(2));
339         bool first_index_tried = false;
340
341 again:
342         if (self_idx->is_symbolic()) {
343                 for (size_t i=1; i<other->nops(); i++) {
344                         const idx &other_idx = ex_to<idx>(other->op(i));
345                         if (is_dummy_pair(*self_idx, other_idx)) {
346
347                                 // Contraction found, remove this tensor and substitute the
348                                 // index in the second object
349                                 try {
350                                         // minimal_dim() throws an exception when index dimensions are not comparable
351                                         ex min_dim = self_idx->minimal_dim(other_idx);
352                                         *other = other->subs(other_idx == free_idx->replace_dim(min_dim));
353                                         *self = _ex1; // *other is assigned first because assigning *self invalidates free_idx
354                                         return true;
355                                 } catch (std::exception &e) {
356                                         return false;
357                                 }
358                         }
359                 }
360         }
361
362         if (!first_index_tried) {
363
364                 // No contraction with the first index found, try the second index
365                 self_idx = &ex_to<idx>(self->op(2));
366                 free_idx = &ex_to<idx>(self->op(1));
367                 first_index_tried = true;
368                 goto again;
369         }
370
371         return false;
372 }
373
374 /** Contraction of an indexed delta tensor with something else. */
375 bool tensdelta::contract_with(exvector::iterator self, exvector::iterator other, exvector & v) const
376 {
377         GINAC_ASSERT(is_a<indexed>(*self));
378         GINAC_ASSERT(is_a<indexed>(*other));
379         GINAC_ASSERT(self->nops() == 3);
380         GINAC_ASSERT(is_a<tensdelta>(self->op(0)));
381
382         // Replace the dummy index with this tensor's other index and remove
383         // the tensor (this is valid for contractions with all other tensors)
384         return replace_contr_index(self, other);
385 }
386
387 /** Contraction of an indexed metric tensor with something else. */
388 bool tensmetric::contract_with(exvector::iterator self, exvector::iterator other, exvector & v) const
389 {
390         GINAC_ASSERT(is_a<indexed>(*self));
391         GINAC_ASSERT(is_a<indexed>(*other));
392         GINAC_ASSERT(self->nops() == 3);
393         GINAC_ASSERT(is_a<tensmetric>(self->op(0)));
394
395         // If contracting with the delta tensor, let the delta do it
396         // (don't raise/lower delta indices)
397         if (is_a<tensdelta>(other->op(0)))
398                 return false;
399
400         // Replace the dummy index with this tensor's other index and remove
401         // the tensor
402         return replace_contr_index(self, other);
403 }
404
405 /** Contraction of an indexed spinor metric with something else. */
406 bool spinmetric::contract_with(exvector::iterator self, exvector::iterator other, exvector & v) const
407 {
408         GINAC_ASSERT(is_a<indexed>(*self));
409         GINAC_ASSERT(is_a<indexed>(*other));
410         GINAC_ASSERT(self->nops() == 3);
411         GINAC_ASSERT(is_a<spinmetric>(self->op(0)));
412
413         // Contractions between spinor metrics
414         if (is_a<spinmetric>(other->op(0))) {
415                 const idx &self_i1 = ex_to<idx>(self->op(1));
416                 const idx &self_i2 = ex_to<idx>(self->op(2));
417                 const idx &other_i1 = ex_to<idx>(other->op(1));
418                 const idx &other_i2 = ex_to<idx>(other->op(2));
419
420                 if (is_dummy_pair(self_i1, other_i1)) {
421                         if (is_dummy_pair(self_i2, other_i2))
422                                 *self = _ex2;
423                         else
424                                 *self = delta_tensor(self_i2, other_i2);
425                         *other = _ex1;
426                         return true;
427                 } else if (is_dummy_pair(self_i1, other_i2)) {
428                         if (is_dummy_pair(self_i2, other_i1))
429                                 *self = _ex_2;
430                         else
431                                 *self = -delta_tensor(self_i2, other_i1);
432                         *other = _ex1;
433                         return true;
434                 } else if (is_dummy_pair(self_i2, other_i1)) {
435                         *self = -delta_tensor(self_i1, other_i2);
436                         *other = _ex1;
437                         return true;
438                 } else if (is_dummy_pair(self_i2, other_i2)) {
439                         *self = delta_tensor(self_i1, other_i1);
440                         *other = _ex1;
441                         return true;
442                 }
443         }
444
445         // If contracting with the delta tensor, let the delta do it
446         // (don't raise/lower delta indices)
447         if (is_a<tensdelta>(other->op(0)))
448                 return false;
449
450         // Try to contract first index
451         const idx *self_idx = &ex_to<idx>(self->op(1));
452         const idx *free_idx = &ex_to<idx>(self->op(2));
453         bool first_index_tried = false;
454         int sign = 1;
455
456 again:
457         if (self_idx->is_symbolic()) {
458                 for (size_t i=1; i<other->nops(); i++) {
459                         const idx &other_idx = ex_to<idx>(other->op(i));
460                         if (is_dummy_pair(*self_idx, other_idx)) {
461
462                                 // Contraction found, remove metric tensor and substitute
463                                 // index in second object (assign *self last because this
464                                 // invalidates free_idx)
465                                 *other = other->subs(other_idx == *free_idx);
466                                 *self = (static_cast<const spinidx *>(self_idx)->is_covariant() ? sign : -sign);
467                                 return true;
468                         }
469                 }
470         }
471
472         if (!first_index_tried) {
473
474                 // No contraction with first index found, try second index
475                 self_idx = &ex_to<idx>(self->op(2));
476                 free_idx = &ex_to<idx>(self->op(1));
477                 first_index_tried = true;
478                 sign = -sign;
479                 goto again;
480         }
481
482         return false;
483 }
484
485 /** Contraction of epsilon tensor with something else. */
486 bool tensepsilon::contract_with(exvector::iterator self, exvector::iterator other, exvector & v) const
487 {
488         GINAC_ASSERT(is_a<indexed>(*self));
489         GINAC_ASSERT(is_a<indexed>(*other));
490         GINAC_ASSERT(is_a<tensepsilon>(self->op(0)));
491         size_t num = self->nops() - 1;
492
493         if (is_exactly_a<tensepsilon>(other->op(0)) && num+1 == other->nops()) {
494
495                 // Contraction of two epsilon tensors is a determinant
496                 bool variance = is_a<varidx>(self->op(1));
497                 matrix M(num, num);
498                 for (size_t i=0; i<num; i++) {
499                         for (size_t j=0; j<num; j++) {
500                                 if (minkowski)
501                                         M(i, j) = lorentz_g(self->op(i+1), other->op(j+1), pos_sig);
502                                 else if (variance)
503                                         M(i, j) = metric_tensor(self->op(i+1), other->op(j+1));
504                                 else
505                                         M(i, j) = delta_tensor(self->op(i+1), other->op(j+1));
506                         }
507                 }
508                 int sign = minkowski ? -1 : 1;
509                 *self = sign * M.determinant().simplify_indexed();
510                 *other = _ex1;
511                 return true;
512         }
513
514         return false;
515 }
516
517 //////////
518 // global functions
519 //////////
520
521 ex delta_tensor(const ex & i1, const ex & i2)
522 {
523         if (!is_a<idx>(i1) || !is_a<idx>(i2))
524                 throw(std::invalid_argument("indices of delta tensor must be of type idx"));
525
526         return indexed(tensdelta(), sy_symm(), i1, i2);
527 }
528
529 ex metric_tensor(const ex & i1, const ex & i2)
530 {
531         if (!is_a<varidx>(i1) || !is_a<varidx>(i2))
532                 throw(std::invalid_argument("indices of metric tensor must be of type varidx"));
533
534         return indexed(tensmetric(), sy_symm(), i1, i2);
535 }
536
537 ex lorentz_g(const ex & i1, const ex & i2, bool pos_sig)
538 {
539         if (!is_a<varidx>(i1) || !is_a<varidx>(i2))
540                 throw(std::invalid_argument("indices of metric tensor must be of type varidx"));
541
542         return indexed(minkmetric(pos_sig), sy_symm(), i1, i2);
543 }
544
545 ex spinor_metric(const ex & i1, const ex & i2)
546 {
547         if (!is_a<spinidx>(i1) || !is_a<spinidx>(i2))
548                 throw(std::invalid_argument("indices of spinor metric must be of type spinidx"));
549         if (!ex_to<idx>(i1).get_dim().is_equal(2) || !ex_to<idx>(i2).get_dim().is_equal(2))
550                 throw(std::runtime_error("index dimension for spinor metric must be 2"));
551
552         return indexed(spinmetric(), sy_anti(), i1, i2);
553 }
554
555 ex epsilon_tensor(const ex & i1, const ex & i2)
556 {
557         if (!is_a<idx>(i1) || !is_a<idx>(i2))
558                 throw(std::invalid_argument("indices of epsilon tensor must be of type idx"));
559
560         ex dim = ex_to<idx>(i1).get_dim();
561         if (!dim.is_equal(ex_to<idx>(i2).get_dim()))
562                 throw(std::invalid_argument("all indices of epsilon tensor must have the same dimension"));
563         if (!ex_to<idx>(i1).get_dim().is_equal(_ex2))
564                 throw(std::runtime_error("index dimension of epsilon tensor must match number of indices"));
565
566         return indexed(tensepsilon(), sy_anti(), i1, i2);
567 }
568
569 ex epsilon_tensor(const ex & i1, const ex & i2, const ex & i3)
570 {
571         if (!is_a<idx>(i1) || !is_a<idx>(i2) || !is_a<idx>(i3))
572                 throw(std::invalid_argument("indices of epsilon tensor must be of type idx"));
573
574         ex dim = ex_to<idx>(i1).get_dim();
575         if (!dim.is_equal(ex_to<idx>(i2).get_dim()) || !dim.is_equal(ex_to<idx>(i3).get_dim()))
576                 throw(std::invalid_argument("all indices of epsilon tensor must have the same dimension"));
577         if (!ex_to<idx>(i1).get_dim().is_equal(_ex3))
578                 throw(std::runtime_error("index dimension of epsilon tensor must match number of indices"));
579
580         return indexed(tensepsilon(), sy_anti(), i1, i2, i3);
581 }
582
583 ex lorentz_eps(const ex & i1, const ex & i2, const ex & i3, const ex & i4, bool pos_sig)
584 {
585         if (!is_a<varidx>(i1) || !is_a<varidx>(i2) || !is_a<varidx>(i3) || !is_a<varidx>(i4))
586                 throw(std::invalid_argument("indices of Lorentz epsilon tensor must be of type varidx"));
587
588         ex dim = ex_to<idx>(i1).get_dim();
589         if (!dim.is_equal(ex_to<idx>(i2).get_dim()) || !dim.is_equal(ex_to<idx>(i3).get_dim()) || !dim.is_equal(ex_to<idx>(i4).get_dim()))
590                 throw(std::invalid_argument("all indices of epsilon tensor must have the same dimension"));
591         if (!ex_to<idx>(i1).get_dim().is_equal(_ex4))
592                 throw(std::runtime_error("index dimension of epsilon tensor must match number of indices"));
593
594         return indexed(tensepsilon(true, pos_sig), sy_anti(), i1, i2, i3, i4);
595 }
596
597 } // namespace GiNaC