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