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