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