baaf91065593c3afadc1bf51cff7ed9dd9f31c69
[ginac.git] / ginac / function.pl
1 $maxargs=13;
2
3 sub generate_seq {
4         my ($seq_template,$n)=@_;
5         my ($res,$N);
6         
7         $res='';
8         for ($N=1; $N<=$n; $N++) {
9                 $res .= eval('"' . $seq_template . '"');
10                 if ($N!=$n) {
11                         $res .= ', ';
12                 }
13         }
14         return $res;
15 }
16
17 sub generate_from_to {
18         my ($template,$seq_template1,$seq_template2,$from,$to)=@_;
19         my ($res,$N,$SEQ);
20
21         $res='';
22         for ($N=$from; $N<=$to; $N++) {
23                 $SEQ1=generate_seq($seq_template1,$N);
24                 $SEQ2=generate_seq($seq_template2,$N);
25                 $res .= eval('"' . $template . '"');
26                 $SEQ1=''; # to avoid main::SEQ1 used only once warning
27                 $SEQ2=''; # same as above
28         }
29         return $res;
30 }
31
32 sub generate {
33         my ($template,$seq_template1,$seq_template2)=@_;
34         return generate_from_to($template,$seq_template1,$seq_template2,1,$maxargs);
35 }
36
37 $declare_function_macro = <<'END_OF_DECLARE_FUNCTION_1_AND_2P_MACRO';
38 #define DECLARE_FUNCTION_1P(NAME) \
39 extern const unsigned function_index_##NAME; \
40 inline GiNaC::function NAME(const GiNaC::ex & p1) { \
41         return GiNaC::function(function_index_##NAME, p1); \
42 }
43 #define DECLARE_FUNCTION_2P(NAME) \
44 extern const unsigned function_index_##NAME; \
45 inline GiNaC::function NAME(const GiNaC::ex & p1, const GiNaC::ex & p2) { \
46         return GiNaC::function(function_index_##NAME, p1, p2); \
47 }
48
49 END_OF_DECLARE_FUNCTION_1_AND_2P_MACRO
50
51 $declare_function_macro .= generate_from_to(
52         <<'END_OF_DECLARE_FUNCTION_MACRO','const GiNaC::ex & p${N}','p${N}',3,$maxargs);
53 #define DECLARE_FUNCTION_${N}P(NAME) \\
54 extern const unsigned function_index_##NAME; \\
55 inline GiNaC::function NAME(${SEQ1}) { \\
56         return GiNaC::function(function_index_##NAME, ${SEQ2}); \\
57 }
58
59 END_OF_DECLARE_FUNCTION_MACRO
60
61 $typedef_eval_funcp=generate(
62 'typedef ex (* eval_funcp_${N})(${SEQ1});'."\n",
63 'const ex &','');
64
65 $typedef_evalf_funcp=generate(
66 'typedef ex (* evalf_funcp_${N})(${SEQ1});'."\n",
67 'const ex &','');
68
69 $typedef_derivative_funcp=generate(
70 'typedef ex (* derivative_funcp_${N})(${SEQ1}, unsigned);'."\n",
71 'const ex &','');
72
73 $typedef_series_funcp=generate(
74 'typedef ex (* series_funcp_${N})(${SEQ1}, const relational &, int, unsigned);'."\n",
75 'const ex &','');
76
77 $eval_func_interface=generate('    function_options & eval_func(eval_funcp_${N} e);'."\n",'','');
78
79 $evalf_func_interface=generate('    function_options & evalf_func(evalf_funcp_${N} ef);'."\n",'','');
80
81 $derivative_func_interface=generate('    function_options & derivative_func(derivative_funcp_${N} d);'."\n",'','');
82
83 $series_func_interface=generate('    function_options & series_func(series_funcp_${N} s);'."\n",'','');
84
85 $constructors_interface=generate(
86 '    function(unsigned ser, ${SEQ1});'."\n",
87 'const ex & param${N}','');
88
89 $constructors_implementation=generate(
90         <<'END_OF_CONSTRUCTORS_IMPLEMENTATION','const ex & param${N}','param${N}');
91 function::function(unsigned ser, ${SEQ1})
92         : exprseq(${SEQ2}), serial(ser)
93 {
94         debugmsg(\"function ctor from unsigned,${N}*ex\",LOGLEVEL_CONSTRUCT);
95         tinfo_key = TINFO_function;
96 }
97 END_OF_CONSTRUCTORS_IMPLEMENTATION
98
99 $eval_switch_statement=generate(
100         <<'END_OF_EVAL_SWITCH_STATEMENT','seq[${N}-1]','');
101         case ${N}:
102                 eval_result = ((eval_funcp_${N})(registered_functions()[serial].eval_f))(${SEQ1});
103                 break;
104 END_OF_EVAL_SWITCH_STATEMENT
105
106 $evalf_switch_statement=generate(
107         <<'END_OF_EVALF_SWITCH_STATEMENT','eseq[${N}-1]','');
108         case ${N}:
109                 return ((evalf_funcp_${N})(registered_functions()[serial].evalf_f))(${SEQ1});
110 END_OF_EVALF_SWITCH_STATEMENT
111
112 $diff_switch_statement=generate(
113         <<'END_OF_DIFF_SWITCH_STATEMENT','seq[${N}-1]','');
114         case ${N}:
115                 return ((derivative_funcp_${N})(registered_functions()[serial].derivative_f))(${SEQ1},diff_param);
116 END_OF_DIFF_SWITCH_STATEMENT
117
118 $series_switch_statement=generate(
119         <<'END_OF_SERIES_SWITCH_STATEMENT','seq[${N}-1]','');
120         case ${N}:
121                 try {
122                         res = ((series_funcp_${N})(registered_functions()[serial].series_f))(${SEQ1},r,order,options);
123                 } catch (do_taylor) {
124                         res = basic::series(r, order, options);
125                 }
126                 return res;
127 END_OF_SERIES_SWITCH_STATEMENT
128
129 $eval_func_implementation=generate(
130         <<'END_OF_EVAL_FUNC_IMPLEMENTATION','','');
131 function_options & function_options::eval_func(eval_funcp_${N} e)
132 {
133         test_and_set_nparams(${N});
134         eval_f = eval_funcp(e);
135         return *this;
136 }
137 END_OF_EVAL_FUNC_IMPLEMENTATION
138
139 $evalf_func_implementation=generate(
140         <<'END_OF_EVALF_FUNC_IMPLEMENTATION','','');
141 function_options & function_options::evalf_func(evalf_funcp_${N} ef)
142 {
143         test_and_set_nparams(${N});
144         evalf_f = evalf_funcp(ef);
145         return *this;
146 }
147 END_OF_EVALF_FUNC_IMPLEMENTATION
148
149 $derivative_func_implementation=generate(
150         <<'END_OF_DERIVATIVE_FUNC_IMPLEMENTATION','','');
151 function_options & function_options::derivative_func(derivative_funcp_${N} d)
152 {
153         test_and_set_nparams(${N});
154         derivative_f = derivative_funcp(d);
155         return *this;
156 }
157 END_OF_DERIVATIVE_FUNC_IMPLEMENTATION
158
159 $series_func_implementation=generate(
160         <<'END_OF_SERIES_FUNC_IMPLEMENTATION','','');
161 function_options & function_options::series_func(series_funcp_${N} s)
162 {
163         test_and_set_nparams(${N});
164         series_f = series_funcp(s);
165         return *this;
166 }
167 END_OF_SERIES_FUNC_IMPLEMENTATION
168
169 $interface=<<END_OF_INTERFACE;
170 /** \@file function.h
171  *
172  *  Interface to abstract class function (new function concept). */
173
174 /*
175  *  This file was generated automatically by function.pl.
176  *  Please do not modify it directly, edit the perl script instead!
177  *  function.pl options: \$maxargs=${maxargs}
178  *
179  *  GiNaC Copyright (C) 1999-2001 Johannes Gutenberg University Mainz, Germany
180  *
181  *  This program is free software; you can redistribute it and/or modify
182  *  it under the terms of the GNU General Public License as published by
183  *  the Free Software Foundation; either version 2 of the License, or
184  *  (at your option) any later version.
185  *
186  *  This program is distributed in the hope that it will be useful,
187  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
188  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
189  *  GNU General Public License for more details.
190  *
191  *  You should have received a copy of the GNU General Public License
192  *  along with this program; if not, write to the Free Software
193  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
194  */
195
196 #ifndef __GINAC_FUNCTION_H__
197 #define __GINAC_FUNCTION_H__
198
199 #include <string>
200 #include <vector>
201
202 // CINT needs <algorithm> to work properly with <vector> 
203 #include <algorithm>
204
205 #include "exprseq.h"
206
207 // the following lines have been generated for max. ${maxargs} parameters
208 $declare_function_macro
209 // end of generated lines
210
211 #define REGISTER_FUNCTION(NAME,OPT) \\
212 const unsigned function_index_##NAME= \\
213         GiNaC::function::register_new(GiNaC::function_options(#NAME).OPT);
214
215 #define BEGIN_TYPECHECK \\
216 bool automatic_typecheck=true;
217
218 #define TYPECHECK(VAR,TYPE) \\
219 if (!is_exactly_a<TYPE>(VAR)) { \\
220         automatic_typecheck=false; \\
221 } else
222
223 #define TYPECHECK_INTEGER(VAR) \\
224 if (!(VAR).info(GiNaC::info_flags::integer)) { \\
225         automatic_typecheck=false; \\
226 } else
227
228 #define END_TYPECHECK(RV) \\
229 {} \\
230 if (!automatic_typecheck) { \\
231         return RV.hold(); \\
232 }
233
234 namespace GiNaC {
235
236 class function;
237 class symmetry;
238
239 typedef ex (* eval_funcp)();
240 typedef ex (* evalf_funcp)();
241 typedef ex (* derivative_funcp)();
242 typedef ex (* series_funcp)();
243
244 // the following lines have been generated for max. ${maxargs} parameters
245 $typedef_eval_funcp
246 $typedef_evalf_funcp
247 $typedef_derivative_funcp
248 $typedef_series_funcp
249 // end of generated lines
250
251 class function_options
252 {
253         friend class function;
254 public:
255         function_options();
256         function_options(std::string const & n, std::string const & tn=std::string());
257         ~function_options();
258         void initialize(void);
259         function_options & set_name(std::string const & n, std::string const & tn=std::string());
260         function_options & latex_name(std::string const & tn);
261 // the following lines have been generated for max. ${maxargs} parameters
262 $eval_func_interface
263 $evalf_func_interface
264 $derivative_func_interface
265 $series_func_interface
266 // end of generated lines
267         function_options & set_return_type(unsigned rt, unsigned rtt=0);
268         function_options & do_not_evalf_params(void);
269         function_options & remember(unsigned size, unsigned assoc_size=0,
270                                     unsigned strategy=remember_strategies::delete_never);
271         function_options & overloaded(unsigned o);
272         function_options & set_symmetry(const symmetry & s);
273         void test_and_set_nparams(unsigned n);
274         std::string get_name(void) const { return name; }
275         unsigned get_nparams(void) const { return nparams; }
276
277 protected:
278         std::string name;
279         std::string TeX_name;
280
281         unsigned nparams;
282
283         eval_funcp eval_f;
284         evalf_funcp evalf_f;
285         derivative_funcp derivative_f;
286         series_funcp series_f;
287
288         bool evalf_params_first;
289
290         bool use_return_type;
291         unsigned return_type;
292         unsigned return_type_tinfo;
293
294         bool use_remember;
295         unsigned remember_size;
296         unsigned remember_assoc_size;
297         unsigned remember_strategy;
298
299         unsigned functions_with_same_name;
300
301         ex symtree;
302 };
303
304 /** The class function is used to implement builtin functions like sin, cos...
305         and user defined functions */
306 class function : public exprseq
307 {
308         GINAC_DECLARE_REGISTERED_CLASS(function, exprseq)
309
310         // CINT has a linking problem
311 #ifndef __MAKECINT__
312         friend void ginsh_get_ginac_functions(void);
313 #endif // def __MAKECINT__
314
315         friend class remember_table_entry;
316         // friend class remember_table_list;
317         // friend class remember_table;
318
319 // member functions
320
321         // other ctors
322 public:
323         function(unsigned ser);
324         // the following lines have been generated for max. ${maxargs} parameters
325 $constructors_interface
326         // end of generated lines
327         function(unsigned ser, const exprseq & es);
328         function(unsigned ser, const exvector & v, bool discardable = false);
329         function(unsigned ser, exvector * vp); // vp will be deleted
330
331         // functions overriding virtual functions from bases classes
332 public:
333         void print(const print_context & c, unsigned level = 0) const;
334         unsigned precedence(void) const {return 70;}
335         int degree(const ex & s) const;
336         int ldegree(const ex & s) const;
337         ex coeff(const ex & s, int n = 1) const;
338         ex expand(unsigned options=0) const;
339         ex eval(int level=0) const;
340         ex evalf(int level=0) const;
341         unsigned calchash(void) const;
342         ex series(const relational & r, int order, unsigned options = 0) const;
343         bool match(const ex & pattern, lst & repl_lst) const;
344         ex thisexprseq(const exvector & v) const;
345         ex thisexprseq(exvector * vp) const;
346 protected:
347         ex derivative(const symbol & s) const;
348         bool is_equal_same_type(const basic & other) const;
349         unsigned return_type(void) const;
350         unsigned return_type_tinfo(void) const;
351         
352         // new virtual functions which can be overridden by derived classes
353         // none
354         
355         // non-virtual functions in this class
356 protected:
357         ex pderivative(unsigned diff_param) const; // partial differentiation
358         static std::vector<function_options> & registered_functions(void);
359         bool lookup_remember_table(ex & result) const;
360         void store_remember_table(ex const & result) const;
361 public:
362         static unsigned register_new(function_options const & opt);
363         static unsigned find_function(const std::string &name, unsigned nparams);
364         unsigned get_serial(void) const {return serial;}
365         std::string get_name(void) const;
366         
367 // member variables
368
369 protected:
370         unsigned serial;
371 };
372
373 // utility functions/macros
374 /** Return the object of type function handled by an ex.
375  *  This is unsafe: you need to check the type first. */
376 inline const function &ex_to_function(const ex &e)
377 {
378         return static_cast<const function &>(*e.bp);
379 }
380
381 /** Specialization of is_exactly_a<function>(obj) for objects of type function. */
382 template<> inline bool is_exactly_a<function>(const basic & obj)
383 {
384         return obj.tinfo()==TINFO_function;
385 }
386
387 #define is_ex_the_function(OBJ, FUNCNAME) \\
388         (is_ex_exactly_of_type(OBJ, function) && static_cast<GiNaC::function *>(OBJ.bp)->get_serial() == function_index_##FUNCNAME)
389
390 } // namespace GiNaC
391
392 #endif // ndef __GINAC_FUNCTION_H__
393
394 END_OF_INTERFACE
395
396 $implementation=<<END_OF_IMPLEMENTATION;
397 /** \@file function.cpp
398  *
399  *  Implementation of class function. */
400
401 /*
402  *  This file was generated automatically by function.pl.
403  *  Please do not modify it directly, edit the perl script instead!
404  *  function.pl options: \$maxargs=${maxargs}
405  *
406  *  GiNaC Copyright (C) 1999-2001 Johannes Gutenberg University Mainz, Germany
407  *
408  *  This program is free software; you can redistribute it and/or modify
409  *  it under the terms of the GNU General Public License as published by
410  *  the Free Software Foundation; either version 2 of the License, or
411  *  (at your option) any later version.
412  *
413  *  This program is distributed in the hope that it will be useful,
414  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
415  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
416  *  GNU General Public License for more details.
417  *
418  *  You should have received a copy of the GNU General Public License
419  *  along with this program; if not, write to the Free Software
420  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
421  */
422
423 #include <string>
424 #include <stdexcept>
425 #include <list>
426
427 #include "function.h"
428 #include "ex.h"
429 #include "lst.h"
430 #include "symmetry.h"
431 #include "print.h"
432 #include "archive.h"
433 #include "inifcns.h"
434 #include "utils.h"
435 #include "debugmsg.h"
436 #include "remember.h"
437
438 namespace GiNaC {
439
440 //////////
441 // helper class function_options
442 //////////
443
444 function_options::function_options()
445 {
446         initialize();
447 }
448
449 function_options::function_options(std::string const & n, std::string const & tn)
450 {
451         initialize();
452         set_name(n,tn);
453 }
454
455 function_options::~function_options()
456 {
457         // nothing to clean up at the moment
458 }
459
460 void function_options::initialize(void)
461 {
462         set_name("unnamed_function","\\\\mbox{unnamed}");
463         nparams = 0;
464         eval_f = evalf_f = derivative_f = series_f = 0;
465         evalf_params_first = true;
466         use_return_type = false;
467         use_remember = false;
468         functions_with_same_name = 1;
469         symtree = 0;
470 }
471
472 function_options & function_options::set_name(std::string const & n,
473                                               std::string const & tn)
474 {
475         name=n;
476         if (tn==std::string())
477                 TeX_name = "\\\\mbox{"+name+"}";
478         else
479                 TeX_name = tn;
480         return *this;
481 }
482
483 function_options & function_options::latex_name(std::string const & tn)
484 {
485         TeX_name=tn;
486         return *this;
487 }
488
489 // the following lines have been generated for max. ${maxargs} parameters
490 $eval_func_implementation
491 $evalf_func_implementation
492 $derivative_func_implementation
493 $series_func_implementation
494 // end of generated lines
495
496 function_options & function_options::set_return_type(unsigned rt, unsigned rtt)
497 {
498         use_return_type = true;
499         return_type = rt;
500         return_type_tinfo = rtt;
501         return *this;
502 }
503
504 function_options & function_options::do_not_evalf_params(void)
505 {
506         evalf_params_first = false;
507         return *this;
508 }
509
510 function_options & function_options::remember(unsigned size,
511                                               unsigned assoc_size,
512                                               unsigned strategy)
513 {
514         use_remember = true;
515         remember_size = size;
516         remember_assoc_size = assoc_size;
517         remember_strategy = strategy;
518         return *this;
519 }
520
521 function_options & function_options::overloaded(unsigned o)
522 {
523         functions_with_same_name = o;
524         return *this;
525 }
526
527 function_options & function_options::set_symmetry(const symmetry & s)
528 {
529         symtree = s;
530         return *this;
531 }
532         
533 void function_options::test_and_set_nparams(unsigned n)
534 {
535         if (nparams==0) {
536                 nparams = n;
537         } else if (nparams!=n) {
538                 // we do not throw an exception here because this code is
539                 // usually executed before main(), so the exception could not
540                 // caught anyhow
541                 std::cerr << "WARNING: number of parameters ("
542                           << n << ") differs from number set before (" 
543                           << nparams << ")" << std::endl;
544         }
545 }
546
547 GINAC_IMPLEMENT_REGISTERED_CLASS(function, exprseq)
548
549 //////////
550 // default ctor, dtor, copy ctor assignment operator and helpers
551 //////////
552
553 // public
554
555 function::function() : serial(0)
556 {
557         debugmsg("function default ctor",LOGLEVEL_CONSTRUCT);
558         tinfo_key = TINFO_function;
559 }
560
561 // protected
562
563 void function::copy(const function & other)
564 {
565         inherited::copy(other);
566         serial = other.serial;
567 }
568
569 void function::destroy(bool call_parent)
570 {
571         if (call_parent)
572                 inherited::destroy(call_parent);
573 }
574
575 //////////
576 // other ctors
577 //////////
578
579 // public
580
581 function::function(unsigned ser) : serial(ser)
582 {
583         debugmsg("function ctor from unsigned",LOGLEVEL_CONSTRUCT);
584         tinfo_key = TINFO_function;
585 }
586
587 // the following lines have been generated for max. ${maxargs} parameters
588 $constructors_implementation
589 // end of generated lines
590
591 function::function(unsigned ser, const exprseq & es) : exprseq(es), serial(ser)
592 {
593         debugmsg("function ctor from unsigned,exprseq",LOGLEVEL_CONSTRUCT);
594         tinfo_key = TINFO_function;
595 }
596
597 function::function(unsigned ser, const exvector & v, bool discardable) 
598   : exprseq(v,discardable), serial(ser)
599 {
600         debugmsg("function ctor from string,exvector,bool",LOGLEVEL_CONSTRUCT);
601         tinfo_key = TINFO_function;
602 }
603
604 function::function(unsigned ser, exvector * vp) 
605   : exprseq(vp), serial(ser)
606 {
607         debugmsg("function ctor from unsigned,exvector *",LOGLEVEL_CONSTRUCT);
608         tinfo_key = TINFO_function;
609 }
610
611 //////////
612 // archiving
613 //////////
614
615 /** Construct object from archive_node. */
616 function::function(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
617 {
618         debugmsg("function ctor from archive_node", LOGLEVEL_CONSTRUCT);
619
620         // Find serial number by function name
621         std::string s;
622         if (n.find_string("name", s)) {
623                 unsigned int ser = 0;
624                 std::vector<function_options>::const_iterator i = registered_functions().begin(), iend = registered_functions().end();
625                 while (i != iend) {
626                         if (s == i->name) {
627                                 serial = ser;
628                                 return;
629                         }
630                         i++; ser++;
631                 }
632                 throw (std::runtime_error("unknown function '" + s + "' in archive"));
633         } else
634                 throw (std::runtime_error("unnamed function in archive"));
635 }
636
637 /** Unarchive the object. */
638 ex function::unarchive(const archive_node &n, const lst &sym_lst)
639 {
640         return (new function(n, sym_lst))->setflag(status_flags::dynallocated);
641 }
642
643 /** Archive the object. */
644 void function::archive(archive_node &n) const
645 {
646         inherited::archive(n);
647         GINAC_ASSERT(serial < registered_functions().size());
648         n.add_string("name", registered_functions()[serial].name);
649 }
650
651 //////////
652 // functions overriding virtual functions from bases classes
653 //////////
654
655 // public
656
657 void function::print(const print_context & c, unsigned level) const
658 {
659         debugmsg("function print", LOGLEVEL_PRINT);
660
661         GINAC_ASSERT(serial<registered_functions().size());
662
663         if (is_of_type(c, print_tree)) {
664
665                 c.s << std::string(level, ' ') << class_name() << " "
666                     << registered_functions()[serial].name
667                     << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
668                     << ", nops=" << nops()
669                     << std::endl;
670                 unsigned delta_indent = static_cast<const print_tree &>(c).delta_indent;
671                 for (unsigned i=0; i<seq.size(); ++i)
672                         seq[i].print(c, level + delta_indent);
673                 c.s << std::string(level + delta_indent, ' ') << "=====" << std::endl;
674
675         } else if (is_of_type(c, print_csrc)) {
676
677                 // Print function name in lowercase
678                 std::string lname = registered_functions()[serial].name;
679                 unsigned num = lname.size();
680                 for (unsigned i=0; i<num; i++)
681                         lname[i] = tolower(lname[i]);
682                 c.s << lname << "(";
683
684                 // Print arguments, separated by commas
685                 exvector::const_iterator it = seq.begin(), itend = seq.end();
686                 while (it != itend) {
687                         it->print(c);
688                         it++;
689                         if (it != itend)
690                                 c.s << ",";
691                 }
692                 c.s << ")";
693
694         } else if (is_of_type(c, print_latex)) {
695                 c.s << registered_functions()[serial].TeX_name;
696                 printseq(c, '(', ',', ')', exprseq::precedence(), function::precedence());
697         } else {
698                 c.s << registered_functions()[serial].name;
699                 printseq(c, '(', ',', ')', exprseq::precedence(), function::precedence());
700         }
701 }
702
703 ex function::expand(unsigned options) const
704 {
705         return this->setflag(status_flags::expanded);
706 }
707
708 int function::degree(const ex & s) const
709 {
710         return is_equal(*s.bp) ? 1 : 0;
711 }
712
713 int function::ldegree(const ex & s) const
714 {
715         return is_equal(*s.bp) ? 1 : 0;
716 }
717
718 ex function::coeff(const ex & s, int n) const
719 {
720         if (is_equal(*s.bp))
721                 return n==1 ? _ex1() : _ex0();
722         else
723                 return n==0 ? ex(*this) : _ex0();
724 }
725
726 ex function::eval(int level) const
727 {
728         GINAC_ASSERT(serial<registered_functions().size());
729
730         if (level>1) {
731                 // first evaluate children, then we will end up here again
732                 return function(serial,evalchildren(level));
733         }
734
735         const function_options &opt = registered_functions()[serial];
736
737         // Canonicalize argument order according to the symmetry properties
738         if (seq.size() > 1 && !(opt.symtree.is_zero())) {
739                 exvector v = seq;
740                 GINAC_ASSERT(is_ex_exactly_of_type(opt.symtree, symmetry));
741                 int sig = canonicalize(v.begin(), ex_to<symmetry>(opt.symtree));
742                 if (sig != INT_MAX) {
743                         // Something has changed while sorting arguments, more evaluations later
744                         if (sig == 0)
745                                 return _ex0();
746                         return ex(sig) * thisexprseq(v);
747                 }
748         }
749
750         if (opt.eval_f==0) {
751                 return this->hold();
752         }
753
754         bool use_remember = opt.use_remember;
755         ex eval_result;
756         if (use_remember && lookup_remember_table(eval_result)) {
757                 return eval_result;
758         }
759
760         switch (opt.nparams) {
761                 // the following lines have been generated for max. ${maxargs} parameters
762 ${eval_switch_statement}
763                 // end of generated lines
764         default:
765                 throw(std::logic_error("function::eval(): invalid nparams"));
766         }
767         if (use_remember) {
768                 store_remember_table(eval_result);
769         }
770         return eval_result;
771 }
772
773 ex function::evalf(int level) const
774 {
775         GINAC_ASSERT(serial<registered_functions().size());
776
777         // Evaluate children first
778         exvector eseq;
779         if (level == 1)
780                 eseq = seq;
781         else if (level == -max_recursion_level)
782                 throw(std::runtime_error("max recursion level reached"));
783         else
784                 eseq.reserve(seq.size());
785         level--;
786         exvector::const_iterator it = seq.begin(), itend = seq.end();
787         while (it != itend) {
788                 eseq.push_back((*it).evalf(level));
789                 it++;
790         }
791         
792         if (registered_functions()[serial].evalf_f==0) {
793                 return function(serial,eseq).hold();
794         }
795         switch (registered_functions()[serial].nparams) {
796                 // the following lines have been generated for max. ${maxargs} parameters
797 ${evalf_switch_statement}
798                 // end of generated lines
799         }
800         throw(std::logic_error("function::evalf(): invalid nparams"));
801 }
802
803 unsigned function::calchash(void) const
804 {
805         unsigned v = golden_ratio_hash(golden_ratio_hash(tinfo()) ^ serial);
806         for (unsigned i=0; i<nops(); i++) {
807                 v = rotate_left_31(v);
808                 v ^= this->op(i).gethash();
809         }
810         v &= 0x7FFFFFFFU;
811         if (flags & status_flags::evaluated) {
812                 setflag(status_flags::hash_calculated);
813                 hashvalue = v;
814         }
815         return v;
816 }
817
818 ex function::thisexprseq(const exvector & v) const
819 {
820         return function(serial,v);
821 }
822
823 ex function::thisexprseq(exvector * vp) const
824 {
825         return function(serial,vp);
826 }
827
828 /** Implementation of ex::series for functions.
829  *  \@see ex::series */
830 ex function::series(const relational & r, int order, unsigned options) const
831 {
832         GINAC_ASSERT(serial<registered_functions().size());
833
834         if (registered_functions()[serial].series_f==0) {
835                 return basic::series(r, order);
836         }
837         ex res;
838         switch (registered_functions()[serial].nparams) {
839                 // the following lines have been generated for max. ${maxargs} parameters
840 ${series_switch_statement}
841                 // end of generated lines
842         }
843         throw(std::logic_error("function::series(): invalid nparams"));
844 }
845
846 bool function::match(const ex & pattern, lst & repl_lst) const
847 {
848         // Serial number must match
849         if (is_ex_of_type(pattern, function) && serial != ex_to<function>(pattern).serial)
850                 return false;
851         return inherited::match(pattern, repl_lst);
852 }
853
854 // protected
855
856
857 /** Implementation of ex::diff() for functions. It applies the chain rule,
858  *  except for the Order term function.
859  *  \@see ex::diff */
860 ex function::derivative(const symbol & s) const
861 {
862         ex result;
863         
864         if (serial == function_index_Order) {
865                 // Order Term function only differentiates the argument
866                 return Order(seq[0].diff(s));
867         } else if (serial == function_index_Derivative) {
868                 // Inert derivative performs chain rule on the first argument only, and
869                 // adds differentiation parameter to list (second argument)
870                 GINAC_ASSERT(is_ex_exactly_of_type(seq[0], function));
871                 GINAC_ASSERT(is_ex_exactly_of_type(seq[1], function));
872                 ex fcn = seq[0];
873                 ex arg_diff;
874                 for (unsigned i=0; i!=fcn.nops(); i++) {
875                         arg_diff = fcn.op(i).diff(s);
876                         if (!arg_diff.is_zero()) {
877                                 lst new_lst = ex_to<lst>(seq[1]);
878                                 new_lst.append(i);
879                                 result += arg_diff * Derivative(fcn, new_lst);
880                         }
881                 }
882         } else {
883                 // Chain rule
884                 ex arg_diff;
885                 unsigned num = seq.size();
886                 for (unsigned i=0; i<num; i++) {
887                         arg_diff = seq[i].diff(s);
888                         // We apply the chain rule only when it makes sense.  This is not
889                         // just for performance reasons but also to allow functions to
890                         // throw when differentiated with respect to one of its arguments
891                         // without running into trouble with our automatic full
892                         // differentiation:
893                         if (!arg_diff.is_zero())
894                                 result += pderivative(i)*arg_diff;
895                 }
896         }
897         return result;
898 }
899
900 int function::compare_same_type(const basic & other) const
901 {
902         GINAC_ASSERT(is_of_type(other, function));
903         const function & o = static_cast<const function &>(other);
904
905         if (serial!=o.serial) {
906                 return serial < o.serial ? -1 : 1;
907         }
908         return exprseq::compare_same_type(o);
909 }
910
911 bool function::is_equal_same_type(const basic & other) const
912 {
913         GINAC_ASSERT(is_of_type(other, function));
914         const function & o = static_cast<const function &>(other);
915
916         if (serial!=o.serial) return false;
917         return exprseq::is_equal_same_type(o);
918 }
919
920 unsigned function::return_type(void) const
921 {
922         if (seq.empty())
923                 return return_types::commutative;
924         else
925                 return seq.begin()->return_type();
926 }
927
928 unsigned function::return_type_tinfo(void) const
929 {
930         if (seq.empty())
931                 return tinfo_key;
932         else
933                 return seq.begin()->return_type_tinfo();
934 }
935
936 //////////
937 // new virtual functions which can be overridden by derived classes
938 //////////
939
940 // none
941
942 //////////
943 // non-virtual functions in this class
944 //////////
945
946 // protected
947
948 ex function::pderivative(unsigned diff_param) const // partial differentiation
949 {
950         GINAC_ASSERT(serial<registered_functions().size());
951         
952         if (registered_functions()[serial].derivative_f==0) {
953                 return Derivative(*this, lst(ex(diff_param)));
954         }
955         switch (registered_functions()[serial].nparams) {
956                 // the following lines have been generated for max. ${maxargs} parameters
957 ${diff_switch_statement}
958                 // end of generated lines
959         }
960         throw(std::logic_error("function::pderivative(): no diff function defined"));
961 }
962
963 std::vector<function_options> & function::registered_functions(void)
964 {
965         static std::vector<function_options> * rf = new std::vector<function_options>;
966         return *rf;
967 }
968
969 bool function::lookup_remember_table(ex & result) const
970 {
971         return remember_table::remember_tables()[serial].lookup_entry(*this,result);
972 }
973
974 void function::store_remember_table(ex const & result) const
975 {
976         remember_table::remember_tables()[serial].add_entry(*this,result);
977 }
978
979 // public
980
981 unsigned function::register_new(function_options const & opt)
982 {
983         unsigned same_name = 0;
984         for (unsigned i=0; i<registered_functions().size(); ++i) {
985                 if (registered_functions()[i].name==opt.name) {
986                         same_name++;
987                 }
988         }
989         if (same_name>=opt.functions_with_same_name) {
990                 // we do not throw an exception here because this code is
991                 // usually executed before main(), so the exception could not
992                 // caught anyhow
993                 std::cerr << "WARNING: function name " << opt.name
994                                   << " already in use!" << std::endl;
995         }
996         registered_functions().push_back(opt);
997         if (opt.use_remember) {
998                 remember_table::remember_tables().
999                         push_back(remember_table(opt.remember_size,
1000                                                                          opt.remember_assoc_size,
1001                                                                          opt.remember_strategy));
1002         } else {
1003                 remember_table::remember_tables().push_back(remember_table());
1004         }
1005         return registered_functions().size()-1;
1006 }
1007
1008 /** Find serial number of function by name and number of parameters.
1009  *  Throws exception if function was not found. */
1010 unsigned function::find_function(const std::string &name, unsigned nparams)
1011 {
1012         std::vector<function_options>::const_iterator i = function::registered_functions().begin(), end = function::registered_functions().end();
1013         unsigned serial = 0;
1014         while (i != end) {
1015                 if (i->get_name() == name && i->get_nparams() == nparams)
1016                         return serial;
1017                 i++;
1018                 serial++;
1019         }
1020         throw (std::runtime_error("no function '" + name + "' with " + ToString(nparams) + " parameters defined"));
1021 }
1022
1023 /** Return the print name of the function. */
1024 std::string function::get_name(void) const
1025 {
1026         GINAC_ASSERT(serial<registered_functions().size());
1027         return registered_functions()[serial].name;
1028 }
1029
1030 } // namespace GiNaC
1031
1032 END_OF_IMPLEMENTATION
1033
1034 print "Creating interface file function.h...";
1035 open OUT,">function.h" or die "cannot open function.h";
1036 print OUT $interface;
1037 close OUT;
1038 print "ok.\n";
1039
1040 print "Creating implementation file function.cpp...";
1041 open OUT,">function.cpp" or die "cannot open function.cpp";
1042 print OUT $implementation;
1043 close OUT;
1044 print "ok.\n";
1045
1046 print "done.\n";