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