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