]> www.ginac.de Git - ginac.git/blob - ginac/idx.cpp
- added documentation to the indexed, color, lortensor and clifford classes
[ginac.git] / ginac / idx.cpp
1 /** @file idx.cpp
2  *
3  *  Implementation of GiNaC's indices. */
4
5 /*
6  *  GiNaC Copyright (C) 1999-2001 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 <stdexcept>
24
25 #include "idx.h"
26 #include "ex.h"
27 #include "lst.h"
28 #include "relational.h"
29 #include "archive.h"
30 #include "utils.h"
31 #include "debugmsg.h"
32
33 #ifndef NO_NAMESPACE_GINAC
34 namespace GiNaC {
35 #endif // ndef NO_NAMESPACE_GINAC
36
37 GINAC_IMPLEMENT_REGISTERED_CLASS(idx, basic)
38
39 //////////
40 // default constructor, destructor, copy constructor assignment operator and helpers
41 //////////
42
43 // public
44
45 idx::idx() : inherited(TINFO_idx), symbolic(true), covariant(false)
46 {
47         debugmsg("idx default constructor",LOGLEVEL_CONSTRUCT);
48         serial=next_serial++;
49         name=autoname_prefix()+ToString(serial);
50 }
51
52 idx::~idx() 
53 {
54         debugmsg("idx destructor",LOGLEVEL_DESTRUCT);
55         destroy(false);
56 }
57
58 idx::idx(const idx & other)
59 {
60         debugmsg("idx copy constructor",LOGLEVEL_CONSTRUCT);
61         copy(other);
62 }
63
64 const idx & idx::operator=(const idx & other)
65 {
66         debugmsg("idx operator=",LOGLEVEL_ASSIGNMENT);
67         if (this != &other) {
68                 destroy(true);
69                 copy(other);
70         }
71         return *this;
72 }
73
74 // protected
75
76 void idx::copy(const idx & other)
77 {
78         inherited::copy(other);
79         serial=other.serial;
80         symbolic=other.symbolic;
81         name=other.name;
82         value=other.value;
83         covariant=other.covariant;
84 }
85
86 void idx::destroy(bool call_parent)
87 {
88         if (call_parent) inherited::destroy(call_parent);
89 }
90
91 //////////
92 // other constructors
93 //////////
94
95 // public
96
97 /** Construct symbolic index, using an automatically generated unique name.
98  *
99  *  @param cov Index is covariant (contravariant otherwise)
100  *  @return newly constructed index */
101 idx::idx(bool cov) : inherited(TINFO_idx), symbolic(true), covariant(cov)
102 {
103         debugmsg("idx constructor from bool",LOGLEVEL_CONSTRUCT);
104         serial = next_serial++;
105         name = autoname_prefix()+ToString(serial);
106 }
107
108 /** Construct symbolic index with specified name.
109  *
110  *  @param n Symbolic index name
111  *  @param cov Index is covariant (contravariant otherwise)
112  *  @return newly constructed index */
113 idx::idx(const std::string & n, bool cov) : inherited(TINFO_idx),  
114         symbolic(true), name(n), covariant(cov)
115 {
116         debugmsg("idx constructor from string,bool",LOGLEVEL_CONSTRUCT);
117         serial = next_serial++;
118 }
119
120 /** Construct symbolic index with specified name.
121  *
122  *  @param n Symbolic index name
123  *  @param cov Index is covariant (contravariant otherwise)
124  *  @return newly constructed index */
125 idx::idx(const char * n, bool cov) : inherited(TINFO_idx), symbolic(true), name(n), covariant(cov)
126 {
127         debugmsg("idx constructor from char*,bool",LOGLEVEL_CONSTRUCT);
128         serial = next_serial++;
129 }
130
131 /** Construct numeric index with specified value.
132  *
133  *  @param v Numeric index value
134  *  @param cov Index is covariant (contravariant otherwise)
135  *  @return newly constructed index */
136 idx::idx(unsigned v, bool cov) : inherited(TINFO_idx), symbolic(false), value(v), covariant(cov)
137 {
138         debugmsg("idx constructor from unsigned,bool",LOGLEVEL_CONSTRUCT);
139         serial = 0;
140 }
141
142 //////////
143 // archiving
144 //////////
145
146 /** Construct object from archive_node. */
147 idx::idx(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
148 {
149         debugmsg("idx constructor from archive_node", LOGLEVEL_CONSTRUCT);
150         n.find_bool("symbolic", symbolic);
151         n.find_bool("covariant", covariant);
152         if (symbolic) {
153                 serial = next_serial++;
154                 if (!(n.find_string("name", name)))
155                         name = autoname_prefix() + ToString(serial);
156         } else {
157                 serial = 0;
158                 n.find_unsigned("value", value);
159         }
160 }
161
162 /** Unarchive the object. */
163 ex idx::unarchive(const archive_node &n, const lst &sym_lst)
164 {
165         ex s = (new idx(n, sym_lst))->setflag(status_flags::dynallocated);
166
167         if (ex_to_idx(s).symbolic) {
168                 // If idx is in sym_lst, return the existing idx
169                 for (unsigned i=0; i<sym_lst.nops(); i++) {
170                         if (is_ex_of_type(sym_lst.op(i), idx) && (ex_to_idx(sym_lst.op(i)).name == ex_to_idx(s).name))
171                                 return sym_lst.op(i);
172                 }
173         }
174         return s;
175 }
176
177 /** Archive the object. */
178 void idx::archive(archive_node &n) const
179 {
180         inherited::archive(n);
181         n.add_bool("symbolic", symbolic);
182         n.add_bool("covariant", covariant);
183         if (symbolic)
184                 n.add_string("name", name);
185         else
186                 n.add_unsigned("value", value);
187 }
188
189 //////////
190 // functions overriding virtual functions from bases classes
191 //////////
192
193 // public
194
195 basic * idx::duplicate() const
196 {
197         debugmsg("idx duplicate",LOGLEVEL_DUPLICATE);
198         return new idx(*this);
199 }
200
201 void idx::printraw(std::ostream & os) const
202 {
203         debugmsg("idx printraw",LOGLEVEL_PRINT);
204
205         os << "idx(";
206
207         if (symbolic) {
208                 os << "symbolic,name=" << name;
209         } else {
210                 os << "non symbolic,value=" << value;
211         }
212
213         if (covariant) {
214                 os << ",covariant";
215         } else {
216                 os << ",contravariant";
217         }
218
219         os << ",serial=" << serial;
220         os << ",hash=" << hashvalue << ",flags=" << flags;
221         os << ")";
222 }
223
224 void idx::printtree(std::ostream & os, unsigned indent) const
225 {
226         debugmsg("idx printtree",LOGLEVEL_PRINT);
227
228         os << std::string(indent,' ') << "idx: ";
229
230         if (symbolic) {
231                 os << "symbolic,name=" << name;
232         } else {
233                 os << "non symbolic,value=" << value;
234         }
235
236         if (covariant) {
237                 os << ",covariant";
238         } else {
239                 os << ",contravariant";
240         }
241
242         os << ", serial=" << serial
243            << ", hash=" << hashvalue
244            << " (0x" << std::hex << hashvalue << std::dec << ")"
245            << ", flags=" << flags << std::endl;
246 }
247
248 void idx::print(std::ostream & os, unsigned upper_precedence) const
249 {
250         debugmsg("idx print",LOGLEVEL_PRINT);
251
252         if (covariant) {
253                 os << "_";
254         } else {
255                 os << "~";
256         }
257         if (symbolic) {
258                 os << name;
259         } else {
260                 os << value;
261         }
262 }
263
264 bool idx::info(unsigned inf) const
265 {
266         if (inf==info_flags::idx) return true;
267         return inherited::info(inf);
268 }
269
270 ex idx::subs(const lst & ls, const lst & lr) const
271 {
272         GINAC_ASSERT(ls.nops()==lr.nops());
273 #ifdef DO_GINAC_ASSERT
274         for (unsigned i=0; i<ls.nops(); i++) {
275                 GINAC_ASSERT(is_ex_exactly_of_type(ls.op(i),symbol)||
276                            is_ex_of_type(ls.op(i),idx));
277         }
278 #endif // def DO_GINAC_ASSERT
279
280         for (unsigned i=0; i<ls.nops(); i++) {
281                 if (is_equal(*(ls.op(i)).bp)) {
282                         return lr.op(i);
283                 }
284         }
285         return *this;
286 }
287
288 // protected
289
290 int idx::compare_same_type(const basic & other) const
291 {
292         GINAC_ASSERT(is_of_type(other,idx));
293         const idx &o = static_cast<const idx &>(&other);
294
295         if (covariant!=o.covariant) {
296                 // different co/contravariant
297                 return covariant ? -1 : 1;
298         }
299
300         if ((!symbolic) && (!o.symbolic)) {
301                 // non-symbolic, of equal type: compare values
302                 if (value==o.value) {
303                         return 0;
304                 }
305                 return value<o.value ? -1 : 1;
306         }
307
308         if (symbolic && o.symbolic) {
309                 // both symbolic: compare serials
310                 if (serial==o.serial) {
311                         return 0;
312                 }
313                 return serial<o.serial ? -1 : 1;
314         }
315
316         // one symbolic, one value: value is sorted first
317         return o.symbolic ? -1 : 1;
318 }
319
320 bool idx::is_equal_same_type(const basic & other) const
321 {
322         GINAC_ASSERT(is_of_type(other,idx));
323         const idx &o = static_cast<const idx &>(other);
324
325         if (covariant != o.covariant) return false;
326         if (symbolic != o.symbolic) return false;
327         if (symbolic && o.symbolic) return serial==o.serial;
328         return value==o.value;
329 }    
330
331 unsigned idx::calchash(void) const
332 {
333         hashvalue=golden_ratio_hash(golden_ratio_hash(tinfo_key ^ serial));
334         setflag(status_flags::hash_calculated);
335         return hashvalue;
336 }
337
338 //////////
339 // new virtual functions which can be overridden by derived classes
340 //////////
341
342 // public
343
344 /** Check whether the index forms a co-/contravariant pair with another
345  *  index (i.e. same name/value but opposite co-/contravariance). */
346 bool idx::is_co_contra_pair(const basic & other) const
347 {
348         // like is_equal_same_type(), but tests for different covariant status
349         GINAC_ASSERT(is_of_type(other,idx));
350         const idx & o=static_cast<const idx &>(const_cast<basic &>(other));
351
352         if (covariant==o.covariant) return false;
353         if (symbolic!=o.symbolic) return false;
354         if (symbolic && o.symbolic) return serial==o.serial;
355         return value==o.value;
356 }    
357
358 /** Toggle co-/contravariance of index. */
359 ex idx::toggle_covariant(void) const
360 {
361         idx * i_copy=static_cast<idx *>(duplicate());
362         i_copy->covariant = !i_copy->covariant;
363         i_copy->clearflag(status_flags::hash_calculated);
364         return i_copy->setflag(status_flags::dynallocated);
365 }
366
367 //////////
368 // non-virtual functions in this class
369 //////////
370
371 // private
372
373 std::string & idx::autoname_prefix(void)
374 {
375         static std::string * s = new std::string("index");
376         return *s;
377 }
378
379 //////////
380 // static member variables
381 //////////
382
383 // protected
384
385 unsigned idx::next_serial=0;
386
387 //////////
388 // global constants
389 //////////
390
391 const idx some_idx;
392 const std::type_info & typeid_idx = typeid(some_idx);
393
394 //////////
395 // other functions
396 //////////
397
398 /** Bring a vector of indices into a canonic order. This operation only makes
399  *  sense if the object carrying these indices is either symmetric or totally
400  *  antisymmetric with respect to the indices.
401  *
402  *  @param iv Index vector
403  *  @param antisymmetric Whether the object carrying the indices is antisymmetric (symmetric otherwise)
404  *  @return the sign introduced by the reordering of the indices. For symmetric
405  *          objects this is always +1. For antisymmetric objects this is either
406  *          +1 or -1 or 0 (if two equal indices were encountered). If the index
407  *          vector was unchanged this function returns INT_MAX. */
408 int canonicalize_indices(exvector & iv, bool antisymmetric)
409 {
410         if (iv.size()<2) {
411                 // nothing do to for 0 or 1 indices
412                 return INT_MAX;
413         }
414
415         bool something_changed=false;
416         int sig=1;
417
418         // simple bubble sort algorithm should be sufficient for the small number of indices needed
419         exvector::const_iterator last_idx=iv.end();
420         exvector::const_iterator next_to_last_idx=iv.end()-1;
421         for (exvector::iterator it1=iv.begin(); it1!=next_to_last_idx; ++it1) {
422                 for (exvector::iterator it2=it1+1; it2!=last_idx; ++it2) {
423                         int cmpval=(*it1).compare(*it2);
424                         if (cmpval==1) {
425                                 iter_swap(it1,it2);
426                                 something_changed=true;
427                                 if (antisymmetric) sig=-sig;
428                         } else if ((cmpval==0) && antisymmetric) {
429                                 something_changed=true;
430                                 sig=0;
431                         }
432                 }
433         }
434
435         return something_changed ? sig : INT_MAX;
436 }
437
438 /** Build a vector of indices as the set intersection of two other index
439  *  vectors (i.e. the returned vector contains the indices which appear in
440  *  both source vectors). */
441 exvector idx_intersect(const exvector & iv1, const exvector & iv2)
442 {
443         // Create union vector
444         exvector iv_union;
445         iv_union.reserve(iv1.size() + iv2.size());
446         iv_union.insert(iv_union.end(), iv1.begin(), iv1.end());
447         iv_union.insert(iv_union.end(), iv2.begin(), iv2.end());
448
449         // Sort it
450         canonicalize_indices(iv_union);
451
452         // Look for duplicates
453         exvector iv_intersect;
454         exvector::const_iterator cit = iv_union.begin(), citend = iv_union.end();
455         ex e;
456         if (cit != citend)
457                 e = *cit++;
458         while (cit != citend) {
459                 if (e.is_equal(*cit)) {
460                         iv_intersect.push_back(e);
461                         do {
462                                 cit++;
463                         } while (cit != citend && e.is_equal(*cit));
464                         if (cit == citend)
465                                 break;
466                 }
467                 e = *cit++;
468         }
469         return iv_intersect;
470 }
471
472 /** Given a vector iv3 of three indices and a vector iv2 of two indices
473  *  where iv2 is a subset of iv3, return the (free) index that is in iv3
474  *  but not in iv2 and the sign introduced by permuting that index to the
475  *  front.
476  *
477  *  @param iv3 Vector of 3 indices
478  *  @param iv2 Vector of 2 indices, must be a subset of iv3
479  *  @param sig Returns the sign introduced by permuting the free index to the
480  *             front if the object carrying the indices was antisymmetric (if
481  *             it's symmetric, you can just ignore the returned value).
482  *  @return the free index (the one that is in iv3 but not in iv2) */
483 ex permute_free_index_to_front(const exvector & iv3, const exvector & iv2, int * sig)
484 {
485         // match (return value,iv2) to iv3 by permuting indices
486         // iv3 is always cyclic
487
488         GINAC_ASSERT(iv3.size()==3);
489         GINAC_ASSERT(iv2.size()==2);
490
491         *sig=1;
492
493 #define TEST_PERMUTATION(A,B,C,P) \
494         if ((iv3[B].is_equal(iv2[0]))&&(iv3[C].is_equal(iv2[1]))) { \
495                 *sig=P; \
496                 return iv3[A]; \
497         }
498         
499         TEST_PERMUTATION(0,1,2,  1);
500         TEST_PERMUTATION(0,2,1, -1);
501         TEST_PERMUTATION(1,0,2, -1);
502         TEST_PERMUTATION(1,2,0,  1);
503         TEST_PERMUTATION(2,0,1,  1);
504         TEST_PERMUTATION(2,1,0, -1);
505         throw(std::logic_error("permute_free_index_to_front(): no valid permutation found"));
506 }
507         
508 /** Substitute one index in a vector of expressions.
509  *
510  *  @param v Vector to substitute in (will be modified)
511  *  @param is Index being substituted
512  *  @param ir Index to replace by
513  *  @return number of performed substitutions */
514 unsigned subs_index_in_exvector(exvector & v, const ex & is, const ex & ir)
515 {
516         exvector::iterator it;
517         unsigned replacements=0;
518         unsigned current_replacements;
519
520         GINAC_ASSERT(is_ex_of_type(is,idx));
521         GINAC_ASSERT(is_ex_of_type(ir,idx));
522    
523         for (it=v.begin(); it!=v.end(); ++it) {
524                 current_replacements=count_index(*it,is);
525                 if (current_replacements>0) {
526                         (*it)=(*it).subs(is==ir);
527                 }
528                 replacements += current_replacements;
529         }
530         return replacements;
531 }
532
533 /** Count number of times a given index appears in the index vector of an
534  *  indexed object.
535  *
536  *  @param e Indexed object
537  *  @param i Index to look for
538  *  @return number of times the index was found */
539 unsigned count_index(const ex & e, const ex & i)
540 {
541         exvector idxv=e.get_indices();
542         unsigned count=0;
543         for (exvector::const_iterator cit=idxv.begin(); cit!=idxv.end(); ++cit) {
544                 if ((*cit).is_equal(i)) count++;
545         }
546         return count;
547 }
548
549 /** Substitute multiple indices in an expression.
550  *
551  *  @param e Expression to substitute in
552  *  @param idxv_subs Vector of indices being substituted
553  *  @param idxv_repl Vector of indices to replace by (1:1 correspondence to idxv_subs)
554  *  @return expression with substituted indices */
555 ex subs_indices(const ex & e, const exvector & idxv_subs, const exvector & idxv_repl)
556 {
557         GINAC_ASSERT(idxv_subs.size()==idxv_repl.size());
558         ex res=e;
559         for (unsigned i=0; i<idxv_subs.size(); ++i) {
560                 res=res.subs(idxv_subs[i]==idxv_repl[i]);
561         }
562         return res;
563 }
564
565 #ifndef NO_NAMESPACE_GINAC
566 } // namespace GiNaC
567 #endif // ndef NO_NAMESPACE_GINAC