]> www.ginac.de Git - ginac.git/blob - ginac/inifcns.cpp
ec74a435de0774290f6d95baa221690b87420de7
[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-2020 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
21  */
22
23 #include "inifcns.h"
24 #include "ex.h"
25 #include "constant.h"
26 #include "lst.h"
27 #include "fderivative.h"
28 #include "matrix.h"
29 #include "mul.h"
30 #include "power.h"
31 #include "operators.h"
32 #include "relational.h"
33 #include "pseries.h"
34 #include "symbol.h"
35 #include "symmetry.h"
36 #include "utils.h"
37
38 #include <stdexcept>
39 #include <vector>
40
41 namespace GiNaC {
42
43 //////////
44 // complex conjugate
45 //////////
46
47 static ex conjugate_evalf(const ex & arg)
48 {
49         if (is_exactly_a<numeric>(arg)) {
50                 return ex_to<numeric>(arg).conjugate();
51         }
52         return conjugate_function(arg).hold();
53 }
54
55 static ex conjugate_eval(const ex & arg)
56 {
57         return arg.conjugate();
58 }
59
60 static void conjugate_print_latex(const ex & arg, const print_context & c)
61 {
62         c.s << "\\bar{"; arg.print(c); c.s << "}";
63 }
64
65 static ex conjugate_conjugate(const ex & arg)
66 {
67         return arg;
68 }
69
70 // If x is real then U.diff(x)-I*V.diff(x) represents both conjugate(U+I*V).diff(x) 
71 // and conjugate((U+I*V).diff(x))
72 static ex conjugate_expl_derivative(const ex & arg, const symbol & s)
73 {
74         if (s.info(info_flags::real))
75                 return conjugate(arg.diff(s));
76         else {
77                 exvector vec_arg;
78                 vec_arg.push_back(arg);
79                 return fderivative(ex_to<function>(conjugate(arg)).get_serial(),0,vec_arg).hold()*arg.diff(s);
80         }
81 }
82
83 static ex conjugate_real_part(const ex & arg)
84 {
85         return arg.real_part();
86 }
87
88 static ex conjugate_imag_part(const ex & arg)
89 {
90         return -arg.imag_part();
91 }
92
93 static bool func_arg_info(const ex & arg, unsigned inf)
94 {
95         // for some functions we can return the info() of its argument
96         // (think of conjugate())
97         switch (inf) {
98                 case info_flags::polynomial:
99                 case info_flags::integer_polynomial:
100                 case info_flags::cinteger_polynomial:
101                 case info_flags::rational_polynomial:
102                 case info_flags::real:
103                 case info_flags::rational:
104                 case info_flags::integer:
105                 case info_flags::crational:
106                 case info_flags::cinteger:
107                 case info_flags::even:
108                 case info_flags::odd:
109                 case info_flags::prime:
110                 case info_flags::crational_polynomial:
111                 case info_flags::rational_function:
112                 case info_flags::positive:
113                 case info_flags::negative:
114                 case info_flags::nonnegative:
115                 case info_flags::posint:
116                 case info_flags::negint:
117                 case info_flags::nonnegint:
118                 case info_flags::has_indices:
119                         return arg.info(inf);
120         }
121         return false;
122 }
123
124 static bool conjugate_info(const ex & arg, unsigned inf)
125 {
126         return func_arg_info(arg, inf);
127 }
128
129 REGISTER_FUNCTION(conjugate_function, eval_func(conjugate_eval).
130                                       evalf_func(conjugate_evalf).
131                                       expl_derivative_func(conjugate_expl_derivative).
132                                       info_func(conjugate_info).
133                                       print_func<print_latex>(conjugate_print_latex).
134                                       conjugate_func(conjugate_conjugate).
135                                       real_part_func(conjugate_real_part).
136                                       imag_part_func(conjugate_imag_part).
137                                       set_name("conjugate","conjugate"));
138
139 //////////
140 // real part
141 //////////
142
143 static ex real_part_evalf(const ex & arg)
144 {
145         if (is_exactly_a<numeric>(arg)) {
146                 return ex_to<numeric>(arg).real();
147         }
148         return real_part_function(arg).hold();
149 }
150
151 static ex real_part_eval(const ex & arg)
152 {
153         return arg.real_part();
154 }
155
156 static void real_part_print_latex(const ex & arg, const print_context & c)
157 {
158         c.s << "\\Re"; arg.print(c); c.s << "";
159 }
160
161 static ex real_part_conjugate(const ex & arg)
162 {
163         return real_part_function(arg).hold();
164 }
165
166 static ex real_part_real_part(const ex & arg)
167 {
168         return real_part_function(arg).hold();
169 }
170
171 static ex real_part_imag_part(const ex & arg)
172 {
173         return 0;
174 }
175
176 // If x is real then Re(e).diff(x) is equal to Re(e.diff(x)) 
177 static ex real_part_expl_derivative(const ex & arg, const symbol & s)
178 {
179         if (s.info(info_flags::real))
180                 return real_part_function(arg.diff(s));
181         else {
182                 exvector vec_arg;
183                 vec_arg.push_back(arg);
184                 return fderivative(ex_to<function>(real_part(arg)).get_serial(),0,vec_arg).hold()*arg.diff(s);
185         }
186 }
187
188 REGISTER_FUNCTION(real_part_function, eval_func(real_part_eval).
189                                       evalf_func(real_part_evalf).
190                                       expl_derivative_func(real_part_expl_derivative).
191                                       print_func<print_latex>(real_part_print_latex).
192                                       conjugate_func(real_part_conjugate).
193                                       real_part_func(real_part_real_part).
194                                       imag_part_func(real_part_imag_part).
195                                       set_name("real_part","real_part"));
196
197 //////////
198 // imag part
199 //////////
200
201 static ex imag_part_evalf(const ex & arg)
202 {
203         if (is_exactly_a<numeric>(arg)) {
204                 return ex_to<numeric>(arg).imag();
205         }
206         return imag_part_function(arg).hold();
207 }
208
209 static ex imag_part_eval(const ex & arg)
210 {
211         return arg.imag_part();
212 }
213
214 static void imag_part_print_latex(const ex & arg, const print_context & c)
215 {
216         c.s << "\\Im"; arg.print(c); c.s << "";
217 }
218
219 static ex imag_part_conjugate(const ex & arg)
220 {
221         return imag_part_function(arg).hold();
222 }
223
224 static ex imag_part_real_part(const ex & arg)
225 {
226         return imag_part_function(arg).hold();
227 }
228
229 static ex imag_part_imag_part(const ex & arg)
230 {
231         return 0;
232 }
233
234 // If x is real then Im(e).diff(x) is equal to Im(e.diff(x)) 
235 static ex imag_part_expl_derivative(const ex & arg, const symbol & s)
236 {
237         if (s.info(info_flags::real))
238                 return imag_part_function(arg.diff(s));
239         else {
240                 exvector vec_arg;
241                 vec_arg.push_back(arg);
242                 return fderivative(ex_to<function>(imag_part(arg)).get_serial(),0,vec_arg).hold()*arg.diff(s);
243         }
244 }
245
246 REGISTER_FUNCTION(imag_part_function, eval_func(imag_part_eval).
247                                       evalf_func(imag_part_evalf).
248                                       expl_derivative_func(imag_part_expl_derivative).
249                                       print_func<print_latex>(imag_part_print_latex).
250                                       conjugate_func(imag_part_conjugate).
251                                       real_part_func(imag_part_real_part).
252                                       imag_part_func(imag_part_imag_part).
253                                       set_name("imag_part","imag_part"));
254
255 //////////
256 // absolute value
257 //////////
258
259 static ex abs_evalf(const ex & arg)
260 {
261         if (is_exactly_a<numeric>(arg))
262                 return abs(ex_to<numeric>(arg));
263         
264         return abs(arg).hold();
265 }
266
267 static ex abs_eval(const ex & arg)
268 {
269         if (is_exactly_a<numeric>(arg))
270                 return abs(ex_to<numeric>(arg));
271
272         if (arg.info(info_flags::nonnegative))
273                 return arg;
274
275         if (arg.info(info_flags::negative) || (-arg).info(info_flags::nonnegative))
276                 return -arg;
277
278         if (is_ex_the_function(arg, abs))
279                 return arg;
280
281         if (is_ex_the_function(arg, exp))
282                 return exp(arg.op(0).real_part());
283
284         if (is_exactly_a<power>(arg)) {
285                 const ex& base = arg.op(0);
286                 const ex& exponent = arg.op(1);
287                 if (base.info(info_flags::positive) || exponent.info(info_flags::real))
288                         return pow(abs(base), exponent.real_part());
289         }
290
291         if (is_ex_the_function(arg, conjugate_function))
292                 return abs(arg.op(0));
293
294         if (is_ex_the_function(arg, step))
295                 return arg;
296
297         return abs(arg).hold();
298 }
299
300 static ex abs_expand(const ex & arg, unsigned options)
301 {
302         if ((options & expand_options::expand_transcendental)
303                 && is_exactly_a<mul>(arg)) {
304                 exvector prodseq;
305                 prodseq.reserve(arg.nops());
306                 for (const_iterator i = arg.begin(); i != arg.end(); ++i) {
307                         if (options & expand_options::expand_function_args)
308                                 prodseq.push_back(abs(i->expand(options)));
309                         else
310                                 prodseq.push_back(abs(*i));
311                 }
312                 return dynallocate<mul>(prodseq).setflag(status_flags::expanded);
313         }
314
315         if (options & expand_options::expand_function_args)
316                 return abs(arg.expand(options)).hold();
317         else
318                 return abs(arg).hold();
319 }
320
321 static ex abs_expl_derivative(const ex & arg, const symbol & s)
322 {
323         ex diff_arg = arg.diff(s);
324         if (arg.info(info_flags::real))
325                 return diff_arg*(2*step(arg) - 1);
326         return (diff_arg*arg.conjugate()+arg*diff_arg.conjugate())/2/abs(arg);
327 }
328
329 static void abs_print_latex(const ex & arg, const print_context & c)
330 {
331         c.s << "{|"; arg.print(c); c.s << "|}";
332 }
333
334 static void abs_print_csrc_float(const ex & arg, const print_context & c)
335 {
336         c.s << "fabs("; arg.print(c); c.s << ")";
337 }
338
339 static ex abs_conjugate(const ex & arg)
340 {
341         return abs(arg).hold();
342 }
343
344 static ex abs_real_part(const ex & arg)
345 {
346         return abs(arg).hold();
347 }
348
349 static ex abs_imag_part(const ex& arg)
350 {
351         return 0;
352 }
353
354 static ex abs_power(const ex & arg, const ex & exp)
355 {
356         if ((is_a<numeric>(exp) && ex_to<numeric>(exp).is_even()) || exp.info(info_flags::even)) {
357                 if (arg.info(info_flags::real) || arg.is_equal(arg.conjugate()))
358                         return pow(arg, exp);
359                 else
360                         return pow(arg, exp/2) * pow(arg.conjugate(), exp/2);
361         } else
362                 return power(abs(arg), exp).hold();
363 }
364
365 bool abs_info(const ex & arg, unsigned inf)
366 {
367         switch (inf) {
368                 case info_flags::integer:
369                 case info_flags::even:
370                 case info_flags::odd:
371                 case info_flags::prime:
372                         return arg.info(inf);
373                 case info_flags::nonnegint:
374                         return arg.info(info_flags::integer);
375                 case info_flags::nonnegative:
376                 case info_flags::real:
377                         return true;
378                 case info_flags::negative:
379                         return false;
380                 case info_flags::positive:
381                         return arg.info(info_flags::positive) || arg.info(info_flags::negative);
382                 case info_flags::has_indices: {
383                         if (arg.info(info_flags::has_indices))
384                                 return true;
385                         else
386                                 return false;
387                 }
388         }
389         return false;
390 }
391
392 REGISTER_FUNCTION(abs, eval_func(abs_eval).
393                        evalf_func(abs_evalf).
394                        expand_func(abs_expand).
395                        expl_derivative_func(abs_expl_derivative).
396                        info_func(abs_info).
397                        print_func<print_latex>(abs_print_latex).
398                        print_func<print_csrc_float>(abs_print_csrc_float).
399                        print_func<print_csrc_double>(abs_print_csrc_float).
400                        conjugate_func(abs_conjugate).
401                        real_part_func(abs_real_part).
402                        imag_part_func(abs_imag_part).
403                        power_func(abs_power));
404
405 //////////
406 // Step function
407 //////////
408
409 static ex step_evalf(const ex & arg)
410 {
411         if (is_exactly_a<numeric>(arg))
412                 return step(ex_to<numeric>(arg));
413         
414         return step(arg).hold();
415 }
416
417 static ex step_eval(const ex & arg)
418 {
419         if (is_exactly_a<numeric>(arg))
420                 return step(ex_to<numeric>(arg));
421         
422         else if (is_exactly_a<mul>(arg) &&
423                  is_exactly_a<numeric>(arg.op(arg.nops()-1))) {
424                 numeric oc = ex_to<numeric>(arg.op(arg.nops()-1));
425                 if (oc.is_real()) {
426                         if (oc > 0)
427                                 // step(42*x) -> step(x)
428                                 return step(arg/oc).hold();
429                         else
430                                 // step(-42*x) -> step(-x)
431                                 return step(-arg/oc).hold();
432                 }
433                 if (oc.real().is_zero()) {
434                         if (oc.imag() > 0)
435                                 // step(42*I*x) -> step(I*x)
436                                 return step(I*arg/oc).hold();
437                         else
438                                 // step(-42*I*x) -> step(-I*x)
439                                 return step(-I*arg/oc).hold();
440                 }
441         }
442         
443         return step(arg).hold();
444 }
445
446 static ex step_series(const ex & arg,
447                       const relational & rel,
448                       int order,
449                       unsigned options)
450 {
451         const ex arg_pt = arg.subs(rel, subs_options::no_pattern);
452         if (arg_pt.info(info_flags::numeric)
453             && ex_to<numeric>(arg_pt).real().is_zero()
454             && !(options & series_options::suppress_branchcut))
455                 throw (std::domain_error("step_series(): on imaginary axis"));
456         
457         epvector seq { expair(step(arg_pt), _ex0) };
458         return pseries(rel, std::move(seq));
459 }
460
461 static ex step_conjugate(const ex& arg)
462 {
463         return step(arg).hold();
464 }
465
466 static ex step_real_part(const ex& arg)
467 {
468         return step(arg).hold();
469 }
470
471 static ex step_imag_part(const ex& arg)
472 {
473         return 0;
474 }
475
476 REGISTER_FUNCTION(step, eval_func(step_eval).
477                         evalf_func(step_evalf).
478                         series_func(step_series).
479                         conjugate_func(step_conjugate).
480                         real_part_func(step_real_part).
481                         imag_part_func(step_imag_part));
482
483 //////////
484 // Complex sign
485 //////////
486
487 static ex csgn_evalf(const ex & arg)
488 {
489         if (is_exactly_a<numeric>(arg))
490                 return csgn(ex_to<numeric>(arg));
491         
492         return csgn(arg).hold();
493 }
494
495 static ex csgn_eval(const ex & arg)
496 {
497         if (is_exactly_a<numeric>(arg))
498                 return csgn(ex_to<numeric>(arg));
499         
500         else if (is_exactly_a<mul>(arg) &&
501                  is_exactly_a<numeric>(arg.op(arg.nops()-1))) {
502                 numeric oc = ex_to<numeric>(arg.op(arg.nops()-1));
503                 if (oc.is_real()) {
504                         if (oc > 0)
505                                 // csgn(42*x) -> csgn(x)
506                                 return csgn(arg/oc).hold();
507                         else
508                                 // csgn(-42*x) -> -csgn(x)
509                                 return -csgn(arg/oc).hold();
510                 }
511                 if (oc.real().is_zero()) {
512                         if (oc.imag() > 0)
513                                 // csgn(42*I*x) -> csgn(I*x)
514                                 return csgn(I*arg/oc).hold();
515                         else
516                                 // csgn(-42*I*x) -> -csgn(I*x)
517                                 return -csgn(I*arg/oc).hold();
518                 }
519         }
520         
521         return csgn(arg).hold();
522 }
523
524 static ex csgn_series(const ex & arg,
525                       const relational & rel,
526                       int order,
527                       unsigned options)
528 {
529         const ex arg_pt = arg.subs(rel, subs_options::no_pattern);
530         if (arg_pt.info(info_flags::numeric)
531             && ex_to<numeric>(arg_pt).real().is_zero()
532             && !(options & series_options::suppress_branchcut))
533                 throw (std::domain_error("csgn_series(): on imaginary axis"));
534         
535         epvector seq { expair(csgn(arg_pt), _ex0) };
536         return pseries(rel, std::move(seq));
537 }
538
539 static ex csgn_conjugate(const ex& arg)
540 {
541         return csgn(arg).hold();
542 }
543
544 static ex csgn_real_part(const ex& arg)
545 {
546         return csgn(arg).hold();
547 }
548
549 static ex csgn_imag_part(const ex& arg)
550 {
551         return 0;
552 }
553
554 static ex csgn_power(const ex & arg, const ex & exp)
555 {
556         if (is_a<numeric>(exp) && exp.info(info_flags::positive) && ex_to<numeric>(exp).is_integer()) {
557                 if (ex_to<numeric>(exp).is_odd())
558                         return csgn(arg).hold();
559                 else
560                         return power(csgn(arg), _ex2).hold();
561         } else
562                 return power(csgn(arg), exp).hold();
563 }
564
565
566 REGISTER_FUNCTION(csgn, eval_func(csgn_eval).
567                         evalf_func(csgn_evalf).
568                         series_func(csgn_series).
569                         conjugate_func(csgn_conjugate).
570                         real_part_func(csgn_real_part).
571                         imag_part_func(csgn_imag_part).
572                         power_func(csgn_power));
573
574
575 //////////
576 // Eta function: eta(x,y) == log(x*y) - log(x) - log(y).
577 // This function is closely related to the unwinding number K, sometimes found
578 // in modern literature: K(z) == (z-log(exp(z)))/(2*Pi*I).
579 //////////
580
581 static ex eta_evalf(const ex &x, const ex &y)
582 {
583         // It seems like we basically have to replicate the eval function here,
584         // since the expression might not be fully evaluated yet.
585         if (x.info(info_flags::positive) || y.info(info_flags::positive))
586                 return _ex0;
587
588         if (x.info(info_flags::numeric) &&      y.info(info_flags::numeric)) {
589                 const numeric nx = ex_to<numeric>(x);
590                 const numeric ny = ex_to<numeric>(y);
591                 const numeric nxy = ex_to<numeric>(x*y);
592                 int cut = 0;
593                 if (nx.is_real() && nx.is_negative())
594                         cut -= 4;
595                 if (ny.is_real() && ny.is_negative())
596                         cut -= 4;
597                 if (nxy.is_real() && nxy.is_negative())
598                         cut += 4;
599                 return evalf(I/4*Pi)*((csgn(-imag(nx))+1)*(csgn(-imag(ny))+1)*(csgn(imag(nxy))+1)-
600                                       (csgn(imag(nx))+1)*(csgn(imag(ny))+1)*(csgn(-imag(nxy))+1)+cut);
601         }
602
603         return eta(x,y).hold();
604 }
605
606 static ex eta_eval(const ex &x, const ex &y)
607 {
608         // trivial:  eta(x,c) -> 0  if c is real and positive
609         if (x.info(info_flags::positive) || y.info(info_flags::positive))
610                 return _ex0;
611
612         if (x.info(info_flags::numeric) &&      y.info(info_flags::numeric)) {
613                 // don't call eta_evalf here because it would call Pi.evalf()!
614                 const numeric nx = ex_to<numeric>(x);
615                 const numeric ny = ex_to<numeric>(y);
616                 const numeric nxy = ex_to<numeric>(x*y);
617                 int cut = 0;
618                 if (nx.is_real() && nx.is_negative())
619                         cut -= 4;
620                 if (ny.is_real() && ny.is_negative())
621                         cut -= 4;
622                 if (nxy.is_real() && nxy.is_negative())
623                         cut += 4;
624                 return (I/4)*Pi*((csgn(-imag(nx))+1)*(csgn(-imag(ny))+1)*(csgn(imag(nxy))+1)-
625                                  (csgn(imag(nx))+1)*(csgn(imag(ny))+1)*(csgn(-imag(nxy))+1)+cut);
626         }
627         
628         return eta(x,y).hold();
629 }
630
631 static ex eta_series(const ex & x, const ex & y,
632                      const relational & rel,
633                      int order,
634                      unsigned options)
635 {
636         const ex x_pt = x.subs(rel, subs_options::no_pattern);
637         const ex y_pt = y.subs(rel, subs_options::no_pattern);
638         if ((x_pt.info(info_flags::numeric) && x_pt.info(info_flags::negative)) ||
639             (y_pt.info(info_flags::numeric) && y_pt.info(info_flags::negative)) ||
640             ((x_pt*y_pt).info(info_flags::numeric) && (x_pt*y_pt).info(info_flags::negative)))
641                         throw (std::domain_error("eta_series(): on discontinuity"));
642         epvector seq { expair(eta(x_pt,y_pt), _ex0) };
643         return pseries(rel, std::move(seq));
644 }
645
646 static ex eta_conjugate(const ex & x, const ex & y)
647 {
648         return -eta(x, y).hold();
649 }
650
651 static ex eta_real_part(const ex & x, const ex & y)
652 {
653         return 0;
654 }
655
656 static ex eta_imag_part(const ex & x, const ex & y)
657 {
658         return -I*eta(x, y).hold();
659 }
660
661 REGISTER_FUNCTION(eta, eval_func(eta_eval).
662                        evalf_func(eta_evalf).
663                        series_func(eta_series).
664                        latex_name("\\eta").
665                        set_symmetry(sy_symm(0, 1)).
666                        conjugate_func(eta_conjugate).
667                        real_part_func(eta_real_part).
668                        imag_part_func(eta_imag_part));
669
670
671 //////////
672 // dilogarithm
673 //////////
674
675 static ex Li2_evalf(const ex & x)
676 {
677         if (is_exactly_a<numeric>(x))
678                 return Li2(ex_to<numeric>(x));
679         
680         return Li2(x).hold();
681 }
682
683 static ex Li2_eval(const ex & x)
684 {
685         if (x.info(info_flags::numeric)) {
686                 // Li2(0) -> 0
687                 if (x.is_zero())
688                         return _ex0;
689                 // Li2(1) -> Pi^2/6
690                 if (x.is_equal(_ex1))
691                         return power(Pi,_ex2)/_ex6;
692                 // Li2(1/2) -> Pi^2/12 - log(2)^2/2
693                 if (x.is_equal(_ex1_2))
694                         return power(Pi,_ex2)/_ex12 + power(log(_ex2),_ex2)*_ex_1_2;
695                 // Li2(-1) -> -Pi^2/12
696                 if (x.is_equal(_ex_1))
697                         return -power(Pi,_ex2)/_ex12;
698                 // Li2(I) -> -Pi^2/48+Catalan*I
699                 if (x.is_equal(I))
700                         return power(Pi,_ex2)/_ex_48 + Catalan*I;
701                 // Li2(-I) -> -Pi^2/48-Catalan*I
702                 if (x.is_equal(-I))
703                         return power(Pi,_ex2)/_ex_48 - Catalan*I;
704                 // Li2(float)
705                 if (!x.info(info_flags::crational))
706                         return Li2(ex_to<numeric>(x));
707         }
708         
709         return Li2(x).hold();
710 }
711
712 static ex Li2_deriv(const ex & x, unsigned deriv_param)
713 {
714         GINAC_ASSERT(deriv_param==0);
715         
716         // d/dx Li2(x) -> -log(1-x)/x
717         return -log(_ex1-x)/x;
718 }
719
720 static ex Li2_series(const ex &x, const relational &rel, int order, unsigned options)
721 {
722         const ex x_pt = x.subs(rel, subs_options::no_pattern);
723         if (x_pt.info(info_flags::numeric)) {
724                 // First special case: x==0 (derivatives have poles)
725                 if (x_pt.is_zero()) {
726                         // method:
727                         // The problem is that in d/dx Li2(x==0) == -log(1-x)/x we cannot 
728                         // simply substitute x==0.  The limit, however, exists: it is 1.
729                         // We also know all higher derivatives' limits:
730                         // (d/dx)^n Li2(x) == n!/n^2.
731                         // So the primitive series expansion is
732                         // Li2(x==0) == x + x^2/4 + x^3/9 + ...
733                         // and so on.
734                         // We first construct such a primitive series expansion manually in
735                         // a dummy symbol s and then insert the argument's series expansion
736                         // for s.  Reexpanding the resulting series returns the desired
737                         // result.
738                         const symbol s;
739                         ex ser;
740                         // manually construct the primitive expansion
741                         for (int i=1; i<order; ++i)
742                                 ser += pow(s,i) / pow(numeric(i), *_num2_p);
743                         // substitute the argument's series expansion
744                         ser = ser.subs(s==x.series(rel, order), subs_options::no_pattern);
745                         // maybe that was terminating, so add a proper order term
746                         epvector nseq { expair(Order(_ex1), order) };
747                         ser += pseries(rel, std::move(nseq));
748                         // reexpanding it will collapse the series again
749                         return ser.series(rel, order);
750                         // NB: Of course, this still does not allow us to compute anything
751                         // like sin(Li2(x)).series(x==0,2), since then this code here is
752                         // not reached and the derivative of sin(Li2(x)) doesn't allow the
753                         // substitution x==0.  Probably limits *are* needed for the general
754                         // cases.  In case L'Hospital's rule is implemented for limits and
755                         // basic::series() takes care of this, this whole block is probably
756                         // obsolete!
757                 }
758                 // second special case: x==1 (branch point)
759                 if (x_pt.is_equal(_ex1)) {
760                         // method:
761                         // construct series manually in a dummy symbol s
762                         const symbol s;
763                         ex ser = zeta(_ex2);
764                         // manually construct the primitive expansion
765                         for (int i=1; i<order; ++i)
766                                 ser += pow(1-s,i) * (numeric(1,i)*(I*Pi+log(s-1)) - numeric(1,i*i));
767                         // substitute the argument's series expansion
768                         ser = ser.subs(s==x.series(rel, order), subs_options::no_pattern);
769                         // maybe that was terminating, so add a proper order term
770                         epvector nseq { expair(Order(_ex1), order) };
771                         ser += pseries(rel, std::move(nseq));
772                         // reexpanding it will collapse the series again
773                         return ser.series(rel, order);
774                 }
775                 // third special case: x real, >=1 (branch cut)
776                 if (!(options & series_options::suppress_branchcut) &&
777                         ex_to<numeric>(x_pt).is_real() && ex_to<numeric>(x_pt)>1) {
778                         // method:
779                         // This is the branch cut: assemble the primitive series manually
780                         // and then add the corresponding complex step function.
781                         const symbol &s = ex_to<symbol>(rel.lhs());
782                         const ex point = rel.rhs();
783                         const symbol foo;
784                         epvector seq;
785                         // zeroth order term:
786                         seq.push_back(expair(Li2(x_pt), _ex0));
787                         // compute the intermediate terms:
788                         ex replarg = series(Li2(x), s==foo, order);
789                         for (size_t i=1; i<replarg.nops()-1; ++i)
790                                 seq.push_back(expair((replarg.op(i)/power(s-foo,i)).series(foo==point,1,options).op(0).subs(foo==s, subs_options::no_pattern),i));
791                         // append an order term:
792                         seq.push_back(expair(Order(_ex1), replarg.nops()-1));
793                         return pseries(rel, std::move(seq));
794                 }
795         }
796         // all other cases should be safe, by now:
797         throw do_taylor();  // caught by function::series()
798 }
799
800 static ex Li2_conjugate(const ex & x)
801 {
802         // conjugate(Li2(x))==Li2(conjugate(x)) unless on the branch cuts which
803         // run along the positive real axis beginning at 1.
804         if (x.info(info_flags::negative)) {
805                 return Li2(x).hold();
806         }
807         if (is_exactly_a<numeric>(x) &&
808             (!x.imag_part().is_zero() || x < *_num1_p)) {
809                 return Li2(x.conjugate());
810         }
811         return conjugate_function(Li2(x)).hold();
812 }
813
814 REGISTER_FUNCTION(Li2, eval_func(Li2_eval).
815                        evalf_func(Li2_evalf).
816                        derivative_func(Li2_deriv).
817                        series_func(Li2_series).
818                        conjugate_func(Li2_conjugate).
819                        latex_name("\\mathrm{Li}_2"));
820
821 //////////
822 // trilogarithm
823 //////////
824
825 static ex Li3_eval(const ex & x)
826 {
827         if (x.is_zero())
828                 return x;
829         return Li3(x).hold();
830 }
831
832 REGISTER_FUNCTION(Li3, eval_func(Li3_eval).
833                        latex_name("\\mathrm{Li}_3"));
834
835 //////////
836 // Derivatives of Riemann's Zeta-function  zetaderiv(0,x)==zeta(x)
837 //////////
838
839 static ex zetaderiv_eval(const ex & n, const ex & x)
840 {
841         if (n.info(info_flags::numeric)) {
842                 // zetaderiv(0,x) -> zeta(x)
843                 if (n.is_zero())
844                         return zeta(x).hold();
845         }
846         
847         return zetaderiv(n, x).hold();
848 }
849
850 static ex zetaderiv_deriv(const ex & n, const ex & x, unsigned deriv_param)
851 {
852         GINAC_ASSERT(deriv_param<2);
853         
854         if (deriv_param==0) {
855                 // d/dn zeta(n,x)
856                 throw(std::logic_error("cannot diff zetaderiv(n,x) with respect to n"));
857         }
858         // d/dx psi(n,x)
859         return zetaderiv(n+1,x);
860 }
861
862 REGISTER_FUNCTION(zetaderiv, eval_func(zetaderiv_eval).
863                                  derivative_func(zetaderiv_deriv).
864                                  latex_name("\\zeta^\\prime"));
865
866 //////////
867 // factorial
868 //////////
869
870 static ex factorial_evalf(const ex & x)
871 {
872         return factorial(x).hold();
873 }
874
875 static ex factorial_eval(const ex & x)
876 {
877         if (is_exactly_a<numeric>(x))
878                 return factorial(ex_to<numeric>(x));
879         else
880                 return factorial(x).hold();
881 }
882
883 static void factorial_print_dflt_latex(const ex & x, const print_context & c)
884 {
885         if (is_exactly_a<symbol>(x) ||
886             is_exactly_a<constant>(x) ||
887                 is_exactly_a<function>(x)) {
888                 x.print(c); c.s << "!";
889         } else {
890                 c.s << "("; x.print(c); c.s << ")!";
891         }
892 }
893
894 static ex factorial_conjugate(const ex & x)
895 {
896         return factorial(x).hold();
897 }
898
899 static ex factorial_real_part(const ex & x)
900 {
901         return factorial(x).hold();
902 }
903
904 static ex factorial_imag_part(const ex & x)
905 {
906         return 0;
907 }
908
909 REGISTER_FUNCTION(factorial, eval_func(factorial_eval).
910                              evalf_func(factorial_evalf).
911                              print_func<print_dflt>(factorial_print_dflt_latex).
912                              print_func<print_latex>(factorial_print_dflt_latex).
913                              conjugate_func(factorial_conjugate).
914                              real_part_func(factorial_real_part).
915                              imag_part_func(factorial_imag_part));
916
917 //////////
918 // binomial
919 //////////
920
921 static ex binomial_evalf(const ex & x, const ex & y)
922 {
923         return binomial(x, y).hold();
924 }
925
926 static ex binomial_sym(const ex & x, const numeric & y)
927 {
928         if (y.is_integer()) {
929                 if (y.is_nonneg_integer()) {
930                         const unsigned N = y.to_int();
931                         if (N == 0) return _ex1;
932                         if (N == 1) return x;
933                         ex t = x.expand();
934                         for (unsigned i = 2; i <= N; ++i)
935                                 t = (t * (x + i - y - 1)).expand() / i;
936                         return t;
937                 } else
938                         return _ex0;
939         }
940
941         return binomial(x, y).hold();
942 }
943
944 static ex binomial_eval(const ex & x, const ex &y)
945 {
946         if (is_exactly_a<numeric>(y)) {
947                 if (is_exactly_a<numeric>(x) && ex_to<numeric>(x).is_integer())
948                         return binomial(ex_to<numeric>(x), ex_to<numeric>(y));
949                 else
950                         return binomial_sym(x, ex_to<numeric>(y));
951         } else
952                 return binomial(x, y).hold();
953 }
954
955 // At the moment the numeric evaluation of a binomial function always
956 // gives a real number, but if this would be implemented using the gamma
957 // function, also complex conjugation should be changed (or rather, deleted).
958 static ex binomial_conjugate(const ex & x, const ex & y)
959 {
960         return binomial(x,y).hold();
961 }
962
963 static ex binomial_real_part(const ex & x, const ex & y)
964 {
965         return binomial(x,y).hold();
966 }
967
968 static ex binomial_imag_part(const ex & x, const ex & y)
969 {
970         return 0;
971 }
972
973 REGISTER_FUNCTION(binomial, eval_func(binomial_eval).
974                             evalf_func(binomial_evalf).
975                             conjugate_func(binomial_conjugate).
976                             real_part_func(binomial_real_part).
977                             imag_part_func(binomial_imag_part));
978
979 //////////
980 // Order term function (for truncated power series)
981 //////////
982
983 static ex Order_eval(const ex & x)
984 {
985         if (is_exactly_a<numeric>(x)) {
986                 // O(c) -> O(1) or 0
987                 if (!x.is_zero())
988                         return Order(_ex1).hold();
989                 else
990                         return _ex0;
991         } else if (is_exactly_a<mul>(x)) {
992                 const mul &m = ex_to<mul>(x);
993                 // O(c*expr) -> O(expr)
994                 if (is_exactly_a<numeric>(m.op(m.nops() - 1)))
995                         return Order(x / m.op(m.nops() - 1)).hold();
996         }
997         return Order(x).hold();
998 }
999
1000 static ex Order_series(const ex & x, const relational & r, int order, unsigned options)
1001 {
1002         // Just wrap the function into a pseries object
1003         GINAC_ASSERT(is_a<symbol>(r.lhs()));
1004         const symbol &s = ex_to<symbol>(r.lhs());
1005         epvector new_seq { expair(Order(_ex1), numeric(std::min(x.ldegree(s), order))) };
1006         return pseries(r, std::move(new_seq));
1007 }
1008
1009 static ex Order_conjugate(const ex & x)
1010 {
1011         return Order(x).hold();
1012 }
1013
1014 static ex Order_real_part(const ex & x)
1015 {
1016         return Order(x).hold();
1017 }
1018
1019 static ex Order_imag_part(const ex & x)
1020 {
1021         if(x.info(info_flags::real))
1022                 return 0;
1023         return Order(x).hold();
1024 }
1025
1026 static ex Order_expl_derivative(const ex & arg, const symbol & s)
1027 {
1028         return Order(arg.diff(s));
1029 }
1030
1031 REGISTER_FUNCTION(Order, eval_func(Order_eval).
1032                          series_func(Order_series).
1033                          latex_name("\\mathcal{O}").
1034                          expl_derivative_func(Order_expl_derivative).
1035                          conjugate_func(Order_conjugate).
1036                          real_part_func(Order_real_part).
1037                          imag_part_func(Order_imag_part));
1038
1039 //////////
1040 // Solve linear system
1041 //////////
1042
1043 class symbolset {
1044         exset s;
1045         void insert_symbols(const ex &e)
1046         {
1047                 if (is_a<symbol>(e)) {
1048                         s.insert(e);
1049                 } else {
1050                         for (const ex &sube : e) {
1051                                 insert_symbols(sube);
1052                         }
1053                 }
1054         }
1055 public:
1056         explicit symbolset(const ex &e)
1057         {
1058                 insert_symbols(e);
1059         }
1060         bool has(const ex &e) const
1061         {
1062                 return s.find(e) != s.end();
1063         }
1064 };
1065
1066 ex lsolve(const ex &eqns, const ex &symbols, unsigned options)
1067 {
1068         // solve a system of linear equations
1069         if (eqns.info(info_flags::relation_equal)) {
1070                 if (!symbols.info(info_flags::symbol))
1071                         throw(std::invalid_argument("lsolve(): 2nd argument must be a symbol"));
1072                 const ex sol = lsolve(lst{eqns}, lst{symbols});
1073                 
1074                 GINAC_ASSERT(sol.nops()==1);
1075                 GINAC_ASSERT(is_exactly_a<relational>(sol.op(0)));
1076                 
1077                 return sol.op(0).op(1); // return rhs of first solution
1078         }
1079         
1080         // syntax checks
1081         if (!(eqns.info(info_flags::list) || eqns.info(info_flags::exprseq))) {
1082                 throw(std::invalid_argument("lsolve(): 1st argument must be a list, a sequence, or an equation"));
1083         }
1084         for (size_t i=0; i<eqns.nops(); i++) {
1085                 if (!eqns.op(i).info(info_flags::relation_equal)) {
1086                         throw(std::invalid_argument("lsolve(): 1st argument must be a list of equations"));
1087                 }
1088         }
1089         if (!(symbols.info(info_flags::list) || symbols.info(info_flags::exprseq))) {
1090                 throw(std::invalid_argument("lsolve(): 2nd argument must be a list, a sequence, or a symbol"));
1091         }
1092         for (size_t i=0; i<symbols.nops(); i++) {
1093                 if (!symbols.op(i).info(info_flags::symbol)) {
1094                         throw(std::invalid_argument("lsolve(): 2nd argument must be a list or a sequence of symbols"));
1095                 }
1096         }
1097         
1098         // build matrix from equation system
1099         matrix sys(eqns.nops(),symbols.nops());
1100         matrix rhs(eqns.nops(),1);
1101         matrix vars(symbols.nops(),1);
1102         
1103         for (size_t r=0; r<eqns.nops(); r++) {
1104                 const ex eq = eqns.op(r).op(0)-eqns.op(r).op(1); // lhs-rhs==0
1105                 const symbolset syms(eq);
1106                 ex linpart = eq;
1107                 for (size_t c=0; c<symbols.nops(); c++) {
1108                         if (!syms.has(symbols.op(c)))
1109                                 continue;
1110                         const ex co = eq.coeff(ex_to<symbol>(symbols.op(c)),1);
1111                         linpart -= co*symbols.op(c);
1112                         sys(r,c) = co;
1113                 }
1114                 linpart = linpart.expand();
1115                 rhs(r,0) = -linpart;
1116         }
1117         
1118         // test if system is linear and fill vars matrix
1119         const symbolset sys_syms(sys);
1120         const symbolset rhs_syms(rhs);
1121         for (size_t i=0; i<symbols.nops(); i++) {
1122                 vars(i,0) = symbols.op(i);
1123                 if (sys_syms.has(symbols.op(i)))
1124                         throw(std::logic_error("lsolve: system is not linear"));
1125                 if (rhs_syms.has(symbols.op(i)))
1126                         throw(std::logic_error("lsolve: system is not linear"));
1127         }
1128         
1129         matrix solution;
1130         try {
1131                 solution = sys.solve(vars,rhs,options);
1132         } catch (const std::runtime_error & e) {
1133                 // Probably singular matrix or otherwise overdetermined system:
1134                 // It is consistent to return an empty list
1135                 return lst{};
1136         }
1137         GINAC_ASSERT(solution.cols()==1);
1138         GINAC_ASSERT(solution.rows()==symbols.nops());
1139         
1140         // return list of equations of the form lst{var1==sol1,var2==sol2,...}
1141         lst sollist;
1142         for (size_t i=0; i<symbols.nops(); i++)
1143                 sollist.append(symbols.op(i)==solution(i,0));
1144         
1145         return sollist;
1146 }
1147
1148 //////////
1149 // Find real root of f(x) numerically
1150 //////////
1151
1152 const numeric
1153 fsolve(const ex& f_in, const symbol& x, const numeric& x1, const numeric& x2)
1154 {
1155         if (!x1.is_real() || !x2.is_real()) {
1156                 throw std::runtime_error("fsolve(): interval not bounded by real numbers");
1157         }
1158         if (x1==x2) {
1159                 throw std::runtime_error("fsolve(): vanishing interval");
1160         }
1161         // xx[0] == left interval limit, xx[1] == right interval limit.
1162         // fx[0] == f(xx[0]), fx[1] == f(xx[1]).
1163         // We keep the root bracketed: xx[0]<xx[1] and fx[0]*fx[1]<0.
1164         numeric xx[2] = { x1<x2 ? x1 : x2,
1165                           x1<x2 ? x2 : x1 };
1166         ex f;
1167         if (is_a<relational>(f_in)) {
1168                 f = f_in.lhs()-f_in.rhs();
1169         } else {
1170                 f = f_in;
1171         }
1172         const ex fx_[2] = { f.subs(x==xx[0]).evalf(),
1173                             f.subs(x==xx[1]).evalf() };
1174         if (!is_a<numeric>(fx_[0]) || !is_a<numeric>(fx_[1])) {
1175                 throw std::runtime_error("fsolve(): function does not evaluate numerically");
1176         }
1177         numeric fx[2] = { ex_to<numeric>(fx_[0]),
1178                           ex_to<numeric>(fx_[1]) };
1179         if (!fx[0].is_real() || !fx[1].is_real()) {
1180                 throw std::runtime_error("fsolve(): function evaluates to complex values at interval boundaries");
1181         }
1182         if (fx[0]*fx[1]>=0) {
1183                 throw std::runtime_error("fsolve(): function does not change sign at interval boundaries");
1184         }
1185
1186         // The Newton-Raphson method has quadratic convergence!  Simply put, it
1187         // replaces x with x-f(x)/f'(x) at each step.  -f/f' is the delta:
1188         const ex ff = normal(-f/f.diff(x));
1189         int side = 0;  // Start at left interval limit.
1190         numeric xxprev;
1191         numeric fxprev;
1192         do {
1193                 xxprev = xx[side];
1194                 fxprev = fx[side];
1195                 ex dx_ = ff.subs(x == xx[side]).evalf();
1196                 if (!is_a<numeric>(dx_))
1197                         throw std::runtime_error("fsolve(): function derivative does not evaluate numerically");
1198                 xx[side] += ex_to<numeric>(dx_);
1199                 // Now check if Newton-Raphson method shot out of the interval 
1200                 bool bad_shot = (side == 0 && xx[0] < xxprev) || 
1201                                 (side == 1 && xx[1] > xxprev) || xx[0] > xx[1];
1202                 if (!bad_shot) {
1203                         // Compute f(x) only if new x is inside the interval.
1204                         // The function might be difficult to compute numerically
1205                         // or even ill defined outside the interval. Also it's
1206                         // a small optimization. 
1207                         ex f_x = f.subs(x == xx[side]).evalf();
1208                         if (!is_a<numeric>(f_x))
1209                                 throw std::runtime_error("fsolve(): function does not evaluate numerically");
1210                         fx[side] = ex_to<numeric>(f_x);
1211                 }
1212                 if (bad_shot) {
1213                         // Oops, Newton-Raphson method shot out of the interval.
1214                         // Restore, and try again with the other side instead!
1215                         xx[side] = xxprev;
1216                         fx[side] = fxprev;
1217                         side = !side;
1218                         xxprev = xx[side];
1219                         fxprev = fx[side];
1220
1221                         ex dx_ = ff.subs(x == xx[side]).evalf();
1222                         if (!is_a<numeric>(dx_))
1223                                 throw std::runtime_error("fsolve(): function derivative does not evaluate numerically [2]");
1224                         xx[side] += ex_to<numeric>(dx_);
1225
1226                         ex f_x = f.subs(x==xx[side]).evalf();
1227                         if (!is_a<numeric>(f_x))
1228                                 throw std::runtime_error("fsolve(): function does not evaluate numerically [2]");
1229                         fx[side] = ex_to<numeric>(f_x);
1230                 }
1231                 if ((fx[side]<0 && fx[!side]<0) || (fx[side]>0 && fx[!side]>0)) {
1232                         // Oops, the root isn't bracketed any more.
1233                         // Restore, and perform a bisection!
1234                         xx[side] = xxprev;
1235                         fx[side] = fxprev;
1236
1237                         // Ah, the bisection! Bisections converge linearly. Unfortunately,
1238                         // they occur pretty often when Newton-Raphson arrives at an x too
1239                         // close to the result on one side of the interval and
1240                         // f(x-f(x)/f'(x)) turns out to have the same sign as f(x) due to
1241                         // precision errors! Recall that this function does not have a
1242                         // precision goal as one of its arguments but instead relies on
1243                         // x converging to a fixed point. We speed up the (safe but slow)
1244                         // bisection method by mixing in a dash of the (unsafer but faster)
1245                         // secant method: Instead of splitting the interval at the
1246                         // arithmetic mean (bisection), we split it nearer to the root as
1247                         // determined by the secant between the values xx[0] and xx[1].
1248                         // Don't set the secant_weight to one because that could disturb
1249                         // the convergence in some corner cases!
1250                         constexpr double secant_weight = 0.984375;  // == 63/64 < 1
1251                         numeric xxmid = (1-secant_weight)*0.5*(xx[0]+xx[1])
1252                             + secant_weight*(xx[0]+fx[0]*(xx[0]-xx[1])/(fx[1]-fx[0]));
1253                         ex fxmid_ = f.subs(x == xxmid).evalf();
1254                         if (!is_a<numeric>(fxmid_))
1255                                 throw std::runtime_error("fsolve(): function does not evaluate numerically [3]");
1256                         numeric fxmid = ex_to<numeric>(fxmid_);
1257                         if (fxmid.is_zero()) {
1258                                 // Luck strikes...
1259                                 return xxmid;
1260                         }
1261                         if ((fxmid<0 && fx[side]>0) || (fxmid>0 && fx[side]<0)) {
1262                                 side = !side;
1263                         }
1264                         xxprev = xx[side];
1265                         fxprev = fx[side];
1266                         xx[side] = xxmid;
1267                         fx[side] = fxmid;
1268                 }
1269         } while (xxprev!=xx[side]);
1270         return xxprev;
1271 }
1272
1273
1274 /* Force inclusion of functions from inifcns_gamma and inifcns_zeta
1275  * for static lib (so ginsh will see them). */
1276 unsigned force_include_tgamma = tgamma_SERIAL::serial;
1277 unsigned force_include_zeta1 = zeta1_SERIAL::serial;
1278
1279 } // namespace GiNaC