]> www.ginac.de Git - ginac.git/blob - ginac/inifcns_nstdsums.cpp
inifcns_nstdsums.cpp: S_num takes cl_N as an argument instead of numeric.
[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 const cln::cl_N S_num(int n, int p, const cln::cl_N& 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) - S_num(1, n-j-1, 1-x))
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) - S_num(1, n-j-1, 1-x_))
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) / cln::factorial(2*j);
1724                                         }
1725                                         else {
1726                                                 result = result + 2 * cln::expt(cln::pi(),2*j) * S_num(n-2*j,p,1) / 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)
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)
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)
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)
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) - 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 const cln::cl_N S_num(int n, int p, const cln::cl_N& 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;
1921         // second guess: the argument's format
1922         if (!instanceof(realpart(value), cln::cl_RA_ring))
1923                 prec = cln::float_format(cln::the<cln::cl_F>(cln::realpart(value)));
1924         else if (!instanceof(imagpart(value), cln::cl_RA_ring))
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) / cln::factorial(r);
1938                         }
1939                         result = result + cln::expt(cln::log(value),s) * (S_num(n-s,p,1) - 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));
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                 const int n_ = ex_to<numeric>(n).to_int();
1991                 const int p_ = ex_to<numeric>(p).to_int();
1992                 if (is_a<numeric>(x)) {
1993                         const cln::cl_N x_ = ex_to<numeric>(x).to_cl_N();
1994                         const cln::cl_N result = S_num(n_, p_, x_);
1995                         return numeric(result);
1996                 } else {
1997                         ex x_val = x.evalf();
1998                         if (is_a<numeric>(x_val)) {
1999                                 const cln::cl_N x_val_ = ex_to<numeric>(x_val).to_cl_N();
2000                                 const cln::cl_N result = S_num(n_, p_, x_val_);
2001                                 return numeric(result);
2002                         }
2003                 }
2004         }
2005         return S(n, p, x).hold();
2006 }
2007
2008
2009 static ex S_eval(const ex& n, const ex& p, const ex& x)
2010 {
2011         if (n.info(info_flags::posint) && p.info(info_flags::posint)) {
2012                 if (x == 0) {
2013                         return _ex0;
2014                 }
2015                 if (x == 1) {
2016                         lst m(n+1);
2017                         for (int i=ex_to<numeric>(p).to_int()-1; i>0; i--) {
2018                                 m.append(1);
2019                         }
2020                         return zeta(m);
2021                 }
2022                 if (p == 1) {
2023                         return Li(n+1, x);
2024                 }
2025                 if (x.info(info_flags::numeric) && (!x.info(info_flags::crational))) {
2026                         int n_ = ex_to<numeric>(n).to_int();
2027                         int p_ = ex_to<numeric>(p).to_int();
2028                         const cln::cl_N x_ = ex_to<numeric>(x).to_cl_N();
2029                         const cln::cl_N result = S_num(n_, p_, x_);
2030                         return numeric(result);
2031                 }
2032         }
2033         if (n.is_zero()) {
2034                 // [Kol] (5.3)
2035                 return pow(-log(1-x), p) / factorial(p);
2036         }
2037         return S(n, p, x).hold();
2038 }
2039
2040
2041 static ex S_series(const ex& n, const ex& p, const ex& x, const relational& rel, int order, unsigned options)
2042 {
2043         if (p == _ex1) {
2044                 return Li(n+1, x).series(rel, order, options);
2045         }
2046
2047         const ex x_pt = x.subs(rel, subs_options::no_pattern);
2048         if (n.info(info_flags::posint) && p.info(info_flags::posint) && x_pt.info(info_flags::numeric)) {
2049                 // First special case: x==0 (derivatives have poles)
2050                 if (x_pt.is_zero()) {
2051                         const symbol s;
2052                         ex ser;
2053                         // manually construct the primitive expansion
2054                         // subsum = Euler-Zagier-Sum is needed
2055                         // dirty hack (slow ...) calculation of subsum:
2056                         std::vector<ex> presubsum, subsum;
2057                         subsum.push_back(0);
2058                         for (int i=1; i<order-1; ++i) {
2059                                 subsum.push_back(subsum[i-1] + numeric(1, i));
2060                         }
2061                         for (int depth=2; depth<p; ++depth) {
2062                                 presubsum = subsum;
2063                                 for (int i=1; i<order-1; ++i) {
2064                                         subsum[i] = subsum[i-1] + numeric(1, i) * presubsum[i-1];
2065                                 }
2066                         }
2067                                 
2068                         for (int i=1; i<order; ++i) {
2069                                 ser += pow(s,i) / pow(numeric(i), n+1) * subsum[i-1];
2070                         }
2071                         // substitute the argument's series expansion
2072                         ser = ser.subs(s==x.series(rel, order), subs_options::no_pattern);
2073                         // maybe that was terminating, so add a proper order term
2074                         epvector nseq;
2075                         nseq.push_back(expair(Order(_ex1), order));
2076                         ser += pseries(rel, nseq);
2077                         // reexpanding it will collapse the series again
2078                         return ser.series(rel, order);
2079                 }
2080                 // TODO special cases: x==1 (branch point) and x real, >=1 (branch cut)
2081                 throw std::runtime_error("S_series: don't know how to do the series expansion at this point!");
2082         }
2083         // all other cases should be safe, by now:
2084         throw do_taylor();  // caught by function::series()
2085 }
2086
2087
2088 static ex S_deriv(const ex& n, const ex& p, const ex& x, unsigned deriv_param)
2089 {
2090         GINAC_ASSERT(deriv_param < 3);
2091         if (deriv_param < 2) {
2092                 return _ex0;
2093         }
2094         if (n > 0) {
2095                 return S(n-1, p, x) / x;
2096         } else {
2097                 return S(n, p-1, x) / (1-x);
2098         }
2099 }
2100
2101
2102 static void S_print_latex(const ex& n, const ex& p, const ex& x, const print_context& c)
2103 {
2104         c.s << "\\mbox{S}_{";
2105         n.print(c);
2106         c.s << ",";
2107         p.print(c);
2108         c.s << "}(";
2109         x.print(c);
2110         c.s << ")";
2111 }
2112
2113
2114 REGISTER_FUNCTION(S,
2115                   evalf_func(S_evalf).
2116                   eval_func(S_eval).
2117                   series_func(S_series).
2118                   derivative_func(S_deriv).
2119                   print_func<print_latex>(S_print_latex).
2120                   do_not_evalf_params());
2121
2122
2123 //////////////////////////////////////////////////////////////////////
2124 //
2125 // Harmonic polylogarithm  H(m,x)
2126 //
2127 // helper functions
2128 //
2129 //////////////////////////////////////////////////////////////////////
2130
2131
2132 // anonymous namespace for helper functions
2133 namespace {
2134
2135         
2136 // regulates the pole (used by 1/x-transformation)
2137 symbol H_polesign("IMSIGN");
2138
2139
2140 // convert parameters from H to Li representation
2141 // parameters are expected to be in expanded form, i.e. only 0, 1 and -1
2142 // returns true if some parameters are negative
2143 bool convert_parameter_H_to_Li(const lst& l, lst& m, lst& s, ex& pf)
2144 {
2145         // expand parameter list
2146         lst mexp;
2147         for (lst::const_iterator it = l.begin(); it != l.end(); it++) {
2148                 if (*it > 1) {
2149                         for (ex count=*it-1; count > 0; count--) {
2150                                 mexp.append(0);
2151                         }
2152                         mexp.append(1);
2153                 } else if (*it < -1) {
2154                         for (ex count=*it+1; count < 0; count++) {
2155                                 mexp.append(0);
2156                         }
2157                         mexp.append(-1);
2158                 } else {
2159                         mexp.append(*it);
2160                 }
2161         }
2162         
2163         ex signum = 1;
2164         pf = 1;
2165         bool has_negative_parameters = false;
2166         ex acc = 1;
2167         for (lst::const_iterator it = mexp.begin(); it != mexp.end(); it++) {
2168                 if (*it == 0) {
2169                         acc++;
2170                         continue;
2171                 }
2172                 if (*it > 0) {
2173                         m.append((*it+acc-1) * signum);
2174                 } else {
2175                         m.append((*it-acc+1) * signum);
2176                 }
2177                 acc = 1;
2178                 signum = *it;
2179                 pf *= *it;
2180                 if (pf < 0) {
2181                         has_negative_parameters = true;
2182                 }
2183         }
2184         if (has_negative_parameters) {
2185                 for (int i=0; i<m.nops(); i++) {
2186                         if (m.op(i) < 0) {
2187                                 m.let_op(i) = -m.op(i);
2188                                 s.append(-1);
2189                         } else {
2190                                 s.append(1);
2191                         }
2192                 }
2193         }
2194         
2195         return has_negative_parameters;
2196 }
2197
2198
2199 // recursivly transforms H to corresponding multiple polylogarithms
2200 struct map_trafo_H_convert_to_Li : public map_function
2201 {
2202         ex operator()(const ex& e)
2203         {
2204                 if (is_a<add>(e) || is_a<mul>(e)) {
2205                         return e.map(*this);
2206                 }
2207                 if (is_a<function>(e)) {
2208                         std::string name = ex_to<function>(e).get_name();
2209                         if (name == "H") {
2210                                 lst parameter;
2211                                 if (is_a<lst>(e.op(0))) {
2212                                                 parameter = ex_to<lst>(e.op(0));
2213                                 } else {
2214                                         parameter = lst(e.op(0));
2215                                 }
2216                                 ex arg = e.op(1);
2217
2218                                 lst m;
2219                                 lst s;
2220                                 ex pf;
2221                                 if (convert_parameter_H_to_Li(parameter, m, s, pf)) {
2222                                         s.let_op(0) = s.op(0) * arg;
2223                                         return pf * Li(m, s).hold();
2224                                 } else {
2225                                         for (int i=0; i<m.nops(); i++) {
2226                                                 s.append(1);
2227                                         }
2228                                         s.let_op(0) = s.op(0) * arg;
2229                                         return Li(m, s).hold();
2230                                 }
2231                         }
2232                 }
2233                 return e;
2234         }
2235 };
2236
2237
2238 // recursivly transforms H to corresponding zetas
2239 struct map_trafo_H_convert_to_zeta : public map_function
2240 {
2241         ex operator()(const ex& e)
2242         {
2243                 if (is_a<add>(e) || is_a<mul>(e)) {
2244                         return e.map(*this);
2245                 }
2246                 if (is_a<function>(e)) {
2247                         std::string name = ex_to<function>(e).get_name();
2248                         if (name == "H") {
2249                                 lst parameter;
2250                                 if (is_a<lst>(e.op(0))) {
2251                                                 parameter = ex_to<lst>(e.op(0));
2252                                 } else {
2253                                         parameter = lst(e.op(0));
2254                                 }
2255
2256                                 lst m;
2257                                 lst s;
2258                                 ex pf;
2259                                 if (convert_parameter_H_to_Li(parameter, m, s, pf)) {
2260                                         return pf * zeta(m, s);
2261                                 } else {
2262                                         return zeta(m);
2263                                 }
2264                         }
2265                 }
2266                 return e;
2267         }
2268 };
2269
2270
2271 // remove trailing zeros from H-parameters
2272 struct map_trafo_H_reduce_trailing_zeros : public map_function
2273 {
2274         ex operator()(const ex& e)
2275         {
2276                 if (is_a<add>(e) || is_a<mul>(e)) {
2277                         return e.map(*this);
2278                 }
2279                 if (is_a<function>(e)) {
2280                         std::string name = ex_to<function>(e).get_name();
2281                         if (name == "H") {
2282                                 lst parameter;
2283                                 if (is_a<lst>(e.op(0))) {
2284                                         parameter = ex_to<lst>(e.op(0));
2285                                 } else {
2286                                         parameter = lst(e.op(0));
2287                                 }
2288                                 ex arg = e.op(1);
2289                                 if (parameter.op(parameter.nops()-1) == 0) {
2290                                         
2291                                         //
2292                                         if (parameter.nops() == 1) {
2293                                                 return log(arg);
2294                                         }
2295                                         
2296                                         //
2297                                         lst::const_iterator it = parameter.begin();
2298                                         while ((it != parameter.end()) && (*it == 0)) {
2299                                                 it++;
2300                                         }
2301                                         if (it == parameter.end()) {
2302                                                 return pow(log(arg),parameter.nops()) / factorial(parameter.nops());
2303                                         }
2304                                         
2305                                         //
2306                                         parameter.remove_last();
2307                                         int lastentry = parameter.nops();
2308                                         while ((lastentry > 0) && (parameter[lastentry-1] == 0)) {
2309                                                 lastentry--;
2310                                         }
2311                                         
2312                                         //
2313                                         ex result = log(arg) * H(parameter,arg).hold();
2314                                         ex acc = 0;
2315                                         for (ex i=0; i<lastentry; i++) {
2316                                                 if (parameter[i] > 0) {
2317                                                         parameter[i]++;
2318                                                         result -= (acc + parameter[i]-1) * H(parameter, arg).hold();
2319                                                         parameter[i]--;
2320                                                         acc = 0;
2321                                                 } else if (parameter[i] < 0) {
2322                                                         parameter[i]--;
2323                                                         result -= (acc + abs(parameter[i]+1)) * H(parameter, arg).hold();
2324                                                         parameter[i]++;
2325                                                         acc = 0;
2326                                                 } else {
2327                                                         acc++;
2328                                                 }
2329                                         }
2330                                         
2331                                         if (lastentry < parameter.nops()) {
2332                                                 result = result / (parameter.nops()-lastentry+1);
2333                                                 return result.map(*this);
2334                                         } else {
2335                                                 return result;
2336                                         }
2337                                 }
2338                         }
2339                 }
2340                 return e;
2341         }
2342 };
2343
2344
2345 // returns an expression with zeta functions corresponding to the parameter list for H
2346 ex convert_H_to_zeta(const lst& m)
2347 {
2348         symbol xtemp("xtemp");
2349         map_trafo_H_reduce_trailing_zeros filter;
2350         map_trafo_H_convert_to_zeta filter2;
2351         return filter2(filter(H(m, xtemp).hold())).subs(xtemp == 1);
2352 }
2353
2354
2355 // convert signs form Li to H representation
2356 lst convert_parameter_Li_to_H(const lst& m, const lst& x, ex& pf)
2357 {
2358         lst res;
2359         lst::const_iterator itm = m.begin();
2360         lst::const_iterator itx = ++x.begin();
2361         int signum = 1;
2362         pf = _ex1;
2363         res.append(*itm);
2364         itm++;
2365         while (itx != x.end()) {
2366                 signum *= (*itx > 0) ? 1 : -1;
2367                 pf *= signum;
2368                 res.append((*itm) * signum);
2369                 itm++;
2370                 itx++;
2371         }
2372         return res;
2373 }
2374
2375
2376 // multiplies an one-dimensional H with another H
2377 // [ReV] (18)
2378 ex trafo_H_mult(const ex& h1, const ex& h2)
2379 {
2380         ex res;
2381         ex hshort;
2382         lst hlong;
2383         ex h1nops = h1.op(0).nops();
2384         ex h2nops = h2.op(0).nops();
2385         if (h1nops > 1) {
2386                 hshort = h2.op(0).op(0);
2387                 hlong = ex_to<lst>(h1.op(0));
2388         } else {
2389                 hshort = h1.op(0).op(0);
2390                 if (h2nops > 1) {
2391                         hlong = ex_to<lst>(h2.op(0));
2392                 } else {
2393                         hlong = h2.op(0).op(0);
2394                 }
2395         }
2396         for (int i=0; i<=hlong.nops(); i++) {
2397                 lst newparameter;
2398                 int j=0;
2399                 for (; j<i; j++) {
2400                         newparameter.append(hlong[j]);
2401                 }
2402                 newparameter.append(hshort);
2403                 for (; j<hlong.nops(); j++) {
2404                         newparameter.append(hlong[j]);
2405                 }
2406                 res += H(newparameter, h1.op(1)).hold();
2407         }
2408         return res;
2409 }
2410
2411
2412 // applies trafo_H_mult recursively on expressions
2413 struct map_trafo_H_mult : public map_function
2414 {
2415         ex operator()(const ex& e)
2416         {
2417                 if (is_a<add>(e)) {
2418                         return e.map(*this);
2419                 }
2420
2421                 if (is_a<mul>(e)) {
2422
2423                         ex result = 1;
2424                         ex firstH;
2425                         lst Hlst;
2426                         for (int pos=0; pos<e.nops(); pos++) {
2427                                 if (is_a<power>(e.op(pos)) && is_a<function>(e.op(pos).op(0))) {
2428                                         std::string name = ex_to<function>(e.op(pos).op(0)).get_name();
2429                                         if (name == "H") {
2430                                                 for (ex i=0; i<e.op(pos).op(1); i++) {
2431                                                         Hlst.append(e.op(pos).op(0));
2432                                                 }
2433                                                 continue;
2434                                         }
2435                                 } else if (is_a<function>(e.op(pos))) {
2436                                         std::string name = ex_to<function>(e.op(pos)).get_name();
2437                                         if (name == "H") {
2438                                                 if (e.op(pos).op(0).nops() > 1) {
2439                                                         firstH = e.op(pos);
2440                                                 } else {
2441                                                         Hlst.append(e.op(pos));
2442                                                 }
2443                                                 continue;
2444                                         }
2445                                 }
2446                                 result *= e.op(pos);
2447                         }
2448                         if (firstH == 0) {
2449                                 if (Hlst.nops() > 0) {
2450                                         firstH = Hlst[Hlst.nops()-1];
2451                                         Hlst.remove_last();
2452                                 } else {
2453                                         return e;
2454                                 }
2455                         }
2456
2457                         if (Hlst.nops() > 0) {
2458                                 ex buffer = trafo_H_mult(firstH, Hlst.op(0));
2459                                 result *= buffer;
2460                                 for (int i=1; i<Hlst.nops(); i++) {
2461                                         result *= Hlst.op(i);
2462                                 }
2463                                 result = result.expand();
2464                                 map_trafo_H_mult recursion;
2465                                 return recursion(result);
2466                         } else {
2467                                 return e;
2468                         }
2469
2470                 }
2471                 return e;
2472         }
2473 };
2474
2475
2476 // do integration [ReV] (55)
2477 // put parameter 0 in front of existing parameters
2478 ex trafo_H_1tx_prepend_zero(const ex& e, const ex& arg)
2479 {
2480         ex h;
2481         std::string name;
2482         if (is_a<function>(e)) {
2483                 name = ex_to<function>(e).get_name();
2484         }
2485         if (name == "H") {
2486                 h = e;
2487         } else {
2488                 for (int i=0; i<e.nops(); i++) {
2489                         if (is_a<function>(e.op(i))) {
2490                                 std::string name = ex_to<function>(e.op(i)).get_name();
2491                                 if (name == "H") {
2492                                         h = e.op(i);
2493                                 }
2494                         }
2495                 }
2496         }
2497         if (h != 0) {
2498                 lst newparameter = ex_to<lst>(h.op(0));
2499                 newparameter.prepend(0);
2500                 ex addzeta = convert_H_to_zeta(newparameter);
2501                 return e.subs(h == (addzeta-H(newparameter, h.op(1)).hold())).expand();
2502         } else {
2503                 return e * (-H(lst(0),1/arg).hold());
2504         }
2505 }
2506
2507
2508 // do integration [ReV] (49)
2509 // put parameter 1 in front of existing parameters
2510 ex trafo_H_prepend_one(const ex& e, const ex& arg)
2511 {
2512         ex h;
2513         std::string name;
2514         if (is_a<function>(e)) {
2515                 name = ex_to<function>(e).get_name();
2516         }
2517         if (name == "H") {
2518                 h = e;
2519         } else {
2520                 for (int i=0; i<e.nops(); i++) {
2521                         if (is_a<function>(e.op(i))) {
2522                                 std::string name = ex_to<function>(e.op(i)).get_name();
2523                                 if (name == "H") {
2524                                         h = e.op(i);
2525                                 }
2526                         }
2527                 }
2528         }
2529         if (h != 0) {
2530                 lst newparameter = ex_to<lst>(h.op(0));
2531                 newparameter.prepend(1);
2532                 return e.subs(h == H(newparameter, h.op(1)).hold());
2533         } else {
2534                 return e * H(lst(1),1-arg).hold();
2535         }
2536 }
2537
2538
2539 // do integration [ReV] (55)
2540 // put parameter -1 in front of existing parameters
2541 ex trafo_H_1tx_prepend_minusone(const ex& e, const ex& arg)
2542 {
2543         ex h;
2544         std::string name;
2545         if (is_a<function>(e)) {
2546                 name = ex_to<function>(e).get_name();
2547         }
2548         if (name == "H") {
2549                 h = e;
2550         } else {
2551                 for (int i=0; i<e.nops(); i++) {
2552                         if (is_a<function>(e.op(i))) {
2553                                 std::string name = ex_to<function>(e.op(i)).get_name();
2554                                 if (name == "H") {
2555                                         h = e.op(i);
2556                                 }
2557                         }
2558                 }
2559         }
2560         if (h != 0) {
2561                 lst newparameter = ex_to<lst>(h.op(0));
2562                 newparameter.prepend(-1);
2563                 ex addzeta = convert_H_to_zeta(newparameter);
2564                 return e.subs(h == (addzeta-H(newparameter, h.op(1)).hold())).expand();
2565         } else {
2566                 ex addzeta = convert_H_to_zeta(lst(-1));
2567                 return (e * (addzeta - H(lst(-1),1/arg).hold())).expand();
2568         }
2569 }
2570
2571
2572 // do integration [ReV] (55)
2573 // put parameter -1 in front of existing parameters
2574 ex trafo_H_1mxt1px_prepend_minusone(const ex& e, const ex& arg)
2575 {
2576         ex h;
2577         std::string name;
2578         if (is_a<function>(e)) {
2579                 name = ex_to<function>(e).get_name();
2580         }
2581         if (name == "H") {
2582                 h = e;
2583         } else {
2584                 for (int i=0; i<e.nops(); i++) {
2585                         if (is_a<function>(e.op(i))) {
2586                                 std::string name = ex_to<function>(e.op(i)).get_name();
2587                                 if (name == "H") {
2588                                         h = e.op(i);
2589                                 }
2590                         }
2591                 }
2592         }
2593         if (h != 0) {
2594                 lst newparameter = ex_to<lst>(h.op(0));
2595                 newparameter.prepend(-1);
2596                 return e.subs(h == H(newparameter, h.op(1)).hold()).expand();
2597         } else {
2598                 return (e * H(lst(-1),(1-arg)/(1+arg)).hold()).expand();
2599         }
2600 }
2601
2602
2603 // do integration [ReV] (55)
2604 // put parameter 1 in front of existing parameters
2605 ex trafo_H_1mxt1px_prepend_one(const ex& e, const ex& arg)
2606 {
2607         ex h;
2608         std::string name;
2609         if (is_a<function>(e)) {
2610                 name = ex_to<function>(e).get_name();
2611         }
2612         if (name == "H") {
2613                 h = e;
2614         } else {
2615                 for (int i=0; i<e.nops(); i++) {
2616                         if (is_a<function>(e.op(i))) {
2617                                 std::string name = ex_to<function>(e.op(i)).get_name();
2618                                 if (name == "H") {
2619                                         h = e.op(i);
2620                                 }
2621                         }
2622                 }
2623         }
2624         if (h != 0) {
2625                 lst newparameter = ex_to<lst>(h.op(0));
2626                 newparameter.prepend(1);
2627                 return e.subs(h == H(newparameter, h.op(1)).hold()).expand();
2628         } else {
2629                 return (e * H(lst(1),(1-arg)/(1+arg)).hold()).expand();
2630         }
2631 }
2632
2633
2634 // do x -> 1-x transformation
2635 struct map_trafo_H_1mx : public map_function
2636 {
2637         ex operator()(const ex& e)
2638         {
2639                 if (is_a<add>(e) || is_a<mul>(e)) {
2640                         return e.map(*this);
2641                 }
2642                 
2643                 if (is_a<function>(e)) {
2644                         std::string name = ex_to<function>(e).get_name();
2645                         if (name == "H") {
2646
2647                                 lst parameter = ex_to<lst>(e.op(0));
2648                                 ex arg = e.op(1);
2649
2650                                 // special cases if all parameters are either 0, 1 or -1
2651                                 bool allthesame = true;
2652                                 if (parameter.op(0) == 0) {
2653                                         for (int i=1; i<parameter.nops(); i++) {
2654                                                 if (parameter.op(i) != 0) {
2655                                                         allthesame = false;
2656                                                         break;
2657                                                 }
2658                                         }
2659                                         if (allthesame) {
2660                                                 lst newparameter;
2661                                                 for (int i=parameter.nops(); i>0; i--) {
2662                                                         newparameter.append(1);
2663                                                 }
2664                                                 return pow(-1, parameter.nops()) * H(newparameter, 1-arg).hold();
2665                                         }
2666                                 } else if (parameter.op(0) == -1) {
2667                                         throw std::runtime_error("map_trafo_H_1mx: cannot handle weights equal -1!");
2668                                 } else {
2669                                         for (int i=1; i<parameter.nops(); i++) {
2670                                                 if (parameter.op(i) != 1) {
2671                                                         allthesame = false;
2672                                                         break;
2673                                                 }
2674                                         }
2675                                         if (allthesame) {
2676                                                 lst newparameter;
2677                                                 for (int i=parameter.nops(); i>0; i--) {
2678                                                         newparameter.append(0);
2679                                                 }
2680                                                 return pow(-1, parameter.nops()) * H(newparameter, 1-arg).hold();
2681                                         }
2682                                 }
2683
2684                                 lst newparameter = parameter;
2685                                 newparameter.remove_first();
2686
2687                                 if (parameter.op(0) == 0) {
2688
2689                                         // leading zero
2690                                         ex res = convert_H_to_zeta(parameter);
2691                                         //ex res = convert_from_RV(parameter, 1).subs(H(wild(1),wild(2))==zeta(wild(1)));
2692                                         map_trafo_H_1mx recursion;
2693                                         ex buffer = recursion(H(newparameter, arg).hold());
2694                                         if (is_a<add>(buffer)) {
2695                                                 for (int i=0; i<buffer.nops(); i++) {
2696                                                         res -= trafo_H_prepend_one(buffer.op(i), arg);
2697                                                 }
2698                                         } else {
2699                                                 res -= trafo_H_prepend_one(buffer, arg);
2700                                         }
2701                                         return res;
2702
2703                                 } else {
2704
2705                                         // leading one
2706                                         map_trafo_H_1mx recursion;
2707                                         map_trafo_H_mult unify;
2708                                         ex res = H(lst(1), arg).hold() * H(newparameter, arg).hold();
2709                                         int firstzero = 0;
2710                                         while (parameter.op(firstzero) == 1) {
2711                                                 firstzero++;
2712                                         }
2713                                         for (int i=firstzero-1; i<parameter.nops()-1; i++) {
2714                                                 lst newparameter;
2715                                                 int j=0;
2716                                                 for (; j<=i; j++) {
2717                                                         newparameter.append(parameter[j+1]);
2718                                                 }
2719                                                 newparameter.append(1);
2720                                                 for (; j<parameter.nops()-1; j++) {
2721                                                         newparameter.append(parameter[j+1]);
2722                                                 }
2723                                                 res -= H(newparameter, arg).hold();
2724                                         }
2725                                         res = recursion(res).expand() / firstzero;
2726                                         return unify(res);
2727                                 }
2728                         }
2729                 }
2730                 return e;
2731         }
2732 };
2733
2734
2735 // do x -> 1/x transformation
2736 struct map_trafo_H_1overx : public map_function
2737 {
2738         ex operator()(const ex& e)
2739         {
2740                 if (is_a<add>(e) || is_a<mul>(e)) {
2741                         return e.map(*this);
2742                 }
2743
2744                 if (is_a<function>(e)) {
2745                         std::string name = ex_to<function>(e).get_name();
2746                         if (name == "H") {
2747
2748                                 lst parameter = ex_to<lst>(e.op(0));
2749                                 ex arg = e.op(1);
2750
2751                                 // special cases if all parameters are either 0, 1 or -1
2752                                 bool allthesame = true;
2753                                 if (parameter.op(0) == 0) {
2754                                         for (int i=1; i<parameter.nops(); i++) {
2755                                                 if (parameter.op(i) != 0) {
2756                                                         allthesame = false;
2757                                                         break;
2758                                                 }
2759                                         }
2760                                         if (allthesame) {
2761                                                 return pow(-1, parameter.nops()) * H(parameter, 1/arg).hold();
2762                                         }
2763                                 } else if (parameter.op(0) == -1) {
2764                                         for (int i=1; i<parameter.nops(); i++) {
2765                                                 if (parameter.op(i) != -1) {
2766                                                         allthesame = false;
2767                                                         break;
2768                                                 }
2769                                         }
2770                                         if (allthesame) {
2771                                                 map_trafo_H_mult unify;
2772                                                 return unify((pow(H(lst(-1),1/arg).hold() - H(lst(0),1/arg).hold(), parameter.nops())
2773                                                        / factorial(parameter.nops())).expand());
2774                                         }
2775                                 } else {
2776                                         for (int i=1; i<parameter.nops(); i++) {
2777                                                 if (parameter.op(i) != 1) {
2778                                                         allthesame = false;
2779                                                         break;
2780                                                 }
2781                                         }
2782                                         if (allthesame) {
2783                                                 map_trafo_H_mult unify;
2784                                                 return unify((pow(H(lst(1),1/arg).hold() + H(lst(0),1/arg).hold() + H_polesign, parameter.nops())
2785                                                        / factorial(parameter.nops())).expand());
2786                                         }
2787                                 }
2788
2789                                 lst newparameter = parameter;
2790                                 newparameter.remove_first();
2791
2792                                 if (parameter.op(0) == 0) {
2793                                         
2794                                         // leading zero
2795                                         ex res = convert_H_to_zeta(parameter);
2796                                         map_trafo_H_1overx recursion;
2797                                         ex buffer = recursion(H(newparameter, arg).hold());
2798                                         if (is_a<add>(buffer)) {
2799                                                 for (int i=0; i<buffer.nops(); i++) {
2800                                                         res += trafo_H_1tx_prepend_zero(buffer.op(i), arg);
2801                                                 }
2802                                         } else {
2803                                                 res += trafo_H_1tx_prepend_zero(buffer, arg);
2804                                         }
2805                                         return res;
2806
2807                                 } else if (parameter.op(0) == -1) {
2808
2809                                         // leading negative one
2810                                         ex res = convert_H_to_zeta(parameter);
2811                                         map_trafo_H_1overx recursion;
2812                                         ex buffer = recursion(H(newparameter, arg).hold());
2813                                         if (is_a<add>(buffer)) {
2814                                                 for (int i=0; i<buffer.nops(); i++) {
2815                                                         res += trafo_H_1tx_prepend_zero(buffer.op(i), arg) - trafo_H_1tx_prepend_minusone(buffer.op(i), arg);
2816                                                 }
2817                                         } else {
2818                                                 res += trafo_H_1tx_prepend_zero(buffer, arg) - trafo_H_1tx_prepend_minusone(buffer, arg);
2819                                         }
2820                                         return res;
2821
2822                                 } else {
2823
2824                                         // leading one
2825                                         map_trafo_H_1overx recursion;
2826                                         map_trafo_H_mult unify;
2827                                         ex res = H(lst(1), arg).hold() * H(newparameter, arg).hold();
2828                                         int firstzero = 0;
2829                                         while (parameter.op(firstzero) == 1) {
2830                                                 firstzero++;
2831                                         }
2832                                         for (int i=firstzero-1; i<parameter.nops()-1; i++) {
2833                                                 lst newparameter;
2834                                                 int j=0;
2835                                                 for (; j<=i; j++) {
2836                                                         newparameter.append(parameter[j+1]);
2837                                                 }
2838                                                 newparameter.append(1);
2839                                                 for (; j<parameter.nops()-1; j++) {
2840                                                         newparameter.append(parameter[j+1]);
2841                                                 }
2842                                                 res -= H(newparameter, arg).hold();
2843                                         }
2844                                         res = recursion(res).expand() / firstzero;
2845                                         return unify(res);
2846
2847                                 }
2848
2849                         }
2850                 }
2851                 return e;
2852         }
2853 };
2854
2855
2856 // do x -> (1-x)/(1+x) transformation
2857 struct map_trafo_H_1mxt1px : public map_function
2858 {
2859         ex operator()(const ex& e)
2860         {
2861                 if (is_a<add>(e) || is_a<mul>(e)) {
2862                         return e.map(*this);
2863                 }
2864
2865                 if (is_a<function>(e)) {
2866                         std::string name = ex_to<function>(e).get_name();
2867                         if (name == "H") {
2868
2869                                 lst parameter = ex_to<lst>(e.op(0));
2870                                 ex arg = e.op(1);
2871
2872                                 // special cases if all parameters are either 0, 1 or -1
2873                                 bool allthesame = true;
2874                                 if (parameter.op(0) == 0) {
2875                                         for (int i=1; i<parameter.nops(); i++) {
2876                                                 if (parameter.op(i) != 0) {
2877                                                         allthesame = false;
2878                                                         break;
2879                                                 }
2880                                         }
2881                                         if (allthesame) {
2882                                                 map_trafo_H_mult unify;
2883                                                 return unify((pow(-H(lst(1),(1-arg)/(1+arg)).hold() - H(lst(-1),(1-arg)/(1+arg)).hold(), parameter.nops())
2884                                                        / factorial(parameter.nops())).expand());
2885                                         }
2886                                 } else if (parameter.op(0) == -1) {
2887                                         for (int i=1; i<parameter.nops(); i++) {
2888                                                 if (parameter.op(i) != -1) {
2889                                                         allthesame = false;
2890                                                         break;
2891                                                 }
2892                                         }
2893                                         if (allthesame) {
2894                                                 map_trafo_H_mult unify;
2895                                                 return unify((pow(log(2) - H(lst(-1),(1-arg)/(1+arg)).hold(), parameter.nops())
2896                                                        / factorial(parameter.nops())).expand());
2897                                         }
2898                                 } else {
2899                                         for (int i=1; i<parameter.nops(); i++) {
2900                                                 if (parameter.op(i) != 1) {
2901                                                         allthesame = false;
2902                                                         break;
2903                                                 }
2904                                         }
2905                                         if (allthesame) {
2906                                                 map_trafo_H_mult unify;
2907                                                 return unify((pow(-log(2) - H(lst(0),(1-arg)/(1+arg)).hold() + H(lst(-1),(1-arg)/(1+arg)).hold(), parameter.nops())
2908                                                        / factorial(parameter.nops())).expand());
2909                                         }
2910                                 }
2911
2912                                 lst newparameter = parameter;
2913                                 newparameter.remove_first();
2914
2915                                 if (parameter.op(0) == 0) {
2916
2917                                         // leading zero
2918                                         ex res = convert_H_to_zeta(parameter);
2919                                         map_trafo_H_1mxt1px recursion;
2920                                         ex buffer = recursion(H(newparameter, arg).hold());
2921                                         if (is_a<add>(buffer)) {
2922                                                 for (int i=0; i<buffer.nops(); i++) {
2923                                                         res -= trafo_H_1mxt1px_prepend_one(buffer.op(i), arg) + trafo_H_1mxt1px_prepend_minusone(buffer.op(i), arg);
2924                                                 }
2925                                         } else {
2926                                                 res -= trafo_H_1mxt1px_prepend_one(buffer, arg) + trafo_H_1mxt1px_prepend_minusone(buffer, arg);
2927                                         }
2928                                         return res;
2929
2930                                 } else if (parameter.op(0) == -1) {
2931
2932                                         // leading negative one
2933                                         ex res = convert_H_to_zeta(parameter);
2934                                         map_trafo_H_1mxt1px recursion;
2935                                         ex buffer = recursion(H(newparameter, arg).hold());
2936                                         if (is_a<add>(buffer)) {
2937                                                 for (int i=0; i<buffer.nops(); i++) {
2938                                                         res -= trafo_H_1mxt1px_prepend_minusone(buffer.op(i), arg);
2939                                                 }
2940                                         } else {
2941                                                 res -= trafo_H_1mxt1px_prepend_minusone(buffer, arg);
2942                                         }
2943                                         return res;
2944
2945                                 } else {
2946
2947                                         // leading one
2948                                         map_trafo_H_1mxt1px recursion;
2949                                         map_trafo_H_mult unify;
2950                                         ex res = H(lst(1), arg).hold() * H(newparameter, arg).hold();
2951                                         int firstzero = 0;
2952                                         while (parameter.op(firstzero) == 1) {
2953                                                 firstzero++;
2954                                         }
2955                                         for (int i=firstzero-1; i<parameter.nops()-1; i++) {
2956                                                 lst newparameter;
2957                                                 int j=0;
2958                                                 for (; j<=i; j++) {
2959                                                         newparameter.append(parameter[j+1]);
2960                                                 }
2961                                                 newparameter.append(1);
2962                                                 for (; j<parameter.nops()-1; j++) {
2963                                                         newparameter.append(parameter[j+1]);
2964                                                 }
2965                                                 res -= H(newparameter, arg).hold();
2966                                         }
2967                                         res = recursion(res).expand() / firstzero;
2968                                         return unify(res);
2969
2970                                 }
2971
2972                         }
2973                 }
2974                 return e;
2975         }
2976 };
2977
2978
2979 // do the actual summation.
2980 cln::cl_N H_do_sum(const std::vector<int>& m, const cln::cl_N& x)
2981 {
2982         const int j = m.size();
2983
2984         std::vector<cln::cl_N> t(j);
2985
2986         cln::cl_F one = cln::cl_float(1, cln::float_format(Digits));
2987         cln::cl_N factor = cln::expt(x, j) * one;
2988         cln::cl_N t0buf;
2989         int q = 0;
2990         do {
2991                 t0buf = t[0];
2992                 q++;
2993                 t[j-1] = t[j-1] + 1 / cln::expt(cln::cl_I(q),m[j-1]);
2994                 for (int k=j-2; k>=1; k--) {
2995                         t[k] = t[k] + t[k+1] / cln::expt(cln::cl_I(q+j-1-k), m[k]);
2996                 }
2997                 t[0] = t[0] + t[1] * factor / cln::expt(cln::cl_I(q+j-1), m[0]);
2998                 factor = factor * x;
2999         } while (t[0] != t0buf);
3000
3001         return t[0];
3002 }
3003
3004
3005 } // end of anonymous namespace
3006
3007
3008 //////////////////////////////////////////////////////////////////////
3009 //
3010 // Harmonic polylogarithm  H(m,x)
3011 //
3012 // GiNaC function
3013 //
3014 //////////////////////////////////////////////////////////////////////
3015
3016
3017 static ex H_evalf(const ex& x1, const ex& x2)
3018 {
3019         if (is_a<lst>(x1)) {
3020                 
3021                 cln::cl_N x;
3022                 if (is_a<numeric>(x2)) {
3023                         x = ex_to<numeric>(x2).to_cl_N();
3024                 } else {
3025                         ex x2_val = x2.evalf();
3026                         if (is_a<numeric>(x2_val)) {
3027                                 x = ex_to<numeric>(x2_val).to_cl_N();
3028                         }
3029                 }
3030
3031                 for (int i=0; i<x1.nops(); i++) {
3032                         if (!x1.op(i).info(info_flags::integer)) {
3033                                 return H(x1, x2).hold();
3034                         }
3035                 }
3036                 if (x1.nops() < 1) {
3037                         return H(x1, x2).hold();
3038                 }
3039
3040                 const lst& morg = ex_to<lst>(x1);
3041                 // remove trailing zeros ...
3042                 if (*(--morg.end()) == 0) {
3043                         symbol xtemp("xtemp");
3044                         map_trafo_H_reduce_trailing_zeros filter;
3045                         return filter(H(x1, xtemp).hold()).subs(xtemp==x2).evalf();
3046                 }
3047                 // ... and expand parameter notation
3048                 bool has_minus_one = false;
3049                 lst m;
3050                 for (lst::const_iterator it = morg.begin(); it != morg.end(); it++) {
3051                         if (*it > 1) {
3052                                 for (ex count=*it-1; count > 0; count--) {
3053                                         m.append(0);
3054                                 }
3055                                 m.append(1);
3056                         } else if (*it <= -1) {
3057                                 for (ex count=*it+1; count < 0; count++) {
3058                                         m.append(0);
3059                                 }
3060                                 m.append(-1);
3061                                 has_minus_one = true;
3062                         } else {
3063                                 m.append(*it);
3064                         }
3065                 }
3066
3067                 // do summation
3068                 if (cln::abs(x) < 0.95) {
3069                         lst m_lst;
3070                         lst s_lst;
3071                         ex pf;
3072                         if (convert_parameter_H_to_Li(m, m_lst, s_lst, pf)) {
3073                                 // negative parameters -> s_lst is filled
3074                                 std::vector<int> m_int;
3075                                 std::vector<cln::cl_N> x_cln;
3076                                 for (lst::const_iterator it_int = m_lst.begin(), it_cln = s_lst.begin(); 
3077                                      it_int != m_lst.end(); it_int++, it_cln++) {
3078                                         m_int.push_back(ex_to<numeric>(*it_int).to_int());
3079                                         x_cln.push_back(ex_to<numeric>(*it_cln).to_cl_N());
3080                                 }
3081                                 x_cln.front() = x_cln.front() * x;
3082                                 return pf * numeric(multipleLi_do_sum(m_int, x_cln));
3083                         } else {
3084                                 // only positive parameters
3085                                 //TODO
3086                                 if (m_lst.nops() == 1) {
3087                                         return Li(m_lst.op(0), x2).evalf();
3088                                 }
3089                                 std::vector<int> m_int;
3090                                 for (lst::const_iterator it = m_lst.begin(); it != m_lst.end(); it++) {
3091                                         m_int.push_back(ex_to<numeric>(*it).to_int());
3092                                 }
3093                                 return numeric(H_do_sum(m_int, x));
3094                         }
3095                 }
3096
3097                 symbol xtemp("xtemp");
3098                 ex res = 1;     
3099                 
3100                 // ensure that the realpart of the argument is positive
3101                 if (cln::realpart(x) < 0) {
3102                         x = -x;
3103                         for (int i=0; i<m.nops(); i++) {
3104                                 if (m.op(i) != 0) {
3105                                         m.let_op(i) = -m.op(i);
3106                                         res *= -1;
3107                                 }
3108                         }
3109                 }
3110
3111                 // x -> 1/x
3112                 if (cln::abs(x) >= 2.0) {
3113                         map_trafo_H_1overx trafo;
3114                         res *= trafo(H(m, xtemp));
3115                         if (cln::imagpart(x) <= 0) {
3116                                 res = res.subs(H_polesign == -I*Pi);
3117                         } else {
3118                                 res = res.subs(H_polesign == I*Pi);
3119                         }
3120                         return res.subs(xtemp == numeric(x)).evalf();
3121                 }
3122                 
3123                 // check transformations for 0.95 <= |x| < 2.0
3124                 
3125                 // |(1-x)/(1+x)| < 0.9 -> circular area with center=9.53+0i and radius=9.47
3126                 if (cln::abs(x-9.53) <= 9.47) {
3127                         // x -> (1-x)/(1+x)
3128                         map_trafo_H_1mxt1px trafo;
3129                         res *= trafo(H(m, xtemp));
3130                 } else {
3131                         // x -> 1-x
3132                         if (has_minus_one) {
3133                                 map_trafo_H_convert_to_Li filter;
3134                                 return filter(H(m, numeric(x)).hold()).evalf();
3135                         }
3136                         map_trafo_H_1mx trafo;
3137                         res *= trafo(H(m, xtemp));
3138                 }
3139
3140                 return res.subs(xtemp == numeric(x)).evalf();
3141         }
3142
3143         return H(x1,x2).hold();
3144 }
3145
3146
3147 static ex H_eval(const ex& m_, const ex& x)
3148 {
3149         lst m;
3150         if (is_a<lst>(m_)) {
3151                 m = ex_to<lst>(m_);
3152         } else {
3153                 m = lst(m_);
3154         }
3155         if (m.nops() == 0) {
3156                 return _ex1;
3157         }
3158         ex pos1;
3159         ex pos2;
3160         ex n;
3161         ex p;
3162         int step = 0;
3163         if (*m.begin() > _ex1) {
3164                 step++;
3165                 pos1 = _ex0;
3166                 pos2 = _ex1;
3167                 n = *m.begin()-1;
3168                 p = _ex1;
3169         } else if (*m.begin() < _ex_1) {
3170                 step++;
3171                 pos1 = _ex0;
3172                 pos2 = _ex_1;
3173                 n = -*m.begin()-1;
3174                 p = _ex1;
3175         } else if (*m.begin() == _ex0) {
3176                 pos1 = _ex0;
3177                 n = _ex1;
3178         } else {
3179                 pos1 = *m.begin();
3180                 p = _ex1;
3181         }
3182         for (lst::const_iterator it = ++m.begin(); it != m.end(); it++) {
3183                 if ((*it).info(info_flags::integer)) {
3184                         if (step == 0) {
3185                                 if (*it > _ex1) {
3186                                         if (pos1 == _ex0) {
3187                                                 step = 1;
3188                                                 pos2 = _ex1;
3189                                                 n += *it-1;
3190                                                 p = _ex1;
3191                                         } else {
3192                                                 step = 2;
3193                                         }
3194                                 } else if (*it < _ex_1) {
3195                                         if (pos1 == _ex0) {
3196                                                 step = 1;
3197                                                 pos2 = _ex_1;
3198                                                 n += -*it-1;
3199                                                 p = _ex1;
3200                                         } else {
3201                                                 step = 2;
3202                                         }
3203                                 } else {
3204                                         if (*it != pos1) {
3205                                                 step = 1;
3206                                                 pos2 = *it;
3207                                         }
3208                                         if (*it == _ex0) {
3209                                                 n++;
3210                                         } else {
3211                                                 p++;
3212                                         }
3213                                 }
3214                         } else if (step == 1) {
3215                                 if (*it != pos2) {
3216                                         step = 2;
3217                                 } else {
3218                                         if (*it == _ex0) {
3219                                                 n++;
3220                                         } else {
3221                                                 p++;
3222                                         }
3223                                 }
3224                         }
3225                 } else {
3226                         // if some m_i is not an integer
3227                         return H(m_, x).hold();
3228                 }
3229         }
3230         if ((x == _ex1) && (*(--m.end()) != _ex0)) {
3231                 return convert_H_to_zeta(m);
3232         }
3233         if (step == 0) {
3234                 if (pos1 == _ex0) {
3235                         // all zero
3236                         if (x == _ex0) {
3237                                 return H(m_, x).hold();
3238                         }
3239                         return pow(log(x), m.nops()) / factorial(m.nops());
3240                 } else {
3241                         // all (minus) one
3242                         return pow(-pos1*log(1-pos1*x), m.nops()) / factorial(m.nops());
3243                 }
3244         } else if ((step == 1) && (pos1 == _ex0)){
3245                 // convertible to S
3246                 if (pos2 == _ex1) {
3247                         return S(n, p, x);
3248                 } else {
3249                         return pow(-1, p) * S(n, p, -x);
3250                 }
3251         }
3252         if (x == _ex0) {
3253                 return _ex0;
3254         }
3255         if (x.info(info_flags::numeric) && (!x.info(info_flags::crational))) {
3256                 return H(m_, x).evalf();
3257         }
3258         return H(m_, x).hold();
3259 }
3260
3261
3262 static ex H_series(const ex& m, const ex& x, const relational& rel, int order, unsigned options)
3263 {
3264         epvector seq;
3265         seq.push_back(expair(H(m, x), 0));
3266         return pseries(rel, seq);
3267 }
3268
3269
3270 static ex H_deriv(const ex& m_, const ex& x, unsigned deriv_param)
3271 {
3272         GINAC_ASSERT(deriv_param < 2);
3273         if (deriv_param == 0) {
3274                 return _ex0;
3275         }
3276         lst m;
3277         if (is_a<lst>(m_)) {
3278                 m = ex_to<lst>(m_);
3279         } else {
3280                 m = lst(m_);
3281         }
3282         ex mb = *m.begin();
3283         if (mb > _ex1) {
3284                 m[0]--;
3285                 return H(m, x) / x;
3286         }
3287         if (mb < _ex_1) {
3288                 m[0]++;
3289                 return H(m, x) / x;
3290         }
3291         m.remove_first();
3292         if (mb == _ex1) {
3293                 return 1/(1-x) * H(m, x);
3294         } else if (mb == _ex_1) {
3295                 return 1/(1+x) * H(m, x);
3296         } else {
3297                 return H(m, x) / x;
3298         }
3299 }
3300
3301
3302 static void H_print_latex(const ex& m_, const ex& x, const print_context& c)
3303 {
3304         lst m;
3305         if (is_a<lst>(m_)) {
3306                 m = ex_to<lst>(m_);
3307         } else {
3308                 m = lst(m_);
3309         }
3310         c.s << "\\mbox{H}_{";
3311         lst::const_iterator itm = m.begin();
3312         (*itm).print(c);
3313         itm++;
3314         for (; itm != m.end(); itm++) {
3315                 c.s << ",";
3316                 (*itm).print(c);
3317         }
3318         c.s << "}(";
3319         x.print(c);
3320         c.s << ")";
3321 }
3322
3323
3324 REGISTER_FUNCTION(H,
3325                   evalf_func(H_evalf).
3326                   eval_func(H_eval).
3327                   series_func(H_series).
3328                   derivative_func(H_deriv).
3329                   print_func<print_latex>(H_print_latex).
3330                   do_not_evalf_params());
3331
3332
3333 // takes a parameter list for H and returns an expression with corresponding multiple polylogarithms
3334 ex convert_H_to_Li(const ex& m, const ex& x)
3335 {
3336         map_trafo_H_reduce_trailing_zeros filter;
3337         map_trafo_H_convert_to_Li filter2;
3338         if (is_a<lst>(m)) {
3339                 return filter2(filter(H(m, x).hold()));
3340         } else {
3341                 return filter2(filter(H(lst(m), x).hold()));
3342         }
3343 }
3344
3345
3346 //////////////////////////////////////////////////////////////////////
3347 //
3348 // Multiple zeta values  zeta(x) and zeta(x,s)
3349 //
3350 // helper functions
3351 //
3352 //////////////////////////////////////////////////////////////////////
3353
3354
3355 // anonymous namespace for helper functions
3356 namespace {
3357
3358
3359 // parameters and data for [Cra] algorithm
3360 const cln::cl_N lambda = cln::cl_N("319/320");
3361 int L1;
3362 int L2;
3363 std::vector<std::vector<cln::cl_N> > f_kj;
3364 std::vector<cln::cl_N> crB;
3365 std::vector<std::vector<cln::cl_N> > crG;
3366 std::vector<cln::cl_N> crX;
3367
3368
3369 void halfcyclic_convolute(const std::vector<cln::cl_N>& a, const std::vector<cln::cl_N>& b, std::vector<cln::cl_N>& c)
3370 {
3371         const int size = a.size();
3372         for (int n=0; n<size; n++) {
3373                 c[n] = 0;
3374                 for (int m=0; m<=n; m++) {
3375                         c[n] = c[n] + a[m]*b[n-m];
3376                 }
3377         }
3378 }
3379
3380
3381 // [Cra] section 4
3382 void initcX(const std::vector<int>& s)
3383 {
3384         const int k = s.size();
3385
3386         crX.clear();
3387         crG.clear();
3388         crB.clear();
3389
3390         for (int i=0; i<=L2; i++) {
3391                 crB.push_back(bernoulli(i).to_cl_N() / cln::factorial(i));
3392         }
3393
3394         int Sm = 0;
3395         int Smp1 = 0;
3396         for (int m=0; m<k-1; m++) {
3397                 std::vector<cln::cl_N> crGbuf;
3398                 Sm = Sm + s[m];
3399                 Smp1 = Sm + s[m+1];
3400                 for (int i=0; i<=L2; i++) {
3401                         crGbuf.push_back(cln::factorial(i + Sm - m - 2) / cln::factorial(i + Smp1 - m - 2));
3402                 }
3403                 crG.push_back(crGbuf);
3404         }
3405
3406         crX = crB;
3407
3408         for (int m=0; m<k-1; m++) {
3409                 std::vector<cln::cl_N> Xbuf;
3410                 for (int i=0; i<=L2; i++) {
3411                         Xbuf.push_back(crX[i] * crG[m][i]);
3412                 }
3413                 halfcyclic_convolute(Xbuf, crB, crX);
3414         }
3415 }
3416
3417
3418 // [Cra] section 4
3419 cln::cl_N crandall_Y_loop(const cln::cl_N& Sqk)
3420 {
3421         cln::cl_F one = cln::cl_float(1, cln::float_format(Digits));
3422         cln::cl_N factor = cln::expt(lambda, Sqk);
3423         cln::cl_N res = factor / Sqk * crX[0] * one;
3424         cln::cl_N resbuf;
3425         int N = 0;
3426         do {
3427                 resbuf = res;
3428                 factor = factor * lambda;
3429                 N++;
3430                 res = res + crX[N] * factor / (N+Sqk);
3431         } while ((res != resbuf) || cln::zerop(crX[N]));
3432         return res;
3433 }
3434
3435
3436 // [Cra] section 4
3437 void calc_f(int maxr)
3438 {
3439         f_kj.clear();
3440         f_kj.resize(L1);
3441         
3442         cln::cl_N t0, t1, t2, t3, t4;
3443         int i, j, k;
3444         std::vector<std::vector<cln::cl_N> >::iterator it = f_kj.begin();
3445         cln::cl_F one = cln::cl_float(1, cln::float_format(Digits));
3446         
3447         t0 = cln::exp(-lambda);
3448         t2 = 1;
3449         for (k=1; k<=L1; k++) {
3450                 t1 = k * lambda;
3451                 t2 = t0 * t2;
3452                 for (j=1; j<=maxr; j++) {
3453                         t3 = 1;
3454                         t4 = 1;
3455                         for (i=2; i<=j; i++) {
3456                                 t4 = t4 * (j-i+1);
3457                                 t3 = t1 * t3 + t4;
3458                         }
3459                         (*it).push_back(t2 * t3 * cln::expt(cln::cl_I(k),-j) * one);
3460                 }
3461                 it++;
3462         }
3463 }
3464
3465
3466 // [Cra] (3.1)
3467 cln::cl_N crandall_Z(const std::vector<int>& s)
3468 {
3469         const int j = s.size();
3470
3471         if (j == 1) {   
3472                 cln::cl_N t0;
3473                 cln::cl_N t0buf;
3474                 int q = 0;
3475                 do {
3476                         t0buf = t0;
3477                         q++;
3478                         t0 = t0 + f_kj[q+j-2][s[0]-1];
3479                 } while (t0 != t0buf);
3480                 
3481                 return t0 / cln::factorial(s[0]-1);
3482         }
3483
3484         std::vector<cln::cl_N> t(j);
3485
3486         cln::cl_N t0buf;
3487         int q = 0;
3488         do {
3489                 t0buf = t[0];
3490                 q++;
3491                 t[j-1] = t[j-1] + 1 / cln::expt(cln::cl_I(q),s[j-1]);
3492                 for (int k=j-2; k>=1; k--) {
3493                         t[k] = t[k] + t[k+1] / cln::expt(cln::cl_I(q+j-1-k), s[k]);
3494                 }
3495                 t[0] = t[0] + t[1] * f_kj[q+j-2][s[0]-1];
3496         } while (t[0] != t0buf);
3497         
3498         return t[0] / cln::factorial(s[0]-1);
3499 }
3500
3501
3502 // [Cra] (2.4)
3503 cln::cl_N zeta_do_sum_Crandall(const std::vector<int>& s)
3504 {
3505         std::vector<int> r = s;
3506         const int j = r.size();
3507
3508         // decide on maximal size of f_kj for crandall_Z
3509         if (Digits < 50) {
3510                 L1 = 150;
3511         } else {
3512                 L1 = Digits * 3 + j*2;
3513         }
3514
3515         // decide on maximal size of crX for crandall_Y
3516         if (Digits < 38) {
3517                 L2 = 63;
3518         } else if (Digits < 86) {
3519                 L2 = 127;
3520         } else if (Digits < 192) {
3521                 L2 = 255;
3522         } else if (Digits < 394) {
3523                 L2 = 511;
3524         } else if (Digits < 808) {
3525                 L2 = 1023;
3526         } else {
3527                 L2 = 2047;
3528         }
3529
3530         cln::cl_N res;
3531
3532         int maxr = 0;
3533         int S = 0;
3534         for (int i=0; i<j; i++) {
3535                 S += r[i];
3536                 if (r[i] > maxr) {
3537                         maxr = r[i];
3538                 }
3539         }
3540
3541         calc_f(maxr);
3542
3543         const cln::cl_N r0factorial = cln::factorial(r[0]-1);
3544
3545         std::vector<int> rz;
3546         int skp1buf;
3547         int Srun = S;
3548         for (int k=r.size()-1; k>0; k--) {
3549
3550                 rz.insert(rz.begin(), r.back());
3551                 skp1buf = rz.front();
3552                 Srun -= skp1buf;
3553                 r.pop_back();
3554
3555                 initcX(r);
3556                 
3557                 for (int q=0; q<skp1buf; q++) {
3558                         
3559                         cln::cl_N pp1 = crandall_Y_loop(Srun+q-k);
3560                         cln::cl_N pp2 = crandall_Z(rz);
3561
3562                         rz.front()--;
3563                         
3564                         if (q & 1) {
3565                                 res = res - pp1 * pp2 / cln::factorial(q);
3566                         } else {
3567                                 res = res + pp1 * pp2 / cln::factorial(q);
3568                         }
3569                 }
3570                 rz.front() = skp1buf;
3571         }
3572         rz.insert(rz.begin(), r.back());
3573
3574         initcX(rz);
3575
3576         res = (res + crandall_Y_loop(S-j)) / r0factorial + crandall_Z(rz);
3577
3578         return res;
3579 }
3580
3581
3582 cln::cl_N zeta_do_sum_simple(const std::vector<int>& r)
3583 {
3584         const int j = r.size();
3585
3586         // buffer for subsums
3587         std::vector<cln::cl_N> t(j);
3588         cln::cl_F one = cln::cl_float(1, cln::float_format(Digits));
3589
3590         cln::cl_N t0buf;
3591         int q = 0;
3592         do {
3593                 t0buf = t[0];
3594                 q++;
3595                 t[j-1] = t[j-1] + one / cln::expt(cln::cl_I(q),r[j-1]);
3596                 for (int k=j-2; k>=0; k--) {
3597                         t[k] = t[k] + one * t[k+1] / cln::expt(cln::cl_I(q+j-1-k), r[k]);
3598                 }
3599         } while (t[0] != t0buf);
3600
3601         return t[0];
3602 }
3603
3604
3605 // does Hoelder convolution. see [BBB] (7.0)
3606 cln::cl_N zeta_do_Hoelder_convolution(const std::vector<int>& m_, const std::vector<int>& s_)
3607 {
3608         // prepare parameters
3609         // holds Li arguments in [BBB] notation
3610         std::vector<int> s = s_;
3611         std::vector<int> m_p = m_;
3612         std::vector<int> m_q;
3613         // holds Li arguments in nested sums notation
3614         std::vector<cln::cl_N> s_p(s.size(), cln::cl_N(1));
3615         s_p[0] = s_p[0] * cln::cl_N("1/2");
3616         // convert notations
3617         int sig = 1;
3618         for (int i=0; i<s_.size(); i++) {
3619                 if (s_[i] < 0) {
3620                         sig = -sig;
3621                         s_p[i] = -s_p[i];
3622                 }
3623                 s[i] = sig * std::abs(s[i]);
3624         }
3625         std::vector<cln::cl_N> s_q;
3626         cln::cl_N signum = 1;
3627
3628         // first term
3629         cln::cl_N res = multipleLi_do_sum(m_p, s_p);
3630
3631         // middle terms
3632         do {
3633
3634                 // change parameters
3635                 if (s.front() > 0) {
3636                         if (m_p.front() == 1) {
3637                                 m_p.erase(m_p.begin());
3638                                 s_p.erase(s_p.begin());
3639                                 if (s_p.size() > 0) {
3640                                         s_p.front() = s_p.front() * cln::cl_N("1/2");
3641                                 }
3642                                 s.erase(s.begin());
3643                                 m_q.front()++;
3644                         } else {
3645                                 m_p.front()--;
3646                                 m_q.insert(m_q.begin(), 1);
3647                                 if (s_q.size() > 0) {
3648                                         s_q.front() = s_q.front() * 2;
3649                                 }
3650                                 s_q.insert(s_q.begin(), cln::cl_N("1/2"));
3651                         }
3652                 } else {
3653                         if (m_p.front() == 1) {
3654                                 m_p.erase(m_p.begin());
3655                                 cln::cl_N spbuf = s_p.front();
3656                                 s_p.erase(s_p.begin());
3657                                 if (s_p.size() > 0) {
3658                                         s_p.front() = s_p.front() * spbuf;
3659                                 }
3660                                 s.erase(s.begin());
3661                                 m_q.insert(m_q.begin(), 1);
3662                                 if (s_q.size() > 0) {
3663                                         s_q.front() = s_q.front() * 4;
3664                                 }
3665                                 s_q.insert(s_q.begin(), cln::cl_N("1/4"));
3666                                 signum = -signum;
3667                         } else {
3668                                 m_p.front()--;
3669                                 m_q.insert(m_q.begin(), 1);
3670                                 if (s_q.size() > 0) {
3671                                         s_q.front() = s_q.front() * 2;
3672                                 }
3673                                 s_q.insert(s_q.begin(), cln::cl_N("1/2"));
3674                         }
3675                 }
3676
3677                 // exiting the loop
3678                 if (m_p.size() == 0) break;
3679
3680                 res = res + signum * multipleLi_do_sum(m_p, s_p) * multipleLi_do_sum(m_q, s_q);
3681
3682         } while (true);
3683
3684         // last term
3685         res = res + signum * multipleLi_do_sum(m_q, s_q);
3686
3687         return res;
3688 }
3689
3690
3691 } // end of anonymous namespace
3692
3693
3694 //////////////////////////////////////////////////////////////////////
3695 //
3696 // Multiple zeta values  zeta(x)
3697 //
3698 // GiNaC function
3699 //
3700 //////////////////////////////////////////////////////////////////////
3701
3702
3703 static ex zeta1_evalf(const ex& x)
3704 {
3705         if (is_exactly_a<lst>(x) && (x.nops()>1)) {
3706
3707                 // multiple zeta value
3708                 const int count = x.nops();
3709                 const lst& xlst = ex_to<lst>(x);
3710                 std::vector<int> r(count);
3711
3712                 // check parameters and convert them
3713                 lst::const_iterator it1 = xlst.begin();
3714                 std::vector<int>::iterator it2 = r.begin();
3715                 do {
3716                         if (!(*it1).info(info_flags::posint)) {
3717                                 return zeta(x).hold();
3718                         }
3719                         *it2 = ex_to<numeric>(*it1).to_int();
3720                         it1++;
3721                         it2++;
3722                 } while (it2 != r.end());
3723
3724                 // check for divergence
3725                 if (r[0] == 1) {
3726                         return zeta(x).hold();
3727                 }
3728
3729                 // decide on summation algorithm
3730                 // this is still a bit clumsy
3731                 int limit = (Digits>17) ? 10 : 6;
3732                 if ((r[0] < limit) || ((count > 3) && (r[1] < limit/2))) {
3733                         return numeric(zeta_do_sum_Crandall(r));
3734                 } else {
3735                         return numeric(zeta_do_sum_simple(r));
3736                 }
3737         }
3738
3739         // single zeta value
3740         if (is_exactly_a<numeric>(x) && (x != 1)) {
3741                 try {
3742                         return zeta(ex_to<numeric>(x));
3743                 } catch (const dunno &e) { }
3744         }
3745
3746         return zeta(x).hold();
3747 }
3748
3749
3750 static ex zeta1_eval(const ex& m)
3751 {
3752         if (is_exactly_a<lst>(m)) {
3753                 if (m.nops() == 1) {
3754                         return zeta(m.op(0));
3755                 }
3756                 return zeta(m).hold();
3757         }
3758
3759         if (m.info(info_flags::numeric)) {
3760                 const numeric& y = ex_to<numeric>(m);
3761                 // trap integer arguments:
3762                 if (y.is_integer()) {
3763                         if (y.is_zero()) {
3764                                 return _ex_1_2;
3765                         }
3766                         if (y.is_equal(*_num1_p)) {
3767                                 return zeta(m).hold();
3768                         }
3769                         if (y.info(info_flags::posint)) {
3770                                 if (y.info(info_flags::odd)) {
3771                                         return zeta(m).hold();
3772                                 } else {
3773                                         return abs(bernoulli(y)) * pow(Pi, y) * pow(*_num2_p, y-(*_num1_p)) / factorial(y);
3774                                 }
3775                         } else {
3776                                 if (y.info(info_flags::odd)) {
3777                                         return -bernoulli((*_num1_p)-y) / ((*_num1_p)-y);
3778                                 } else {
3779                                         return _ex0;
3780                                 }
3781                         }
3782                 }
3783                 // zeta(float)
3784                 if (y.info(info_flags::numeric) && !y.info(info_flags::crational)) {
3785                         return zeta1_evalf(m);
3786                 }
3787         }
3788         return zeta(m).hold();
3789 }
3790
3791
3792 static ex zeta1_deriv(const ex& m, unsigned deriv_param)
3793 {
3794         GINAC_ASSERT(deriv_param==0);
3795
3796         if (is_exactly_a<lst>(m)) {
3797                 return _ex0;
3798         } else {
3799                 return zetaderiv(_ex1, m);
3800         }
3801 }
3802
3803
3804 static void zeta1_print_latex(const ex& m_, const print_context& c)
3805 {
3806         c.s << "\\zeta(";
3807         if (is_a<lst>(m_)) {
3808                 const lst& m = ex_to<lst>(m_);
3809                 lst::const_iterator it = m.begin();
3810                 (*it).print(c);
3811                 it++;
3812                 for (; it != m.end(); it++) {
3813                         c.s << ",";
3814                         (*it).print(c);
3815                 }
3816         } else {
3817                 m_.print(c);
3818         }
3819         c.s << ")";
3820 }
3821
3822
3823 unsigned zeta1_SERIAL::serial = function::register_new(function_options("zeta", 1).
3824                                 evalf_func(zeta1_evalf).
3825                                 eval_func(zeta1_eval).
3826                                 derivative_func(zeta1_deriv).
3827                                 print_func<print_latex>(zeta1_print_latex).
3828                                 do_not_evalf_params().
3829                                 overloaded(2));
3830
3831
3832 //////////////////////////////////////////////////////////////////////
3833 //
3834 // Alternating Euler sum  zeta(x,s)
3835 //
3836 // GiNaC function
3837 //
3838 //////////////////////////////////////////////////////////////////////
3839
3840
3841 static ex zeta2_evalf(const ex& x, const ex& s)
3842 {
3843         if (is_exactly_a<lst>(x)) {
3844
3845                 // alternating Euler sum
3846                 const int count = x.nops();
3847                 const lst& xlst = ex_to<lst>(x);
3848                 const lst& slst = ex_to<lst>(s);
3849                 std::vector<int> xi(count);
3850                 std::vector<int> si(count);
3851
3852                 // check parameters and convert them
3853                 lst::const_iterator it_xread = xlst.begin();
3854                 lst::const_iterator it_sread = slst.begin();
3855                 std::vector<int>::iterator it_xwrite = xi.begin();
3856                 std::vector<int>::iterator it_swrite = si.begin();
3857                 do {
3858                         if (!(*it_xread).info(info_flags::posint)) {
3859                                 return zeta(x, s).hold();
3860                         }
3861                         *it_xwrite = ex_to<numeric>(*it_xread).to_int();
3862                         if (*it_sread > 0) {
3863                                 *it_swrite = 1;
3864                         } else {
3865                                 *it_swrite = -1;
3866                         }
3867                         it_xread++;
3868                         it_sread++;
3869                         it_xwrite++;
3870                         it_swrite++;
3871                 } while (it_xwrite != xi.end());
3872
3873                 // check for divergence
3874                 if ((xi[0] == 1) && (si[0] == 1)) {
3875                         return zeta(x, s).hold();
3876                 }
3877
3878                 // use Hoelder convolution
3879                 return numeric(zeta_do_Hoelder_convolution(xi, si));
3880         }
3881
3882         return zeta(x, s).hold();
3883 }
3884
3885
3886 static ex zeta2_eval(const ex& m, const ex& s_)
3887 {
3888         if (is_exactly_a<lst>(s_)) {
3889                 const lst& s = ex_to<lst>(s_);
3890                 for (lst::const_iterator it = s.begin(); it != s.end(); it++) {
3891                         if ((*it).info(info_flags::positive)) {
3892                                 continue;
3893                         }
3894                         return zeta(m, s_).hold();
3895                 }
3896                 return zeta(m);
3897         } else if (s_.info(info_flags::positive)) {
3898                 return zeta(m);
3899         }
3900
3901         return zeta(m, s_).hold();
3902 }
3903
3904
3905 static ex zeta2_deriv(const ex& m, const ex& s, unsigned deriv_param)
3906 {
3907         GINAC_ASSERT(deriv_param==0);
3908
3909         if (is_exactly_a<lst>(m)) {
3910                 return _ex0;
3911         } else {
3912                 if ((is_exactly_a<lst>(s) && s.op(0).info(info_flags::positive)) || s.info(info_flags::positive)) {
3913                         return zetaderiv(_ex1, m);
3914                 }
3915                 return _ex0;
3916         }
3917 }
3918
3919
3920 static void zeta2_print_latex(const ex& m_, const ex& s_, const print_context& c)
3921 {
3922         lst m;
3923         if (is_a<lst>(m_)) {
3924                 m = ex_to<lst>(m_);
3925         } else {
3926                 m = lst(m_);
3927         }
3928         lst s;
3929         if (is_a<lst>(s_)) {
3930                 s = ex_to<lst>(s_);
3931         } else {
3932                 s = lst(s_);
3933         }
3934         c.s << "\\zeta(";
3935         lst::const_iterator itm = m.begin();
3936         lst::const_iterator its = s.begin();
3937         if (*its < 0) {
3938                 c.s << "\\overline{";
3939                 (*itm).print(c);
3940                 c.s << "}";
3941         } else {
3942                 (*itm).print(c);
3943         }
3944         its++;
3945         itm++;
3946         for (; itm != m.end(); itm++, its++) {
3947                 c.s << ",";
3948                 if (*its < 0) {
3949                         c.s << "\\overline{";
3950                         (*itm).print(c);
3951                         c.s << "}";
3952                 } else {
3953                         (*itm).print(c);
3954                 }
3955         }
3956         c.s << ")";
3957 }
3958
3959
3960 unsigned zeta2_SERIAL::serial = function::register_new(function_options("zeta", 2).
3961                                 evalf_func(zeta2_evalf).
3962                                 eval_func(zeta2_eval).
3963                                 derivative_func(zeta2_deriv).
3964                                 print_func<print_latex>(zeta2_print_latex).
3965                                 do_not_evalf_params().
3966                                 overloaded(2));
3967
3968
3969 } // namespace GiNaC
3970