3 * Implementation of class of symbolic functions. */
6 * This file was generated automatically by function.py.
7 * Please do not modify it directly, edit function.cppy instead!
8 * function.py options: maxargs=@maxargs@
10 * GiNaC Copyright (C) 1999-2010 Johannes Gutenberg University Mainz, Germany
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
28 #include "operators.h"
29 #include "fderivative.h"
39 #include "hash_seed.h"
51 // helper class function_options
54 function_options::function_options()
59 function_options::function_options(std::string const & n, std::string const & tn)
65 function_options::function_options(std::string const & n, unsigned np)
68 set_name(n, std::string());
72 function_options::~function_options()
74 // nothing to clean up at the moment
77 void function_options::initialize()
79 set_name("unnamed_function", "\\\\mbox{unnamed}");
81 eval_f = evalf_f = real_part_f = imag_part_f = conjugate_f = derivative_f
82 = power_f = series_f = 0;
83 evalf_params_first = true;
84 use_return_type = false;
85 eval_use_exvector_args = false;
86 evalf_use_exvector_args = false;
87 conjugate_use_exvector_args = false;
88 real_part_use_exvector_args = false;
89 imag_part_use_exvector_args = false;
90 derivative_use_exvector_args = false;
91 power_use_exvector_args = false;
92 series_use_exvector_args = false;
93 print_use_exvector_args = false;
95 functions_with_same_name = 1;
99 function_options & function_options::set_name(std::string const & n,
100 std::string const & tn)
103 if (tn==std::string())
104 TeX_name = "\\\\mbox{"+name+"}";
110 function_options & function_options::latex_name(std::string const & tn)
116 // the following lines have been generated for max. @maxargs@ parameters
117 +++ for method, N in [ (f, N) for f in methods[0:-1] for N in range(1, maxargs + 1)]:
118 function_options & function_options::@method@_func(@method@_funcp_@N@ e)
120 test_and_set_nparams(@N@);
121 @method@_f = @method@_funcp(e);
125 // end of generated lines
127 +++ for method in methods[0:-1]:
128 function_options & function_options::@method@_func(@method@_funcp_exvector e)
130 @method@_use_exvector_args = true;
131 @method@_f = @method@_funcp(e);
136 // end of generated lines
138 function_options & function_options::set_return_type(unsigned rt, const return_type_t* rtt)
140 use_return_type = true;
143 return_type_tinfo = *rtt;
145 return_type_tinfo = make_return_type_t<function>();
149 function_options & function_options::do_not_evalf_params()
151 evalf_params_first = false;
155 function_options & function_options::remember(unsigned size,
160 remember_size = size;
161 remember_assoc_size = assoc_size;
162 remember_strategy = strategy;
166 function_options & function_options::overloaded(unsigned o)
168 functions_with_same_name = o;
172 function_options & function_options::set_symmetry(const symmetry & s)
178 void function_options::test_and_set_nparams(unsigned n)
182 } else if (nparams!=n) {
183 // we do not throw an exception here because this code is
184 // usually executed before main(), so the exception could not
186 std::cerr << "WARNING: " << name << "(): number of parameters ("
187 << n << ") differs from number set before ("
188 << nparams << ")" << std::endl;
192 void function_options::set_print_func(unsigned id, print_funcp f)
194 if (id >= print_dispatch_table.size())
195 print_dispatch_table.resize(id + 1);
196 print_dispatch_table[id] = f;
199 /** This can be used as a hook for external applications. */
200 unsigned function::current_serial = 0;
203 GINAC_IMPLEMENT_REGISTERED_CLASS(function, exprseq)
206 // default constructor
211 function::function() : serial(0)
216 // other constructors
221 function::function(unsigned ser) : serial(ser)
225 // the following lines have been generated for max. @maxargs@ parameters
226 +++ for N in range(1, maxargs + 1):
227 function::function(unsigned ser, @seq('const ex & param%(n)d', N)@)
228 : exprseq(@seq('param%(n)d', N)@), serial(ser)
233 function::function(unsigned ser, const exprseq & es) : exprseq(es), serial(ser)
236 // Force re-evaluation even if the exprseq was already evaluated
237 // (the exprseq copy constructor copies the flags)
238 clearflag(status_flags::evaluated);
241 function::function(unsigned ser, const exvector & v, bool discardable)
242 : exprseq(v,discardable), serial(ser)
246 function::function(unsigned ser, std::auto_ptr<exvector> vp)
247 : exprseq(vp), serial(ser)
255 /** Construct object from archive_node. */
256 void function::read_archive(const archive_node& n, lst& sym_lst)
258 inherited::read_archive(n, sym_lst);
259 // Find serial number by function name
261 if (n.find_string("name", s)) {
262 unsigned int ser = 0;
263 std::vector<function_options>::const_iterator i = registered_functions().begin(), iend = registered_functions().end();
271 throw (std::runtime_error("unknown function '" + s + "' in archive"));
273 throw (std::runtime_error("unnamed function in archive"));
276 /** Archive the object. */
277 void function::archive(archive_node &n) const
279 inherited::archive(n);
280 GINAC_ASSERT(serial < registered_functions().size());
281 n.add_string("name", registered_functions()[serial].name);
284 GINAC_BIND_UNARCHIVER(function);
287 // functions overriding virtual functions from base classes
292 void function::print(const print_context & c, unsigned level) const
294 GINAC_ASSERT(serial<registered_functions().size());
295 const function_options &opt = registered_functions()[serial];
296 const std::vector<print_funcp> &pdt = opt.print_dispatch_table;
298 // Dynamically dispatch on print_context type
299 const print_context_class_info *pc_info = &c.get_class_info();
302 unsigned id = pc_info->options.get_id();
303 if (id >= pdt.size() || pdt[id] == NULL) {
305 // Method not found, try parent print_context class
306 const print_context_class_info *parent_pc_info = pc_info->get_parent();
307 if (parent_pc_info) {
308 pc_info = parent_pc_info;
312 // Method still not found, use default output
313 if (is_a<print_tree>(c)) {
315 c.s << std::string(level, ' ') << class_name() << " "
316 << opt.name << " @" << this
317 << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
318 << ", nops=" << nops()
320 unsigned delta_indent = static_cast<const print_tree &>(c).delta_indent;
321 for (size_t i=0; i<seq.size(); ++i)
322 seq[i].print(c, level + delta_indent);
323 c.s << std::string(level + delta_indent, ' ') << "=====" << std::endl;
325 } else if (is_a<print_csrc>(c)) {
327 // Print function name in lowercase
328 std::string lname = opt.name;
329 size_t num = lname.size();
330 for (size_t i=0; i<num; i++)
331 lname[i] = tolower(lname[i]);
333 printseq(c, '(', ',', ')', exprseq::precedence(), function::precedence());
335 } else if (is_a<print_latex>(c)) {
337 printseq(c, '(', ',', ')', exprseq::precedence(), function::precedence());
340 printseq(c, '(', ',', ')', exprseq::precedence(), function::precedence());
345 // Method found, call it
346 current_serial = serial;
347 if (opt.print_use_exvector_args)
348 ((print_funcp_exvector)pdt[id])(seq, c);
349 else switch (opt.nparams) {
350 // the following lines have been generated for max. @maxargs@ parameters
351 +++ for N in range(1, maxargs + 1):
353 ((print_funcp_@N@)(pdt[id]))(@seq('seq[%(n)d]', N, 0)@, c);
356 // end of generated lines
358 throw(std::logic_error("function::print(): invalid nparams"));
363 ex function::expand(unsigned options) const
365 // Only expand arguments when asked to do so
366 if (options & expand_options::expand_function_args)
367 return inherited::expand(options);
369 return (options == 0) ? setflag(status_flags::expanded) : *this;
372 ex function::eval(int level) const
375 // first evaluate children, then we will end up here again
376 return function(serial,evalchildren(level));
379 GINAC_ASSERT(serial<registered_functions().size());
380 const function_options &opt = registered_functions()[serial];
382 // Canonicalize argument order according to the symmetry properties
383 if (seq.size() > 1 && !(opt.symtree.is_zero())) {
385 GINAC_ASSERT(is_a<symmetry>(opt.symtree));
386 int sig = canonicalize(v.begin(), ex_to<symmetry>(opt.symtree));
387 if (sig != std::numeric_limits<int>::max()) {
388 // Something has changed while sorting arguments, more evaluations later
391 return ex(sig) * thiscontainer(v);
399 bool use_remember = opt.use_remember;
401 if (use_remember && lookup_remember_table(eval_result)) {
404 current_serial = serial;
405 if (opt.eval_use_exvector_args)
406 eval_result = ((eval_funcp_exvector)(opt.eval_f))(seq);
408 switch (opt.nparams) {
409 // the following lines have been generated for max. @maxargs@ parameters
410 +++ for N in range(1, maxargs + 1):
412 eval_result = ((eval_funcp_@N@)(opt.eval_f))(@seq('seq[%(n)d]', N, 0)@);
415 // end of generated lines
417 throw(std::logic_error("function::eval(): invalid nparams"));
420 store_remember_table(eval_result);
425 ex function::evalf(int level) const
427 GINAC_ASSERT(serial<registered_functions().size());
428 const function_options &opt = registered_functions()[serial];
430 // Evaluate children first
432 if (level == 1 || !(opt.evalf_params_first))
434 else if (level == -max_recursion_level)
435 throw(std::runtime_error("max recursion level reached"));
437 eseq.reserve(seq.size());
439 exvector::const_iterator it = seq.begin(), itend = seq.end();
440 while (it != itend) {
441 eseq.push_back(it->evalf(level));
446 if (opt.evalf_f==0) {
447 return function(serial,eseq).hold();
449 current_serial = serial;
450 if (opt.evalf_use_exvector_args)
451 return ((evalf_funcp_exvector)(opt.evalf_f))(seq);
452 switch (opt.nparams) {
453 // the following lines have been generated for max. @maxargs@ parameters
454 +++ for N in range(1, maxargs + 1):
456 return ((evalf_funcp_@N@)(opt.evalf_f))(@seq('eseq[%(n)d]', N, 0)@);
458 // end of generated lines
460 throw(std::logic_error("function::evalf(): invalid nparams"));
464 * This method is defined to be in line with behaviour of function::return_type()
466 ex function::eval_ncmul(const exvector & v) const
468 // If this function is called then the list of arguments is non-empty
469 // and the first argument is non-commutative, see function::return_type()
470 return seq.begin()->eval_ncmul(v);
473 unsigned function::calchash() const
475 unsigned v = golden_ratio_hash(make_hash_seed(typeid(*this)) ^ serial);
476 for (size_t i=0; i<nops(); i++) {
478 v ^= this->op(i).gethash();
481 if (flags & status_flags::evaluated) {
482 setflag(status_flags::hash_calculated);
488 ex function::thiscontainer(const exvector & v) const
490 return function(serial, v);
493 ex function::thiscontainer(std::auto_ptr<exvector> vp) const
495 return function(serial, vp);
498 /** Implementation of ex::series for functions.
499 * \@see ex::series */
500 ex function::series(const relational & r, int order, unsigned options) const
502 GINAC_ASSERT(serial<registered_functions().size());
503 const function_options &opt = registered_functions()[serial];
505 if (opt.series_f==0) {
506 return basic::series(r, order);
509 current_serial = serial;
510 if (opt.series_use_exvector_args) {
512 res = ((series_funcp_exvector)(opt.series_f))(seq, r, order, options);
513 } catch (do_taylor) {
514 res = basic::series(r, order, options);
518 switch (opt.nparams) {
519 // the following lines have been generated for max. @maxargs@ parameters
520 +++ for N in range(1, maxargs + 1):
523 res = ((series_funcp_@N@)(opt.series_f))(@seq('seq[%(n)d]', N, 0)@, r, order, options);
524 } catch (do_taylor) {
525 res = basic::series(r, order, options);
529 // end of generated lines
531 throw(std::logic_error("function::series(): invalid nparams"));
534 /** Implementation of ex::conjugate for functions. */
535 ex function::conjugate() const
537 GINAC_ASSERT(serial<registered_functions().size());
538 const function_options & opt = registered_functions()[serial];
540 if (opt.conjugate_f==0) {
541 return conjugate_function(*this).hold();
544 if (opt.conjugate_use_exvector_args) {
545 return ((conjugate_funcp_exvector)(opt.conjugate_f))(seq);
548 switch (opt.nparams) {
549 // the following lines have been generated for max. @maxargs@ parameters
550 +++ for N in range(1, maxargs + 1):
552 return ((conjugate_funcp_@N@)(opt.conjugate_f))(@seq('seq[%(n)d]', N, 0)@);
554 // end of generated lines
556 throw(std::logic_error("function::conjugate(): invalid nparams"));
559 /** Implementation of ex::real_part for functions. */
560 ex function::real_part() const
562 GINAC_ASSERT(serial<registered_functions().size());
563 const function_options & opt = registered_functions()[serial];
565 if (opt.real_part_f==0)
566 return basic::real_part();
568 if (opt.real_part_use_exvector_args)
569 return ((real_part_funcp_exvector)(opt.real_part_f))(seq);
571 switch (opt.nparams) {
572 // the following lines have been generated for max. @maxargs@ parameters
573 +++ for N in range(1, maxargs + 1):
575 return ((real_part_funcp_@N@)(opt.real_part_f))(@seq('seq[%(n)d]', N, 0)@);
577 // end of generated lines
579 throw(std::logic_error("function::real_part(): invalid nparams"));
582 /** Implementation of ex::imag_part for functions. */
583 ex function::imag_part() const
585 GINAC_ASSERT(serial<registered_functions().size());
586 const function_options & opt = registered_functions()[serial];
588 if (opt.imag_part_f==0)
589 return basic::imag_part();
591 if (opt.imag_part_use_exvector_args)
592 return ((imag_part_funcp_exvector)(opt.imag_part_f))(seq);
594 switch (opt.nparams) {
595 // the following lines have been generated for max. @maxargs@ parameters
596 +++ for N in range(1, maxargs + 1):
598 return ((imag_part_funcp_@N@)(opt.imag_part_f))(@seq('seq[%(n)d]', N, 0)@);
600 // end of generated lines
602 throw(std::logic_error("function::imag_part(): invalid nparams"));
607 /** Implementation of ex::diff() for functions. It applies the chain rule,
608 * except for the Order term function.
610 ex function::derivative(const symbol & s) const
614 if (serial == Order_SERIAL::serial) {
615 // Order Term function only differentiates the argument
616 return Order(seq[0].diff(s));
620 size_t num = seq.size();
621 for (size_t i=0; i<num; i++) {
622 arg_diff = seq[i].diff(s);
623 // We apply the chain rule only when it makes sense. This is not
624 // just for performance reasons but also to allow functions to
625 // throw when differentiated with respect to one of its arguments
626 // without running into trouble with our automatic full
628 if (!arg_diff.is_zero())
629 result += pderivative(i)*arg_diff;
635 int function::compare_same_type(const basic & other) const
637 GINAC_ASSERT(is_a<function>(other));
638 const function & o = static_cast<const function &>(other);
640 if (serial != o.serial)
641 return serial < o.serial ? -1 : 1;
643 return exprseq::compare_same_type(o);
646 bool function::is_equal_same_type(const basic & other) const
648 GINAC_ASSERT(is_a<function>(other));
649 const function & o = static_cast<const function &>(other);
651 if (serial != o.serial)
654 return exprseq::is_equal_same_type(o);
657 bool function::match_same_type(const basic & other) const
659 GINAC_ASSERT(is_a<function>(other));
660 const function & o = static_cast<const function &>(other);
662 return serial == o.serial;
665 unsigned function::return_type() const
667 GINAC_ASSERT(serial<registered_functions().size());
668 const function_options &opt = registered_functions()[serial];
670 if (opt.use_return_type) {
671 // Return type was explicitly specified
672 return opt.return_type;
674 // Default behavior is to use the return type of the first
675 // argument. Thus, exp() of a matrix behaves like a matrix, etc.
677 return return_types::commutative;
679 return seq.begin()->return_type();
683 return_type_t function::return_type_tinfo() const
685 GINAC_ASSERT(serial<registered_functions().size());
686 const function_options &opt = registered_functions()[serial];
688 if (opt.use_return_type) {
689 // Return type was explicitly specified
690 return opt.return_type_tinfo;
692 // Default behavior is to use the return type of the first
693 // argument. Thus, exp() of a matrix behaves like a matrix, etc.
695 return make_return_type_t<function>();
697 return seq.begin()->return_type_tinfo();
702 // new virtual functions which can be overridden by derived classes
708 // non-virtual functions in this class
713 ex function::pderivative(unsigned diff_param) const // partial differentiation
715 GINAC_ASSERT(serial<registered_functions().size());
716 const function_options &opt = registered_functions()[serial];
718 // No derivative defined? Then return abstract derivative object
719 if (opt.derivative_f == NULL)
720 return fderivative(serial, diff_param, seq);
722 current_serial = serial;
723 if (opt.derivative_use_exvector_args)
724 return ((derivative_funcp_exvector)(opt.derivative_f))(seq, diff_param);
725 switch (opt.nparams) {
726 // the following lines have been generated for max. @maxargs@ parameters
727 +++ for N in range(1, maxargs + 1):
729 return ((derivative_funcp_@N@)(opt.derivative_f))(@seq('seq[%(n)d]', N, 0)@, diff_param);
731 // end of generated lines
733 throw(std::logic_error("function::pderivative(): no diff function defined"));
736 ex function::power(const ex & power_param) const // power of function
738 GINAC_ASSERT(serial<registered_functions().size());
739 const function_options &opt = registered_functions()[serial];
741 if (opt.power_f == NULL)
742 return (new GiNaC::power(*this, power_param))->setflag(status_flags::dynallocated |
743 status_flags::evaluated);
745 current_serial = serial;
746 if (opt.power_use_exvector_args)
747 return ((power_funcp_exvector)(opt.power_f))(seq, power_param);
748 switch (opt.nparams) {
749 // the following lines have been generated for max. @maxargs@ parameters
750 +++ for N in range(1, maxargs + 1):
752 return ((power_funcp_@N@)(opt.power_f))(@seq('seq[%(n)d]', N, 0)@, power_param);
754 // end of generated lines
756 throw(std::logic_error("function::power(): no power function defined"));
759 std::vector<function_options> & function::registered_functions()
761 static std::vector<function_options> rf = std::vector<function_options>();
765 bool function::lookup_remember_table(ex & result) const
767 return remember_table::remember_tables()[this->serial].lookup_entry(*this,result);
770 void function::store_remember_table(ex const & result) const
772 remember_table::remember_tables()[this->serial].add_entry(*this,result);
777 unsigned function::register_new(function_options const & opt)
779 size_t same_name = 0;
780 for (size_t i=0; i<registered_functions().size(); ++i) {
781 if (registered_functions()[i].name==opt.name) {
785 if (same_name>=opt.functions_with_same_name) {
786 // we do not throw an exception here because this code is
787 // usually executed before main(), so the exception could not
789 std::cerr << "WARNING: function name " << opt.name
790 << " already in use!" << std::endl;
792 registered_functions().push_back(opt);
793 if (opt.use_remember) {
794 remember_table::remember_tables().
795 push_back(remember_table(opt.remember_size,
796 opt.remember_assoc_size,
797 opt.remember_strategy));
799 remember_table::remember_tables().push_back(remember_table());
801 return registered_functions().size()-1;
804 /** Find serial number of function by name and number of parameters.
805 * Throws exception if function was not found. */
806 unsigned function::find_function(const std::string &name, unsigned nparams)
808 std::vector<function_options>::const_iterator i = function::registered_functions().begin(), end = function::registered_functions().end();
811 if (i->get_name() == name && i->get_nparams() == nparams)
816 throw (std::runtime_error("no function '" + name + "' with " + ToString(nparams) + " parameters defined"));
819 /** Return the print name of the function. */
820 std::string function::get_name() const
822 GINAC_ASSERT(serial<registered_functions().size());
823 return registered_functions()[serial].name;