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