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