]> www.ginac.de Git - ginac.git/blob - ginac/basic.cpp
* Tidied some old crap.
[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 namespace GiNaC {
39
40 GINAC_IMPLEMENT_REGISTERED_CLASS_NO_CTORS(basic, void)
41
42 //////////
43 // default ctor, dtor, copy ctor assignment operator and helpers
44 //////////
45
46 // public
47
48 basic::basic(const basic & other) : tinfo_key(TINFO_basic), flags(0), refcount(0)
49 {
50         debugmsg("basic copy ctor", LOGLEVEL_CONSTRUCT);
51         copy(other);
52 }
53
54 const basic & basic::operator=(const basic & other)
55 {
56         debugmsg("basic operator=", LOGLEVEL_ASSIGNMENT);
57         if (this != &other) {
58                 destroy(true);
59                 copy(other);
60         }
61         return *this;
62 }
63
64 // protected
65
66 // none (all conditionally inlined)
67
68 //////////
69 // other ctors
70 //////////
71
72 // none (all conditionally inlined)
73
74 //////////
75 // archiving
76 //////////
77
78 /** Construct object from archive_node. */
79 basic::basic(const archive_node &n, const lst &sym_lst) : flags(0), refcount(0)
80 {
81         debugmsg("basic ctor from archive_node", LOGLEVEL_CONSTRUCT);
82
83         // Reconstruct tinfo_key from class name
84         std::string class_name;
85         if (n.find_string("class", class_name))
86                 tinfo_key = find_tinfo_key(class_name);
87         else
88                 throw (std::runtime_error("archive node contains no class name"));
89 }
90
91 /** Unarchive the object. */
92 ex basic::unarchive(const archive_node &n, const lst &sym_lst)
93 {
94         return (new basic(n, sym_lst))->setflag(status_flags::dynallocated);
95 }
96
97 /** Archive the object. */
98 void basic::archive(archive_node &n) const
99 {
100         n.add_string("class", class_name());
101 }
102
103 //////////
104 // functions overriding virtual functions from bases classes
105 //////////
106
107 // none
108
109 //////////
110 // new virtual functions which can be overridden by derived classes
111 //////////
112
113 // public
114
115 /** Output to ostream formatted as parsable (as in ginsh) input.
116  *  Generally, superfluous parenthesis should be avoided as far as possible. */
117 void basic::print(std::ostream & os, unsigned upper_precedence) const
118 {
119         debugmsg("basic print",LOGLEVEL_PRINT);
120         os << "[" << class_name() << " object]";
121 }
122
123 /** Output to ostream in ugly raw format, so brave developers can have a look
124  *  at the underlying structure. */
125 void basic::printraw(std::ostream & os) const
126 {
127         debugmsg("basic printraw",LOGLEVEL_PRINT);
128         os << "[" << class_name() << " object]";
129 }
130
131 /** Output to ostream formatted in tree- (indented-) form, so developers can
132  *  have a look at the underlying structure. */
133 void basic::printtree(std::ostream & os, unsigned indent) const
134 {
135         debugmsg("basic printtree",LOGLEVEL_PRINT);
136         os << std::string(indent,' ') << "type=" << class_name()
137            << ", hash=" << hashvalue
138            << " (0x" << std::hex << hashvalue << std::dec << ")"
139            << ", flags=" << flags
140            << ", nops=" << nops() << std::endl;
141         for (unsigned i=0; i<nops(); ++i) {
142                 op(i).printtree(os,indent+delta_indent);
143         }
144 }
145
146 /** Output to ostream formatted as C-source.
147  *
148  *  @param os a stream for output
149  *  @param type variable type (one of the csrc_types)
150  *  @param upper_precedence operator precedence of caller
151  *  @see ex::printcsrc */
152 void basic::printcsrc(std::ostream & os, unsigned type, unsigned upper_precedence) const
153 {
154         debugmsg("basic print csrc", LOGLEVEL_PRINT);
155 }
156
157 /** Little wrapper arount print to be called within a debugger.
158  *  This is needed because you cannot call foo.print(cout) from within the
159  *  debugger because it might not know what cout is.  This method can be
160  *  invoked with no argument and it will simply print to stdout.
161  *
162  *  @see basic::print*/
163 void basic::dbgprint(void) const
164 {
165         this->print(std::cerr);
166         std::cerr << std::endl;
167 }
168
169 /** Little wrapper arount printtree to be called within a debugger.
170  *
171  *  @see basic::dbgprint
172  *  @see basic::printtree */
173 void basic::dbgprinttree(void) const
174 {
175         this->printtree(std::cerr,0);
176 }
177
178 /** Create a new copy of this on the heap.  One can think of this as simulating
179  *  a virtual copy constructor which is needed for instance by the refcounted
180  *  construction of an ex from a basic. */
181 basic * basic::duplicate() const
182 {
183         debugmsg("basic duplicate",LOGLEVEL_DUPLICATE);
184         return new basic(*this);
185 }
186
187 /** Information about the object.
188  *
189  *  @see class info_flags */
190 bool basic::info(unsigned inf) const
191 {
192         // all possible properties are false for basic objects
193         return false;
194 }
195
196 /** Number of operands/members. */
197 unsigned basic::nops() const
198 {
199         // iterating from 0 to nops() on atomic objects should be an empty loop,
200         // and accessing their elements is a range error.  Container objects should
201         // override this.
202         return 0;
203 }
204
205 /** Return operand/member at position i. */
206 ex basic::op(int i) const
207 {
208         return (const_cast<basic *>(this))->let_op(i);
209 }
210
211 /** Return modifyable operand/member at position i. */
212 ex & basic::let_op(int i)
213 {
214         throw(std::out_of_range("op() out of range"));
215 }
216
217 ex basic::operator[](const ex & index) const
218 {
219         if (is_exactly_of_type(*index.bp,numeric))
220                 return op(static_cast<const numeric &>(*index.bp).to_int());
221         
222         throw(std::invalid_argument("non-numeric indices not supported by this type"));
223 }
224
225 ex basic::operator[](int i) const
226 {
227         return op(i);
228 }
229
230 /** Search ocurrences.  An object  'has' an expression if it is the expression
231  *  itself or one of the children 'has' it.  As a consequence (according to
232  *  the definition of children) given e=x+y+z, e.has(x) is true but e.has(x+y)
233  *  is false. */
234 bool basic::has(const ex & other) const
235 {
236         GINAC_ASSERT(other.bp!=0);
237         if (is_equal(*other.bp)) return true;
238         if (nops()>0) {
239                 for (unsigned i=0; i<nops(); i++)
240                         if (op(i).has(other))
241                                 return true;
242         }
243         
244         return false;
245 }
246
247 /** Return degree of highest power in symbol s. */
248 int basic::degree(const symbol & s) const
249 {
250         return 0;
251 }
252
253 /** Return degree of lowest power in symbol s. */
254 int basic::ldegree(const symbol & s) const
255 {
256         return 0;
257 }
258
259 /** Return coefficient of degree n in symbol s. */
260 ex basic::coeff(const symbol & s, int n) const
261 {
262         return n==0 ? *this : _ex0();
263 }
264
265 /** Sort expression in terms of powers of some symbol.
266  *  @param s symbol to sort in. */
267 ex basic::collect(const symbol & s) const
268 {
269         ex x;
270         for (int n=this->ldegree(s); n<=this->degree(s); n++)
271                 x += this->coeff(s,n)*power(s,n);
272         
273         return x;
274 }
275
276 /** Perform automatic non-interruptive symbolic evaluation on expression. */
277 ex basic::eval(int level) const
278 {
279         // There is nothing to do for basic objects:
280         return this->hold();
281 }
282
283 /** Evaluate object numerically. */
284 ex basic::evalf(int level) const
285 {
286         // There is nothing to do for basic objects:
287         return *this;
288 }
289
290 /** Perform automatic symbolic evaluations on indexed expression that
291  *  contains this object as the base expression. */
292 ex basic::eval_indexed(const basic & i) const
293  // this function can't take a "const ex & i" because that would result
294  // in an infinite eval() loop
295 {
296         // There is nothing to do for basic objects
297         return i.hold();
298 }
299
300 /** Add two indexed expressions. They are guaranteed to be of class indexed
301  *  (or a subclass) and their indices are compatible. This function is used
302  *  internally by simplify_indexed().
303  *
304  *  @param self First indexed expression; it's base object is *this
305  *  @param other Second indexed expression
306  *  @return sum of self and other 
307  *  @see ex::simplify_indexed() */
308 ex basic::add_indexed(const ex & self, const ex & other) const
309 {
310         return self + other;
311 }
312
313 /** Multiply an indexed expression with a scalar. This function is used
314  *  internally by simplify_indexed().
315  *
316  *  @param self Indexed expression; it's base object is *this
317  *  @param other Numeric value
318  *  @return product of self and other
319  *  @see ex::simplify_indexed() */
320 ex basic::scalar_mul_indexed(const ex & self, const numeric & other) const
321 {
322         return self * other;
323 }
324
325 /** Try to contract two indexed expressions that appear in the same product. 
326  *  If a contraction exists, the function overwrites one or both of the
327  *  expressions and returns true. Otherwise it returns false. It is
328  *  guaranteed that both expressions are of class indexed (or a subclass)
329  *  and that at least one dummy index has been found. This functions is
330  *  used internally by simplify_indexed().
331  *
332  *  @param self Pointer to first indexed expression; it's base object is *this
333  *  @param other Pointer to second indexed expression
334  *  @param v The complete vector of factors
335  *  @return true if the contraction was successful, false otherwise
336  *  @see ex::simplify_indexed() */
337 bool basic::contract_with(exvector::iterator self, exvector::iterator other, exvector & v) const
338 {
339         // Do nothing
340         return false;
341 }
342
343 /** Substitute a set of symbols by arbitrary expressions. The ex returned
344  *  will already be evaluated. */
345 ex basic::subs(const lst & ls, const lst & lr) const
346 {
347         return *this;
348 }
349
350 /** Default interface of nth derivative ex::diff(s, n).  It should be called
351  *  instead of ::derivative(s) for first derivatives and for nth derivatives it
352  *  just recurses down.
353  *
354  *  @param s symbol to differentiate in
355  *  @param nth order of differentiation
356  *  @see ex::diff */
357 ex basic::diff(const symbol & s, unsigned nth) const
358 {
359         // trivial: zeroth derivative
360         if (nth==0)
361                 return ex(*this);
362         
363         // evaluate unevaluated *this before differentiating
364         if (!(flags & status_flags::evaluated))
365                 return ex(*this).diff(s, nth);
366         
367         ex ndiff = this->derivative(s);
368         while (!ndiff.is_zero() &&    // stop differentiating zeros
369                nth>1) {
370                 ndiff = ndiff.diff(s);
371                 --nth;
372         }
373         return ndiff;
374 }
375
376 /** Return a vector containing the free indices of an expression. */
377 exvector basic::get_free_indices(void) const
378 {
379         return exvector(); // return an empty exvector
380 }
381
382 ex basic::simplify_ncmul(const exvector & v) const
383 {
384         return simplified_ncmul(v);
385 }
386
387 // protected
388
389 /** Default implementation of ex::diff(). It simply throws an error message.
390  *
391  *  @exception logic_error (differentiation not supported by this type)
392  *  @see ex::diff */
393 ex basic::derivative(const symbol & s) const
394 {
395         throw(std::logic_error("differentiation not supported by this type"));
396 }
397
398 /** Returns order relation between two objects of same type.  This needs to be
399  *  implemented by each class. It may never return anything else than 0,
400  *  signalling equality, or +1 and -1 signalling inequality and determining
401  *  the canonical ordering.  (Perl hackers will wonder why C++ doesn't feature
402  *  the spaceship operator <=> for denoting just this.) */
403 int basic::compare_same_type(const basic & other) const
404 {
405         return compare_pointers(this, &other);
406 }
407
408 /** Returns true if two objects of same type are equal.  Normally needs
409  *  not be reimplemented as long as it wasn't overwritten by some parent
410  *  class, since it just calls compare_same_type().  The reason why this
411  *  function exists is that sometimes it is easier to determine equality
412  *  than an order relation and then it can be overridden. */
413 bool basic::is_equal_same_type(const basic & other) const
414 {
415         return this->compare_same_type(other)==0;
416 }
417
418 unsigned basic::return_type(void) const
419 {
420         return return_types::commutative;
421 }
422
423 unsigned basic::return_type_tinfo(void) const
424 {
425         return tinfo();
426 }
427
428 /** Compute the hash value of an object and if it makes sense to store it in
429  *  the objects status_flags, do so.  The method inherited from class basic
430  *  computes a hash value based on the type and hash values of possible
431  *  members.  For this reason it is well suited for container classes but
432  *  atomic classes should override this implementation because otherwise they
433  *  would all end up with the same hashvalue. */
434 unsigned basic::calchash(void) const
435 {
436         unsigned v = golden_ratio_hash(tinfo());
437         for (unsigned i=0; i<nops(); i++) {
438                 v = rotate_left_31(v);
439                 v ^= (const_cast<basic *>(this))->op(i).gethash();
440         }
441         
442         // mask out numeric hashes:
443         v &= 0x7FFFFFFFU;
444         
445         // store calculated hash value only if object is already evaluated
446         if (flags & status_flags::evaluated) {
447                 setflag(status_flags::hash_calculated);
448                 hashvalue = v;
449         }
450
451         return v;
452 }
453
454 /** Expand expression, i.e. multiply it out and return the result as a new
455  *  expression. */
456 ex basic::expand(unsigned options) const
457 {
458         return this->setflag(status_flags::expanded);
459 }
460
461
462 //////////
463 // non-virtual functions in this class
464 //////////
465
466 // public
467
468 /** Substitute symbols in expression and return the result as a new expression.
469  *  There are two valid types of replacement arguments: 1) a relational like
470  *  symbol==ex and 2) a list of relationals lst(symbol1==ex1,symbol2==ex2,...),
471  *  which is converted to subs(lst(symbol1,symbol2,...),lst(ex1,ex2,...)).
472  *  In addition, an object of class idx can be used instead of a symbol. */
473 ex basic::subs(const ex & e) const
474 {
475         if (e.info(info_flags::relation_equal)) {
476                 return subs(lst(e));
477         }
478         if (!e.info(info_flags::list)) {
479                 throw(std::invalid_argument("basic::subs(ex): argument must be a list"));
480         }
481         lst ls;
482         lst lr;
483         for (unsigned i=0; i<e.nops(); i++) {
484                 if (!e.op(i).info(info_flags::relation_equal)) {
485                         throw(std::invalid_argument("basic::subs(ex): argument must be a list or equations"));
486                 }
487                 if (!e.op(i).op(0).info(info_flags::symbol)) {
488                         if (!e.op(i).op(0).info(info_flags::idx)) {
489                                 throw(std::invalid_argument("basic::subs(ex): lhs must be a symbol or an idx"));
490                         }
491                 }
492                 ls.append(e.op(i).op(0));
493                 lr.append(e.op(i).op(1));
494         }
495         return subs(ls,lr);
496 }
497
498 /** Compare objects to establish canonical ordering.
499  *  All compare functions return: -1 for *this less than other, 0 equal,
500  *  1 greater. */
501 int basic::compare(const basic & other) const
502 {
503         unsigned hash_this = gethash();
504         unsigned hash_other = other.gethash();
505         
506         if (hash_this<hash_other) return -1;
507         if (hash_this>hash_other) return 1;
508         
509         unsigned typeid_this = tinfo();
510         unsigned typeid_other = other.tinfo();
511         
512         if (typeid_this<typeid_other) {
513 //              std::cout << "hash collision, different types: " 
514 //                        << *this << " and " << other << std::endl;
515 //              this->printraw(std::cout);
516 //              std::cout << " and ";
517 //              other.printraw(std::cout);
518 //              std::cout << std::endl;
519                 return -1;
520         }
521         if (typeid_this>typeid_other) {
522 //              std::cout << "hash collision, different types: " 
523 //                        << *this << " and " << other << std::endl;
524 //              this->printraw(std::cout);
525 //              std::cout << " and ";
526 //              other.printraw(std::cout);
527 //              std::cout << std::endl;
528                 return 1;
529         }
530         
531         GINAC_ASSERT(typeid(*this)==typeid(other));
532         
533 //      int cmpval = compare_same_type(other);
534 //      if ((cmpval!=0) && (hash_this<0x80000000U)) {
535 //              std::cout << "hash collision, same type: " 
536 //                        << *this << " and " << other << std::endl;
537 //              this->printraw(std::cout);
538 //              std::cout << " and ";
539 //              other.printraw(std::cout);
540 //              std::cout << std::endl;
541 //      }
542 //      return cmpval;
543         
544         return compare_same_type(other);
545 }
546
547 /** Test for equality.
548  *  This is only a quick test, meaning objects should be in the same domain.
549  *  You might have to .expand(), .normal() objects first, depending on the
550  *  domain of your computation, to get a more reliable answer.
551  *
552  *  @see is_equal_same_type */
553 bool basic::is_equal(const basic & other) const
554 {
555         if (this->gethash()!=other.gethash())
556                 return false;
557         if (this->tinfo()!=other.tinfo())
558                 return false;
559         
560         GINAC_ASSERT(typeid(*this)==typeid(other));
561         
562         return this->is_equal_same_type(other);
563 }
564
565 // protected
566
567 /** Stop further evaluation.
568  *
569  *  @see basic::eval */
570 const basic & basic::hold(void) const
571 {
572         return this->setflag(status_flags::evaluated);
573 }
574
575 /** Ensure the object may be modified without hurting others, throws if this
576  *  is not the case. */
577 void basic::ensure_if_modifiable(void) const
578 {
579         if (this->refcount>1)
580                 throw(std::runtime_error("cannot modify multiply referenced object"));
581 }
582
583 //////////
584 // static member variables
585 //////////
586
587 // protected
588
589 unsigned basic::precedence = 70;
590 unsigned basic::delta_indent = 4;
591
592 //////////
593 // global variables
594 //////////
595
596 int max_recursion_level = 1024;
597
598 } // namespace GiNaC