- indentation is now done with tabs
[ginac.git] / ginac / inifcns.cpp
1 /** @file inifcns.cpp
2  *
3  *  Implementation of GiNaC's initially known functions. */
4
5 /*
6  *  GiNaC Copyright (C) 1999-2000 Johannes Gutenberg University Mainz, Germany
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 2 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 #include <vector>
24 #include <stdexcept>
25
26 #include "inifcns.h"
27 #include "ex.h"
28 #include "constant.h"
29 #include "lst.h"
30 #include "matrix.h"
31 #include "mul.h"
32 #include "ncmul.h"
33 #include "numeric.h"
34 #include "power.h"
35 #include "relational.h"
36 #include "pseries.h"
37 #include "symbol.h"
38 #include "utils.h"
39
40 #ifndef NO_NAMESPACE_GINAC
41 namespace GiNaC {
42 #endif // ndef NO_NAMESPACE_GINAC
43
44 //////////
45 // absolute value
46 //////////
47
48 static ex abs_evalf(const ex & arg)
49 {
50         BEGIN_TYPECHECK
51                 TYPECHECK(arg,numeric)
52         END_TYPECHECK(abs(arg))
53         
54         return abs(ex_to_numeric(arg));
55 }
56
57 static ex abs_eval(const ex & arg)
58 {
59         if (is_ex_exactly_of_type(arg, numeric))
60                 return abs(ex_to_numeric(arg));
61         else
62                 return abs(arg).hold();
63 }
64
65 REGISTER_FUNCTION(abs, eval_func(abs_eval).
66                                            evalf_func(abs_evalf));
67
68
69 //////////
70 // Complex sign
71 //////////
72
73 static ex csgn_evalf(const ex & arg)
74 {
75         BEGIN_TYPECHECK
76                 TYPECHECK(arg,numeric)
77         END_TYPECHECK(csgn(arg))
78         
79         return csgn(ex_to_numeric(arg));
80 }
81
82 static ex csgn_eval(const ex & arg)
83 {
84         if (is_ex_exactly_of_type(arg, numeric))
85                 return csgn(ex_to_numeric(arg));
86         
87         else if (is_ex_exactly_of_type(arg, mul)) {
88                 numeric oc = ex_to_numeric(arg.op(arg.nops()-1));
89                 if (oc.is_real()) {
90                         if (oc > 0)
91                                 // csgn(42*x) -> csgn(x)
92                                 return csgn(arg/oc).hold();
93                         else
94                                 // csgn(-42*x) -> -csgn(x)
95                                 return -csgn(arg/oc).hold();
96                 }
97                 if (oc.real().is_zero()) {
98                         if (oc.imag() > 0)
99                                 // csgn(42*I*x) -> csgn(I*x)
100                                 return csgn(I*arg/oc).hold();
101                         else
102                                 // csgn(-42*I*x) -> -csgn(I*x)
103                                 return -csgn(I*arg/oc).hold();
104                 }
105         }
106    
107         return csgn(arg).hold();
108 }
109
110 static ex csgn_series(const ex & arg,
111                                           const relational & rel,
112                                           int order,
113                                           unsigned options)
114 {
115         const ex arg_pt = arg.subs(rel);
116         if (arg_pt.info(info_flags::numeric) &&
117                 ex_to_numeric(arg_pt).real().is_zero())
118                 throw (std::domain_error("csgn_series(): on imaginary axis"));
119         
120         epvector seq;
121         seq.push_back(expair(csgn(arg_pt), _ex0()));
122         return pseries(rel,seq);
123 }
124
125 REGISTER_FUNCTION(csgn, eval_func(csgn_eval).
126                                                 evalf_func(csgn_evalf).
127                                                 series_func(csgn_series));
128
129
130 //////////
131 // Eta function: log(x*y) == log(x) + log(y) + eta(x,y).
132 //////////
133
134 static ex eta_evalf(const ex & x, const ex & y)
135 {
136         BEGIN_TYPECHECK
137                 TYPECHECK(x,numeric)
138                 TYPECHECK(y,numeric)
139         END_TYPECHECK(eta(x,y))
140                 
141         numeric xim = imag(ex_to_numeric(x));
142         numeric yim = imag(ex_to_numeric(y));
143         numeric xyim = imag(ex_to_numeric(x*y));
144         return evalf(I/4*Pi)*((csgn(-xim)+1)*(csgn(-yim)+1)*(csgn(xyim)+1)-(csgn(xim)+1)*(csgn(yim)+1)*(csgn(-xyim)+1));
145 }
146
147 static ex eta_eval(const ex & x, const ex & y)
148 {
149         if (is_ex_exactly_of_type(x, numeric) &&
150                 is_ex_exactly_of_type(y, numeric)) {
151                 // don't call eta_evalf here because it would call Pi.evalf()!
152                 numeric xim = imag(ex_to_numeric(x));
153                 numeric yim = imag(ex_to_numeric(y));
154                 numeric xyim = imag(ex_to_numeric(x*y));
155                 return (I/4)*Pi*((csgn(-xim)+1)*(csgn(-yim)+1)*(csgn(xyim)+1)-(csgn(xim)+1)*(csgn(yim)+1)*(csgn(-xyim)+1));
156         }
157         
158         return eta(x,y).hold();
159 }
160
161 static ex eta_series(const ex & arg1,
162                                          const ex & arg2,
163                                          const relational & rel,
164                                          int order,
165                                          unsigned options)
166 {
167         const ex arg1_pt = arg1.subs(rel);
168         const ex arg2_pt = arg2.subs(rel);
169         if (ex_to_numeric(arg1_pt).imag().is_zero() ||
170                 ex_to_numeric(arg2_pt).imag().is_zero() ||
171                 ex_to_numeric(arg1_pt*arg2_pt).imag().is_zero()) {
172                 throw (std::domain_error("eta_series(): on discontinuity"));
173         }
174         epvector seq;
175         seq.push_back(expair(eta(arg1_pt,arg2_pt), _ex0()));
176         return pseries(rel,seq);
177 }
178
179 REGISTER_FUNCTION(eta, eval_func(eta_eval).
180                                            evalf_func(eta_evalf).
181                                            series_func(eta_series));
182
183
184 //////////
185 // dilogarithm
186 //////////
187
188 static ex Li2_evalf(const ex & x)
189 {
190         BEGIN_TYPECHECK
191                 TYPECHECK(x,numeric)
192         END_TYPECHECK(Li2(x))
193         
194         return Li2(ex_to_numeric(x));  // -> numeric Li2(numeric)
195 }
196
197 static ex Li2_eval(const ex & x)
198 {
199         if (x.info(info_flags::numeric)) {
200                 // Li2(0) -> 0
201                 if (x.is_zero())
202                         return _ex0();
203                 // Li2(1) -> Pi^2/6
204                 if (x.is_equal(_ex1()))
205                         return power(Pi,_ex2())/_ex6();
206                 // Li2(1/2) -> Pi^2/12 - log(2)^2/2
207                 if (x.is_equal(_ex1_2()))
208                         return power(Pi,_ex2())/_ex12() + power(log(_ex2()),_ex2())*_ex_1_2();
209                 // Li2(-1) -> -Pi^2/12
210                 if (x.is_equal(_ex_1()))
211                         return -power(Pi,_ex2())/_ex12();
212                 // Li2(I) -> -Pi^2/48+Catalan*I
213                 if (x.is_equal(I))
214                         return power(Pi,_ex2())/_ex_48() + Catalan*I;
215                 // Li2(-I) -> -Pi^2/48-Catalan*I
216                 if (x.is_equal(-I))
217                         return power(Pi,_ex2())/_ex_48() - Catalan*I;
218                 // Li2(float)
219                 if (!x.info(info_flags::crational))
220                         return Li2_evalf(x);
221         }
222         
223         return Li2(x).hold();
224 }
225
226 static ex Li2_deriv(const ex & x, unsigned deriv_param)
227 {
228         GINAC_ASSERT(deriv_param==0);
229         
230         // d/dx Li2(x) -> -log(1-x)/x
231         return -log(1-x)/x;
232 }
233
234 static ex Li2_series(const ex &x, const relational &rel, int order, unsigned options)
235 {
236         const ex x_pt = x.subs(rel);
237         if (x_pt.info(info_flags::numeric)) {
238                 // First special case: x==0 (derivatives have poles)
239                 if (x_pt.is_zero()) {
240                         // method:
241                         // The problem is that in d/dx Li2(x==0) == -log(1-x)/x we cannot 
242                         // simply substitute x==0.  The limit, however, exists: it is 1.
243                         // We also know all higher derivatives' limits:
244                         // (d/dx)^n Li2(x) == n!/n^2.
245                         // So the primitive series expansion is
246                         // Li2(x==0) == x + x^2/4 + x^3/9 + ...
247                         // and so on.
248                         // We first construct such a primitive series expansion manually in
249                         // a dummy symbol s and then insert the argument's series expansion
250                         // for s.  Reexpanding the resulting series returns the desired
251                         // result.
252                         const symbol s;
253                         ex ser;
254                         // manually construct the primitive expansion
255                         for (int i=1; i<order; ++i)
256                                 ser += pow(s,i) / pow(numeric(i), _num2());
257                         // substitute the argument's series expansion
258                         ser = ser.subs(s==x.series(rel, order));
259                         // maybe that was terminating, so add a proper order term
260                         epvector nseq;
261                         nseq.push_back(expair(Order(_ex1()), order));
262                         ser += pseries(rel, nseq);
263                         // reexpanding it will collapse the series again
264                         return ser.series(rel, order);
265                         // NB: Of course, this still does not allow us to compute anything
266                         // like sin(Li2(x)).series(x==0,2), since then this code here is
267                         // not reached and the derivative of sin(Li2(x)) doesn't allow the
268                         // substitution x==0.  Probably limits *are* needed for the general
269                         // cases.  In case L'Hospital's rule is implemented for limits and
270                         // basic::series() takes care of this, this whole block is probably
271                         // obsolete!
272                 }
273                 // second special case: x==1 (branch point)
274                 if (x_pt == _ex1()) {
275                         // method:
276                         // construct series manually in a dummy symbol s
277                         const symbol s;
278                         ex ser = zeta(2);
279                         // manually construct the primitive expansion
280                         for (int i=1; i<order; ++i)
281                                 ser += pow(1-s,i) * (numeric(1,i)*(I*Pi+log(s-1)) - numeric(1,i*i));
282                         // substitute the argument's series expansion
283                         ser = ser.subs(s==x.series(rel, order));
284                         // maybe that was terminating, so add a proper order term
285                         epvector nseq;
286                         nseq.push_back(expair(Order(_ex1()), order));
287                         ser += pseries(rel, nseq);
288                         // reexpanding it will collapse the series again
289                         return ser.series(rel, order);
290                 }
291                 // third special case: x real, >=1 (branch cut)
292                 if (!(options & series_options::suppress_branchcut) &&
293                         ex_to_numeric(x_pt).is_real() && ex_to_numeric(x_pt)>1) {
294                         // method:
295                         // This is the branch cut: assemble the primitive series manually
296                         // and then add the corresponding complex step function.
297                         const symbol *s = static_cast<symbol *>(rel.lhs().bp);
298                         const ex point = rel.rhs();
299                         const symbol foo;
300                         epvector seq;
301                         // zeroth order term:
302                         seq.push_back(expair(Li2(x_pt), _ex0()));
303                         // compute the intermediate terms:
304                         ex replarg = series(Li2(x), *s==foo, order);
305                         for (unsigned i=1; i<replarg.nops()-1; ++i)
306                                 seq.push_back(expair((replarg.op(i)/power(*s-foo,i)).series(foo==point,1,options).op(0).subs(foo==*s),i));
307                         // append an order term:
308                         seq.push_back(expair(Order(_ex1()), replarg.nops()-1));
309                         return pseries(rel, seq);
310                 }
311         }
312         // all other cases should be safe, by now:
313         throw do_taylor();  // caught by function::series()
314 }
315
316 REGISTER_FUNCTION(Li2, eval_func(Li2_eval).
317                                            evalf_func(Li2_evalf).
318                                            derivative_func(Li2_deriv).
319                                            series_func(Li2_series));
320
321 //////////
322 // trilogarithm
323 //////////
324
325 static ex Li3_eval(const ex & x)
326 {
327         if (x.is_zero())
328                 return x;
329         return Li3(x).hold();
330 }
331
332 REGISTER_FUNCTION(Li3, eval_func(Li3_eval));
333
334 //////////
335 // factorial
336 //////////
337
338 static ex factorial_evalf(const ex & x)
339 {
340         return factorial(x).hold();
341 }
342
343 static ex factorial_eval(const ex & x)
344 {
345         if (is_ex_exactly_of_type(x, numeric))
346                 return factorial(ex_to_numeric(x));
347         else
348                 return factorial(x).hold();
349 }
350
351 REGISTER_FUNCTION(factorial, eval_func(factorial_eval).
352                                                          evalf_func(factorial_evalf));
353
354 //////////
355 // binomial
356 //////////
357
358 static ex binomial_evalf(const ex & x, const ex & y)
359 {
360         return binomial(x, y).hold();
361 }
362
363 static ex binomial_eval(const ex & x, const ex &y)
364 {
365         if (is_ex_exactly_of_type(x, numeric) && is_ex_exactly_of_type(y, numeric))
366                 return binomial(ex_to_numeric(x), ex_to_numeric(y));
367         else
368                 return binomial(x, y).hold();
369 }
370
371 REGISTER_FUNCTION(binomial, eval_func(binomial_eval).
372                                                         evalf_func(binomial_evalf));
373
374 //////////
375 // Order term function (for truncated power series)
376 //////////
377
378 static ex Order_eval(const ex & x)
379 {
380         if (is_ex_exactly_of_type(x, numeric)) {
381                 // O(c) -> O(1) or 0
382                 if (!x.is_zero())
383                         return Order(_ex1()).hold();
384                 else
385                         return _ex0();
386         } else if (is_ex_exactly_of_type(x, mul)) {
387                 mul *m = static_cast<mul *>(x.bp);
388                 // O(c*expr) -> O(expr)
389                 if (is_ex_exactly_of_type(m->op(m->nops() - 1), numeric))
390                         return Order(x / m->op(m->nops() - 1)).hold();
391         }
392         return Order(x).hold();
393 }
394
395 static ex Order_series(const ex & x, const relational & r, int order, unsigned options)
396 {
397         // Just wrap the function into a pseries object
398         epvector new_seq;
399         GINAC_ASSERT(is_ex_exactly_of_type(r.lhs(),symbol));
400         const symbol *s = static_cast<symbol *>(r.lhs().bp);
401         new_seq.push_back(expair(Order(_ex1()), numeric(std::min(x.ldegree(*s), order))));
402         return pseries(r, new_seq);
403 }
404
405 // Differentiation is handled in function::derivative because of its special requirements
406
407 REGISTER_FUNCTION(Order, eval_func(Order_eval).
408                                                  series_func(Order_series));
409
410 //////////
411 // Inert partial differentiation operator
412 //////////
413
414 static ex Derivative_eval(const ex & f, const ex & l)
415 {
416         if (!is_ex_exactly_of_type(f, function)) {
417                 throw(std::invalid_argument("Derivative(): 1st argument must be a function"));
418         }
419         if (!is_ex_exactly_of_type(l, lst)) {
420                 throw(std::invalid_argument("Derivative(): 2nd argument must be a list"));
421         }
422         return Derivative(f, l).hold();
423 }
424
425 REGISTER_FUNCTION(Derivative, eval_func(Derivative_eval));
426
427 //////////
428 // Solve linear system
429 //////////
430
431 ex lsolve(const ex &eqns, const ex &symbols)
432 {
433         // solve a system of linear equations
434         if (eqns.info(info_flags::relation_equal)) {
435                 if (!symbols.info(info_flags::symbol))
436                         throw(std::invalid_argument("lsolve(): 2nd argument must be a symbol"));
437                 ex sol=lsolve(lst(eqns),lst(symbols));
438                 
439                 GINAC_ASSERT(sol.nops()==1);
440                 GINAC_ASSERT(is_ex_exactly_of_type(sol.op(0),relational));
441                 
442                 return sol.op(0).op(1); // return rhs of first solution
443         }
444         
445         // syntax checks
446         if (!eqns.info(info_flags::list)) {
447                 throw(std::invalid_argument("lsolve(): 1st argument must be a list"));
448         }
449         for (unsigned i=0; i<eqns.nops(); i++) {
450                 if (!eqns.op(i).info(info_flags::relation_equal)) {
451                         throw(std::invalid_argument("lsolve(): 1st argument must be a list of equations"));
452                 }
453         }
454         if (!symbols.info(info_flags::list)) {
455                 throw(std::invalid_argument("lsolve(): 2nd argument must be a list"));
456         }
457         for (unsigned i=0; i<symbols.nops(); i++) {
458                 if (!symbols.op(i).info(info_flags::symbol)) {
459                         throw(std::invalid_argument("lsolve(): 2nd argument must be a list of symbols"));
460                 }
461         }
462         
463         // build matrix from equation system
464         matrix sys(eqns.nops(),symbols.nops());
465         matrix rhs(eqns.nops(),1);
466         matrix vars(symbols.nops(),1);
467         
468         for (unsigned r=0; r<eqns.nops(); r++) {
469                 ex eq = eqns.op(r).op(0)-eqns.op(r).op(1); // lhs-rhs==0
470                 ex linpart = eq;
471                 for (unsigned c=0; c<symbols.nops(); c++) {
472                         ex co = eq.coeff(ex_to_symbol(symbols.op(c)),1);
473                         linpart -= co*symbols.op(c);
474                         sys.set(r,c,co);
475                 }
476                 linpart = linpart.expand();
477                 rhs.set(r,0,-linpart);
478         }
479         
480         // test if system is linear and fill vars matrix
481         for (unsigned i=0; i<symbols.nops(); i++) {
482                 vars.set(i,0,symbols.op(i));
483                 if (sys.has(symbols.op(i)))
484                         throw(std::logic_error("lsolve: system is not linear"));
485                 if (rhs.has(symbols.op(i)))
486                         throw(std::logic_error("lsolve: system is not linear"));
487         }
488         
489         matrix solution;
490         try {
491                 solution = sys.solve(vars,rhs);
492         } catch (const runtime_error & e) {
493                 // Probably singular matrix or otherwise overdetermined system:
494                 // It is consistent to return an empty list
495                 return lst();
496         }    
497         GINAC_ASSERT(solution.cols()==1);
498         GINAC_ASSERT(solution.rows()==symbols.nops());
499         
500         // return list of equations of the form lst(var1==sol1,var2==sol2,...)
501         lst sollist;
502         for (unsigned i=0; i<symbols.nops(); i++)
503                 sollist.append(symbols.op(i)==solution(i,0));
504         
505         return sollist;
506 }
507
508 /** non-commutative power. */
509 ex ncpower(const ex &basis, unsigned exponent)
510 {
511         if (exponent==0) {
512                 return _ex1();
513         }
514
515         exvector v;
516         v.reserve(exponent);
517         for (unsigned i=0; i<exponent; ++i) {
518                 v.push_back(basis);
519         }
520
521         return ncmul(v,1);
522 }
523
524 /** Force inclusion of functions from initcns_gamma and inifcns_zeta
525  *  for static lib (so ginsh will see them). */
526 unsigned force_include_tgamma = function_index_tgamma;
527 unsigned force_include_zeta1 = function_index_zeta1;
528
529 #ifndef NO_NAMESPACE_GINAC
530 } // namespace GiNaC
531 #endif // ndef NO_NAMESPACE_GINAC