]> www.ginac.de Git - ginac.git/blob - ginac/basic.cpp
a33433daf262863df202c7e0f231b93f1ab2398d
[ginac.git] / ginac / basic.cpp
1 /** @file basic.cpp
2  *
3  *  Implementation of GiNaC's ABC. */
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 <iostream>
24 #include <typeinfo>
25 #include <stdexcept>
26
27 #include "basic.h"
28 #include "ex.h"
29 #include "numeric.h"
30 #include "power.h"
31 #include "symbol.h"
32 #include "lst.h"
33 #include "ncmul.h"
34 #include "archive.h"
35 #include "utils.h"
36 #include "debugmsg.h"
37
38 #ifndef NO_NAMESPACE_GINAC
39 namespace GiNaC {
40 #endif // ndef NO_NAMESPACE_GINAC
41
42 GINAC_IMPLEMENT_REGISTERED_CLASS_NO_CTORS(basic, void)
43
44 //////////
45 // default constructor, destructor, copy constructor assignment operator and helpers
46 //////////
47
48 // public
49
50 #ifndef INLINE_BASIC_CONSTRUCTORS
51 basic::basic() : flags(0), refcount(0), tinfo_key(TINFO_BASIC)
52 {
53         debugmsg("basic default constructor", LOGLEVEL_CONSTRUCT);
54         // nothing to do
55 }
56
57 basic::~basic() 
58 {
59         debugmsg("basic destructor", LOGLEVEL_DESTRUCT);
60         destroy(false);
61         GINAC_ASSERT((!(flags & status_flags::dynallocated))||(refcount==0));
62 }
63
64 basic::basic(const basic & other) : flags(0), refcount(0), tinfo_key(TINFO_BASIC)
65 {
66         debugmsg("basic copy constructor", LOGLEVEL_CONSTRUCT);
67         copy(other);
68 }
69 #endif
70
71 const basic & basic::operator=(const basic & other)
72 {
73         debugmsg("basic operator=", LOGLEVEL_ASSIGNMENT);
74         if (this != &other) {
75                 destroy(true);
76                 copy(other);
77         }
78         return *this;
79 }
80
81 // protected
82
83 // none (all inlined)
84
85 //////////
86 // other constructors
87 //////////
88
89 #ifndef INLINE_BASIC_CONSTRUCTORS
90 basic::basic(unsigned ti) : flags(0), refcount(0), tinfo_key(ti)
91 {
92         debugmsg("basic constructor with tinfo_key", LOGLEVEL_CONSTRUCT);
93         // nothing to do
94 }
95 #endif
96
97 //////////
98 // archiving
99 //////////
100
101 /** Construct object from archive_node. */
102 basic::basic(const archive_node &n, const lst &sym_lst) : flags(0), refcount(0)
103 {
104         debugmsg("basic constructor from archive_node", LOGLEVEL_CONSTRUCT);
105
106         // Reconstruct tinfo_key from class name
107         std::string class_name;
108         if (n.find_string("class", class_name))
109                 tinfo_key = find_tinfo_key(class_name);
110         else
111                 throw (std::runtime_error("archive node contains no class name"));
112 }
113
114 /** Unarchive the object. */
115 ex basic::unarchive(const archive_node &n, const lst &sym_lst)
116 {
117         return (new basic(n, sym_lst))->setflag(status_flags::dynallocated);
118 }
119
120 /** Archive the object. */
121 void basic::archive(archive_node &n) const
122 {
123         n.add_string("class", class_name());
124 }
125
126 //////////
127 // functions overriding virtual functions from bases classes
128 //////////
129
130 // none
131
132 //////////
133 // new virtual functions which can be overridden by derived classes
134 //////////
135
136 // public
137
138 /** Output to stream formatted to be useful as ginsh input. */
139 void basic::print(std::ostream & os, unsigned upper_precedence) const
140 {
141         debugmsg("basic print",LOGLEVEL_PRINT);
142         os << "[basic object]";
143 }
144
145 /** Output to stream in ugly raw format, so brave developers can have a look
146  *  at the underlying structure. */
147 void basic::printraw(std::ostream & os) const
148 {
149         debugmsg("basic printraw",LOGLEVEL_PRINT);
150         os << "[basic object]";
151 }
152
153 /** Output to stream formatted in tree- (indented-) form, so developers can
154  *  have a look at the underlying structure. */
155 void basic::printtree(std::ostream & os, unsigned indent) const
156 {
157         debugmsg("basic printtree",LOGLEVEL_PRINT);
158         os << std::string(indent,' ') << "type=" << class_name()
159            << ", hash=" << hashvalue
160            << " (0x" << std::hex << hashvalue << std::dec << ")"
161            << ", flags=" << flags
162            << ", nops=" << nops() << std::endl;
163         for (unsigned i=0; i<nops(); ++i) {
164                 op(i).printtree(os,indent+delta_indent);
165         }
166 }
167
168 /** Output to stream formatted as C-source.
169  *
170  *  @param os a stream for output
171  *  @param type variable type (one of the csrc_types)
172  *  @param upper_precedence operator precedence of caller
173  *  @see ex::printcsrc */
174 void basic::printcsrc(std::ostream & os, unsigned type, unsigned upper_precedence) const
175 {
176         debugmsg("basic print csrc", LOGLEVEL_PRINT);
177 }
178
179 /** Little wrapper arount print to be called within a debugger.
180  *  This is needed because you cannot call foo.print(cout) from within the
181  *  debugger because it might not know what cout is.  This method can be invoked
182  *  with no argument and it will simply print to stdout.
183  *
184  *  @see basic::print*/
185 void basic::dbgprint(void) const
186 {
187         print(std::cerr);
188         std::cerr << std::endl;
189 }
190
191 /** Little wrapper arount printtree to be called within a debugger.
192  *
193  *  @see basic::dbgprint
194  *  @see basic::printtree */
195 void basic::dbgprinttree(void) const
196 {
197         printtree(std::cerr,0);
198 }
199
200 basic * basic::duplicate() const
201 {
202         debugmsg("basic duplicate",LOGLEVEL_DUPLICATE);
203         return new basic(*this);
204 }
205
206 /** Information about the object.
207  *
208  *  @see class info_flags */
209 bool basic::info(unsigned inf) const
210 {
211         return false; // all possible properties are false for basic objects
212 }
213
214 /** Number of operands/members. */
215 unsigned basic::nops() const
216 {
217         // iterating from 0 to nops() on atomic objects should be an empty loop,
218         // and accessing their elements is a range error.  Container objects should
219         // override this.
220         return 0;
221 }
222
223 /** Return operand/member at position i. */
224 ex basic::op(int i) const
225 {
226         return (const_cast<basic *>(this))->let_op(i);
227 }
228
229 /** Return modifyable operand/member at position i. */
230 ex & basic::let_op(int i)
231 {
232         throw(std::out_of_range("op() out of range"));
233 }
234
235 ex basic::operator[](const ex & index) const
236 {
237         if (is_exactly_of_type(*index.bp,numeric))
238                 return op(static_cast<const numeric &>(*index.bp).to_int());
239         
240         throw(std::invalid_argument("non-numeric indices not supported by this type"));
241 }
242
243 ex basic::operator[](int i) const
244 {
245         return op(i);
246 }
247
248 /** Search ocurrences.  An object  'has' an expression if it is the expression
249  *  itself or one of the children 'has' it. */
250 bool basic::has(const ex & other) const
251 {
252         GINAC_ASSERT(other.bp!=0);
253         if (is_equal(*other.bp)) return true;
254         if (nops()>0) {
255                 for (unsigned i=0; i<nops(); i++) {
256                         if (op(i).has(other)) return true;
257                 }
258         }
259         return false;
260 }
261
262 /** Return degree of highest power in symbol s. */
263 int basic::degree(const symbol & s) const
264 {
265         return 0;
266 }
267
268 /** Return degree of lowest power in symbol s. */
269 int basic::ldegree(const symbol & s) const
270 {
271         return 0;
272 }
273
274 /** Return coefficient of degree n in symbol s. */
275 ex basic::coeff(const symbol & s, int n) const
276 {
277         return n==0 ? *this : _ex0();
278 }
279
280 /** Sort expression in terms of powers of some symbol.
281  *  @param s symbol to sort in. */
282 ex basic::collect(const symbol & s) const
283 {
284         ex x;
285         int ldeg = this->ldegree(s);
286         int deg = this->degree(s);
287         for (int n=ldeg; n<=deg; n++) {
288                 x += this->coeff(s,n)*power(s,n);
289         }
290         return x;
291 }
292
293 /* Perform automatic symbolic evaluations on expression. */
294 ex basic::eval(int level) const
295 {
296         // There is nothing to do for basic objects:
297         return this->hold();
298 }
299
300 /** Evaluate object numerically. */
301 ex basic::evalf(int level) const
302 {
303         // There is nothing to do for basic objects:
304         return *this;
305 }
306
307 /* Substitute a set of symbols. */
308 ex basic::subs(const lst & ls, const lst & lr) const
309 {
310         return *this;
311 }
312
313 /** Default interface of nth derivative ex::diff(s, n).  It should be called
314  *  instead of ::derivative(s) for first derivatives and for nth derivatives it
315  *  just recurses down.
316  *
317  *  @param s symbol to differentiate in
318  *  @param nth order of differentiation
319  *  @see ex::diff */
320 ex basic::diff(const symbol & s, unsigned nth) const
321 {
322         // trivial: zeroth derivative
323         if (nth==0)
324                 return ex(*this);
325         
326         // evaluate unevaluated *this before differentiating
327         if (!(flags & status_flags::evaluated))
328                 return ex(*this).diff(s, nth);
329         
330         ex ndiff = this->derivative(s);
331         while (!ndiff.is_zero() &&    // stop differentiating zeros
332                nth>1) {
333                 ndiff = ndiff.diff(s);
334                 --nth;
335         }
336         return ndiff;
337 }
338
339 exvector basic::get_indices(void) const
340 {
341         return exvector(); // return an empty exvector
342 }
343
344 ex basic::simplify_ncmul(const exvector & v) const
345 {
346         return simplified_ncmul(v);
347 }
348
349 // protected
350
351 /** Default implementation of ex::diff(). It simply throws an error message.
352  *
353  *  @exception logic_error (differentiation not supported by this type)
354  *  @see ex::diff */
355 ex basic::derivative(const symbol & s) const
356 {
357         throw(std::logic_error("differentiation not supported by this type"));
358 }
359
360 /** Returns order relation between two objects of same type.  Needs to be
361  *  implemented by each class. */
362 int basic::compare_same_type(const basic & other) const
363 {
364         return compare_pointers(this, &other);
365 }
366
367 /** Returns true if two objects of same type are equal.  Normally needs
368  *  not be reimplemented as long as it wasn't overwritten by some parent
369  *  class, since it just calls complare_same_type(). */
370 bool basic::is_equal_same_type(const basic & other) const
371 {
372         return compare_same_type(other)==0;
373 }
374
375 unsigned basic::return_type(void) const
376 {
377         return return_types::commutative;
378 }
379
380 unsigned basic::return_type_tinfo(void) const
381 {
382         return tinfo();
383 }
384
385 unsigned basic::calchash(void) const
386 {
387         unsigned v=golden_ratio_hash(tinfo());
388         for (unsigned i=0; i<nops(); i++) {
389                 v=rotate_left_31(v);
390                 v ^= (const_cast<basic *>(this))->op(i).gethash();
391         }
392
393         v = v & 0x7FFFFFFFU;
394         
395         // store calculated hash value only if object is already evaluated
396         if (flags & status_flags::evaluated) {
397                 setflag(status_flags::hash_calculated);
398                 hashvalue=v;
399         }
400
401         return v;
402 }
403
404 /** Expand expression, i.e. multiply it out and return the result as a new
405  *  expression. */
406 ex basic::expand(unsigned options) const
407 {
408         return this->setflag(status_flags::expanded);
409 }
410
411
412 //////////
413 // non-virtual functions in this class
414 //////////
415
416 // public
417
418 /** Substitute symbols in expression and return the result as a new expression.
419  *  There are two valid types of replacement arguments: 1) a relational like
420  *  symbol==ex and 2) a list of relationals lst(symbol1==ex1,symbol2==ex2,...),
421  *  which is converted to subs(lst(symbol1,symbol2,...),lst(ex1,ex2,...)).
422  *  In addition, an object of class idx can be used instead of a symbol. */
423 ex basic::subs(const ex & e) const
424 {
425         if (e.info(info_flags::relation_equal)) {
426                 return subs(lst(e));
427         }
428         if (!e.info(info_flags::list)) {
429                 throw(std::invalid_argument("basic::subs(ex): argument must be a list"));
430         }
431         lst ls;
432         lst lr;
433         for (unsigned i=0; i<e.nops(); i++) {
434                 if (!e.op(i).info(info_flags::relation_equal)) {
435                         throw(std::invalid_argument("basic::subs(ex): argument must be a list or equations"));
436                 }
437                 if (!e.op(i).op(0).info(info_flags::symbol)) {
438                         if (!e.op(i).op(0).info(info_flags::idx)) {
439                                 throw(std::invalid_argument("basic::subs(ex): lhs must be a symbol or an idx"));
440                         }
441                 }
442                 ls.append(e.op(i).op(0));
443                 lr.append(e.op(i).op(1));
444         }
445         return subs(ls,lr);
446 }
447
448 /** Compare objects to establish canonical order.
449  *  All compare functions return: -1 for *this less than other, 0 equal,
450  *  1 greater. */
451 int basic::compare(const basic & other) const
452 {
453         unsigned hash_this = gethash();
454         unsigned hash_other = other.gethash();
455
456         if (hash_this<hash_other) return -1;
457         if (hash_this>hash_other) return 1;
458
459         unsigned typeid_this = tinfo();
460         unsigned typeid_other = other.tinfo();
461
462         if (typeid_this<typeid_other) {
463                 /*
464                 cout << "hash collision, different types: " 
465                          << *this << " and " << other << endl;
466                 this->printraw(cout);
467                 cout << " and ";
468                 other.printraw(cout);
469                 cout << endl;
470                 */
471                 return -1;
472         }
473         if (typeid_this>typeid_other) {
474                 /*
475                 cout << "hash collision, different types: " 
476                          << *this << " and " << other << endl;
477                 this->printraw(cout);
478                 cout << " and ";
479                 other.printraw(cout);
480                 cout << endl;
481                 */
482                 return 1;
483         }
484
485         GINAC_ASSERT(typeid(*this)==typeid(other));
486
487         int cmpval=compare_same_type(other);
488         if ((cmpval!=0)&&(hash_this<0x80000000U)) {
489                 /*
490                 cout << "hash collision, same type: " 
491                          << *this << " and " << other << endl;
492                 this->printraw(cout);
493                 cout << " and ";
494                 other.printraw(cout);
495                 cout << endl;
496                 */
497         }
498         return cmpval;
499 }
500
501 /** Test for equality. */
502 bool basic::is_equal(const basic & other) const
503 {
504         unsigned hash_this = gethash();
505         unsigned hash_other = other.gethash();
506
507         if (hash_this!=hash_other) return false;
508
509         unsigned typeid_this = tinfo();
510         unsigned typeid_other = other.tinfo();
511
512         if (typeid_this!=typeid_other) return false;
513
514         GINAC_ASSERT(typeid(*this)==typeid(other));
515
516         return is_equal_same_type(other);
517 }
518
519 // protected
520
521 /** Stop further evaluation.
522  *  @see basic::eval */
523 const basic & basic::hold(void) const
524 {
525         return setflag(status_flags::evaluated);
526 }
527
528 void basic::ensure_if_modifiable(void) const
529 {
530         if (refcount>1)
531                 throw(std::runtime_error("cannot modify multiply referenced object"));
532 }
533
534 //////////
535 // static member variables
536 //////////
537
538 // protected
539
540 unsigned basic::precedence = 70;
541 unsigned basic::delta_indent = 4;
542
543 //////////
544 // global variables
545 //////////
546
547 int max_recursion_level=1024;
548
549 #ifndef NO_NAMESPACE_GINAC
550 } // namespace GiNaC
551 #endif // ndef NO_NAMESPACE_GINAC