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