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