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