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