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