]> www.ginac.de Git - ginac.git/blob - ginac/inifcns_nstdsums.cpp
Added series expansion for functions (classical) Li and S around x==0.
[ginac.git] / ginac / inifcns_nstdsums.cpp
1 /** @file inifcns_nstdsums.cpp
2  *
3  *  Implementation of some special functions that have a representation as nested sums.
4  *
5  *  The functions are:
6  *    classical polylogarithm              Li(n,x)
7  *    multiple polylogarithm               Li(lst(m_1,...,m_k),lst(x_1,...,x_k))
8  *                                         G(lst(a_1,...,a_k),y) or G(lst(a_1,...,a_k),lst(s_1,...,s_k),y)
9  *    Nielsen's generalized polylogarithm  S(n,p,x)
10  *    harmonic polylogarithm               H(m,x) or H(lst(m_1,...,m_k),x)
11  *    multiple zeta value                  zeta(m) or zeta(lst(m_1,...,m_k))
12  *    alternating Euler sum                zeta(m,s) or zeta(lst(m_1,...,m_k),lst(s_1,...,s_k))
13  *
14  *  Some remarks:
15  *
16  *    - All formulae used can be looked up in the following publications:
17  *      [Kol] Nielsen's Generalized Polylogarithms, K.S.Kolbig, SIAM J.Math.Anal. 17 (1986), pp. 1232-1258.
18  *      [Cra] Fast Evaluation of Multiple Zeta Sums, R.E.Crandall, Math.Comp. 67 (1998), pp. 1163-1172.
19  *      [ReV] Harmonic Polylogarithms, E.Remiddi, J.A.M.Vermaseren, Int.J.Mod.Phys. A15 (2000), pp. 725-754
20  *      [BBB] Special Values of Multiple Polylogarithms, J.Borwein, D.Bradley, D.Broadhurst, P.Lisonek, Trans.Amer.Math.Soc. 353/3 (2001), pp. 907-941
21  *      [VSW] Numerical evaluation of multiple polylogarithms, J.Vollinga, S.Weinzierl, hep-ph/0410259
22  *
23  *    - The order of parameters and arguments of Li and zeta is defined according to the nested sums
24  *      representation. The parameters for H are understood as in [ReV]. They can be in expanded --- only
25  *      0, 1 and -1 --- or in compactified --- a string with zeros in front of 1 or -1 is written as a single
26  *      number --- notation.
27  *
28  *    - All functions can be nummerically evaluated with arguments in the whole complex plane. The parameters
29  *      for Li, zeta and S must be positive integers. If you want to have an alternating Euler sum, you have
30  *      to give the signs of the parameters as a second argument s to zeta(m,s) containing 1 and -1.
31  *
32  *    - The calculation of classical polylogarithms is speeded up by using Bernoulli numbers and 
33  *      look-up tables. S uses look-up tables as well. The zeta function applies the algorithms in
34  *      [Cra] and [BBB] for speed up. Multiple polylogarithms use Hoelder convolution [BBB].
35  *
36  *    - The functions have no means to do a series expansion into nested sums. To do this, you have to convert
37  *      these functions into the appropriate objects from the nestedsums library, do the expansion and convert
38  *      the result back.
39  *
40  *    - Numerical testing of this implementation has been performed by doing a comparison of results
41  *      between this software and the commercial M.......... 4.1. Multiple zeta values have been checked
42  *      by means of evaluations into simple zeta values. Harmonic polylogarithms have been checked by
43  *      comparison to S(n,p,x) for corresponding parameter combinations and by continuity checks
44  *      around |x|=1 along with comparisons to corresponding zeta functions. Multiple polylogarithms were
45  *      checked against H and zeta and by means of shuffle and quasi-shuffle relations.
46  *
47  */
48
49 /*
50  *  GiNaC Copyright (C) 1999-2005 Johannes Gutenberg University Mainz, Germany
51  *
52  *  This program is free software; you can redistribute it and/or modify
53  *  it under the terms of the GNU General Public License as published by
54  *  the Free Software Foundation; either version 2 of the License, or
55  *  (at your option) any later version.
56  *
57  *  This program is distributed in the hope that it will be useful,
58  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
59  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
60  *  GNU General Public License for more details.
61  *
62  *  You should have received a copy of the GNU General Public License
63  *  along with this program; if not, write to the Free Software
64  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
65  */
66
67 #include <sstream>
68 #include <stdexcept>
69 #include <vector>
70 #include <cln/cln.h>
71
72 #include "inifcns.h"
73
74 #include "add.h"
75 #include "constant.h"
76 #include "lst.h"
77 #include "mul.h"
78 #include "numeric.h"
79 #include "operators.h"
80 #include "power.h"
81 #include "pseries.h"
82 #include "relational.h"
83 #include "symbol.h"
84 #include "utils.h"
85 #include "wildcard.h"
86
87
88 namespace GiNaC {
89
90
91 //////////////////////////////////////////////////////////////////////
92 //
93 // Classical polylogarithm  Li(n,x)
94 //
95 // helper functions
96 //
97 //////////////////////////////////////////////////////////////////////
98
99
100 // anonymous namespace for helper functions
101 namespace {
102
103
104 // lookup table for factors built from Bernoulli numbers
105 // see fill_Xn()
106 std::vector<std::vector<cln::cl_N> > Xn;
107 // initial size of Xn that should suffice for 32bit machines (must be even)
108 const int xninitsizestep = 26;
109 int xninitsize = xninitsizestep;
110 int xnsize = 0;
111
112
113 // This function calculates the X_n. The X_n are needed for speed up of classical polylogarithms.
114 // With these numbers the polylogs can be calculated as follows:
115 //   Li_p (x)  =  \sum_{n=0}^\infty X_{p-2}(n) u^{n+1}/(n+1)! with  u = -log(1-x)
116 //   X_0(n) = B_n (Bernoulli numbers)
117 //   X_p(n) = \sum_{k=0}^n binomial(n,k) B_{n-k} / (k+1) * X_{p-1}(k)
118 // The calculation of Xn depends on X0 and X{n-1}.
119 // X_0 is special, it holds only the non-zero Bernoulli numbers with index 2 or greater.
120 // This results in a slightly more complicated algorithm for the X_n.
121 // The first index in Xn corresponds to the index of the polylog minus 2.
122 // The second index in Xn corresponds to the index from the actual sum.
123 void fill_Xn(int n)
124 {
125         if (n>1) {
126                 // calculate X_2 and higher (corresponding to Li_4 and higher)
127                 std::vector<cln::cl_N> buf(xninitsize);
128                 std::vector<cln::cl_N>::iterator it = buf.begin();
129                 cln::cl_N result;
130                 *it = -(cln::expt(cln::cl_I(2),n+1) - 1) / cln::expt(cln::cl_I(2),n+1); // i == 1
131                 it++;
132                 for (int i=2; i<=xninitsize; i++) {
133                         if (i&1) {
134                                 result = 0; // k == 0
135                         } else {
136                                 result = Xn[0][i/2-1]; // k == 0
137                         }
138                         for (int k=1; k<i-1; k++) {
139                                 if ( !(((i-k) & 1) && ((i-k) > 1)) ) {
140                                         result = result + cln::binomial(i,k) * Xn[0][(i-k)/2-1] * Xn[n-1][k-1] / (k+1);
141                                 }
142                         }
143                         result = result - cln::binomial(i,i-1) * Xn[n-1][i-2] / 2 / i; // k == i-1
144                         result = result + Xn[n-1][i-1] / (i+1); // k == i
145                         
146                         *it = result;
147                         it++;
148                 }
149                 Xn.push_back(buf);
150         } else if (n==1) {
151                 // special case to handle the X_0 correct
152                 std::vector<cln::cl_N> buf(xninitsize);
153                 std::vector<cln::cl_N>::iterator it = buf.begin();
154                 cln::cl_N result;
155                 *it = cln::cl_I(-3)/cln::cl_I(4); // i == 1
156                 it++;
157                 *it = cln::cl_I(17)/cln::cl_I(36); // i == 2
158                 it++;
159                 for (int i=3; i<=xninitsize; i++) {
160                         if (i & 1) {
161                                 result = -Xn[0][(i-3)/2]/2;
162                                 *it = (cln::binomial(i,1)/cln::cl_I(2) + cln::binomial(i,i-1)/cln::cl_I(i))*result;
163                                 it++;
164                         } else {
165                                 result = Xn[0][i/2-1] + Xn[0][i/2-1]/(i+1);
166                                 for (int k=1; k<i/2; k++) {
167                                         result = result + cln::binomial(i,k*2) * Xn[0][k-1] * Xn[0][i/2-k-1] / (k*2+1);
168                                 }
169                                 *it = result;
170                                 it++;
171                         }
172                 }
173                 Xn.push_back(buf);
174         } else {
175                 // calculate X_0
176                 std::vector<cln::cl_N> buf(xninitsize/2);
177                 std::vector<cln::cl_N>::iterator it = buf.begin();
178                 for (int i=1; i<=xninitsize/2; i++) {
179                         *it = bernoulli(i*2).to_cl_N();
180                         it++;
181                 }
182                 Xn.push_back(buf);
183         }
184
185         xnsize++;
186 }
187
188 // doubles the number of entries in each Xn[]
189 void double_Xn()
190 {
191         const int pos0 = xninitsize / 2;
192         // X_0
193         for (int i=1; i<=xninitsizestep/2; ++i) {
194                 Xn[0].push_back(bernoulli((i+pos0)*2).to_cl_N());
195         }
196         if (Xn.size() > 1) {
197                 int xend = xninitsize + xninitsizestep;
198                 cln::cl_N result;
199                 // X_1
200                 for (int i=xninitsize+1; i<=xend; ++i) {
201                         if (i & 1) {
202                                 result = -Xn[0][(i-3)/2]/2;
203                                 Xn[1].push_back((cln::binomial(i,1)/cln::cl_I(2) + cln::binomial(i,i-1)/cln::cl_I(i))*result);
204                         } else {
205                                 result = Xn[0][i/2-1] + Xn[0][i/2-1]/(i+1);
206                                 for (int k=1; k<i/2; k++) {
207                                         result = result + cln::binomial(i,k*2) * Xn[0][k-1] * Xn[0][i/2-k-1] / (k*2+1);
208                                 }
209                                 Xn[1].push_back(result);
210                         }
211                 }
212                 // X_n
213                 for (int n=2; n<Xn.size(); ++n) {
214                         for (int i=xninitsize+1; i<=xend; ++i) {
215                                 if (i & 1) {
216                                         result = 0; // k == 0
217                                 } else {
218                                         result = Xn[0][i/2-1]; // k == 0
219                                 }
220                                 for (int k=1; k<i-1; ++k) {
221                                         if ( !(((i-k) & 1) && ((i-k) > 1)) ) {
222                                                 result = result + cln::binomial(i,k) * Xn[0][(i-k)/2-1] * Xn[n-1][k-1] / (k+1);
223                                         }
224                                 }
225                                 result = result - cln::binomial(i,i-1) * Xn[n-1][i-2] / 2 / i; // k == i-1
226                                 result = result + Xn[n-1][i-1] / (i+1); // k == i
227                                 Xn[n].push_back(result);
228                         }
229                 }
230         }
231         xninitsize += xninitsizestep;
232 }
233
234
235 // calculates Li(2,x) without Xn
236 cln::cl_N Li2_do_sum(const cln::cl_N& x)
237 {
238         cln::cl_N res = x;
239         cln::cl_N resbuf;
240         cln::cl_N num = x * cln::cl_float(1, cln::float_format(Digits));
241         cln::cl_I den = 1; // n^2 = 1
242         unsigned i = 3;
243         do {
244                 resbuf = res;
245                 num = num * x;
246                 den = den + i;  // n^2 = 4, 9, 16, ...
247                 i += 2;
248                 res = res + num / den;
249         } while (res != resbuf);
250         return res;
251 }
252
253
254 // calculates Li(2,x) with Xn
255 cln::cl_N Li2_do_sum_Xn(const cln::cl_N& x)
256 {
257         std::vector<cln::cl_N>::const_iterator it = Xn[0].begin();
258         std::vector<cln::cl_N>::const_iterator xend = Xn[0].end();
259         cln::cl_N u = -cln::log(1-x);
260         cln::cl_N factor = u * cln::cl_float(1, cln::float_format(Digits));
261         cln::cl_N uu = cln::square(u);
262         cln::cl_N res = u - uu/4;
263         cln::cl_N resbuf;
264         unsigned i = 1;
265         do {
266                 resbuf = res;
267                 factor = factor * uu / (2*i * (2*i+1));
268                 res = res + (*it) * factor;
269                 i++;
270                 if (++it == xend) {
271                         double_Xn();
272                         it = Xn[0].begin() + (i-1);
273                         xend = Xn[0].end();
274                 }
275         } while (res != resbuf);
276         return res;
277 }
278
279
280 // calculates Li(n,x), n>2 without Xn
281 cln::cl_N Lin_do_sum(int n, const cln::cl_N& x)
282 {
283         cln::cl_N factor = x * cln::cl_float(1, cln::float_format(Digits));
284         cln::cl_N res = x;
285         cln::cl_N resbuf;
286         int i=2;
287         do {
288                 resbuf = res;
289                 factor = factor * x;
290                 res = res + factor / cln::expt(cln::cl_I(i),n);
291                 i++;
292         } while (res != resbuf);
293         return res;
294 }
295
296
297 // calculates Li(n,x), n>2 with Xn
298 cln::cl_N Lin_do_sum_Xn(int n, const cln::cl_N& x)
299 {
300         std::vector<cln::cl_N>::const_iterator it = Xn[n-2].begin();
301         std::vector<cln::cl_N>::const_iterator xend = Xn[n-2].end();
302         cln::cl_N u = -cln::log(1-x);
303         cln::cl_N factor = u * cln::cl_float(1, cln::float_format(Digits));
304         cln::cl_N res = u;
305         cln::cl_N resbuf;
306         unsigned i=2;
307         do {
308                 resbuf = res;
309                 factor = factor * u / i;
310                 res = res + (*it) * factor;
311                 i++;
312                 if (++it == xend) {
313                         double_Xn();
314                         it = Xn[n-2].begin() + (i-2);
315                         xend = Xn[n-2].end();
316                 }
317         } while (res != resbuf);
318         return res;
319 }
320
321
322 // forward declaration needed by function Li_projection and C below
323 numeric S_num(int n, int p, const numeric& x);
324
325
326 // helper function for classical polylog Li
327 cln::cl_N Li_projection(int n, const cln::cl_N& x, const cln::float_format_t& prec)
328 {
329         // treat n=2 as special case
330         if (n == 2) {
331                 // check if precalculated X0 exists
332                 if (xnsize == 0) {
333                         fill_Xn(0);
334                 }
335
336                 if (cln::realpart(x) < 0.5) {
337                         // choose the faster algorithm
338                         // the switching point was empirically determined. the optimal point
339                         // depends on hardware, Digits, ... so an approx value is okay.
340                         // it solves also the problem with precision due to the u=-log(1-x) transformation
341                         if (cln::abs(cln::realpart(x)) < 0.25) {
342                                 
343                                 return Li2_do_sum(x);
344                         } else {
345                                 return Li2_do_sum_Xn(x);
346                         }
347                 } else {
348                         // choose the faster algorithm
349                         if (cln::abs(cln::realpart(x)) > 0.75) {
350                                 return -Li2_do_sum(1-x) - cln::log(x) * cln::log(1-x) + cln::zeta(2);
351                         } else {
352                                 return -Li2_do_sum_Xn(1-x) - cln::log(x) * cln::log(1-x) + cln::zeta(2);
353                         }
354                 }
355         } else {
356                 // check if precalculated Xn exist
357                 if (n > xnsize+1) {
358                         for (int i=xnsize; i<n-1; i++) {
359                                 fill_Xn(i);
360                         }
361                 }
362
363                 if (cln::realpart(x) < 0.5) {
364                         // choose the faster algorithm
365                         // with n>=12 the "normal" summation always wins against the method with Xn
366                         if ((cln::abs(cln::realpart(x)) < 0.3) || (n >= 12)) {
367                                 return Lin_do_sum(n, x);
368                         } else {
369                                 return Lin_do_sum_Xn(n, x);
370                         }
371                 } else {
372                         cln::cl_N result = -cln::expt(cln::log(x), n-1) * cln::log(1-x) / cln::factorial(n-1);
373                         for (int j=0; j<n-1; j++) {
374                                 result = result + (S_num(n-j-1, 1, 1).to_cl_N() - S_num(1, n-j-1, 1-x).to_cl_N())
375                                                   * cln::expt(cln::log(x), j) / cln::factorial(j);
376                         }
377                         return result;
378                 }
379         }
380 }
381
382
383 // helper function for classical polylog Li
384 numeric Lin_numeric(int n, const numeric& x)
385 {
386         if (n == 1) {
387                 // just a log
388                 return -cln::log(1-x.to_cl_N());
389         }
390         if (x.is_zero()) {
391                 return 0;
392         }
393         if (x == 1) {
394                 // [Kol] (2.22)
395                 return cln::zeta(n);
396         }
397         else if (x == -1) {
398                 // [Kol] (2.22)
399                 return -(1-cln::expt(cln::cl_I(2),1-n)) * cln::zeta(n);
400         }
401         if (abs(x.real()) < 0.4 && abs(abs(x)-1) < 0.01) {
402                 cln::cl_N x_ = ex_to<numeric>(x).to_cl_N();
403                 cln::cl_N result = -cln::expt(cln::log(x_), n-1) * cln::log(1-x_) / cln::factorial(n-1);
404                 for (int j=0; j<n-1; j++) {
405                         result = result + (S_num(n-j-1, 1, 1).to_cl_N() - S_num(1, n-j-1, 1-x_).to_cl_N())
406                                 * cln::expt(cln::log(x_), j) / cln::factorial(j);
407                 }
408                 return result;
409         }
410
411         // what is the desired float format?
412         // first guess: default format
413         cln::float_format_t prec = cln::default_float_format;
414         const cln::cl_N value = x.to_cl_N();
415         // second guess: the argument's format
416         if (!x.real().is_rational())
417                 prec = cln::float_format(cln::the<cln::cl_F>(cln::realpart(value)));
418         else if (!x.imag().is_rational())
419                 prec = cln::float_format(cln::the<cln::cl_F>(cln::imagpart(value)));
420         
421         // [Kol] (5.15)
422         if (cln::abs(value) > 1) {
423                 cln::cl_N result = -cln::expt(cln::log(-value),n) / cln::factorial(n);
424                 // check if argument is complex. if it is real, the new polylog has to be conjugated.
425                 if (cln::zerop(cln::imagpart(value))) {
426                         if (n & 1) {
427                                 result = result + conjugate(Li_projection(n, cln::recip(value), prec));
428                         }
429                         else {
430                                 result = result - conjugate(Li_projection(n, cln::recip(value), prec));
431                         }
432                 }
433                 else {
434                         if (n & 1) {
435                                 result = result + Li_projection(n, cln::recip(value), prec);
436                         }
437                         else {
438                                 result = result - Li_projection(n, cln::recip(value), prec);
439                         }
440                 }
441                 cln::cl_N add;
442                 for (int j=0; j<n-1; j++) {
443                         add = add + (1+cln::expt(cln::cl_I(-1),n-j)) * (1-cln::expt(cln::cl_I(2),1-n+j))
444                                     * Lin_numeric(n-j,1).to_cl_N() * cln::expt(cln::log(-value),j) / cln::factorial(j);
445                 }
446                 result = result - add;
447                 return result;
448         }
449         else {
450                 return Li_projection(n, value, prec);
451         }
452 }
453
454
455 } // end of anonymous namespace
456
457
458 //////////////////////////////////////////////////////////////////////
459 //
460 // Multiple polylogarithm  Li(n,x)
461 //
462 // helper function
463 //
464 //////////////////////////////////////////////////////////////////////
465
466
467 // anonymous namespace for helper function
468 namespace {
469
470
471 // performs the actual series summation for multiple polylogarithms
472 cln::cl_N multipleLi_do_sum(const std::vector<int>& s, const std::vector<cln::cl_N>& x)
473 {
474         const int j = s.size();
475
476         std::vector<cln::cl_N> t(j);
477         cln::cl_F one = cln::cl_float(1, cln::float_format(Digits));
478
479         cln::cl_N t0buf;
480         int q = 0;
481         do {
482                 t0buf = t[0];
483                 // do it once ...
484                 q++;
485                 t[j-1] = t[j-1] + cln::expt(x[j-1], q) / cln::expt(cln::cl_I(q),s[j-1]) * one;
486                 for (int k=j-2; k>=0; k--) {
487                         t[k] = t[k] + t[k+1] * cln::expt(x[k], q+j-1-k) / cln::expt(cln::cl_I(q+j-1-k), s[k]);
488                 }
489                 // ... and do it again (to avoid premature drop out due to special arguments)
490                 q++;
491                 t[j-1] = t[j-1] + cln::expt(x[j-1], q) / cln::expt(cln::cl_I(q),s[j-1]) * one;
492                 for (int k=j-2; k>=0; k--) {
493                         t[k] = t[k] + t[k+1] * cln::expt(x[k], q+j-1-k) / cln::expt(cln::cl_I(q+j-1-k), s[k]);
494                 }
495         } while (t[0] != t0buf);
496
497         return t[0];
498 }
499
500
501 // converts parameter types and calls multipleLi_do_sum (convenience function for G_numeric)
502 cln::cl_N mLi_do_summation(const lst& m, const lst& x)
503 {
504         std::vector<int> m_int;
505         std::vector<cln::cl_N> x_cln;
506         for (lst::const_iterator itm = m.begin(), itx = x.begin(); itm != m.end(); ++itm, ++itx) {
507                 m_int.push_back(ex_to<numeric>(*itm).to_int());
508                 x_cln.push_back(ex_to<numeric>(*itx).to_cl_N());
509         }
510         return multipleLi_do_sum(m_int, x_cln);
511 }
512
513
514 // forward declaration for Li_eval()
515 lst convert_parameter_Li_to_H(const lst& m, const lst& x, ex& pf);
516
517
518 // holding dummy-symbols for the G/Li transformations
519 std::vector<ex> gsyms;
520
521
522 // type used by the transformation functions for G
523 typedef std::vector<int> Gparameter;
524
525
526 // G_eval1-function for G transformations
527 ex G_eval1(int a, int scale)
528 {
529         if (a != 0) {
530                 const ex& scs = gsyms[std::abs(scale)];
531                 const ex& as = gsyms[std::abs(a)];
532                 if (as != scs) {
533                         return -log(1 - scs/as);
534                 } else {
535                         return -zeta(1);
536                 }
537         } else {
538                 return log(gsyms[std::abs(scale)]);
539         }
540 }
541
542
543 // G_eval-function for G transformations
544 ex G_eval(const Gparameter& a, int scale)
545 {
546         // check for properties of G
547         ex sc = gsyms[std::abs(scale)];
548         lst newa;
549         bool all_zero = true;
550         bool all_ones = true;
551         int count_ones = 0;
552         for (Gparameter::const_iterator it = a.begin(); it != a.end(); ++it) {
553                 if (*it != 0) {
554                         const ex sym = gsyms[std::abs(*it)];
555                         newa.append(sym);
556                         all_zero = false;
557                         if (sym != sc) {
558                                 all_ones = false;
559                         }
560                         if (all_ones) {
561                                 ++count_ones;
562                         }
563                 } else {
564                         all_ones = false;
565                 }
566         }
567
568         // care about divergent G: shuffle to separate divergencies that will be canceled
569         // later on in the transformation
570         if (newa.nops() > 1 && newa.op(0) == sc && !all_ones && a.front()!=0) {
571                 // do shuffle
572                 Gparameter short_a;
573                 Gparameter::const_iterator it = a.begin();
574                 ++it;
575                 for (; it != a.end(); ++it) {
576                         short_a.push_back(*it);
577                 }
578                 ex result = G_eval1(a.front(), scale) * G_eval(short_a, scale);
579                 it = short_a.begin();
580                 for (int i=1; i<count_ones; ++i) {
581                         ++it;
582                 }
583                 for (; it != short_a.end(); ++it) {
584
585                         Gparameter newa;
586                         Gparameter::const_iterator it2 = short_a.begin();
587                         for (--it2; it2 != it;) {
588                                 ++it2;
589                                 newa.push_back(*it2);
590                         }
591                         newa.push_back(a[0]);
592                         ++it2;
593                         for (; it2 != short_a.end(); ++it2) {
594                                 newa.push_back(*it2);   
595                         }
596                         result -= G_eval(newa, scale);
597                 }
598                 return result / count_ones;
599         }
600
601         // G({1,...,1};y) -> G({1};y)^k / k!
602         if (all_ones && a.size() > 1) {
603                 return pow(G_eval1(a.front(),scale), count_ones) / factorial(count_ones);
604         }
605
606         // G({0,...,0};y) -> log(y)^k / k!
607         if (all_zero) {
608                 return pow(log(gsyms[std::abs(scale)]), a.size()) / factorial(a.size());
609         }
610
611         // no special cases anymore -> convert it into Li
612         lst m;
613         lst x;
614         ex argbuf = gsyms[std::abs(scale)];
615         ex mval = _ex1;
616         for (Gparameter::const_iterator it=a.begin(); it!=a.end(); ++it) {
617                 if (*it != 0) {
618                         const ex& sym = gsyms[std::abs(*it)];
619                         x.append(argbuf / sym);
620                         m.append(mval);
621                         mval = _ex1;
622                         argbuf = sym;
623                 } else {
624                         ++mval;
625                 }
626         }
627         return pow(-1, x.nops()) * Li(m, x);
628 }
629
630
631 // converts data for G: pending_integrals -> a
632 Gparameter convert_pending_integrals_G(const Gparameter& pending_integrals)
633 {
634         GINAC_ASSERT(pending_integrals.size() != 1);
635
636         if (pending_integrals.size() > 0) {
637                 // get rid of the first element, which would stand for the new upper limit
638                 Gparameter new_a(pending_integrals.begin()+1, pending_integrals.end());
639                 return new_a;
640         } else {
641                 // just return empty parameter list
642                 Gparameter new_a;
643                 return new_a;
644         }
645 }
646
647
648 // check the parameters a and scale for G and return information about convergence, depth, etc.
649 // convergent     : true if G(a,scale) is convergent
650 // depth          : depth of G(a,scale)
651 // trailing_zeros : number of trailing zeros of a
652 // min_it         : iterator of a pointing on the smallest element in a
653 Gparameter::const_iterator check_parameter_G(const Gparameter& a, int scale,
654                 bool& convergent, int& depth, int& trailing_zeros, Gparameter::const_iterator& min_it)
655 {
656         convergent = true;
657         depth = 0;
658         trailing_zeros = 0;
659         min_it = a.end();
660         Gparameter::const_iterator lastnonzero = a.end();
661         for (Gparameter::const_iterator it = a.begin(); it != a.end(); ++it) {
662                 if (std::abs(*it) > 0) {
663                         ++depth;
664                         trailing_zeros = 0;
665                         lastnonzero = it;
666                         if (std::abs(*it) < scale) {
667                                 convergent = false;
668                                 if ((min_it == a.end()) || (std::abs(*it) < std::abs(*min_it))) {
669                                         min_it = it;
670                                 }
671                         }
672                 } else {
673                         ++trailing_zeros;
674                 }
675         }
676         return ++lastnonzero;
677 }
678
679
680 // add scale to pending_integrals if pending_integrals is empty
681 Gparameter prepare_pending_integrals(const Gparameter& pending_integrals, int scale)
682 {
683         GINAC_ASSERT(pending_integrals.size() != 1);
684
685         if (pending_integrals.size() > 0) {
686                 return pending_integrals;
687         } else {
688                 Gparameter new_pending_integrals;
689                 new_pending_integrals.push_back(scale);
690                 return new_pending_integrals;
691         }
692 }
693
694
695 // handles trailing zeroes for an otherwise convergent integral
696 ex trailing_zeros_G(const Gparameter& a, int scale)
697 {
698         bool convergent;
699         int depth, trailing_zeros;
700         Gparameter::const_iterator last, dummyit;
701         last = check_parameter_G(a, scale, convergent, depth, trailing_zeros, dummyit);
702
703         GINAC_ASSERT(convergent);
704
705         if ((trailing_zeros > 0) && (depth > 0)) {
706                 ex result;
707                 Gparameter new_a(a.begin(), a.end()-1);
708                 result += G_eval1(0, scale) * trailing_zeros_G(new_a, scale);
709                 for (Gparameter::const_iterator it = a.begin(); it != last; ++it) {
710                         Gparameter new_a(a.begin(), it);
711                         new_a.push_back(0);
712                         new_a.insert(new_a.end(), it, a.end()-1);
713                         result -= trailing_zeros_G(new_a, scale);
714                 }
715
716                 return result / trailing_zeros;
717         } else {
718                 return G_eval(a, scale);
719         }
720 }
721
722
723 // G transformation [VSW] (57),(58)
724 ex depth_one_trafo_G(const Gparameter& pending_integrals, const Gparameter& a, int scale)
725 {
726         // pendint = ( y1, b1, ..., br )
727         //       a = ( 0, ..., 0, amin )
728         //   scale = y2
729         //
730         // int_0^y1 ds1/(s1-b1) ... int dsr/(sr-br) G(0, ..., 0, sr; y2)
731         // where sr replaces amin
732
733         GINAC_ASSERT(a.back() != 0);
734         GINAC_ASSERT(a.size() > 0);
735
736         ex result;
737         Gparameter new_pending_integrals = prepare_pending_integrals(pending_integrals, std::abs(a.back()));
738         const int psize = pending_integrals.size();
739
740         // length == 1
741         // G(sr_{+-}; y2 ) = G(y2_{-+}; sr) - G(0; sr) + ln(-y2_{-+})
742
743         if (a.size() == 1) {
744
745           // ln(-y2_{-+})
746           result += log(gsyms[ex_to<numeric>(scale).to_int()]);
747                 if (a.back() > 0) {
748                         new_pending_integrals.push_back(-scale);
749                         result += I*Pi;
750                 } else {
751                         new_pending_integrals.push_back(scale);
752                         result -= I*Pi;
753                 }
754                 if (psize) {
755                         result *= trailing_zeros_G(convert_pending_integrals_G(pending_integrals), pending_integrals.front());
756                 }
757                 
758                 // G(y2_{-+}; sr)
759                 result += trailing_zeros_G(convert_pending_integrals_G(new_pending_integrals), new_pending_integrals.front());
760                 
761                 // G(0; sr)
762                 new_pending_integrals.back() = 0;
763                 result -= trailing_zeros_G(convert_pending_integrals_G(new_pending_integrals), new_pending_integrals.front());
764
765                 return result;
766         }
767
768         // length > 1
769         // G_m(sr_{+-}; y2) = -zeta_m + int_0^y2 dt/t G_{m-1}( (1/y2)_{+-}; 1/t )
770         //                            - int_0^sr dt/t G_{m-1}( (1/y2)_{+-}; 1/t )
771
772         //term zeta_m
773         result -= zeta(a.size());
774         if (psize) {
775                 result *= trailing_zeros_G(convert_pending_integrals_G(pending_integrals), pending_integrals.front());
776         }
777         
778         // term int_0^sr dt/t G_{m-1}( (1/y2)_{+-}; 1/t )
779         //    = int_0^sr dt/t G_{m-1}( t_{+-}; y2 )
780         Gparameter new_a(a.begin()+1, a.end());
781         new_pending_integrals.push_back(0);
782         result -= depth_one_trafo_G(new_pending_integrals, new_a, scale);
783         
784         // term int_0^y2 dt/t G_{m-1}( (1/y2)_{+-}; 1/t )
785         //    = int_0^y2 dt/t G_{m-1}( t_{+-}; y2 )
786         Gparameter new_pending_integrals_2;
787         new_pending_integrals_2.push_back(scale);
788         new_pending_integrals_2.push_back(0);
789         if (psize) {
790                 result += trailing_zeros_G(convert_pending_integrals_G(pending_integrals), pending_integrals.front())
791                           * depth_one_trafo_G(new_pending_integrals_2, new_a, scale);
792         } else {
793                 result += depth_one_trafo_G(new_pending_integrals_2, new_a, scale);
794         }
795
796         return result;
797 }
798
799
800 // forward declaration
801 ex shuffle_G(const Gparameter & a0, const Gparameter & a1, const Gparameter & a2,
802              const Gparameter& pendint, const Gparameter& a_old, int scale);
803
804
805 // G transformation [VSW]
806 ex G_transform(const Gparameter& pendint, const Gparameter& a, int scale)
807 {
808         // main recursion routine
809         //
810         // pendint = ( y1, b1, ..., br )
811         //       a = ( a1, ..., amin, ..., aw )
812         //   scale = y2
813         //
814         // int_0^y1 ds1/(s1-b1) ... int dsr/(sr-br) G(a1,...,sr,...,aw,y2)
815         // where sr replaces amin
816
817         // find smallest alpha, determine depth and trailing zeros, and check for convergence
818         bool convergent;
819         int depth, trailing_zeros;
820         Gparameter::const_iterator min_it;
821         Gparameter::const_iterator firstzero = 
822                 check_parameter_G(a, scale, convergent, depth, trailing_zeros, min_it);
823         int min_it_pos = min_it - a.begin();
824
825         // special case: all a's are zero
826         if (depth == 0) {
827                 ex result;
828
829                 if (a.size() == 0) {
830                   result = 1;
831                 } else {
832                   result = G_eval(a, scale);
833                 }
834                 if (pendint.size() > 0) {
835                   result *= trailing_zeros_G(convert_pending_integrals_G(pendint), pendint.front());
836                 } 
837                 return result;
838         }
839
840         // handle trailing zeros
841         if (trailing_zeros > 0) {
842                 ex result;
843                 Gparameter new_a(a.begin(), a.end()-1);
844                 result += G_eval1(0, scale) * G_transform(pendint, new_a, scale);
845                 for (Gparameter::const_iterator it = a.begin(); it != firstzero; ++it) {
846                         Gparameter new_a(a.begin(), it);
847                         new_a.push_back(0);
848                         new_a.insert(new_a.end(), it, a.end()-1);
849                         result -= G_transform(pendint, new_a, scale);
850                 }
851                 return result / trailing_zeros;
852         }
853
854         // convergence case
855         if (convergent) {
856                 if (pendint.size() > 0) {
857                         return G_eval(convert_pending_integrals_G(pendint), pendint.front()) * G_eval(a, scale);
858                 } else {
859                         return G_eval(a, scale);
860                 }
861         }
862
863         // call basic transformation for depth equal one
864         if (depth == 1) {
865                 return depth_one_trafo_G(pendint, a, scale);
866         }
867
868         // do recursion
869         // int_0^y1 ds1/(s1-b1) ... int dsr/(sr-br) G(a1,...,sr,...,aw,y2)
870         //  =  int_0^y1 ds1/(s1-b1) ... int dsr/(sr-br) G(a1,...,0,...,aw,y2)
871         //   + int_0^y1 ds1/(s1-b1) ... int dsr/(sr-br) int_0^{sr} ds_{r+1} d/ds_{r+1} G(a1,...,s_{r+1},...,aw,y2)
872
873         // smallest element in last place
874         if (min_it + 1 == a.end()) {
875                 do { --min_it; } while (*min_it == 0);
876                 Gparameter empty;
877                 Gparameter a1(a.begin(),min_it+1);
878                 Gparameter a2(min_it+1,a.end());
879
880                 ex result = G_transform(pendint,a2,scale)*G_transform(empty,a1,scale);
881
882                 result -= shuffle_G(empty,a1,a2,pendint,a,scale);
883                 return result;
884         }
885
886         Gparameter empty;
887         Gparameter::iterator changeit;
888
889         // first term G(a_1,..,0,...,a_w;a_0)
890         Gparameter new_pendint = prepare_pending_integrals(pendint, a[min_it_pos]);
891         Gparameter new_a = a;
892         new_a[min_it_pos] = 0;
893         ex result = G_transform(empty, new_a, scale);
894         if (pendint.size() > 0) {
895                 result *= trailing_zeros_G(convert_pending_integrals_G(pendint), pendint.front());
896         }
897
898         // other terms
899         changeit = new_a.begin() + min_it_pos;
900         changeit = new_a.erase(changeit);
901         if (changeit != new_a.begin()) {
902                 // smallest in the middle
903                 new_pendint.push_back(*changeit);
904                 result -= trailing_zeros_G(convert_pending_integrals_G(new_pendint), new_pendint.front())
905                         * G_transform(empty, new_a, scale);
906                 int buffer = *changeit;
907                 *changeit = *min_it;
908                 result += G_transform(new_pendint, new_a, scale);
909                 *changeit = buffer;
910                 new_pendint.pop_back();
911                 --changeit;
912                 new_pendint.push_back(*changeit);
913                 result += trailing_zeros_G(convert_pending_integrals_G(new_pendint), new_pendint.front())
914                         * G_transform(empty, new_a, scale);
915                 *changeit = *min_it;
916                 result -= G_transform(new_pendint, new_a, scale);
917         } else {
918                 // smallest at the front
919                 new_pendint.push_back(scale);
920                 result += trailing_zeros_G(convert_pending_integrals_G(new_pendint), new_pendint.front())
921                         * G_transform(empty, new_a, scale);
922                 new_pendint.back() =  *changeit;
923                 result -= trailing_zeros_G(convert_pending_integrals_G(new_pendint), new_pendint.front())
924                         * G_transform(empty, new_a, scale);
925                 *changeit = *min_it;
926                 result += G_transform(new_pendint, new_a, scale);
927         }
928         return result;
929 }
930
931
932 // shuffles the two parameter list a1 and a2 and calls G_transform for every term except
933 // for the one that is equal to a_old
934 ex shuffle_G(const Gparameter & a0, const Gparameter & a1, const Gparameter & a2,
935              const Gparameter& pendint, const Gparameter& a_old, int scale) 
936 {
937         if (a1.size()==0 && a2.size()==0) {
938                 // veto the one configuration we don't want
939                 if ( a0 == a_old ) return 0;
940
941                 return G_transform(pendint,a0,scale);
942         }
943
944         if (a2.size()==0) {
945                 Gparameter empty;
946                 Gparameter aa0 = a0;
947                 aa0.insert(aa0.end(),a1.begin(),a1.end());
948                 return shuffle_G(aa0,empty,empty,pendint,a_old,scale);
949         }
950
951         if (a1.size()==0) {
952                 Gparameter empty;
953                 Gparameter aa0 = a0;
954                 aa0.insert(aa0.end(),a2.begin(),a2.end());
955                 return shuffle_G(aa0,empty,empty,pendint,a_old,scale);
956         }
957
958         Gparameter a1_removed(a1.begin()+1,a1.end());
959         Gparameter a2_removed(a2.begin()+1,a2.end());
960
961         Gparameter a01 = a0;
962         Gparameter a02 = a0;
963
964         a01.push_back( a1[0] );
965         a02.push_back( a2[0] );
966
967         return shuffle_G(a01,a1_removed,a2,pendint,a_old,scale)
968              + shuffle_G(a02,a1,a2_removed,pendint,a_old,scale);
969 }
970
971
972 // handles the transformations and the numerical evaluation of G
973 // the parameter x, s and y must only contain numerics
974 ex G_numeric(const lst& x, const lst& s, const ex& y)
975 {
976         // check for convergence and necessary accelerations
977         bool need_trafo = false;
978         bool need_hoelder = false;
979         int depth = 0;
980         for (lst::const_iterator it = x.begin(); it != x.end(); ++it) {
981                 if (!(*it).is_zero()) {
982                         ++depth;
983                         if (abs(*it) - y < -pow(10,-Digits+2)) {
984                                 need_trafo = true;
985                                 break;
986                         }
987                         if (abs((abs(*it) - y)/y) < 0.01) {
988                                 need_hoelder = true;
989                         }
990                 }
991         }
992         if (x.op(x.nops()-1).is_zero()) {
993                 need_trafo = true;
994         }
995         if (depth == 1 && !need_trafo) {
996                 return -Li(x.nops(), y / x.op(x.nops()-1)).evalf();
997         }
998         
999         // convergence transformation
1000         if (need_trafo) {
1001
1002                 // sort (|x|<->position) to determine indices
1003                 std::multimap<ex,int> sortmap;
1004                 int size = 0;
1005                 for (int i=0; i<x.nops(); ++i) {
1006                         if (!x[i].is_zero()) {
1007                                 sortmap.insert(std::pair<ex,int>(abs(x[i]), i));
1008                                 ++size;
1009                         }
1010                 }
1011                 // include upper limit (scale)
1012                 sortmap.insert(std::pair<ex,int>(abs(y), x.nops()));
1013
1014                 // generate missing dummy-symbols
1015                 int i = 1;
1016                 gsyms.clear();
1017                 gsyms.push_back(symbol("GSYMS_ERROR"));
1018                 ex lastentry;
1019                 for (std::multimap<ex,int>::const_iterator it = sortmap.begin(); it != sortmap.end(); ++it) {
1020                         if (it != sortmap.begin()) {
1021                                 if (it->second < x.nops()) {
1022                                         if (x[it->second] == lastentry) {
1023                                                 gsyms.push_back(gsyms.back());
1024                                                 continue;
1025                                         }
1026                                 } else {
1027                                         if (y == lastentry) {
1028                                                 gsyms.push_back(gsyms.back());
1029                                                 continue;
1030                                         }
1031                                 }
1032                         }
1033                         std::ostringstream os;
1034                         os << "a" << i;
1035                         gsyms.push_back(symbol(os.str()));
1036                         ++i;
1037                         if (it->second < x.nops()) {
1038                                 lastentry = x[it->second];
1039                         } else {
1040                                 lastentry = y;
1041                         }
1042                 }
1043
1044                 // fill position data according to sorted indices and prepare substitution list
1045                 Gparameter a(x.nops());
1046                 lst subslst;
1047                 int pos = 1;
1048                 int scale;
1049                 for (std::multimap<ex,int>::const_iterator it = sortmap.begin(); it != sortmap.end(); ++it) {
1050                         if (it->second < x.nops()) {
1051                                 if (s[it->second] > 0) {
1052                                         a[it->second] = pos;
1053                                 } else {
1054                                         a[it->second] = -pos;
1055                                 }
1056                                 subslst.append(gsyms[pos] == x[it->second]);
1057                         } else {
1058                                 scale = pos;
1059                                 subslst.append(gsyms[pos] == y);
1060                         }
1061                         ++pos;
1062                 }
1063
1064                 // do transformation
1065                 Gparameter pendint;
1066                 ex result = G_transform(pendint, a, scale);
1067                 // replace dummy symbols with their values
1068                 result = result.eval().expand();
1069                 result = result.subs(subslst).evalf();
1070                 
1071                 return result;
1072         }
1073
1074         // do acceleration transformation (hoelder convolution [BBB])
1075         if (need_hoelder) {
1076                 
1077                 ex result;
1078                 const int size = x.nops();
1079                 lst newx;
1080                 for (lst::const_iterator it = x.begin(); it != x.end(); ++it) {
1081                         newx.append(*it / y);
1082                 }
1083                 
1084                 for (int r=0; r<=size; ++r) {
1085                         ex buffer = pow(-1, r);
1086                         ex p = 2;
1087                         bool adjustp;
1088                         do {
1089                                 adjustp = false;
1090                                 for (lst::const_iterator it = newx.begin(); it != newx.end(); ++it) {
1091                                         if (*it == 1/p) {
1092                                                 p += (3-p)/2; 
1093                                                 adjustp = true;
1094                                                 continue;
1095                                         }
1096                                 }
1097                         } while (adjustp);
1098                         ex q = p / (p-1);
1099                         lst qlstx;
1100                         lst qlsts;
1101                         for (int j=r; j>=1; --j) {
1102                                 qlstx.append(1-newx.op(j-1));
1103                                 if (newx.op(j-1).info(info_flags::real) && newx.op(j-1) > 1 && newx.op(j-1) <= 2) {
1104                                         qlsts.append( s.op(j-1));
1105                                 } else {
1106                                         qlsts.append( -s.op(j-1));
1107                                 }
1108                         }
1109                         if (qlstx.nops() > 0) {
1110                                 buffer *= G_numeric(qlstx, qlsts, 1/q);
1111                         }
1112                         lst plstx;
1113                         lst plsts;
1114                         for (int j=r+1; j<=size; ++j) {
1115                                 plstx.append(newx.op(j-1));
1116                                 plsts.append(s.op(j-1));
1117                         }
1118                         if (plstx.nops() > 0) {
1119                                 buffer *= G_numeric(plstx, plsts, 1/p);
1120                         }
1121                         result += buffer;
1122                 }
1123                 return result;
1124         }
1125         
1126         // do summation
1127         lst newx;
1128         lst m;
1129         int mcount = 1;
1130         ex sign = 1;
1131         ex factor = y;
1132         for (lst::const_iterator it = x.begin(); it != x.end(); ++it) {
1133                 if ((*it).is_zero()) {
1134                         ++mcount;
1135                 } else {
1136                         newx.append(factor / (*it));
1137                         factor = *it;
1138                         m.append(mcount);
1139                         mcount = 1;
1140                         sign = -sign;
1141                 }
1142         }
1143
1144         return sign * numeric(mLi_do_summation(m, newx));
1145 }
1146
1147
1148 ex mLi_numeric(const lst& m, const lst& x)
1149 {
1150         // let G_numeric do the transformation
1151         lst newx;
1152         lst s;
1153         ex factor = 1;
1154         for (lst::const_iterator itm = m.begin(), itx = x.begin(); itm != m.end(); ++itm, ++itx) {
1155                 for (int i = 1; i < *itm; ++i) {
1156                         newx.append(0);
1157                         s.append(1);
1158                 }
1159                 newx.append(factor / *itx);
1160                 factor /= *itx;
1161                 s.append(1);
1162         }
1163         return pow(-1, m.nops()) * G_numeric(newx, s, _ex1);
1164 }
1165
1166
1167 } // end of anonymous namespace
1168
1169
1170 //////////////////////////////////////////////////////////////////////
1171 //
1172 // Generalized multiple polylogarithm  G(x, y) and G(x, s, y)
1173 //
1174 // GiNaC function
1175 //
1176 //////////////////////////////////////////////////////////////////////
1177
1178
1179 static ex G2_evalf(const ex& x_, const ex& y)
1180 {
1181         if (!y.info(info_flags::positive)) {
1182                 return G(x_, y).hold();
1183         }
1184         lst x = is_a<lst>(x_) ? ex_to<lst>(x_) : lst(x_);
1185         if (x.nops() == 0) {
1186                 return _ex1;
1187         }
1188         if (x.op(0) == y) {
1189                 return G(x_, y).hold();
1190         }
1191         lst s;
1192         bool all_zero = true;
1193         for (lst::const_iterator it = x.begin(); it != x.end(); ++it) {
1194                 if (!(*it).info(info_flags::numeric)) {
1195                         return G(x_, y).hold();
1196                 }
1197                 if (*it != _ex0) {
1198                         all_zero = false;
1199                 }
1200                 s.append(+1);
1201         }
1202         if (all_zero) {
1203                 return pow(log(y), x.nops()) / factorial(x.nops());
1204         }
1205         return G_numeric(x, s, y);
1206 }
1207
1208
1209 static ex G2_eval(const ex& x_, const ex& y)
1210 {
1211         //TODO eval to MZV or H or S or Lin
1212
1213         if (!y.info(info_flags::positive)) {
1214                 return G(x_, y).hold();
1215         }
1216         lst x = is_a<lst>(x_) ? ex_to<lst>(x_) : lst(x_);
1217         if (x.nops() == 0) {
1218                 return _ex1;
1219         }
1220         if (x.op(0) == y) {
1221                 return G(x_, y).hold();
1222         }
1223         lst s;
1224         bool all_zero = true;
1225         bool crational = true;
1226         for (lst::const_iterator it = x.begin(); it != x.end(); ++it) {
1227                 if (!(*it).info(info_flags::numeric)) {
1228                         return G(x_, y).hold();
1229                 }
1230                 if (!(*it).info(info_flags::crational)) {
1231                         crational = false;
1232                 }
1233                 if (*it != _ex0) {
1234                         all_zero = false;
1235                 }
1236                 s.append(+1);
1237         }
1238         if (all_zero) {
1239                 return pow(log(y), x.nops()) / factorial(x.nops());
1240         }
1241         if (!y.info(info_flags::crational)) {
1242                 crational = false;
1243         }
1244         if (crational) {
1245                 return G(x_, y).hold();
1246         }
1247         return G_numeric(x, s, y);
1248 }
1249
1250
1251 unsigned G2_SERIAL::serial = function::register_new(function_options("G", 2).
1252                                 evalf_func(G2_evalf).
1253                                 eval_func(G2_eval).
1254                                 do_not_evalf_params().
1255                                 overloaded(2));
1256 //TODO
1257 //                                derivative_func(G2_deriv).
1258 //                                print_func<print_latex>(G2_print_latex).
1259
1260
1261 static ex G3_evalf(const ex& x_, const ex& s_, const ex& y)
1262 {
1263         if (!y.info(info_flags::positive)) {
1264                 return G(x_, s_, y).hold();
1265         }
1266         lst x = is_a<lst>(x_) ? ex_to<lst>(x_) : lst(x_);
1267         lst s = is_a<lst>(s_) ? ex_to<lst>(s_) : lst(s_);
1268         if (x.nops() != s.nops()) {
1269                 return G(x_, s_, y).hold();
1270         }
1271         if (x.nops() == 0) {
1272                 return _ex1;
1273         }
1274         if (x.op(0) == y) {
1275                 return G(x_, s_, y).hold();
1276         }
1277         lst sn;
1278         bool all_zero = true;
1279         for (lst::const_iterator itx = x.begin(), its = s.begin(); itx != x.end(); ++itx, ++its) {
1280                 if (!(*itx).info(info_flags::numeric)) {
1281                         return G(x_, y).hold();
1282                 }
1283                 if (!(*its).info(info_flags::real)) {
1284                         return G(x_, y).hold();
1285                 }
1286                 if (*itx != _ex0) {
1287                         all_zero = false;
1288                 }
1289                 if (*its >= 0) {
1290                         sn.append(+1);
1291                 } else {
1292                         sn.append(-1);
1293                 }
1294         }
1295         if (all_zero) {
1296                 return pow(log(y), x.nops()) / factorial(x.nops());
1297         }
1298         return G_numeric(x, sn, y);
1299 }
1300
1301
1302 static ex G3_eval(const ex& x_, const ex& s_, const ex& y)
1303 {
1304         //TODO eval to MZV or H or S or Lin
1305
1306         if (!y.info(info_flags::positive)) {
1307                 return G(x_, s_, y).hold();
1308         }
1309         lst x = is_a<lst>(x_) ? ex_to<lst>(x_) : lst(x_);
1310         lst s = is_a<lst>(s_) ? ex_to<lst>(s_) : lst(s_);
1311         if (x.nops() != s.nops()) {
1312                 return G(x_, s_, y).hold();
1313         }
1314         if (x.nops() == 0) {
1315                 return _ex1;
1316         }
1317         if (x.op(0) == y) {
1318                 return G(x_, s_, y).hold();
1319         }
1320         lst sn;
1321         bool all_zero = true;
1322         bool crational = true;
1323         for (lst::const_iterator itx = x.begin(), its = s.begin(); itx != x.end(); ++itx, ++its) {
1324                 if (!(*itx).info(info_flags::numeric)) {
1325                         return G(x_, s_, y).hold();
1326                 }
1327                 if (!(*its).info(info_flags::real)) {
1328                         return G(x_, s_, y).hold();
1329                 }
1330                 if (!(*itx).info(info_flags::crational)) {
1331                         crational = false;
1332                 }
1333                 if (*itx != _ex0) {
1334                         all_zero = false;
1335                 }
1336                 if (*its >= 0) {
1337                         sn.append(+1);
1338                 } else {
1339                         sn.append(-1);
1340                 }
1341         }
1342         if (all_zero) {
1343                 return pow(log(y), x.nops()) / factorial(x.nops());
1344         }
1345         if (!y.info(info_flags::crational)) {
1346                 crational = false;
1347         }
1348         if (crational) {
1349                 return G(x_, s_, y).hold();
1350         }
1351         return G_numeric(x, sn, y);
1352 }
1353
1354
1355 unsigned G3_SERIAL::serial = function::register_new(function_options("G", 3).
1356                                 evalf_func(G3_evalf).
1357                                 eval_func(G3_eval).
1358                                 do_not_evalf_params().
1359                                 overloaded(2));
1360 //TODO
1361 //                                derivative_func(G3_deriv).
1362 //                                print_func<print_latex>(G3_print_latex).
1363
1364
1365 //////////////////////////////////////////////////////////////////////
1366 //
1367 // Classical polylogarithm and multiple polylogarithm  Li(m,x)
1368 //
1369 // GiNaC function
1370 //
1371 //////////////////////////////////////////////////////////////////////
1372
1373
1374 static ex Li_evalf(const ex& m_, const ex& x_)
1375 {
1376         // classical polylogs
1377         if (m_.info(info_flags::posint)) {
1378                 if (x_.info(info_flags::numeric)) {
1379                         return Lin_numeric(ex_to<numeric>(m_).to_int(), ex_to<numeric>(x_));
1380                 } else {
1381                         // try to numerically evaluate second argument
1382                         ex x_val = x_.evalf();
1383                         if (x_val.info(info_flags::numeric)) {
1384                                 return Lin_numeric(ex_to<numeric>(m_).to_int(), ex_to<numeric>(x_val));
1385                         }
1386                 }
1387         }
1388         // multiple polylogs
1389         if (is_a<lst>(m_) && is_a<lst>(x_)) {
1390
1391                 const lst& m = ex_to<lst>(m_);
1392                 const lst& x = ex_to<lst>(x_);
1393                 if (m.nops() != x.nops()) {
1394                         return Li(m_,x_).hold();
1395                 }
1396                 if (x.nops() == 0) {
1397                         return _ex1;
1398                 }
1399                 if ((m.op(0) == _ex1) && (x.op(0) == _ex1)) {
1400                         return Li(m_,x_).hold();
1401                 }
1402
1403                 for (lst::const_iterator itm = m.begin(), itx = x.begin(); itm != m.end(); ++itm, ++itx) {
1404                         if (!(*itm).info(info_flags::posint)) {
1405                                 return Li(m_, x_).hold();
1406                         }
1407                         if (!(*itx).info(info_flags::numeric)) {
1408                                 return Li(m_, x_).hold();
1409                         }
1410                         if (*itx == _ex0) {
1411                                 return _ex0;
1412                         }
1413                 }
1414
1415                 return mLi_numeric(m, x);
1416         }
1417
1418         return Li(m_,x_).hold();
1419 }
1420
1421
1422 static ex Li_eval(const ex& m_, const ex& x_)
1423 {
1424         if (is_a<lst>(m_)) {
1425                 if (is_a<lst>(x_)) {
1426                         // multiple polylogs
1427                         const lst& m = ex_to<lst>(m_);
1428                         const lst& x = ex_to<lst>(x_);
1429                         if (m.nops() != x.nops()) {
1430                                 return Li(m_,x_).hold();
1431                         }
1432                         if (x.nops() == 0) {
1433                                 return _ex1;
1434                         }
1435                         bool is_H = true;
1436                         bool is_zeta = true;
1437                         bool do_evalf = true;
1438                         bool crational = true;
1439                         for (lst::const_iterator itm = m.begin(), itx = x.begin(); itm != m.end(); ++itm, ++itx) {
1440                                 if (!(*itm).info(info_flags::posint)) {
1441                                         return Li(m_,x_).hold();
1442                                 }
1443                                 if ((*itx != _ex1) && (*itx != _ex_1)) {
1444                                         if (itx != x.begin()) {
1445                                                 is_H = false;
1446                                         }
1447                                         is_zeta = false;
1448                                 }
1449                                 if (*itx == _ex0) {
1450                                         return _ex0;
1451                                 }
1452                                 if (!(*itx).info(info_flags::numeric)) {
1453                                         do_evalf = false;
1454                                 }
1455                                 if (!(*itx).info(info_flags::crational)) {
1456                                         crational = false;
1457                                 }
1458                         }
1459                         if (is_zeta) {
1460                                 return zeta(m_,x_);
1461                         }
1462                         if (is_H) {
1463                                 ex prefactor;
1464                                 lst newm = convert_parameter_Li_to_H(m, x, prefactor);
1465                                 return prefactor * H(newm, x[0]);
1466                         }
1467                         if (do_evalf && !crational) {
1468                                 return mLi_numeric(m,x);
1469                         }
1470                 }
1471                 return Li(m_, x_).hold();
1472         } else if (is_a<lst>(x_)) {
1473                 return Li(m_, x_).hold();
1474         }
1475
1476         // classical polylogs
1477         if (x_ == _ex0) {
1478                 return _ex0;
1479         }
1480         if (x_ == _ex1) {
1481                 return zeta(m_);
1482         }
1483         if (x_ == _ex_1) {
1484                 return (pow(2,1-m_)-1) * zeta(m_);
1485         }
1486         if (m_ == _ex1) {
1487                 return -log(1-x_);
1488         }
1489         if (m_ == _ex2) {
1490                 if (x_.is_equal(I)) {
1491                         return power(Pi,_ex2)/_ex_48 + Catalan*I;
1492                 }
1493                 if (x_.is_equal(-I)) {
1494                         return power(Pi,_ex2)/_ex_48 - Catalan*I;
1495                 }
1496         }
1497         if (m_.info(info_flags::posint) && x_.info(info_flags::numeric) && !x_.info(info_flags::crational)) {
1498                 return Lin_numeric(ex_to<numeric>(m_).to_int(), ex_to<numeric>(x_));
1499         }
1500
1501         return Li(m_, x_).hold();
1502 }
1503
1504
1505 static ex Li_series(const ex& m, const ex& x, const relational& rel, int order, unsigned options)
1506 {
1507         if (is_a<lst>(m) || is_a<lst>(x)) {
1508                 // multiple polylog
1509                 epvector seq;
1510                 seq.push_back(expair(Li(m, x), 0));
1511                 return pseries(rel, seq);
1512         }
1513         
1514         // classical polylog
1515         const ex x_pt = x.subs(rel, subs_options::no_pattern);
1516         if (m.info(info_flags::numeric) && x_pt.info(info_flags::numeric)) {
1517                 // First special case: x==0 (derivatives have poles)
1518                 if (x_pt.is_zero()) {
1519                         const symbol s;
1520                         ex ser;
1521                         // manually construct the primitive expansion
1522                         for (int i=1; i<order; ++i)
1523                                 ser += pow(s,i) / pow(numeric(i), m);
1524                         // substitute the argument's series expansion
1525                         ser = ser.subs(s==x.series(rel, order), subs_options::no_pattern);
1526                         // maybe that was terminating, so add a proper order term
1527                         epvector nseq;
1528                         nseq.push_back(expair(Order(_ex1), order));
1529                         ser += pseries(rel, nseq);
1530                         // reexpanding it will collapse the series again
1531                         return ser.series(rel, order);
1532                 }
1533                 // TODO special cases: x==1 (branch point) and x real, >=1 (branch cut)
1534                 throw std::runtime_error("Li_series: don't know how to do the series expansion at this point!");
1535         }
1536         // all other cases should be safe, by now:
1537         throw do_taylor();  // caught by function::series()
1538 }
1539
1540
1541 static ex Li_deriv(const ex& m_, const ex& x_, unsigned deriv_param)
1542 {
1543         GINAC_ASSERT(deriv_param < 2);
1544         if (deriv_param == 0) {
1545                 return _ex0;
1546         }
1547         if (m_.nops() > 1) {
1548                 throw std::runtime_error("don't know how to derivate multiple polylogarithm!");
1549         }
1550         ex m;
1551         if (is_a<lst>(m_)) {
1552                 m = m_.op(0);
1553         } else {
1554                 m = m_;
1555         }
1556         ex x;
1557         if (is_a<lst>(x_)) {
1558                 x = x_.op(0);
1559         } else {
1560                 x = x_;
1561         }
1562         if (m > 0) {
1563                 return Li(m-1, x) / x;
1564         } else {
1565                 return 1/(1-x);
1566         }
1567 }
1568
1569
1570 static void Li_print_latex(const ex& m_, const ex& x_, const print_context& c)
1571 {
1572         lst m;
1573         if (is_a<lst>(m_)) {
1574                 m = ex_to<lst>(m_);
1575         } else {
1576                 m = lst(m_);
1577         }
1578         lst x;
1579         if (is_a<lst>(x_)) {
1580                 x = ex_to<lst>(x_);
1581         } else {
1582                 x = lst(x_);
1583         }
1584         c.s << "\\mbox{Li}_{";
1585         lst::const_iterator itm = m.begin();
1586         (*itm).print(c);
1587         itm++;
1588         for (; itm != m.end(); itm++) {
1589                 c.s << ",";
1590                 (*itm).print(c);
1591         }
1592         c.s << "}(";
1593         lst::const_iterator itx = x.begin();
1594         (*itx).print(c);
1595         itx++;
1596         for (; itx != x.end(); itx++) {
1597                 c.s << ",";
1598                 (*itx).print(c);
1599         }
1600         c.s << ")";
1601 }
1602
1603
1604 REGISTER_FUNCTION(Li,
1605                   evalf_func(Li_evalf).
1606                   eval_func(Li_eval).
1607                   series_func(Li_series).
1608                   derivative_func(Li_deriv).
1609                   print_func<print_latex>(Li_print_latex).
1610                   do_not_evalf_params());
1611
1612
1613 //////////////////////////////////////////////////////////////////////
1614 //
1615 // Nielsen's generalized polylogarithm  S(n,p,x)
1616 //
1617 // helper functions
1618 //
1619 //////////////////////////////////////////////////////////////////////
1620
1621
1622 // anonymous namespace for helper functions
1623 namespace {
1624
1625
1626 // lookup table for special Euler-Zagier-Sums (used for S_n,p(x))
1627 // see fill_Yn()
1628 std::vector<std::vector<cln::cl_N> > Yn;
1629 int ynsize = 0; // number of Yn[]
1630 int ynlength = 100; // initial length of all Yn[i]
1631
1632
1633 // This function calculates the Y_n. The Y_n are needed for the evaluation of S_{n,p}(x).
1634 // The Y_n are basically Euler-Zagier sums with all m_i=1. They are subsums in the Z-sum
1635 // representing S_{n,p}(x).
1636 // The first index in Y_n corresponds to the parameter p minus one, i.e. the depth of the
1637 // equivalent Z-sum.
1638 // The second index in Y_n corresponds to the running index of the outermost sum in the full Z-sum
1639 // representing S_{n,p}(x).
1640 // The calculation of Y_n uses the values from Y_{n-1}.
1641 void fill_Yn(int n, const cln::float_format_t& prec)
1642 {
1643         const int initsize = ynlength;
1644         //const int initsize = initsize_Yn;
1645         cln::cl_N one = cln::cl_float(1, prec);
1646
1647         if (n) {
1648                 std::vector<cln::cl_N> buf(initsize);
1649                 std::vector<cln::cl_N>::iterator it = buf.begin();
1650                 std::vector<cln::cl_N>::iterator itprev = Yn[n-1].begin();
1651                 *it = (*itprev) / cln::cl_N(n+1) * one;
1652                 it++;
1653                 itprev++;
1654                 // sums with an index smaller than the depth are zero and need not to be calculated.
1655                 // calculation starts with depth, which is n+2)
1656                 for (int i=n+2; i<=initsize+n; i++) {
1657                         *it = *(it-1) + (*itprev) / cln::cl_N(i) * one;
1658                         it++;
1659                         itprev++;
1660                 }
1661                 Yn.push_back(buf);
1662         } else {
1663                 std::vector<cln::cl_N> buf(initsize);
1664                 std::vector<cln::cl_N>::iterator it = buf.begin();
1665                 *it = 1 * one;
1666                 it++;
1667                 for (int i=2; i<=initsize; i++) {
1668                         *it = *(it-1) + 1 / cln::cl_N(i) * one;
1669                         it++;
1670                 }
1671                 Yn.push_back(buf);
1672         }
1673         ynsize++;
1674 }
1675
1676
1677 // make Yn longer ... 
1678 void make_Yn_longer(int newsize, const cln::float_format_t& prec)
1679 {
1680
1681         cln::cl_N one = cln::cl_float(1, prec);
1682
1683         Yn[0].resize(newsize);
1684         std::vector<cln::cl_N>::iterator it = Yn[0].begin();
1685         it += ynlength;
1686         for (int i=ynlength+1; i<=newsize; i++) {
1687                 *it = *(it-1) + 1 / cln::cl_N(i) * one;
1688                 it++;
1689         }
1690
1691         for (int n=1; n<ynsize; n++) {
1692                 Yn[n].resize(newsize);
1693                 std::vector<cln::cl_N>::iterator it = Yn[n].begin();
1694                 std::vector<cln::cl_N>::iterator itprev = Yn[n-1].begin();
1695                 it += ynlength;
1696                 itprev += ynlength;
1697                 for (int i=ynlength+n+1; i<=newsize+n; i++) {
1698                         *it = *(it-1) + (*itprev) / cln::cl_N(i) * one;
1699                         it++;
1700                         itprev++;
1701                 }
1702         }
1703         
1704         ynlength = newsize;
1705 }
1706
1707
1708 // helper function for S(n,p,x)
1709 // [Kol] (7.2)
1710 cln::cl_N C(int n, int p)
1711 {
1712         cln::cl_N result;
1713
1714         for (int k=0; k<p; k++) {
1715                 for (int j=0; j<=(n+k-1)/2; j++) {
1716                         if (k == 0) {
1717                                 if (n & 1) {
1718                                         if (j & 1) {
1719                                                 result = result - 2 * cln::expt(cln::pi(),2*j) * S_num(n-2*j,p,1).to_cl_N() / cln::factorial(2*j);
1720                                         }
1721                                         else {
1722                                                 result = result + 2 * cln::expt(cln::pi(),2*j) * S_num(n-2*j,p,1).to_cl_N() / cln::factorial(2*j);
1723                                         }
1724                                 }
1725                         }
1726                         else {
1727                                 if (k & 1) {
1728                                         if (j & 1) {
1729                                                 result = result + cln::factorial(n+k-1)
1730                                                                   * cln::expt(cln::pi(),2*j) * S_num(n+k-2*j,p-k,1).to_cl_N()
1731                                                                   / (cln::factorial(k) * cln::factorial(n-1) * cln::factorial(2*j));
1732                                         }
1733                                         else {
1734                                                 result = result - cln::factorial(n+k-1)
1735                                                                   * cln::expt(cln::pi(),2*j) * S_num(n+k-2*j,p-k,1).to_cl_N()
1736                                                                   / (cln::factorial(k) * cln::factorial(n-1) * cln::factorial(2*j));
1737                                         }
1738                                 }
1739                                 else {
1740                                         if (j & 1) {
1741                                                 result = result - cln::factorial(n+k-1) * cln::expt(cln::pi(),2*j) * S_num(n+k-2*j,p-k,1).to_cl_N()
1742                                                                   / (cln::factorial(k) * cln::factorial(n-1) * cln::factorial(2*j));
1743                                         }
1744                                         else {
1745                                                 result = result + cln::factorial(n+k-1)
1746                                                                   * cln::expt(cln::pi(),2*j) * S_num(n+k-2*j,p-k,1).to_cl_N()
1747                                                                   / (cln::factorial(k) * cln::factorial(n-1) * cln::factorial(2*j));
1748                                         }
1749                                 }
1750                         }
1751                 }
1752         }
1753         int np = n+p;
1754         if ((np-1) & 1) {
1755                 if (((np)/2+n) & 1) {
1756                         result = -result - cln::expt(cln::pi(),np) / (np * cln::factorial(n-1) * cln::factorial(p));
1757                 }
1758                 else {
1759                         result = -result + cln::expt(cln::pi(),np) / (np * cln::factorial(n-1) * cln::factorial(p));
1760                 }
1761         }
1762
1763         return result;
1764 }
1765
1766
1767 // helper function for S(n,p,x)
1768 // [Kol] remark to (9.1)
1769 cln::cl_N a_k(int k)
1770 {
1771         cln::cl_N result;
1772
1773         if (k == 0) {
1774                 return 1;
1775         }
1776
1777         result = result;
1778         for (int m=2; m<=k; m++) {
1779                 result = result + cln::expt(cln::cl_N(-1),m) * cln::zeta(m) * a_k(k-m);
1780         }
1781
1782         return -result / k;
1783 }
1784
1785
1786 // helper function for S(n,p,x)
1787 // [Kol] remark to (9.1)
1788 cln::cl_N b_k(int k)
1789 {
1790         cln::cl_N result;
1791
1792         if (k == 0) {
1793                 return 1;
1794         }
1795
1796         result = result;
1797         for (int m=2; m<=k; m++) {
1798                 result = result + cln::expt(cln::cl_N(-1),m) * cln::zeta(m) * b_k(k-m);
1799         }
1800
1801         return result / k;
1802 }
1803
1804
1805 // helper function for S(n,p,x)
1806 cln::cl_N S_do_sum(int n, int p, const cln::cl_N& x, const cln::float_format_t& prec)
1807 {
1808         if (p==1) {
1809                 return Li_projection(n+1, x, prec);
1810         }
1811         
1812         // check if precalculated values are sufficient
1813         if (p > ynsize+1) {
1814                 for (int i=ynsize; i<p-1; i++) {
1815                         fill_Yn(i, prec);
1816                 }
1817         }
1818
1819         // should be done otherwise
1820         cln::cl_F one = cln::cl_float(1, cln::float_format(Digits));
1821         cln::cl_N xf = x * one;
1822         //cln::cl_N xf = x * cln::cl_float(1, prec);
1823
1824         cln::cl_N res;
1825         cln::cl_N resbuf;
1826         cln::cl_N factor = cln::expt(xf, p);
1827         int i = p;
1828         do {
1829                 resbuf = res;
1830                 if (i-p >= ynlength) {
1831                         // make Yn longer
1832                         make_Yn_longer(ynlength*2, prec);
1833                 }
1834                 res = res + factor / cln::expt(cln::cl_I(i),n+1) * Yn[p-2][i-p]; // should we check it? or rely on magic number? ...
1835                 //res = res + factor / cln::expt(cln::cl_I(i),n+1) * (*it); // should we check it? or rely on magic number? ...
1836                 factor = factor * xf;
1837                 i++;
1838         } while (res != resbuf);
1839         
1840         return res;
1841 }
1842
1843
1844 // helper function for S(n,p,x)
1845 cln::cl_N S_projection(int n, int p, const cln::cl_N& x, const cln::float_format_t& prec)
1846 {
1847         // [Kol] (5.3)
1848         if (cln::abs(cln::realpart(x)) > cln::cl_F("0.5")) {
1849
1850                 cln::cl_N result = cln::expt(cln::cl_I(-1),p) * cln::expt(cln::log(x),n)
1851                                    * cln::expt(cln::log(1-x),p) / cln::factorial(n) / cln::factorial(p);
1852
1853                 for (int s=0; s<n; s++) {
1854                         cln::cl_N res2;
1855                         for (int r=0; r<p; r++) {
1856                                 res2 = res2 + cln::expt(cln::cl_I(-1),r) * cln::expt(cln::log(1-x),r)
1857                                               * S_do_sum(p-r,n-s,1-x,prec) / cln::factorial(r);
1858                         }
1859                         result = result + cln::expt(cln::log(x),s) * (S_num(n-s,p,1).to_cl_N() - res2) / cln::factorial(s);
1860                 }
1861
1862                 return result;
1863         }
1864         
1865         return S_do_sum(n, p, x, prec);
1866 }
1867
1868
1869 // helper function for S(n,p,x)
1870 numeric S_num(int n, int p, const numeric& x)
1871 {
1872         if (x == 1) {
1873                 if (n == 1) {
1874                     // [Kol] (2.22) with (2.21)
1875                         return cln::zeta(p+1);
1876                 }
1877
1878                 if (p == 1) {
1879                     // [Kol] (2.22)
1880                         return cln::zeta(n+1);
1881                 }
1882
1883                 // [Kol] (9.1)
1884                 cln::cl_N result;
1885                 for (int nu=0; nu<n; nu++) {
1886                         for (int rho=0; rho<=p; rho++) {
1887                                 result = result + b_k(n-nu-1) * b_k(p-rho) * a_k(nu+rho+1)
1888                                                   * cln::factorial(nu+rho+1) / cln::factorial(rho) / cln::factorial(nu+1);
1889                         }
1890                 }
1891                 result = result * cln::expt(cln::cl_I(-1),n+p-1);
1892
1893                 return result;
1894         }
1895         else if (x == -1) {
1896                 // [Kol] (2.22)
1897                 if (p == 1) {
1898                         return -(1-cln::expt(cln::cl_I(2),-n)) * cln::zeta(n+1);
1899                 }
1900 //              throw std::runtime_error("don't know how to evaluate this function!");
1901         }
1902
1903         // what is the desired float format?
1904         // first guess: default format
1905         cln::float_format_t prec = cln::default_float_format;
1906         const cln::cl_N value = x.to_cl_N();
1907         // second guess: the argument's format
1908         if (!x.real().is_rational())
1909                 prec = cln::float_format(cln::the<cln::cl_F>(cln::realpart(value)));
1910         else if (!x.imag().is_rational())
1911                 prec = cln::float_format(cln::the<cln::cl_F>(cln::imagpart(value)));
1912
1913         // [Kol] (5.3)
1914         if ((cln::realpart(value) < -0.5) || (n == 0)) {
1915
1916                 cln::cl_N result = cln::expt(cln::cl_I(-1),p) * cln::expt(cln::log(value),n)
1917                                    * cln::expt(cln::log(1-value),p) / cln::factorial(n) / cln::factorial(p);
1918
1919                 for (int s=0; s<n; s++) {
1920                         cln::cl_N res2;
1921                         for (int r=0; r<p; r++) {
1922                                 res2 = res2 + cln::expt(cln::cl_I(-1),r) * cln::expt(cln::log(1-value),r)
1923                                               * S_num(p-r,n-s,1-value).to_cl_N() / cln::factorial(r);
1924                         }
1925                         result = result + cln::expt(cln::log(value),s) * (S_num(n-s,p,1).to_cl_N() - res2) / cln::factorial(s);
1926                 }
1927
1928                 return result;
1929                 
1930         }
1931         // [Kol] (5.12)
1932         if (cln::abs(value) > 1) {
1933                 
1934                 cln::cl_N result;
1935
1936                 for (int s=0; s<p; s++) {
1937                         for (int r=0; r<=s; r++) {
1938                                 result = result + cln::expt(cln::cl_I(-1),s) * cln::expt(cln::log(-value),r) * cln::factorial(n+s-r-1)
1939                                                   / cln::factorial(r) / cln::factorial(s-r) / cln::factorial(n-1)
1940                                                   * S_num(n+s-r,p-s,cln::recip(value)).to_cl_N();
1941                         }
1942                 }
1943                 result = result * cln::expt(cln::cl_I(-1),n);
1944
1945                 cln::cl_N res2;
1946                 for (int r=0; r<n; r++) {
1947                         res2 = res2 + cln::expt(cln::log(-value),r) * C(n-r,p) / cln::factorial(r);
1948                 }
1949                 res2 = res2 + cln::expt(cln::log(-value),n+p) / cln::factorial(n+p);
1950
1951                 result = result + cln::expt(cln::cl_I(-1),p) * res2;
1952
1953                 return result;
1954         }
1955         else {
1956                 return S_projection(n, p, value, prec);
1957         }
1958 }
1959
1960
1961 } // end of anonymous namespace
1962
1963
1964 //////////////////////////////////////////////////////////////////////
1965 //
1966 // Nielsen's generalized polylogarithm  S(n,p,x)
1967 //
1968 // GiNaC function
1969 //
1970 //////////////////////////////////////////////////////////////////////
1971
1972
1973 static ex S_evalf(const ex& n, const ex& p, const ex& x)
1974 {
1975         if (n.info(info_flags::posint) && p.info(info_flags::posint)) {
1976                 if (is_a<numeric>(x)) {
1977                         return S_num(ex_to<numeric>(n).to_int(), ex_to<numeric>(p).to_int(), ex_to<numeric>(x));
1978                 } else {
1979                         ex x_val = x.evalf();
1980                         if (is_a<numeric>(x_val)) {
1981                                 return S_num(ex_to<numeric>(n).to_int(), ex_to<numeric>(p).to_int(), ex_to<numeric>(x_val));
1982                         }
1983                 }
1984         }
1985         return S(n, p, x).hold();
1986 }
1987
1988
1989 static ex S_eval(const ex& n, const ex& p, const ex& x)
1990 {
1991         if (n.info(info_flags::posint) && p.info(info_flags::posint)) {
1992                 if (x == 0) {
1993                         return _ex0;
1994                 }
1995                 if (x == 1) {
1996                         lst m(n+1);
1997                         for (int i=ex_to<numeric>(p).to_int()-1; i>0; i--) {
1998                                 m.append(1);
1999                         }
2000                         return zeta(m);
2001                 }
2002                 if (p == 1) {
2003                         return Li(n+1, x);
2004                 }
2005                 if (x.info(info_flags::numeric) && (!x.info(info_flags::crational))) {
2006                         return S_num(ex_to<numeric>(n).to_int(), ex_to<numeric>(p).to_int(), ex_to<numeric>(x));
2007                 }
2008         }
2009         if (n.is_zero()) {
2010                 // [Kol] (5.3)
2011                 return pow(-log(1-x), p) / factorial(p);
2012         }
2013         return S(n, p, x).hold();
2014 }
2015
2016
2017 static ex S_series(const ex& n, const ex& p, const ex& x, const relational& rel, int order, unsigned options)
2018 {
2019         if (p == _ex1) {
2020                 return Li(n+1, x).series(rel, order, options);
2021         }
2022
2023         const ex x_pt = x.subs(rel, subs_options::no_pattern);
2024         if (n.info(info_flags::posint) && p.info(info_flags::posint) && x_pt.info(info_flags::numeric)) {
2025                 // First special case: x==0 (derivatives have poles)
2026                 if (x_pt.is_zero()) {
2027                         const symbol s;
2028                         ex ser;
2029                         // manually construct the primitive expansion
2030                         // subsum = Euler-Zagier-Sum is needed
2031                         // dirty hack (slow ...) calculation of subsum:
2032                         std::vector<ex> presubsum, subsum;
2033                         subsum.push_back(0);
2034                         for (int i=1; i<order-1; ++i) {
2035                                 subsum.push_back(subsum[i-1] + numeric(1, i));
2036                         }
2037                         for (int depth=2; depth<p; ++depth) {
2038                                 presubsum = subsum;
2039                                 for (int i=1; i<order-1; ++i) {
2040                                         subsum[i] = subsum[i-1] + numeric(1, i) * presubsum[i-1];
2041                                 }
2042                         }
2043                                 
2044                         for (int i=1; i<order; ++i) {
2045                                 ser += pow(s,i) / pow(numeric(i), n+1) * subsum[i-1];
2046                         }
2047                         // substitute the argument's series expansion
2048                         ser = ser.subs(s==x.series(rel, order), subs_options::no_pattern);
2049                         // maybe that was terminating, so add a proper order term
2050                         epvector nseq;
2051                         nseq.push_back(expair(Order(_ex1), order));
2052                         ser += pseries(rel, nseq);
2053                         // reexpanding it will collapse the series again
2054                         return ser.series(rel, order);
2055                 }
2056                 // TODO special cases: x==1 (branch point) and x real, >=1 (branch cut)
2057                 throw std::runtime_error("S_series: don't know how to do the series expansion at this point!");
2058         }
2059         // all other cases should be safe, by now:
2060         throw do_taylor();  // caught by function::series()
2061 }
2062
2063
2064 static ex S_deriv(const ex& n, const ex& p, const ex& x, unsigned deriv_param)
2065 {
2066         GINAC_ASSERT(deriv_param < 3);
2067         if (deriv_param < 2) {
2068                 return _ex0;
2069         }
2070         if (n > 0) {
2071                 return S(n-1, p, x) / x;
2072         } else {
2073                 return S(n, p-1, x) / (1-x);
2074         }
2075 }
2076
2077
2078 static void S_print_latex(const ex& n, const ex& p, const ex& x, const print_context& c)
2079 {
2080         c.s << "\\mbox{S}_{";
2081         n.print(c);
2082         c.s << ",";
2083         p.print(c);
2084         c.s << "}(";
2085         x.print(c);
2086         c.s << ")";
2087 }
2088
2089
2090 REGISTER_FUNCTION(S,
2091                   evalf_func(S_evalf).
2092                   eval_func(S_eval).
2093                   series_func(S_series).
2094                   derivative_func(S_deriv).
2095                   print_func<print_latex>(S_print_latex).
2096                   do_not_evalf_params());
2097
2098
2099 //////////////////////////////////////////////////////////////////////
2100 //
2101 // Harmonic polylogarithm  H(m,x)
2102 //
2103 // helper functions
2104 //
2105 //////////////////////////////////////////////////////////////////////
2106
2107
2108 // anonymous namespace for helper functions
2109 namespace {
2110
2111         
2112 // regulates the pole (used by 1/x-transformation)
2113 symbol H_polesign("IMSIGN");
2114
2115
2116 // convert parameters from H to Li representation
2117 // parameters are expected to be in expanded form, i.e. only 0, 1 and -1
2118 // returns true if some parameters are negative
2119 bool convert_parameter_H_to_Li(const lst& l, lst& m, lst& s, ex& pf)
2120 {
2121         // expand parameter list
2122         lst mexp;
2123         for (lst::const_iterator it = l.begin(); it != l.end(); it++) {
2124                 if (*it > 1) {
2125                         for (ex count=*it-1; count > 0; count--) {
2126                                 mexp.append(0);
2127                         }
2128                         mexp.append(1);
2129                 } else if (*it < -1) {
2130                         for (ex count=*it+1; count < 0; count++) {
2131                                 mexp.append(0);
2132                         }
2133                         mexp.append(-1);
2134                 } else {
2135                         mexp.append(*it);
2136                 }
2137         }
2138         
2139         ex signum = 1;
2140         pf = 1;
2141         bool has_negative_parameters = false;
2142         ex acc = 1;
2143         for (lst::const_iterator it = mexp.begin(); it != mexp.end(); it++) {
2144                 if (*it == 0) {
2145                         acc++;
2146                         continue;
2147                 }
2148                 if (*it > 0) {
2149                         m.append((*it+acc-1) * signum);
2150                 } else {
2151                         m.append((*it-acc+1) * signum);
2152                 }
2153                 acc = 1;
2154                 signum = *it;
2155                 pf *= *it;
2156                 if (pf < 0) {
2157                         has_negative_parameters = true;
2158                 }
2159         }
2160         if (has_negative_parameters) {
2161                 for (int i=0; i<m.nops(); i++) {
2162                         if (m.op(i) < 0) {
2163                                 m.let_op(i) = -m.op(i);
2164                                 s.append(-1);
2165                         } else {
2166                                 s.append(1);
2167                         }
2168                 }
2169         }
2170         
2171         return has_negative_parameters;
2172 }
2173
2174
2175 // recursivly transforms H to corresponding multiple polylogarithms
2176 struct map_trafo_H_convert_to_Li : public map_function
2177 {
2178         ex operator()(const ex& e)
2179         {
2180                 if (is_a<add>(e) || is_a<mul>(e)) {
2181                         return e.map(*this);
2182                 }
2183                 if (is_a<function>(e)) {
2184                         std::string name = ex_to<function>(e).get_name();
2185                         if (name == "H") {
2186                                 lst parameter;
2187                                 if (is_a<lst>(e.op(0))) {
2188                                                 parameter = ex_to<lst>(e.op(0));
2189                                 } else {
2190                                         parameter = lst(e.op(0));
2191                                 }
2192                                 ex arg = e.op(1);
2193
2194                                 lst m;
2195                                 lst s;
2196                                 ex pf;
2197                                 if (convert_parameter_H_to_Li(parameter, m, s, pf)) {
2198                                         s.let_op(0) = s.op(0) * arg;
2199                                         return pf * Li(m, s).hold();
2200                                 } else {
2201                                         for (int i=0; i<m.nops(); i++) {
2202                                                 s.append(1);
2203                                         }
2204                                         s.let_op(0) = s.op(0) * arg;
2205                                         return Li(m, s).hold();
2206                                 }
2207                         }
2208                 }
2209                 return e;
2210         }
2211 };
2212
2213
2214 // recursivly transforms H to corresponding zetas
2215 struct map_trafo_H_convert_to_zeta : public map_function
2216 {
2217         ex operator()(const ex& e)
2218         {
2219                 if (is_a<add>(e) || is_a<mul>(e)) {
2220                         return e.map(*this);
2221                 }
2222                 if (is_a<function>(e)) {
2223                         std::string name = ex_to<function>(e).get_name();
2224                         if (name == "H") {
2225                                 lst parameter;
2226                                 if (is_a<lst>(e.op(0))) {
2227                                                 parameter = ex_to<lst>(e.op(0));
2228                                 } else {
2229                                         parameter = lst(e.op(0));
2230                                 }
2231
2232                                 lst m;
2233                                 lst s;
2234                                 ex pf;
2235                                 if (convert_parameter_H_to_Li(parameter, m, s, pf)) {
2236                                         return pf * zeta(m, s);
2237                                 } else {
2238                                         return zeta(m);
2239                                 }
2240                         }
2241                 }
2242                 return e;
2243         }
2244 };
2245
2246
2247 // remove trailing zeros from H-parameters
2248 struct map_trafo_H_reduce_trailing_zeros : public map_function
2249 {
2250         ex operator()(const ex& e)
2251         {
2252                 if (is_a<add>(e) || is_a<mul>(e)) {
2253                         return e.map(*this);
2254                 }
2255                 if (is_a<function>(e)) {
2256                         std::string name = ex_to<function>(e).get_name();
2257                         if (name == "H") {
2258                                 lst parameter;
2259                                 if (is_a<lst>(e.op(0))) {
2260                                         parameter = ex_to<lst>(e.op(0));
2261                                 } else {
2262                                         parameter = lst(e.op(0));
2263                                 }
2264                                 ex arg = e.op(1);
2265                                 if (parameter.op(parameter.nops()-1) == 0) {
2266                                         
2267                                         //
2268                                         if (parameter.nops() == 1) {
2269                                                 return log(arg);
2270                                         }
2271                                         
2272                                         //
2273                                         lst::const_iterator it = parameter.begin();
2274                                         while ((it != parameter.end()) && (*it == 0)) {
2275                                                 it++;
2276                                         }
2277                                         if (it == parameter.end()) {
2278                                                 return pow(log(arg),parameter.nops()) / factorial(parameter.nops());
2279                                         }
2280                                         
2281                                         //
2282                                         parameter.remove_last();
2283                                         int lastentry = parameter.nops();
2284                                         while ((lastentry > 0) && (parameter[lastentry-1] == 0)) {
2285                                                 lastentry--;
2286                                         }
2287                                         
2288                                         //
2289                                         ex result = log(arg) * H(parameter,arg).hold();
2290                                         ex acc = 0;
2291                                         for (ex i=0; i<lastentry; i++) {
2292                                                 if (parameter[i] > 0) {
2293                                                         parameter[i]++;
2294                                                         result -= (acc + parameter[i]-1) * H(parameter, arg).hold();
2295                                                         parameter[i]--;
2296                                                         acc = 0;
2297                                                 } else if (parameter[i] < 0) {
2298                                                         parameter[i]--;
2299                                                         result -= (acc + abs(parameter[i]+1)) * H(parameter, arg).hold();
2300                                                         parameter[i]++;
2301                                                         acc = 0;
2302                                                 } else {
2303                                                         acc++;
2304                                                 }
2305                                         }
2306                                         
2307                                         if (lastentry < parameter.nops()) {
2308                                                 result = result / (parameter.nops()-lastentry+1);
2309                                                 return result.map(*this);
2310                                         } else {
2311                                                 return result;
2312                                         }
2313                                 }
2314                         }
2315                 }
2316                 return e;
2317         }
2318 };
2319
2320
2321 // returns an expression with zeta functions corresponding to the parameter list for H
2322 ex convert_H_to_zeta(const lst& m)
2323 {
2324         symbol xtemp("xtemp");
2325         map_trafo_H_reduce_trailing_zeros filter;
2326         map_trafo_H_convert_to_zeta filter2;
2327         return filter2(filter(H(m, xtemp).hold())).subs(xtemp == 1);
2328 }
2329
2330
2331 // convert signs form Li to H representation
2332 lst convert_parameter_Li_to_H(const lst& m, const lst& x, ex& pf)
2333 {
2334         lst res;
2335         lst::const_iterator itm = m.begin();
2336         lst::const_iterator itx = ++x.begin();
2337         int signum = 1;
2338         pf = _ex1;
2339         res.append(*itm);
2340         itm++;
2341         while (itx != x.end()) {
2342                 signum *= (*itx > 0) ? 1 : -1;
2343                 pf *= signum;
2344                 res.append((*itm) * signum);
2345                 itm++;
2346                 itx++;
2347         }
2348         return res;
2349 }
2350
2351
2352 // multiplies an one-dimensional H with another H
2353 // [ReV] (18)
2354 ex trafo_H_mult(const ex& h1, const ex& h2)
2355 {
2356         ex res;
2357         ex hshort;
2358         lst hlong;
2359         ex h1nops = h1.op(0).nops();
2360         ex h2nops = h2.op(0).nops();
2361         if (h1nops > 1) {
2362                 hshort = h2.op(0).op(0);
2363                 hlong = ex_to<lst>(h1.op(0));
2364         } else {
2365                 hshort = h1.op(0).op(0);
2366                 if (h2nops > 1) {
2367                         hlong = ex_to<lst>(h2.op(0));
2368                 } else {
2369                         hlong = h2.op(0).op(0);
2370                 }
2371         }
2372         for (int i=0; i<=hlong.nops(); i++) {
2373                 lst newparameter;
2374                 int j=0;
2375                 for (; j<i; j++) {
2376                         newparameter.append(hlong[j]);
2377                 }
2378                 newparameter.append(hshort);
2379                 for (; j<hlong.nops(); j++) {
2380                         newparameter.append(hlong[j]);
2381                 }
2382                 res += H(newparameter, h1.op(1)).hold();
2383         }
2384         return res;
2385 }
2386
2387
2388 // applies trafo_H_mult recursively on expressions
2389 struct map_trafo_H_mult : public map_function
2390 {
2391         ex operator()(const ex& e)
2392         {
2393                 if (is_a<add>(e)) {
2394                         return e.map(*this);
2395                 }
2396
2397                 if (is_a<mul>(e)) {
2398
2399                         ex result = 1;
2400                         ex firstH;
2401                         lst Hlst;
2402                         for (int pos=0; pos<e.nops(); pos++) {
2403                                 if (is_a<power>(e.op(pos)) && is_a<function>(e.op(pos).op(0))) {
2404                                         std::string name = ex_to<function>(e.op(pos).op(0)).get_name();
2405                                         if (name == "H") {
2406                                                 for (ex i=0; i<e.op(pos).op(1); i++) {
2407                                                         Hlst.append(e.op(pos).op(0));
2408                                                 }
2409                                                 continue;
2410                                         }
2411                                 } else if (is_a<function>(e.op(pos))) {
2412                                         std::string name = ex_to<function>(e.op(pos)).get_name();
2413                                         if (name == "H") {
2414                                                 if (e.op(pos).op(0).nops() > 1) {
2415                                                         firstH = e.op(pos);
2416                                                 } else {
2417                                                         Hlst.append(e.op(pos));
2418                                                 }
2419                                                 continue;
2420                                         }
2421                                 }
2422                                 result *= e.op(pos);
2423                         }
2424                         if (firstH == 0) {
2425                                 if (Hlst.nops() > 0) {
2426                                         firstH = Hlst[Hlst.nops()-1];
2427                                         Hlst.remove_last();
2428                                 } else {
2429                                         return e;
2430                                 }
2431                         }
2432
2433                         if (Hlst.nops() > 0) {
2434                                 ex buffer = trafo_H_mult(firstH, Hlst.op(0));
2435                                 result *= buffer;
2436                                 for (int i=1; i<Hlst.nops(); i++) {
2437                                         result *= Hlst.op(i);
2438                                 }
2439                                 result = result.expand();
2440                                 map_trafo_H_mult recursion;
2441                                 return recursion(result);
2442                         } else {
2443                                 return e;
2444                         }
2445
2446                 }
2447                 return e;
2448         }
2449 };
2450
2451
2452 // do integration [ReV] (55)
2453 // put parameter 0 in front of existing parameters
2454 ex trafo_H_1tx_prepend_zero(const ex& e, const ex& arg)
2455 {
2456         ex h;
2457         std::string name;
2458         if (is_a<function>(e)) {
2459                 name = ex_to<function>(e).get_name();
2460         }
2461         if (name == "H") {
2462                 h = e;
2463         } else {
2464                 for (int i=0; i<e.nops(); i++) {
2465                         if (is_a<function>(e.op(i))) {
2466                                 std::string name = ex_to<function>(e.op(i)).get_name();
2467                                 if (name == "H") {
2468                                         h = e.op(i);
2469                                 }
2470                         }
2471                 }
2472         }
2473         if (h != 0) {
2474                 lst newparameter = ex_to<lst>(h.op(0));
2475                 newparameter.prepend(0);
2476                 ex addzeta = convert_H_to_zeta(newparameter);
2477                 return e.subs(h == (addzeta-H(newparameter, h.op(1)).hold())).expand();
2478         } else {
2479                 return e * (-H(lst(0),1/arg).hold());
2480         }
2481 }
2482
2483
2484 // do integration [ReV] (49)
2485 // put parameter 1 in front of existing parameters
2486 ex trafo_H_prepend_one(const ex& e, const ex& arg)
2487 {
2488         ex h;
2489         std::string name;
2490         if (is_a<function>(e)) {
2491                 name = ex_to<function>(e).get_name();
2492         }
2493         if (name == "H") {
2494                 h = e;
2495         } else {
2496                 for (int i=0; i<e.nops(); i++) {
2497                         if (is_a<function>(e.op(i))) {
2498                                 std::string name = ex_to<function>(e.op(i)).get_name();
2499                                 if (name == "H") {
2500                                         h = e.op(i);
2501                                 }
2502                         }
2503                 }
2504         }
2505         if (h != 0) {
2506                 lst newparameter = ex_to<lst>(h.op(0));
2507                 newparameter.prepend(1);
2508                 return e.subs(h == H(newparameter, h.op(1)).hold());
2509         } else {
2510                 return e * H(lst(1),1-arg).hold();
2511         }
2512 }
2513
2514
2515 // do integration [ReV] (55)
2516 // put parameter -1 in front of existing parameters
2517 ex trafo_H_1tx_prepend_minusone(const ex& e, const ex& arg)
2518 {
2519         ex h;
2520         std::string name;
2521         if (is_a<function>(e)) {
2522                 name = ex_to<function>(e).get_name();
2523         }
2524         if (name == "H") {
2525                 h = e;
2526         } else {
2527                 for (int i=0; i<e.nops(); i++) {
2528                         if (is_a<function>(e.op(i))) {
2529                                 std::string name = ex_to<function>(e.op(i)).get_name();
2530                                 if (name == "H") {
2531                                         h = e.op(i);
2532                                 }
2533                         }
2534                 }
2535         }
2536         if (h != 0) {
2537                 lst newparameter = ex_to<lst>(h.op(0));
2538                 newparameter.prepend(-1);
2539                 ex addzeta = convert_H_to_zeta(newparameter);
2540                 return e.subs(h == (addzeta-H(newparameter, h.op(1)).hold())).expand();
2541         } else {
2542                 ex addzeta = convert_H_to_zeta(lst(-1));
2543                 return (e * (addzeta - H(lst(-1),1/arg).hold())).expand();
2544         }
2545 }
2546
2547
2548 // do integration [ReV] (55)
2549 // put parameter -1 in front of existing parameters
2550 ex trafo_H_1mxt1px_prepend_minusone(const ex& e, const ex& arg)
2551 {
2552         ex h;
2553         std::string name;
2554         if (is_a<function>(e)) {
2555                 name = ex_to<function>(e).get_name();
2556         }
2557         if (name == "H") {
2558                 h = e;
2559         } else {
2560                 for (int i=0; i<e.nops(); i++) {
2561                         if (is_a<function>(e.op(i))) {
2562                                 std::string name = ex_to<function>(e.op(i)).get_name();
2563                                 if (name == "H") {
2564                                         h = e.op(i);
2565                                 }
2566                         }
2567                 }
2568         }
2569         if (h != 0) {
2570                 lst newparameter = ex_to<lst>(h.op(0));
2571                 newparameter.prepend(-1);
2572                 return e.subs(h == H(newparameter, h.op(1)).hold()).expand();
2573         } else {
2574                 return (e * H(lst(-1),(1-arg)/(1+arg)).hold()).expand();
2575         }
2576 }
2577
2578
2579 // do integration [ReV] (55)
2580 // put parameter 1 in front of existing parameters
2581 ex trafo_H_1mxt1px_prepend_one(const ex& e, const ex& arg)
2582 {
2583         ex h;
2584         std::string name;
2585         if (is_a<function>(e)) {
2586                 name = ex_to<function>(e).get_name();
2587         }
2588         if (name == "H") {
2589                 h = e;
2590         } else {
2591                 for (int i=0; i<e.nops(); i++) {
2592                         if (is_a<function>(e.op(i))) {
2593                                 std::string name = ex_to<function>(e.op(i)).get_name();
2594                                 if (name == "H") {
2595                                         h = e.op(i);
2596                                 }
2597                         }
2598                 }
2599         }
2600         if (h != 0) {
2601                 lst newparameter = ex_to<lst>(h.op(0));
2602                 newparameter.prepend(1);
2603                 return e.subs(h == H(newparameter, h.op(1)).hold()).expand();
2604         } else {
2605                 return (e * H(lst(1),(1-arg)/(1+arg)).hold()).expand();
2606         }
2607 }
2608
2609
2610 // do x -> 1-x transformation
2611 struct map_trafo_H_1mx : public map_function
2612 {
2613         ex operator()(const ex& e)
2614         {
2615                 if (is_a<add>(e) || is_a<mul>(e)) {
2616                         return e.map(*this);
2617                 }
2618                 
2619                 if (is_a<function>(e)) {
2620                         std::string name = ex_to<function>(e).get_name();
2621                         if (name == "H") {
2622
2623                                 lst parameter = ex_to<lst>(e.op(0));
2624                                 ex arg = e.op(1);
2625
2626                                 // special cases if all parameters are either 0, 1 or -1
2627                                 bool allthesame = true;
2628                                 if (parameter.op(0) == 0) {
2629                                         for (int i=1; i<parameter.nops(); i++) {
2630                                                 if (parameter.op(i) != 0) {
2631                                                         allthesame = false;
2632                                                         break;
2633                                                 }
2634                                         }
2635                                         if (allthesame) {
2636                                                 lst newparameter;
2637                                                 for (int i=parameter.nops(); i>0; i--) {
2638                                                         newparameter.append(0);
2639                                                 }
2640                                                 return pow(-1, parameter.nops()) * H(newparameter, 1-arg).hold();
2641                                         }
2642                                 } else if (parameter.op(0) == -1) {
2643                                         throw std::runtime_error("map_trafo_H_1mx: cannot handle weights equal -1!");
2644                                 } else {
2645                                         for (int i=1; i<parameter.nops(); i++) {
2646                                                 if (parameter.op(i) != 1) {
2647                                                         allthesame = false;
2648                                                         break;
2649                                                 }
2650                                         }
2651                                         if (allthesame) {
2652                                                 lst newparameter;
2653                                                 for (int i=parameter.nops(); i>0; i--) {
2654                                                         newparameter.append(1);
2655                                                 }
2656                                                 return pow(-1, parameter.nops()) * H(newparameter, 1-arg).hold();
2657                                         }
2658                                 }
2659
2660                                 lst newparameter = parameter;
2661                                 newparameter.remove_first();
2662
2663                                 if (parameter.op(0) == 0) {
2664
2665                                         // leading zero
2666                                         ex res = convert_H_to_zeta(parameter);
2667                                         //ex res = convert_from_RV(parameter, 1).subs(H(wild(1),wild(2))==zeta(wild(1)));
2668                                         map_trafo_H_1mx recursion;
2669                                         ex buffer = recursion(H(newparameter, arg).hold());
2670                                         if (is_a<add>(buffer)) {
2671                                                 for (int i=0; i<buffer.nops(); i++) {
2672                                                         res -= trafo_H_prepend_one(buffer.op(i), arg);
2673                                                 }
2674                                         } else {
2675                                                 res -= trafo_H_prepend_one(buffer, arg);
2676                                         }
2677                                         return res;
2678
2679                                 } else {
2680
2681                                         // leading one
2682                                         map_trafo_H_1mx recursion;
2683                                         map_trafo_H_mult unify;
2684                                         ex res;
2685                                         int firstzero = 0;
2686                                         while (parameter.op(firstzero) == 1) {
2687                                                 firstzero++;
2688                                         }
2689                                         for (int i=firstzero-1; i<parameter.nops()-1; i++) {
2690                                                 lst newparameter;
2691                                                 int j=0;
2692                                                 for (; j<=i; j++) {
2693                                                         newparameter.append(parameter[j+1]);
2694                                                 }
2695                                                 newparameter.append(1);
2696                                                 for (; j<parameter.nops()-1; j++) {
2697                                                         newparameter.append(parameter[j+1]);
2698                                                 }
2699                                                 res -= H(newparameter, arg).hold();
2700                                         }
2701                                         return (unify((-H(lst(0), 1-arg).hold() * recursion(H(newparameter, arg).hold())).expand()) +
2702                                                         recursion(res)) / firstzero;
2703
2704                                 }
2705
2706                         }
2707                 }
2708                 return e;
2709         }
2710 };
2711
2712
2713 // do x -> 1/x transformation
2714 struct map_trafo_H_1overx : public map_function
2715 {
2716         ex operator()(const ex& e)
2717         {
2718                 if (is_a<add>(e) || is_a<mul>(e)) {
2719                         return e.map(*this);
2720                 }
2721
2722                 if (is_a<function>(e)) {
2723                         std::string name = ex_to<function>(e).get_name();
2724                         if (name == "H") {
2725
2726                                 lst parameter = ex_to<lst>(e.op(0));
2727                                 ex arg = e.op(1);
2728
2729                                 // special cases if all parameters are either 0, 1 or -1
2730                                 bool allthesame = true;
2731                                 if (parameter.op(0) == 0) {
2732                                         for (int i=1; i<parameter.nops(); i++) {
2733                                                 if (parameter.op(i) != 0) {
2734                                                         allthesame = false;
2735                                                         break;
2736                                                 }
2737                                         }
2738                                         if (allthesame) {
2739                                                 return pow(-1, parameter.nops()) * H(parameter, 1/arg).hold();
2740                                         }
2741                                 } else if (parameter.op(0) == -1) {
2742                                         for (int i=1; i<parameter.nops(); i++) {
2743                                                 if (parameter.op(i) != -1) {
2744                                                         allthesame = false;
2745                                                         break;
2746                                                 }
2747                                         }
2748                                         if (allthesame) {
2749                                                 map_trafo_H_mult unify;
2750                                                 return unify((pow(H(lst(-1),1/arg).hold() - H(lst(0),1/arg).hold(), parameter.nops())
2751                                                        / factorial(parameter.nops())).expand());
2752                                         }
2753                                 } else {
2754                                         for (int i=1; i<parameter.nops(); i++) {
2755                                                 if (parameter.op(i) != 1) {
2756                                                         allthesame = false;
2757                                                         break;
2758                                                 }
2759                                         }
2760                                         if (allthesame) {
2761                                                 map_trafo_H_mult unify;
2762                                                 return unify((pow(H(lst(1),1/arg).hold() + H(lst(0),1/arg).hold() + H_polesign, parameter.nops())
2763                                                        / factorial(parameter.nops())).expand());
2764                                         }
2765                                 }
2766
2767                                 lst newparameter = parameter;
2768                                 newparameter.remove_first();
2769
2770                                 if (parameter.op(0) == 0) {
2771                                         
2772                                         // leading zero
2773                                         ex res = convert_H_to_zeta(parameter);
2774                                         map_trafo_H_1overx recursion;
2775                                         ex buffer = recursion(H(newparameter, arg).hold());
2776                                         if (is_a<add>(buffer)) {
2777                                                 for (int i=0; i<buffer.nops(); i++) {
2778                                                         res += trafo_H_1tx_prepend_zero(buffer.op(i), arg);
2779                                                 }
2780                                         } else {
2781                                                 res += trafo_H_1tx_prepend_zero(buffer, arg);
2782                                         }
2783                                         return res;
2784
2785                                 } else if (parameter.op(0) == -1) {
2786
2787                                         // leading negative one
2788                                         ex res = convert_H_to_zeta(parameter);
2789                                         map_trafo_H_1overx recursion;
2790                                         ex buffer = recursion(H(newparameter, arg).hold());
2791                                         if (is_a<add>(buffer)) {
2792                                                 for (int i=0; i<buffer.nops(); i++) {
2793                                                         res += trafo_H_1tx_prepend_zero(buffer.op(i), arg) - trafo_H_1tx_prepend_minusone(buffer.op(i), arg);
2794                                                 }
2795                                         } else {
2796                                                 res += trafo_H_1tx_prepend_zero(buffer, arg) - trafo_H_1tx_prepend_minusone(buffer, arg);
2797                                         }
2798                                         return res;
2799
2800                                 } else {
2801
2802                                         // leading one
2803                                         map_trafo_H_1overx recursion;
2804                                         map_trafo_H_mult unify;
2805                                         ex res = H(lst(1), arg).hold() * H(newparameter, arg).hold();
2806                                         int firstzero = 0;
2807                                         while (parameter.op(firstzero) == 1) {
2808                                                 firstzero++;
2809                                         }
2810                                         for (int i=firstzero-1; i<parameter.nops()-1; i++) {
2811                                                 lst newparameter;
2812                                                 int j=0;
2813                                                 for (; j<=i; j++) {
2814                                                         newparameter.append(parameter[j+1]);
2815                                                 }
2816                                                 newparameter.append(1);
2817                                                 for (; j<parameter.nops()-1; j++) {
2818                                                         newparameter.append(parameter[j+1]);
2819                                                 }
2820                                                 res -= H(newparameter, arg).hold();
2821                                         }
2822                                         res = recursion(res).expand() / firstzero;
2823                                         return unify(res);
2824
2825                                 }
2826
2827                         }
2828                 }
2829                 return e;
2830         }
2831 };
2832
2833
2834 // do x -> (1-x)/(1+x) transformation
2835 struct map_trafo_H_1mxt1px : public map_function
2836 {
2837         ex operator()(const ex& e)
2838         {
2839                 if (is_a<add>(e) || is_a<mul>(e)) {
2840                         return e.map(*this);
2841                 }
2842
2843                 if (is_a<function>(e)) {
2844                         std::string name = ex_to<function>(e).get_name();
2845                         if (name == "H") {
2846
2847                                 lst parameter = ex_to<lst>(e.op(0));
2848                                 ex arg = e.op(1);
2849
2850                                 // special cases if all parameters are either 0, 1 or -1
2851                                 bool allthesame = true;
2852                                 if (parameter.op(0) == 0) {
2853                                         for (int i=1; i<parameter.nops(); i++) {
2854                                                 if (parameter.op(i) != 0) {
2855                                                         allthesame = false;
2856                                                         break;
2857                                                 }
2858                                         }
2859                                         if (allthesame) {
2860                                                 map_trafo_H_mult unify;
2861                                                 return unify((pow(-H(lst(1),(1-arg)/(1+arg)).hold() - H(lst(-1),(1-arg)/(1+arg)).hold(), parameter.nops())
2862                                                        / factorial(parameter.nops())).expand());
2863                                         }
2864                                 } else if (parameter.op(0) == -1) {
2865                                         for (int i=1; i<parameter.nops(); i++) {
2866                                                 if (parameter.op(i) != -1) {
2867                                                         allthesame = false;
2868                                                         break;
2869                                                 }
2870                                         }
2871                                         if (allthesame) {
2872                                                 map_trafo_H_mult unify;
2873                                                 return unify((pow(log(2) - H(lst(-1),(1-arg)/(1+arg)).hold(), parameter.nops())
2874                                                        / factorial(parameter.nops())).expand());
2875                                         }
2876                                 } else {
2877                                         for (int i=1; i<parameter.nops(); i++) {
2878                                                 if (parameter.op(i) != 1) {
2879                                                         allthesame = false;
2880                                                         break;
2881                                                 }
2882                                         }
2883                                         if (allthesame) {
2884                                                 map_trafo_H_mult unify;
2885                                                 return unify((pow(-log(2) - H(lst(0),(1-arg)/(1+arg)).hold() + H(lst(-1),(1-arg)/(1+arg)).hold(), parameter.nops())
2886                                                        / factorial(parameter.nops())).expand());
2887                                         }
2888                                 }
2889
2890                                 lst newparameter = parameter;
2891                                 newparameter.remove_first();
2892
2893                                 if (parameter.op(0) == 0) {
2894
2895                                         // leading zero
2896                                         ex res = convert_H_to_zeta(parameter);
2897                                         map_trafo_H_1mxt1px recursion;
2898                                         ex buffer = recursion(H(newparameter, arg).hold());
2899                                         if (is_a<add>(buffer)) {
2900                                                 for (int i=0; i<buffer.nops(); i++) {
2901                                                         res -= trafo_H_1mxt1px_prepend_one(buffer.op(i), arg) + trafo_H_1mxt1px_prepend_minusone(buffer.op(i), arg);
2902                                                 }
2903                                         } else {
2904                                                 res -= trafo_H_1mxt1px_prepend_one(buffer, arg) + trafo_H_1mxt1px_prepend_minusone(buffer, arg);
2905                                         }
2906                                         return res;
2907
2908                                 } else if (parameter.op(0) == -1) {
2909
2910                                         // leading negative one
2911                                         ex res = convert_H_to_zeta(parameter);
2912                                         map_trafo_H_1mxt1px recursion;
2913                                         ex buffer = recursion(H(newparameter, arg).hold());
2914                                         if (is_a<add>(buffer)) {
2915                                                 for (int i=0; i<buffer.nops(); i++) {
2916                                                         res -= trafo_H_1mxt1px_prepend_minusone(buffer.op(i), arg);
2917                                                 }
2918                                         } else {
2919                                                 res -= trafo_H_1mxt1px_prepend_minusone(buffer, arg);
2920                                         }
2921                                         return res;
2922
2923                                 } else {
2924
2925                                         // leading one
2926                                         map_trafo_H_1mxt1px recursion;
2927                                         map_trafo_H_mult unify;
2928                                         ex res = H(lst(1), arg).hold() * H(newparameter, arg).hold();
2929                                         int firstzero = 0;
2930                                         while (parameter.op(firstzero) == 1) {
2931                                                 firstzero++;
2932                                         }
2933                                         for (int i=firstzero-1; i<parameter.nops()-1; i++) {
2934                                                 lst newparameter;
2935                                                 int j=0;
2936                                                 for (; j<=i; j++) {
2937                                                         newparameter.append(parameter[j+1]);
2938                                                 }
2939                                                 newparameter.append(1);
2940                                                 for (; j<parameter.nops()-1; j++) {
2941                                                         newparameter.append(parameter[j+1]);
2942                                                 }
2943                                                 res -= H(newparameter, arg).hold();
2944                                         }
2945                                         res = recursion(res).expand() / firstzero;
2946                                         return unify(res);
2947
2948                                 }
2949
2950                         }
2951                 }
2952                 return e;
2953         }
2954 };
2955
2956
2957 // do the actual summation.
2958 cln::cl_N H_do_sum(const std::vector<int>& m, const cln::cl_N& x)
2959 {
2960         const int j = m.size();
2961
2962         std::vector<cln::cl_N> t(j);
2963
2964         cln::cl_F one = cln::cl_float(1, cln::float_format(Digits));
2965         cln::cl_N factor = cln::expt(x, j) * one;
2966         cln::cl_N t0buf;
2967         int q = 0;
2968         do {
2969                 t0buf = t[0];
2970                 q++;
2971                 t[j-1] = t[j-1] + 1 / cln::expt(cln::cl_I(q),m[j-1]);
2972                 for (int k=j-2; k>=1; k--) {
2973                         t[k] = t[k] + t[k+1] / cln::expt(cln::cl_I(q+j-1-k), m[k]);
2974                 }
2975                 t[0] = t[0] + t[1] * factor / cln::expt(cln::cl_I(q+j-1), m[0]);
2976                 factor = factor * x;
2977         } while (t[0] != t0buf);
2978
2979         return t[0];
2980 }
2981
2982
2983 } // end of anonymous namespace
2984
2985
2986 //////////////////////////////////////////////////////////////////////
2987 //
2988 // Harmonic polylogarithm  H(m,x)
2989 //
2990 // GiNaC function
2991 //
2992 //////////////////////////////////////////////////////////////////////
2993
2994
2995 static ex H_evalf(const ex& x1, const ex& x2)
2996 {
2997         if (is_a<lst>(x1)) {
2998                 
2999                 cln::cl_N x;
3000                 if (is_a<numeric>(x2)) {
3001                         x = ex_to<numeric>(x2).to_cl_N();
3002                 } else {
3003                         ex x2_val = x2.evalf();
3004                         if (is_a<numeric>(x2_val)) {
3005                                 x = ex_to<numeric>(x2_val).to_cl_N();
3006                         }
3007                 }
3008
3009                 for (int i=0; i<x1.nops(); i++) {
3010                         if (!x1.op(i).info(info_flags::integer)) {
3011                                 return H(x1, x2).hold();
3012                         }
3013                 }
3014                 if (x1.nops() < 1) {
3015                         return H(x1, x2).hold();
3016                 }
3017
3018                 const lst& morg = ex_to<lst>(x1);
3019                 // remove trailing zeros ...
3020                 if (*(--morg.end()) == 0) {
3021                         symbol xtemp("xtemp");
3022                         map_trafo_H_reduce_trailing_zeros filter;
3023                         return filter(H(x1, xtemp).hold()).subs(xtemp==x2).evalf();
3024                 }
3025                 // ... and expand parameter notation
3026                 bool has_minus_one = false;
3027                 lst m;
3028                 for (lst::const_iterator it = morg.begin(); it != morg.end(); it++) {
3029                         if (*it > 1) {
3030                                 for (ex count=*it-1; count > 0; count--) {
3031                                         m.append(0);
3032                                 }
3033                                 m.append(1);
3034                         } else if (*it <= -1) {
3035                                 for (ex count=*it+1; count < 0; count++) {
3036                                         m.append(0);
3037                                 }
3038                                 m.append(-1);
3039                                 has_minus_one = true;
3040                         } else {
3041                                 m.append(*it);
3042                         }
3043                 }
3044
3045                 // do summation
3046                 if (cln::abs(x) < 0.95) {
3047                         lst m_lst;
3048                         lst s_lst;
3049                         ex pf;
3050                         if (convert_parameter_H_to_Li(m, m_lst, s_lst, pf)) {
3051                                 // negative parameters -> s_lst is filled
3052                                 std::vector<int> m_int;
3053                                 std::vector<cln::cl_N> x_cln;
3054                                 for (lst::const_iterator it_int = m_lst.begin(), it_cln = s_lst.begin(); 
3055                                      it_int != m_lst.end(); it_int++, it_cln++) {
3056                                         m_int.push_back(ex_to<numeric>(*it_int).to_int());
3057                                         x_cln.push_back(ex_to<numeric>(*it_cln).to_cl_N());
3058                                 }
3059                                 x_cln.front() = x_cln.front() * x;
3060                                 return pf * numeric(multipleLi_do_sum(m_int, x_cln));
3061                         } else {
3062                                 // only positive parameters
3063                                 //TODO
3064                                 if (m_lst.nops() == 1) {
3065                                         return Li(m_lst.op(0), x2).evalf();
3066                                 }
3067                                 std::vector<int> m_int;
3068                                 for (lst::const_iterator it = m_lst.begin(); it != m_lst.end(); it++) {
3069                                         m_int.push_back(ex_to<numeric>(*it).to_int());
3070                                 }
3071                                 return numeric(H_do_sum(m_int, x));
3072                         }
3073                 }
3074
3075                 symbol xtemp("xtemp");
3076                 ex res = 1;     
3077                 
3078                 // ensure that the realpart of the argument is positive
3079                 if (cln::realpart(x) < 0) {
3080                         x = -x;
3081                         for (int i=0; i<m.nops(); i++) {
3082                                 if (m.op(i) != 0) {
3083                                         m.let_op(i) = -m.op(i);
3084                                         res *= -1;
3085                                 }
3086                         }
3087                 }
3088
3089                 // x -> 1/x
3090                 if (cln::abs(x) >= 2.0) {
3091                         map_trafo_H_1overx trafo;
3092                         res *= trafo(H(m, xtemp));
3093                         if (cln::imagpart(x) <= 0) {
3094                                 res = res.subs(H_polesign == -I*Pi);
3095                         } else {
3096                                 res = res.subs(H_polesign == I*Pi);
3097                         }
3098                         return res.subs(xtemp == numeric(x)).evalf();
3099                 }
3100                 
3101                 // check transformations for 0.95 <= |x| < 2.0
3102                 
3103                 // |(1-x)/(1+x)| < 0.9 -> circular area with center=9,53+0i and radius=9.47
3104                 if (cln::abs(x-9.53) <= 9.47) {
3105                         // x -> (1-x)/(1+x)
3106                         map_trafo_H_1mxt1px trafo;
3107                         res *= trafo(H(m, xtemp));
3108                 } else {
3109                         // x -> 1-x
3110                         if (has_minus_one) {
3111                                 map_trafo_H_convert_to_Li filter;
3112                                 return filter(H(m, numeric(x)).hold()).evalf();
3113                         }
3114                         map_trafo_H_1mx trafo;
3115                         res *= trafo(H(m, xtemp));
3116                 }
3117
3118                 return res.subs(xtemp == numeric(x)).evalf();
3119         }
3120
3121         return H(x1,x2).hold();
3122 }
3123
3124
3125 static ex H_eval(const ex& m_, const ex& x)
3126 {
3127         lst m;
3128         if (is_a<lst>(m_)) {
3129                 m = ex_to<lst>(m_);
3130         } else {
3131                 m = lst(m_);
3132         }
3133         if (m.nops() == 0) {
3134                 return _ex1;
3135         }
3136         ex pos1;
3137         ex pos2;
3138         ex n;
3139         ex p;
3140         int step = 0;
3141         if (*m.begin() > _ex1) {
3142                 step++;
3143                 pos1 = _ex0;
3144                 pos2 = _ex1;
3145                 n = *m.begin()-1;
3146                 p = _ex1;
3147         } else if (*m.begin() < _ex_1) {
3148                 step++;
3149                 pos1 = _ex0;
3150                 pos2 = _ex_1;
3151                 n = -*m.begin()-1;
3152                 p = _ex1;
3153         } else if (*m.begin() == _ex0) {
3154                 pos1 = _ex0;
3155                 n = _ex1;
3156         } else {
3157                 pos1 = *m.begin();
3158                 p = _ex1;
3159         }
3160         for (lst::const_iterator it = ++m.begin(); it != m.end(); it++) {
3161                 if ((*it).info(info_flags::integer)) {
3162                         if (step == 0) {
3163                                 if (*it > _ex1) {
3164                                         if (pos1 == _ex0) {
3165                                                 step = 1;
3166                                                 pos2 = _ex1;
3167                                                 n += *it-1;
3168                                                 p = _ex1;
3169                                         } else {
3170                                                 step = 2;
3171                                         }
3172                                 } else if (*it < _ex_1) {
3173                                         if (pos1 == _ex0) {
3174                                                 step = 1;
3175                                                 pos2 = _ex_1;
3176                                                 n += -*it-1;
3177                                                 p = _ex1;
3178                                         } else {
3179                                                 step = 2;
3180                                         }
3181                                 } else {
3182                                         if (*it != pos1) {
3183                                                 step = 1;
3184                                                 pos2 = *it;
3185                                         }
3186                                         if (*it == _ex0) {
3187                                                 n++;
3188                                         } else {
3189                                                 p++;
3190                                         }
3191                                 }
3192                         } else if (step == 1) {
3193                                 if (*it != pos2) {
3194                                         step = 2;
3195                                 } else {
3196                                         if (*it == _ex0) {
3197                                                 n++;
3198                                         } else {
3199                                                 p++;
3200                                         }
3201                                 }
3202                         }
3203                 } else {
3204                         // if some m_i is not an integer
3205                         return H(m_, x).hold();
3206                 }
3207         }
3208         if ((x == _ex1) && (*(--m.end()) != _ex0)) {
3209                 return convert_H_to_zeta(m);
3210         }
3211         if (step == 0) {
3212                 if (pos1 == _ex0) {
3213                         // all zero
3214                         if (x == _ex0) {
3215                                 return H(m_, x).hold();
3216                         }
3217                         return pow(log(x), m.nops()) / factorial(m.nops());
3218                 } else {
3219                         // all (minus) one
3220                         return pow(-pos1*log(1-pos1*x), m.nops()) / factorial(m.nops());
3221                 }
3222         } else if ((step == 1) && (pos1 == _ex0)){
3223                 // convertible to S
3224                 if (pos2 == _ex1) {
3225                         return S(n, p, x);
3226                 } else {
3227                         return pow(-1, p) * S(n, p, -x);
3228                 }
3229         }
3230         if (x == _ex0) {
3231                 return _ex0;
3232         }
3233         if (x.info(info_flags::numeric) && (!x.info(info_flags::crational))) {
3234                 return H(m_, x).evalf();
3235         }
3236         return H(m_, x).hold();
3237 }
3238
3239
3240 static ex H_series(const ex& m, const ex& x, const relational& rel, int order, unsigned options)
3241 {
3242         epvector seq;
3243         seq.push_back(expair(H(m, x), 0));
3244         return pseries(rel, seq);
3245 }
3246
3247
3248 static ex H_deriv(const ex& m_, const ex& x, unsigned deriv_param)
3249 {
3250         GINAC_ASSERT(deriv_param < 2);
3251         if (deriv_param == 0) {
3252                 return _ex0;
3253         }
3254         lst m;
3255         if (is_a<lst>(m_)) {
3256                 m = ex_to<lst>(m_);
3257         } else {
3258                 m = lst(m_);
3259         }
3260         ex mb = *m.begin();
3261         if (mb > _ex1) {
3262                 m[0]--;
3263                 return H(m, x) / x;
3264         }
3265         if (mb < _ex_1) {
3266                 m[0]++;
3267                 return H(m, x) / x;
3268         }
3269         m.remove_first();
3270         if (mb == _ex1) {
3271                 return 1/(1-x) * H(m, x);
3272         } else if (mb == _ex_1) {
3273                 return 1/(1+x) * H(m, x);
3274         } else {
3275                 return H(m, x) / x;
3276         }
3277 }
3278
3279
3280 static void H_print_latex(const ex& m_, const ex& x, const print_context& c)
3281 {
3282         lst m;
3283         if (is_a<lst>(m_)) {
3284                 m = ex_to<lst>(m_);
3285         } else {
3286                 m = lst(m_);
3287         }
3288         c.s << "\\mbox{H}_{";
3289         lst::const_iterator itm = m.begin();
3290         (*itm).print(c);
3291         itm++;
3292         for (; itm != m.end(); itm++) {
3293                 c.s << ",";
3294                 (*itm).print(c);
3295         }
3296         c.s << "}(";
3297         x.print(c);
3298         c.s << ")";
3299 }
3300
3301
3302 REGISTER_FUNCTION(H,
3303                   evalf_func(H_evalf).
3304                   eval_func(H_eval).
3305                   series_func(H_series).
3306                   derivative_func(H_deriv).
3307                   print_func<print_latex>(H_print_latex).
3308                   do_not_evalf_params());
3309
3310
3311 // takes a parameter list for H and returns an expression with corresponding multiple polylogarithms
3312 ex convert_H_to_Li(const ex& m, const ex& x)
3313 {
3314         map_trafo_H_reduce_trailing_zeros filter;
3315         map_trafo_H_convert_to_Li filter2;
3316         if (is_a<lst>(m)) {
3317                 return filter2(filter(H(m, x).hold()));
3318         } else {
3319                 return filter2(filter(H(lst(m), x).hold()));
3320         }
3321 }
3322
3323
3324 //////////////////////////////////////////////////////////////////////
3325 //
3326 // Multiple zeta values  zeta(x) and zeta(x,s)
3327 //
3328 // helper functions
3329 //
3330 //////////////////////////////////////////////////////////////////////
3331
3332
3333 // anonymous namespace for helper functions
3334 namespace {
3335
3336
3337 // parameters and data for [Cra] algorithm
3338 const cln::cl_N lambda = cln::cl_N("319/320");
3339 int L1;
3340 int L2;
3341 std::vector<std::vector<cln::cl_N> > f_kj;
3342 std::vector<cln::cl_N> crB;
3343 std::vector<std::vector<cln::cl_N> > crG;
3344 std::vector<cln::cl_N> crX;
3345
3346
3347 void halfcyclic_convolute(const std::vector<cln::cl_N>& a, const std::vector<cln::cl_N>& b, std::vector<cln::cl_N>& c)
3348 {
3349         const int size = a.size();
3350         for (int n=0; n<size; n++) {
3351                 c[n] = 0;
3352                 for (int m=0; m<=n; m++) {
3353                         c[n] = c[n] + a[m]*b[n-m];
3354                 }
3355         }
3356 }
3357
3358
3359 // [Cra] section 4
3360 void initcX(const std::vector<int>& s)
3361 {
3362         const int k = s.size();
3363
3364         crX.clear();
3365         crG.clear();
3366         crB.clear();
3367
3368         for (int i=0; i<=L2; i++) {
3369                 crB.push_back(bernoulli(i).to_cl_N() / cln::factorial(i));
3370         }
3371
3372         int Sm = 0;
3373         int Smp1 = 0;
3374         for (int m=0; m<k-1; m++) {
3375                 std::vector<cln::cl_N> crGbuf;
3376                 Sm = Sm + s[m];
3377                 Smp1 = Sm + s[m+1];
3378                 for (int i=0; i<=L2; i++) {
3379                         crGbuf.push_back(cln::factorial(i + Sm - m - 2) / cln::factorial(i + Smp1 - m - 2));
3380                 }
3381                 crG.push_back(crGbuf);
3382         }
3383
3384         crX = crB;
3385
3386         for (int m=0; m<k-1; m++) {
3387                 std::vector<cln::cl_N> Xbuf;
3388                 for (int i=0; i<=L2; i++) {
3389                         Xbuf.push_back(crX[i] * crG[m][i]);
3390                 }
3391                 halfcyclic_convolute(Xbuf, crB, crX);
3392         }
3393 }
3394
3395
3396 // [Cra] section 4
3397 cln::cl_N crandall_Y_loop(const cln::cl_N& Sqk)
3398 {
3399         cln::cl_F one = cln::cl_float(1, cln::float_format(Digits));
3400         cln::cl_N factor = cln::expt(lambda, Sqk);
3401         cln::cl_N res = factor / Sqk * crX[0] * one;
3402         cln::cl_N resbuf;
3403         int N = 0;
3404         do {
3405                 resbuf = res;
3406                 factor = factor * lambda;
3407                 N++;
3408                 res = res + crX[N] * factor / (N+Sqk);
3409         } while ((res != resbuf) || cln::zerop(crX[N]));
3410         return res;
3411 }
3412
3413
3414 // [Cra] section 4
3415 void calc_f(int maxr)
3416 {
3417         f_kj.clear();
3418         f_kj.resize(L1);
3419         
3420         cln::cl_N t0, t1, t2, t3, t4;
3421         int i, j, k;
3422         std::vector<std::vector<cln::cl_N> >::iterator it = f_kj.begin();
3423         cln::cl_F one = cln::cl_float(1, cln::float_format(Digits));
3424         
3425         t0 = cln::exp(-lambda);
3426         t2 = 1;
3427         for (k=1; k<=L1; k++) {
3428                 t1 = k * lambda;
3429                 t2 = t0 * t2;
3430                 for (j=1; j<=maxr; j++) {
3431                         t3 = 1;
3432                         t4 = 1;
3433                         for (i=2; i<=j; i++) {
3434                                 t4 = t4 * (j-i+1);
3435                                 t3 = t1 * t3 + t4;
3436                         }
3437                         (*it).push_back(t2 * t3 * cln::expt(cln::cl_I(k),-j) * one);
3438                 }
3439                 it++;
3440         }
3441 }
3442
3443
3444 // [Cra] (3.1)
3445 cln::cl_N crandall_Z(const std::vector<int>& s)
3446 {
3447         const int j = s.size();
3448
3449         if (j == 1) {   
3450                 cln::cl_N t0;
3451                 cln::cl_N t0buf;
3452                 int q = 0;
3453                 do {
3454                         t0buf = t0;
3455                         q++;
3456                         t0 = t0 + f_kj[q+j-2][s[0]-1];
3457                 } while (t0 != t0buf);
3458                 
3459                 return t0 / cln::factorial(s[0]-1);
3460         }
3461
3462         std::vector<cln::cl_N> t(j);
3463
3464         cln::cl_N t0buf;
3465         int q = 0;
3466         do {
3467                 t0buf = t[0];
3468                 q++;
3469                 t[j-1] = t[j-1] + 1 / cln::expt(cln::cl_I(q),s[j-1]);
3470                 for (int k=j-2; k>=1; k--) {
3471                         t[k] = t[k] + t[k+1] / cln::expt(cln::cl_I(q+j-1-k), s[k]);
3472                 }
3473                 t[0] = t[0] + t[1] * f_kj[q+j-2][s[0]-1];
3474         } while (t[0] != t0buf);
3475         
3476         return t[0] / cln::factorial(s[0]-1);
3477 }
3478
3479
3480 // [Cra] (2.4)
3481 cln::cl_N zeta_do_sum_Crandall(const std::vector<int>& s)
3482 {
3483         std::vector<int> r = s;
3484         const int j = r.size();
3485
3486         // decide on maximal size of f_kj for crandall_Z
3487         if (Digits < 50) {
3488                 L1 = 150;
3489         } else {
3490                 L1 = Digits * 3 + j*2;
3491         }
3492
3493         // decide on maximal size of crX for crandall_Y
3494         if (Digits < 38) {
3495                 L2 = 63;
3496         } else if (Digits < 86) {
3497                 L2 = 127;
3498         } else if (Digits < 192) {
3499                 L2 = 255;
3500         } else if (Digits < 394) {
3501                 L2 = 511;
3502         } else if (Digits < 808) {
3503                 L2 = 1023;
3504         } else {
3505                 L2 = 2047;
3506         }
3507
3508         cln::cl_N res;
3509
3510         int maxr = 0;
3511         int S = 0;
3512         for (int i=0; i<j; i++) {
3513                 S += r[i];
3514                 if (r[i] > maxr) {
3515                         maxr = r[i];
3516                 }
3517         }
3518
3519         calc_f(maxr);
3520
3521         const cln::cl_N r0factorial = cln::factorial(r[0]-1);
3522
3523         std::vector<int> rz;
3524         int skp1buf;
3525         int Srun = S;
3526         for (int k=r.size()-1; k>0; k--) {
3527
3528                 rz.insert(rz.begin(), r.back());
3529                 skp1buf = rz.front();
3530                 Srun -= skp1buf;
3531                 r.pop_back();
3532
3533                 initcX(r);
3534                 
3535                 for (int q=0; q<skp1buf; q++) {
3536                         
3537                         cln::cl_N pp1 = crandall_Y_loop(Srun+q-k);
3538                         cln::cl_N pp2 = crandall_Z(rz);
3539
3540                         rz.front()--;
3541                         
3542                         if (q & 1) {
3543                                 res = res - pp1 * pp2 / cln::factorial(q);
3544                         } else {
3545                                 res = res + pp1 * pp2 / cln::factorial(q);
3546                         }
3547                 }
3548                 rz.front() = skp1buf;
3549         }
3550         rz.insert(rz.begin(), r.back());
3551
3552         initcX(rz);
3553
3554         res = (res + crandall_Y_loop(S-j)) / r0factorial + crandall_Z(rz);
3555
3556         return res;
3557 }
3558
3559
3560 cln::cl_N zeta_do_sum_simple(const std::vector<int>& r)
3561 {
3562         const int j = r.size();
3563
3564         // buffer for subsums
3565         std::vector<cln::cl_N> t(j);
3566         cln::cl_F one = cln::cl_float(1, cln::float_format(Digits));
3567
3568         cln::cl_N t0buf;
3569         int q = 0;
3570         do {
3571                 t0buf = t[0];
3572                 q++;
3573                 t[j-1] = t[j-1] + one / cln::expt(cln::cl_I(q),r[j-1]);
3574                 for (int k=j-2; k>=0; k--) {
3575                         t[k] = t[k] + one * t[k+1] / cln::expt(cln::cl_I(q+j-1-k), r[k]);
3576                 }
3577         } while (t[0] != t0buf);
3578
3579         return t[0];
3580 }
3581
3582
3583 // does Hoelder convolution. see [BBB] (7.0)
3584 cln::cl_N zeta_do_Hoelder_convolution(const std::vector<int>& m_, const std::vector<int>& s_)
3585 {
3586         // prepare parameters
3587         // holds Li arguments in [BBB] notation
3588         std::vector<int> s = s_;
3589         std::vector<int> m_p = m_;
3590         std::vector<int> m_q;
3591         // holds Li arguments in nested sums notation
3592         std::vector<cln::cl_N> s_p(s.size(), cln::cl_N(1));
3593         s_p[0] = s_p[0] * cln::cl_N("1/2");
3594         // convert notations
3595         int sig = 1;
3596         for (int i=0; i<s_.size(); i++) {
3597                 if (s_[i] < 0) {
3598                         sig = -sig;
3599                         s_p[i] = -s_p[i];
3600                 }
3601                 s[i] = sig * std::abs(s[i]);
3602         }
3603         std::vector<cln::cl_N> s_q;
3604         cln::cl_N signum = 1;
3605
3606         // first term
3607         cln::cl_N res = multipleLi_do_sum(m_p, s_p);
3608
3609         // middle terms
3610         do {
3611
3612                 // change parameters
3613                 if (s.front() > 0) {
3614                         if (m_p.front() == 1) {
3615                                 m_p.erase(m_p.begin());
3616                                 s_p.erase(s_p.begin());
3617                                 if (s_p.size() > 0) {
3618                                         s_p.front() = s_p.front() * cln::cl_N("1/2");
3619                                 }
3620                                 s.erase(s.begin());
3621                                 m_q.front()++;
3622                         } else {
3623                                 m_p.front()--;
3624                                 m_q.insert(m_q.begin(), 1);
3625                                 if (s_q.size() > 0) {
3626                                         s_q.front() = s_q.front() * 2;
3627                                 }
3628                                 s_q.insert(s_q.begin(), cln::cl_N("1/2"));
3629                         }
3630                 } else {
3631                         if (m_p.front() == 1) {
3632                                 m_p.erase(m_p.begin());
3633                                 cln::cl_N spbuf = s_p.front();
3634                                 s_p.erase(s_p.begin());
3635                                 if (s_p.size() > 0) {
3636                                         s_p.front() = s_p.front() * spbuf;
3637                                 }
3638                                 s.erase(s.begin());
3639                                 m_q.insert(m_q.begin(), 1);
3640                                 if (s_q.size() > 0) {
3641                                         s_q.front() = s_q.front() * 4;
3642                                 }
3643                                 s_q.insert(s_q.begin(), cln::cl_N("1/4"));
3644                                 signum = -signum;
3645                         } else {
3646                                 m_p.front()--;
3647                                 m_q.insert(m_q.begin(), 1);
3648                                 if (s_q.size() > 0) {
3649                                         s_q.front() = s_q.front() * 2;
3650                                 }
3651                                 s_q.insert(s_q.begin(), cln::cl_N("1/2"));
3652                         }
3653                 }
3654
3655                 // exiting the loop
3656                 if (m_p.size() == 0) break;
3657
3658                 res = res + signum * multipleLi_do_sum(m_p, s_p) * multipleLi_do_sum(m_q, s_q);
3659
3660         } while (true);
3661
3662         // last term
3663         res = res + signum * multipleLi_do_sum(m_q, s_q);
3664
3665         return res;
3666 }
3667
3668
3669 } // end of anonymous namespace
3670
3671
3672 //////////////////////////////////////////////////////////////////////
3673 //
3674 // Multiple zeta values  zeta(x)
3675 //
3676 // GiNaC function
3677 //
3678 //////////////////////////////////////////////////////////////////////
3679
3680
3681 static ex zeta1_evalf(const ex& x)
3682 {
3683         if (is_exactly_a<lst>(x) && (x.nops()>1)) {
3684
3685                 // multiple zeta value
3686                 const int count = x.nops();
3687                 const lst& xlst = ex_to<lst>(x);
3688                 std::vector<int> r(count);
3689
3690                 // check parameters and convert them
3691                 lst::const_iterator it1 = xlst.begin();
3692                 std::vector<int>::iterator it2 = r.begin();
3693                 do {
3694                         if (!(*it1).info(info_flags::posint)) {
3695                                 return zeta(x).hold();
3696                         }
3697                         *it2 = ex_to<numeric>(*it1).to_int();
3698                         it1++;
3699                         it2++;
3700                 } while (it2 != r.end());
3701
3702                 // check for divergence
3703                 if (r[0] == 1) {
3704                         return zeta(x).hold();
3705                 }
3706
3707                 // decide on summation algorithm
3708                 // this is still a bit clumsy
3709                 int limit = (Digits>17) ? 10 : 6;
3710                 if ((r[0] < limit) || ((count > 3) && (r[1] < limit/2))) {
3711                         return numeric(zeta_do_sum_Crandall(r));
3712                 } else {
3713                         return numeric(zeta_do_sum_simple(r));
3714                 }
3715         }
3716
3717         // single zeta value
3718         if (is_exactly_a<numeric>(x) && (x != 1)) {
3719                 try {
3720                         return zeta(ex_to<numeric>(x));
3721                 } catch (const dunno &e) { }
3722         }
3723
3724         return zeta(x).hold();
3725 }
3726
3727
3728 static ex zeta1_eval(const ex& m)
3729 {
3730         if (is_exactly_a<lst>(m)) {
3731                 if (m.nops() == 1) {
3732                         return zeta(m.op(0));
3733                 }
3734                 return zeta(m).hold();
3735         }
3736
3737         if (m.info(info_flags::numeric)) {
3738                 const numeric& y = ex_to<numeric>(m);
3739                 // trap integer arguments:
3740                 if (y.is_integer()) {
3741                         if (y.is_zero()) {
3742                                 return _ex_1_2;
3743                         }
3744                         if (y.is_equal(*_num1_p)) {
3745                                 return zeta(m).hold();
3746                         }
3747                         if (y.info(info_flags::posint)) {
3748                                 if (y.info(info_flags::odd)) {
3749                                         return zeta(m).hold();
3750                                 } else {
3751                                         return abs(bernoulli(y)) * pow(Pi, y) * pow(*_num2_p, y-(*_num1_p)) / factorial(y);
3752                                 }
3753                         } else {
3754                                 if (y.info(info_flags::odd)) {
3755                                         return -bernoulli((*_num1_p)-y) / ((*_num1_p)-y);
3756                                 } else {
3757                                         return _ex0;
3758                                 }
3759                         }
3760                 }
3761                 // zeta(float)
3762                 if (y.info(info_flags::numeric) && !y.info(info_flags::crational)) {
3763                         return zeta1_evalf(m);
3764                 }
3765         }
3766         return zeta(m).hold();
3767 }
3768
3769
3770 static ex zeta1_deriv(const ex& m, unsigned deriv_param)
3771 {
3772         GINAC_ASSERT(deriv_param==0);
3773
3774         if (is_exactly_a<lst>(m)) {
3775                 return _ex0;
3776         } else {
3777                 return zetaderiv(_ex1, m);
3778         }
3779 }
3780
3781
3782 static void zeta1_print_latex(const ex& m_, const print_context& c)
3783 {
3784         c.s << "\\zeta(";
3785         if (is_a<lst>(m_)) {
3786                 const lst& m = ex_to<lst>(m_);
3787                 lst::const_iterator it = m.begin();
3788                 (*it).print(c);
3789                 it++;
3790                 for (; it != m.end(); it++) {
3791                         c.s << ",";
3792                         (*it).print(c);
3793                 }
3794         } else {
3795                 m_.print(c);
3796         }
3797         c.s << ")";
3798 }
3799
3800
3801 unsigned zeta1_SERIAL::serial = function::register_new(function_options("zeta", 1).
3802                                 evalf_func(zeta1_evalf).
3803                                 eval_func(zeta1_eval).
3804                                 derivative_func(zeta1_deriv).
3805                                 print_func<print_latex>(zeta1_print_latex).
3806                                 do_not_evalf_params().
3807                                 overloaded(2));
3808
3809
3810 //////////////////////////////////////////////////////////////////////
3811 //
3812 // Alternating Euler sum  zeta(x,s)
3813 //
3814 // GiNaC function
3815 //
3816 //////////////////////////////////////////////////////////////////////
3817
3818
3819 static ex zeta2_evalf(const ex& x, const ex& s)
3820 {
3821         if (is_exactly_a<lst>(x)) {
3822
3823                 // alternating Euler sum
3824                 const int count = x.nops();
3825                 const lst& xlst = ex_to<lst>(x);
3826                 const lst& slst = ex_to<lst>(s);
3827                 std::vector<int> xi(count);
3828                 std::vector<int> si(count);
3829
3830                 // check parameters and convert them
3831                 lst::const_iterator it_xread = xlst.begin();
3832                 lst::const_iterator it_sread = slst.begin();
3833                 std::vector<int>::iterator it_xwrite = xi.begin();
3834                 std::vector<int>::iterator it_swrite = si.begin();
3835                 do {
3836                         if (!(*it_xread).info(info_flags::posint)) {
3837                                 return zeta(x, s).hold();
3838                         }
3839                         *it_xwrite = ex_to<numeric>(*it_xread).to_int();
3840                         if (*it_sread > 0) {
3841                                 *it_swrite = 1;
3842                         } else {
3843                                 *it_swrite = -1;
3844                         }
3845                         it_xread++;
3846                         it_sread++;
3847                         it_xwrite++;
3848                         it_swrite++;
3849                 } while (it_xwrite != xi.end());
3850
3851                 // check for divergence
3852                 if ((xi[0] == 1) && (si[0] == 1)) {
3853                         return zeta(x, s).hold();
3854                 }
3855
3856                 // use Hoelder convolution
3857                 return numeric(zeta_do_Hoelder_convolution(xi, si));
3858         }
3859
3860         return zeta(x, s).hold();
3861 }
3862
3863
3864 static ex zeta2_eval(const ex& m, const ex& s_)
3865 {
3866         if (is_exactly_a<lst>(s_)) {
3867                 const lst& s = ex_to<lst>(s_);
3868                 for (lst::const_iterator it = s.begin(); it != s.end(); it++) {
3869                         if ((*it).info(info_flags::positive)) {
3870                                 continue;
3871                         }
3872                         return zeta(m, s_).hold();
3873                 }
3874                 return zeta(m);
3875         } else if (s_.info(info_flags::positive)) {
3876                 return zeta(m);
3877         }
3878
3879         return zeta(m, s_).hold();
3880 }
3881
3882
3883 static ex zeta2_deriv(const ex& m, const ex& s, unsigned deriv_param)
3884 {
3885         GINAC_ASSERT(deriv_param==0);
3886
3887         if (is_exactly_a<lst>(m)) {
3888                 return _ex0;
3889         } else {
3890                 if ((is_exactly_a<lst>(s) && s.op(0).info(info_flags::positive)) || s.info(info_flags::positive)) {
3891                         return zetaderiv(_ex1, m);
3892                 }
3893                 return _ex0;
3894         }
3895 }
3896
3897
3898 static void zeta2_print_latex(const ex& m_, const ex& s_, const print_context& c)
3899 {
3900         lst m;
3901         if (is_a<lst>(m_)) {
3902                 m = ex_to<lst>(m_);
3903         } else {
3904                 m = lst(m_);
3905         }
3906         lst s;
3907         if (is_a<lst>(s_)) {
3908                 s = ex_to<lst>(s_);
3909         } else {
3910                 s = lst(s_);
3911         }
3912         c.s << "\\zeta(";
3913         lst::const_iterator itm = m.begin();
3914         lst::const_iterator its = s.begin();
3915         if (*its < 0) {
3916                 c.s << "\\overline{";
3917                 (*itm).print(c);
3918                 c.s << "}";
3919         } else {
3920                 (*itm).print(c);
3921         }
3922         its++;
3923         itm++;
3924         for (; itm != m.end(); itm++, its++) {
3925                 c.s << ",";
3926                 if (*its < 0) {
3927                         c.s << "\\overline{";
3928                         (*itm).print(c);
3929                         c.s << "}";
3930                 } else {
3931                         (*itm).print(c);
3932                 }
3933         }
3934         c.s << ")";
3935 }
3936
3937
3938 unsigned zeta2_SERIAL::serial = function::register_new(function_options("zeta", 2).
3939                                 evalf_func(zeta2_evalf).
3940                                 eval_func(zeta2_eval).
3941                                 derivative_func(zeta2_deriv).
3942                                 print_func<print_latex>(zeta2_print_latex).
3943                                 do_not_evalf_params().
3944                                 overloaded(2));
3945
3946
3947 } // namespace GiNaC
3948