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