]> www.ginac.de Git - ginac.git/blob - ginac/basic.cpp
5c3c147faf57d039fe57e94c9be0e2f92112d7bb
[ginac.git] / ginac / basic.cpp
1 /** @file basic.cpp
2  *
3  *  Implementation of GiNaC's ABC. */
4
5 /*
6  *  GiNaC Copyright (C) 1999-2000 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(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(0);
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(1);
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     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(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(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(ostream & os, unsigned indent) const
156 {
157     debugmsg("basic printtree",LOGLEVEL_PRINT);
158     os << string(indent,' ') << "type=" << typeid(*this).name()
159        << ", hash=" << hashvalue << " (0x" << hex << hashvalue << dec << ")"
160        << ", flags=" << flags
161        << ", nops=" << nops() << endl;
162     for (unsigned i=0; i<nops(); ++i) {
163         op(i).printtree(os,indent+delta_indent);
164     }
165 }
166
167 /** Output to stream formatted as C-source.
168  *
169  *  @param os a stream for output
170  *  @param type variable type (one of the csrc_types)
171  *  @param upper_precedence operator precedence of caller
172  *  @see ex::printcsrc */
173 void basic::printcsrc(ostream & os, unsigned type, unsigned upper_precedence) const
174 {
175     debugmsg("basic print csrc", LOGLEVEL_PRINT);
176 }
177
178 /** Little wrapper arount print to be called within a debugger. */
179 void basic::dbgprint(void) const
180 {
181     print(cerr);
182     cerr << endl;
183 }
184
185 /** Little wrapper arount printtree to be called within a debugger. */
186 void basic::dbgprinttree(void) const
187 {
188     printtree(cerr,0);
189 }
190
191 basic * basic::duplicate() const
192 {
193     debugmsg("basic duplicate",LOGLEVEL_DUPLICATE);
194     return new basic(*this);
195 }
196
197 /** Information about the object.
198  *
199  *  @see class info_flags */
200 bool basic::info(unsigned inf) const
201 {
202     return false; // all possible properties are false for basic objects
203 }
204
205 /** Number of operands/members. */
206 unsigned basic::nops() const
207 {
208     return 0;
209 }
210
211 /** Return operand/member at position i. */
212 ex basic::op(int i) const
213 {
214     return (const_cast<basic *>(this))->let_op(i);
215 }
216
217 /** Return modifyable operand/member at position i. */
218 ex & basic::let_op(int i)
219 {
220     throw(std::out_of_range("op() out of range"));
221 }
222
223 ex basic::operator[](const ex & index) const
224 {
225     if (is_exactly_of_type(*index.bp,numeric))
226         return op(static_cast<const numeric &>(*index.bp).to_int());
227     
228     throw(std::invalid_argument("non-numeric indices not supported by this type"));
229 }
230
231 ex basic::operator[](int i) const
232 {
233     return op(i);
234 }
235
236 /** Search ocurrences.  An object  'has' an expression if it is the expression
237  *  itself or one of the children 'has' it. */
238 bool basic::has(const ex & other) const
239 {
240     GINAC_ASSERT(other.bp!=0);
241     if (is_equal(*other.bp)) return true;
242     if (nops()>0) {
243         for (unsigned i=0; i<nops(); i++) {
244             if (op(i).has(other)) return true;
245         }
246     }
247     return false;
248 }
249
250 /** Return degree of highest power in symbol s. */
251 int basic::degree(const symbol & s) const
252 {
253     return 0;
254 }
255
256 /** Return degree of lowest power in symbol s. */
257 int basic::ldegree(const symbol & s) const
258 {
259     return 0;
260 }
261
262 /** Return coefficient of degree n in symbol s. */
263 ex basic::coeff(const symbol & s, int n) const
264 {
265     return n==0 ? *this : _ex0();
266 }
267
268 /** Sort expression in terms of powers of some symbol.
269  *  @param s symbol to sort in. */
270 ex basic::collect(const symbol & s) const
271 {
272     ex x;
273     int ldeg = this->ldegree(s);
274     int deg = this->degree(s);
275     for (int n=ldeg; n<=deg; n++) {
276         x += this->coeff(s,n)*power(s,n);
277     }
278     return x;
279 }
280
281 /* Perform automatic symbolic evaluations on expression. */
282 ex basic::eval(int level) const
283 {
284     return this->hold();
285 }
286
287 /** Evaluate object numerically. */
288 ex basic::evalf(int level) const
289 {
290     return *this;
291 }
292
293 /* Substitute a set of symbols. */
294 ex basic::subs(const lst & ls, const lst & lr) const
295 {
296     return *this;
297 }
298
299 /** Default interface of nth derivative ex::diff(s, n).  It should be called
300  *  instead of ::derivative(s) for first derivatives and for nth derivatives it
301  *  just recurses down.
302  *
303  *  @param s symbol to differentiate in
304  *  @param nth order of differentiation
305  *  @see ex::diff */
306 ex basic::diff(const symbol & s, unsigned nth) const
307 {
308     // trivial: zeroth derivative
309     if (!nth)
310         return ex(*this);
311     
312     // evaluate unevalueted *this before differentiating
313     if (!(flags & status_flags::evaluated))
314         return ex(*this).diff(s, nth);
315     
316     ex ndiff = derivative(s);
317     while (!ndiff.is_zero() &&    // stop differentiating zeros
318            nth>1) {
319         ndiff = ndiff.diff(s);
320         --nth;
321     }
322     return ndiff;
323 }
324
325 exvector basic::get_indices(void) const
326 {
327     return exvector(); // return an empty exvector
328 }
329
330 ex basic::simplify_ncmul(const exvector & v) const
331 {
332     return simplified_ncmul(v);
333 }
334
335 // protected
336
337 /** Default implementation of ex::diff(). It simply throws an error message.
338  *
339  *  @exception logic_error (differentiation not supported by this type)
340  *  @see ex::diff */
341 ex basic::derivative(const symbol & s) const
342 {
343     throw(std::logic_error("differentiation not supported by this type"));
344 }
345
346 int basic::compare_same_type(const basic & other) const
347 {
348     return compare_pointers(this, &other);
349 }
350
351 bool basic::is_equal_same_type(const basic & other) const
352 {
353     return compare_same_type(other)==0;
354 }
355
356 unsigned basic::return_type(void) const
357 {
358     return return_types::commutative;
359 }
360
361 unsigned basic::return_type_tinfo(void) const
362 {
363     return tinfo();
364 }
365
366 unsigned basic::calchash(void) const
367 {
368     unsigned v=golden_ratio_hash(tinfo());
369     for (unsigned i=0; i<nops(); i++) {
370         v=rotate_left_31(v);
371         v ^= (const_cast<basic *>(this))->op(i).gethash();
372     }
373
374     v = v & 0x7FFFFFFFU;
375     
376     // store calculated hash value only if object is already evaluated
377     if (flags & status_flags::evaluated) {
378         setflag(status_flags::hash_calculated);
379         hashvalue=v;
380     }
381
382     return v;
383 }
384
385 /** Expand expression, i.e. multiply it out and return the result as a new
386  *  expression. */
387 ex basic::expand(unsigned options) const
388 {
389     return this->setflag(status_flags::expanded);
390 }
391
392
393 //////////
394 // non-virtual functions in this class
395 //////////
396
397 // public
398
399 /** Substitute symbols in expression and return the result as a new expression.
400  *  There are two valid types of replacement arguments: 1) a relational like
401  *  symbol==ex and 2) a list of relationals lst(symbol1==ex1,symbol2==ex2,...),
402  *  which is converted to subs(lst(symbol1,symbol2,...),lst(ex1,ex2,...)).
403  *  In addition, an object of class idx can be used instead of a symbol. */
404 ex basic::subs(const ex & e) const
405 {
406     if (e.info(info_flags::relation_equal)) {
407         return subs(lst(e));
408     }
409     if (!e.info(info_flags::list)) {
410         throw(std::invalid_argument("basic::subs(ex): argument must be a list"));
411     }
412     lst ls;
413     lst lr;
414     for (unsigned i=0; i<e.nops(); i++) {
415         if (!e.op(i).info(info_flags::relation_equal)) {
416             throw(std::invalid_argument("basic::subs(ex): argument must be a list or equations"));
417         }
418         if (!e.op(i).op(0).info(info_flags::symbol)) {
419             if (!e.op(i).op(0).info(info_flags::idx)) {
420                 throw(std::invalid_argument("basic::subs(ex): lhs must be a symbol or an idx"));
421             }
422         }
423         ls.append(e.op(i).op(0));
424         lr.append(e.op(i).op(1));
425     }
426     return subs(ls,lr);
427 }
428
429 /** Compare objects to establish canonical order.
430  *  All compare functions return: -1 for *this less than other, 0 equal,
431  *  1 greater. */
432 int basic::compare(const basic & other) const
433 {
434     unsigned hash_this = gethash();
435     unsigned hash_other = other.gethash();
436
437     if (hash_this<hash_other) return -1;
438     if (hash_this>hash_other) return 1;
439
440     unsigned typeid_this = tinfo();
441     unsigned typeid_other = other.tinfo();
442
443     if (typeid_this<typeid_other) {
444         /*
445         cout << "hash collision, different types: " 
446              << *this << " and " << other << endl;
447         this->printraw(cout);
448         cout << " and ";
449         other.printraw(cout);
450         cout << endl;
451         */
452         return -1;
453     }
454     if (typeid_this>typeid_other) {
455         /*
456         cout << "hash collision, different types: " 
457              << *this << " and " << other << endl;
458         this->printraw(cout);
459         cout << " and ";
460         other.printraw(cout);
461         cout << endl;
462         */
463         return 1;
464     }
465
466     GINAC_ASSERT(typeid(*this)==typeid(other));
467
468     int cmpval=compare_same_type(other);
469     if ((cmpval!=0)&&(hash_this<0x80000000U)) {
470         /*
471         cout << "hash collision, same type: " 
472              << *this << " and " << other << endl;
473         this->printraw(cout);
474         cout << " and ";
475         other.printraw(cout);
476         cout << endl;
477         */
478     }
479     return cmpval;
480 }
481
482 /** Test for equality. */
483 bool basic::is_equal(const basic & other) const
484 {
485     unsigned hash_this = gethash();
486     unsigned hash_other = other.gethash();
487
488     if (hash_this!=hash_other) return false;
489
490     unsigned typeid_this = tinfo();
491     unsigned typeid_other = other.tinfo();
492
493     if (typeid_this!=typeid_other) return false;
494
495     GINAC_ASSERT(typeid(*this)==typeid(other));
496
497     return is_equal_same_type(other);
498 }
499
500 // protected
501
502 /** Stop further evaluation.
503  *  @see basic::eval */
504 const basic & basic::hold(void) const
505 {
506     return setflag(status_flags::evaluated);
507 }
508
509 void basic::ensure_if_modifiable(void) const
510 {
511     if (refcount>1) {
512         throw(std::runtime_error("cannot modify multiply referenced object"));
513     }
514 }
515
516 //////////
517 // static member variables
518 //////////
519
520 // protected
521
522 unsigned basic::precedence = 70;
523 unsigned basic::delta_indent = 4;
524
525 //////////
526 // global constants
527 //////////
528
529 const basic some_basic;
530 const type_info & typeid_basic=typeid(some_basic);
531
532 //////////
533 // global variables
534 //////////
535
536 int max_recursion_level=1024;
537
538 #ifndef NO_NAMESPACE_GINAC
539 } // namespace GiNaC
540 #endif // ndef NO_NAMESPACE_GINAC