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