3 * Implementation of GiNaC's ABC. */
6 * GiNaC Copyright (C) 1999-2001 Johannes Gutenberg University Mainz, Germany
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.
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.
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
40 GINAC_IMPLEMENT_REGISTERED_CLASS_NO_CTORS(basic, void)
43 // default ctor, dtor, copy ctor assignment operator and helpers
48 basic::basic(const basic & other) : tinfo_key(TINFO_basic), flags(0), refcount(0)
50 debugmsg("basic copy ctor", LOGLEVEL_CONSTRUCT);
54 const basic & basic::operator=(const basic & other)
56 debugmsg("basic operator=", LOGLEVEL_ASSIGNMENT);
66 // none (all conditionally inlined)
72 // none (all conditionally inlined)
78 /** Construct object from archive_node. */
79 basic::basic(const archive_node &n, const lst &sym_lst) : flags(0), refcount(0)
81 debugmsg("basic ctor from archive_node", LOGLEVEL_CONSTRUCT);
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);
88 throw (std::runtime_error("archive node contains no class name"));
91 /** Unarchive the object. */
92 DEFAULT_UNARCHIVE(basic)
94 /** Archive the object. */
95 void basic::archive(archive_node &n) const
97 n.add_string("class", class_name());
101 // functions overriding virtual functions from bases classes
107 // new virtual functions which can be overridden by derived classes
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
118 debugmsg("basic print", LOGLEVEL_PRINT);
120 if (is_of_type(c, print_tree)) {
122 c.s << std::string(level, ' ') << class_name()
123 << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
124 << ", nops=" << nops()
126 for (unsigned i=0; i<nops(); ++i)
127 op(i).print(c, level + static_cast<const print_tree &>(c).delta_indent);
130 c.s << "[" << class_name() << " object]";
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.
138 * @see basic::print */
139 void basic::dbgprint(void) const
141 this->print(std::cerr);
142 std::cerr << std::endl;
145 /** Little wrapper arount printtree to be called within a debugger.
147 * @see basic::dbgprint
148 * @see basic::printtree */
149 void basic::dbgprinttree(void) const
151 this->print(print_tree(std::cerr));
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
159 debugmsg("basic duplicate",LOGLEVEL_DUPLICATE);
160 return new basic(*this);
163 /** Information about the object.
165 * @see class info_flags */
166 bool basic::info(unsigned inf) const
168 // all possible properties are false for basic objects
172 /** Number of operands/members. */
173 unsigned basic::nops() const
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
181 /** Return operand/member at position i. */
182 ex basic::op(int i) const
184 return (const_cast<basic *>(this))->let_op(i);
187 /** Return modifyable operand/member at position i. */
188 ex & basic::let_op(int i)
190 throw(std::out_of_range("op() out of range"));
193 ex basic::operator[](const ex & index) const
195 if (is_exactly_of_type(*index.bp,numeric))
196 return op(static_cast<const numeric &>(*index.bp).to_int());
198 throw(std::invalid_argument("non-numeric indices not supported by this type"));
201 ex basic::operator[](int i) const
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)
210 bool basic::has(const ex & other) const
212 GINAC_ASSERT(other.bp!=0);
213 if (is_equal(*other.bp)) return true;
215 for (unsigned i=0; i<nops(); i++)
216 if (op(i).has(other))
223 /** Return degree of highest power in symbol s. */
224 int basic::degree(const ex & s) const
229 /** Return degree of lowest power in symbol s. */
230 int basic::ldegree(const ex & s) const
235 /** Return coefficient of degree n in symbol s. */
236 ex basic::coeff(const ex & s, int n) const
238 return n==0 ? *this : _ex0();
241 /** Sort expression in terms of powers of some symbol.
242 * @param s symbol to sort in. */
243 ex basic::collect(const ex & s) const
246 for (int n=this->ldegree(s); n<=this->degree(s); n++)
247 x += this->coeff(s,n)*power(s,n);
252 /** Perform automatic non-interruptive symbolic evaluation on expression. */
253 ex basic::eval(int level) const
255 // There is nothing to do for basic objects:
259 /** Evaluate object numerically. */
260 ex basic::evalf(int level) const
262 // There is nothing to do for basic objects:
266 /** Perform automatic symbolic evaluations on indexed expression that
267 * contains this object as the base expression. */
268 ex basic::eval_indexed(const basic & i) const
269 // this function can't take a "const ex & i" because that would result
270 // in an infinite eval() loop
272 // There is nothing to do for basic objects
276 /** Add two indexed expressions. They are guaranteed to be of class indexed
277 * (or a subclass) and their indices are compatible. This function is used
278 * internally by simplify_indexed().
280 * @param self First indexed expression; it's base object is *this
281 * @param other Second indexed expression
282 * @return sum of self and other
283 * @see ex::simplify_indexed() */
284 ex basic::add_indexed(const ex & self, const ex & other) const
289 /** Multiply an indexed expression with a scalar. This function is used
290 * internally by simplify_indexed().
292 * @param self Indexed expression; it's base object is *this
293 * @param other Numeric value
294 * @return product of self and other
295 * @see ex::simplify_indexed() */
296 ex basic::scalar_mul_indexed(const ex & self, const numeric & other) const
301 /** Try to contract two indexed expressions that appear in the same product.
302 * If a contraction exists, the function overwrites one or both of the
303 * expressions and returns true. Otherwise it returns false. It is
304 * guaranteed that both expressions are of class indexed (or a subclass)
305 * and that at least one dummy index has been found. This functions is
306 * used internally by simplify_indexed().
308 * @param self Pointer to first indexed expression; it's base object is *this
309 * @param other Pointer to second indexed expression
310 * @param v The complete vector of factors
311 * @return true if the contraction was successful, false otherwise
312 * @see ex::simplify_indexed() */
313 bool basic::contract_with(exvector::iterator self, exvector::iterator other, exvector & v) const
319 /** Substitute a set of objects by arbitrary expressions. The ex returned
320 * will already be evaluated. */
321 ex basic::subs(const lst & ls, const lst & lr) const
323 GINAC_ASSERT(ls.nops() == lr.nops());
325 for (unsigned i=0; i<ls.nops(); i++) {
326 if (is_equal(*ls.op(i).bp))
333 /** Default interface of nth derivative ex::diff(s, n). It should be called
334 * instead of ::derivative(s) for first derivatives and for nth derivatives it
335 * just recurses down.
337 * @param s symbol to differentiate in
338 * @param nth order of differentiation
340 ex basic::diff(const symbol & s, unsigned nth) const
342 // trivial: zeroth derivative
346 // evaluate unevaluated *this before differentiating
347 if (!(flags & status_flags::evaluated))
348 return ex(*this).diff(s, nth);
350 ex ndiff = this->derivative(s);
351 while (!ndiff.is_zero() && // stop differentiating zeros
353 ndiff = ndiff.diff(s);
359 /** Return a vector containing the free indices of an expression. */
360 exvector basic::get_free_indices(void) const
362 return exvector(); // return an empty exvector
365 ex basic::simplify_ncmul(const exvector & v) const
367 return simplified_ncmul(v);
372 /** Default implementation of ex::diff(). It simply throws an error message.
374 * @exception logic_error (differentiation not supported by this type)
376 ex basic::derivative(const symbol & s) const
378 throw(std::logic_error("differentiation not supported by this type"));
381 /** Returns order relation between two objects of same type. This needs to be
382 * implemented by each class. It may never return anything else than 0,
383 * signalling equality, or +1 and -1 signalling inequality and determining
384 * the canonical ordering. (Perl hackers will wonder why C++ doesn't feature
385 * the spaceship operator <=> for denoting just this.) */
386 int basic::compare_same_type(const basic & other) const
388 return compare_pointers(this, &other);
391 /** Returns true if two objects of same type are equal. Normally needs
392 * not be reimplemented as long as it wasn't overwritten by some parent
393 * class, since it just calls compare_same_type(). The reason why this
394 * function exists is that sometimes it is easier to determine equality
395 * than an order relation and then it can be overridden. */
396 bool basic::is_equal_same_type(const basic & other) const
398 return this->compare_same_type(other)==0;
401 unsigned basic::return_type(void) const
403 return return_types::commutative;
406 unsigned basic::return_type_tinfo(void) const
411 /** Compute the hash value of an object and if it makes sense to store it in
412 * the objects status_flags, do so. The method inherited from class basic
413 * computes a hash value based on the type and hash values of possible
414 * members. For this reason it is well suited for container classes but
415 * atomic classes should override this implementation because otherwise they
416 * would all end up with the same hashvalue. */
417 unsigned basic::calchash(void) const
419 unsigned v = golden_ratio_hash(tinfo());
420 for (unsigned i=0; i<nops(); i++) {
421 v = rotate_left_31(v);
422 v ^= (const_cast<basic *>(this))->op(i).gethash();
425 // mask out numeric hashes:
428 // store calculated hash value only if object is already evaluated
429 if (flags & status_flags::evaluated) {
430 setflag(status_flags::hash_calculated);
437 /** Expand expression, i.e. multiply it out and return the result as a new
439 ex basic::expand(unsigned options) const
441 return this->setflag(status_flags::expanded);
446 // non-virtual functions in this class
451 /** Substitute objects in an expression (syntactic substitution) and return
452 * the result as a new expression. There are two valid types of
453 * replacement arguments: 1) a relational like object==ex and 2) a list of
454 * relationals lst(object1==ex1,object2==ex2,...), which is converted to
455 * subs(lst(object1,object2,...),lst(ex1,ex2,...)). */
456 ex basic::subs(const ex & e) const
458 if (e.info(info_flags::relation_equal)) {
461 if (!e.info(info_flags::list)) {
462 throw(std::invalid_argument("basic::subs(ex): argument must be a list"));
466 for (unsigned i=0; i<e.nops(); i++) {
468 if (!r.info(info_flags::relation_equal)) {
469 throw(std::invalid_argument("basic::subs(ex): argument must be a list or equations"));
477 /** Compare objects to establish canonical ordering.
478 * All compare functions return: -1 for *this less than other, 0 equal,
480 int basic::compare(const basic & other) const
482 unsigned hash_this = gethash();
483 unsigned hash_other = other.gethash();
485 if (hash_this<hash_other) return -1;
486 if (hash_this>hash_other) return 1;
488 unsigned typeid_this = tinfo();
489 unsigned typeid_other = other.tinfo();
491 if (typeid_this<typeid_other) {
492 // std::cout << "hash collision, different types: "
493 // << *this << " and " << other << std::endl;
494 // this->print(print_tree(std::cout));
495 // std::cout << " and ";
496 // other.print(print_tree(std::cout));
497 // std::cout << std::endl;
500 if (typeid_this>typeid_other) {
501 // std::cout << "hash collision, different types: "
502 // << *this << " and " << other << std::endl;
503 // this->print(print_tree(std::cout));
504 // std::cout << " and ";
505 // other.print(print_tree(std::cout));
506 // std::cout << std::endl;
510 GINAC_ASSERT(typeid(*this)==typeid(other));
512 // int cmpval = compare_same_type(other);
513 // if ((cmpval!=0) && (hash_this<0x80000000U)) {
514 // std::cout << "hash collision, same type: "
515 // << *this << " and " << other << std::endl;
516 // this->print(print_tree(std::cout));
517 // std::cout << " and ";
518 // other.print(print_tree(std::cout));
519 // std::cout << std::endl;
523 return compare_same_type(other);
526 /** Test for equality.
527 * This is only a quick test, meaning objects should be in the same domain.
528 * You might have to .expand(), .normal() objects first, depending on the
529 * domain of your computation, to get a more reliable answer.
531 * @see is_equal_same_type */
532 bool basic::is_equal(const basic & other) const
534 if (this->gethash()!=other.gethash())
536 if (this->tinfo()!=other.tinfo())
539 GINAC_ASSERT(typeid(*this)==typeid(other));
541 return this->is_equal_same_type(other);
546 /** Stop further evaluation.
548 * @see basic::eval */
549 const basic & basic::hold(void) const
551 return this->setflag(status_flags::evaluated);
554 /** Ensure the object may be modified without hurting others, throws if this
555 * is not the case. */
556 void basic::ensure_if_modifiable(void) const
558 if (this->refcount>1)
559 throw(std::runtime_error("cannot modify multiply referenced object"));
563 // static member variables
568 unsigned basic::precedence = 70;
574 int max_recursion_level = 1024;