]> www.ginac.de Git - ginac.git/blob - ginac/pseries.cpp
./configure now gives more information/warnings about missing utilities.
[ginac.git] / ginac / pseries.cpp
1 /** @file pseries.cpp
2  *
3  *  Implementation of class for extended truncated power series and
4  *  methods for series expansion. */
5
6 /*
7  *  GiNaC Copyright (C) 1999-2011 Johannes Gutenberg University Mainz, Germany
8  *
9  *  This program is free software; you can redistribute it and/or modify
10  *  it under the terms of the GNU General Public License as published by
11  *  the Free Software Foundation; either version 2 of the License, or
12  *  (at your option) any later version.
13  *
14  *  This program is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *  GNU General Public License for more details.
18  *
19  *  You should have received a copy of the GNU General Public License
20  *  along with this program; if not, write to the Free Software
21  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
22  */
23
24 #include "pseries.h"
25 #include "add.h"
26 #include "inifcns.h" // for Order function
27 #include "lst.h"
28 #include "mul.h"
29 #include "power.h"
30 #include "relational.h"
31 #include "operators.h"
32 #include "symbol.h"
33 #include "integral.h"
34 #include "archive.h"
35 #include "utils.h"
36
37 #include <limits>
38 #include <numeric>
39 #include <stdexcept>
40
41 namespace GiNaC {
42
43 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(pseries, basic,
44   print_func<print_context>(&pseries::do_print).
45   print_func<print_latex>(&pseries::do_print_latex).
46   print_func<print_tree>(&pseries::do_print_tree).
47   print_func<print_python>(&pseries::do_print_python).
48   print_func<print_python_repr>(&pseries::do_print_python_repr))
49
50
51 /*
52  *  Default constructor
53  */
54
55 pseries::pseries() { }
56
57
58 /*
59  *  Other ctors
60  */
61
62 /** Construct pseries from a vector of coefficients and powers.
63  *  expair.rest holds the coefficient, expair.coeff holds the power.
64  *  The powers must be integers (positive or negative) and in ascending order;
65  *  the last coefficient can be Order(_ex1) to represent a truncated,
66  *  non-terminating series.
67  *
68  *  @param rel_  expansion variable and point (must hold a relational)
69  *  @param ops_  vector of {coefficient, power} pairs (coefficient must not be zero)
70  *  @return newly constructed pseries */
71 pseries::pseries(const ex &rel_, const epvector &ops_) : seq(ops_)
72 {
73         GINAC_ASSERT(is_a<relational>(rel_));
74         GINAC_ASSERT(is_a<symbol>(rel_.lhs()));
75         point = rel_.rhs();
76         var = rel_.lhs();
77 }
78
79
80 /*
81  *  Archiving
82  */
83
84 void pseries::read_archive(const archive_node &n, lst &sym_lst) 
85 {
86         inherited::read_archive(n, sym_lst);
87         archive_node::archive_node_cit first = n.find_first("coeff");
88         archive_node::archive_node_cit last = n.find_last("power");
89         ++last;
90         seq.reserve((last-first)/2);
91
92         for (archive_node::archive_node_cit loc = first; loc < last;) {
93                 ex rest;
94                 ex coeff;
95                 n.find_ex_by_loc(loc++, rest, sym_lst);
96                 n.find_ex_by_loc(loc++, coeff, sym_lst);
97                 seq.push_back(expair(rest, coeff));
98         }
99
100         n.find_ex("var", var, sym_lst);
101         n.find_ex("point", point, sym_lst);
102 }
103
104 void pseries::archive(archive_node &n) const
105 {
106         inherited::archive(n);
107         epvector::const_iterator i = seq.begin(), iend = seq.end();
108         while (i != iend) {
109                 n.add_ex("coeff", i->rest);
110                 n.add_ex("power", i->coeff);
111                 ++i;
112         }
113         n.add_ex("var", var);
114         n.add_ex("point", point);
115 }
116
117
118 //////////
119 // functions overriding virtual functions from base classes
120 //////////
121
122 void pseries::print_series(const print_context & c, const char *openbrace, const char *closebrace, const char *mul_sym, const char *pow_sym, unsigned level) const
123 {
124         if (precedence() <= level)
125                 c.s << '(';
126                 
127         // objects of type pseries must not have any zero entries, so the
128         // trivial (zero) pseries needs a special treatment here:
129         if (seq.empty())
130                 c.s << '0';
131
132         epvector::const_iterator i = seq.begin(), end = seq.end();
133         while (i != end) {
134
135                 // print a sign, if needed
136                 if (i != seq.begin())
137                         c.s << '+';
138
139                 if (!is_order_function(i->rest)) {
140
141                         // print 'rest', i.e. the expansion coefficient
142                         if (i->rest.info(info_flags::numeric) &&
143                                 i->rest.info(info_flags::positive)) {
144                                 i->rest.print(c);
145                         } else {
146                                 c.s << openbrace << '(';
147                                 i->rest.print(c);
148                                 c.s << ')' << closebrace;
149                         }
150
151                         // print 'coeff', something like (x-1)^42
152                         if (!i->coeff.is_zero()) {
153                                 c.s << mul_sym;
154                                 if (!point.is_zero()) {
155                                         c.s << openbrace << '(';
156                                         (var-point).print(c);
157                                         c.s << ')' << closebrace;
158                                 } else
159                                         var.print(c);
160                                 if (i->coeff.compare(_ex1)) {
161                                         c.s << pow_sym;
162                                         c.s << openbrace;
163                                         if (i->coeff.info(info_flags::negative)) {
164                                                 c.s << '(';
165                                                 i->coeff.print(c);
166                                                 c.s << ')';
167                                         } else
168                                                 i->coeff.print(c);
169                                         c.s << closebrace;
170                                 }
171                         }
172                 } else
173                         Order(power(var-point,i->coeff)).print(c);
174                 ++i;
175         }
176
177         if (precedence() <= level)
178                 c.s << ')';
179 }
180
181 void pseries::do_print(const print_context & c, unsigned level) const
182 {
183         print_series(c, "", "", "*", "^", level);
184 }
185
186 void pseries::do_print_latex(const print_latex & c, unsigned level) const
187 {
188         print_series(c, "{", "}", " ", "^", level);
189 }
190
191 void pseries::do_print_python(const print_python & c, unsigned level) const
192 {
193         print_series(c, "", "", "*", "**", level);
194 }
195
196 void pseries::do_print_tree(const print_tree & c, unsigned level) const
197 {
198         c.s << std::string(level, ' ') << class_name() << " @" << this
199             << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
200             << std::endl;
201         size_t num = seq.size();
202         for (size_t i=0; i<num; ++i) {
203                 seq[i].rest.print(c, level + c.delta_indent);
204                 seq[i].coeff.print(c, level + c.delta_indent);
205                 c.s << std::string(level + c.delta_indent, ' ') << "-----" << std::endl;
206         }
207         var.print(c, level + c.delta_indent);
208         point.print(c, level + c.delta_indent);
209 }
210
211 void pseries::do_print_python_repr(const print_python_repr & c, unsigned level) const
212 {
213         c.s << class_name() << "(relational(";
214         var.print(c);
215         c.s << ',';
216         point.print(c);
217         c.s << "),[";
218         size_t num = seq.size();
219         for (size_t i=0; i<num; ++i) {
220                 if (i)
221                         c.s << ',';
222                 c.s << '(';
223                 seq[i].rest.print(c);
224                 c.s << ',';
225                 seq[i].coeff.print(c);
226                 c.s << ')';
227         }
228         c.s << "])";
229 }
230
231 int pseries::compare_same_type(const basic & other) const
232 {
233         GINAC_ASSERT(is_a<pseries>(other));
234         const pseries &o = static_cast<const pseries &>(other);
235         
236         // first compare the lengths of the series...
237         if (seq.size()>o.seq.size())
238                 return 1;
239         if (seq.size()<o.seq.size())
240                 return -1;
241         
242         // ...then the expansion point...
243         int cmpval = var.compare(o.var);
244         if (cmpval)
245                 return cmpval;
246         cmpval = point.compare(o.point);
247         if (cmpval)
248                 return cmpval;
249         
250         // ...and if that failed the individual elements
251         epvector::const_iterator it = seq.begin(), o_it = o.seq.begin();
252         while (it!=seq.end() && o_it!=o.seq.end()) {
253                 cmpval = it->compare(*o_it);
254                 if (cmpval)
255                         return cmpval;
256                 ++it;
257                 ++o_it;
258         }
259
260         // so they are equal.
261         return 0;
262 }
263
264 /** Return the number of operands including a possible order term. */
265 size_t pseries::nops() const
266 {
267         return seq.size();
268 }
269
270 /** Return the ith term in the series when represented as a sum. */
271 ex pseries::op(size_t i) const
272 {
273         if (i >= seq.size())
274                 throw (std::out_of_range("op() out of range"));
275
276         if (is_order_function(seq[i].rest))
277                 return Order(power(var-point, seq[i].coeff));
278         return seq[i].rest * power(var - point, seq[i].coeff);
279 }
280
281 /** Return degree of highest power of the series.  This is usually the exponent
282  *  of the Order term.  If s is not the expansion variable of the series, the
283  *  series is examined termwise. */
284 int pseries::degree(const ex &s) const
285 {
286         if (var.is_equal(s)) {
287                 // Return last exponent
288                 if (seq.size())
289                         return ex_to<numeric>((seq.end()-1)->coeff).to_int();
290                 else
291                         return 0;
292         } else {
293                 epvector::const_iterator it = seq.begin(), itend = seq.end();
294                 if (it == itend)
295                         return 0;
296                 int max_pow = std::numeric_limits<int>::min();
297                 while (it != itend) {
298                         int pow = it->rest.degree(s);
299                         if (pow > max_pow)
300                                 max_pow = pow;
301                         ++it;
302                 }
303                 return max_pow;
304         }
305 }
306
307 /** Return degree of lowest power of the series.  This is usually the exponent
308  *  of the leading term.  If s is not the expansion variable of the series, the
309  *  series is examined termwise.  If s is the expansion variable but the
310  *  expansion point is not zero the series is not expanded to find the degree.
311  *  I.e.: (1-x) + (1-x)^2 + Order((1-x)^3) has ldegree(x) 1, not 0. */
312 int pseries::ldegree(const ex &s) const
313 {
314         if (var.is_equal(s)) {
315                 // Return first exponent
316                 if (seq.size())
317                         return ex_to<numeric>((seq.begin())->coeff).to_int();
318                 else
319                         return 0;
320         } else {
321                 epvector::const_iterator it = seq.begin(), itend = seq.end();
322                 if (it == itend)
323                         return 0;
324                 int min_pow = std::numeric_limits<int>::max();
325                 while (it != itend) {
326                         int pow = it->rest.ldegree(s);
327                         if (pow < min_pow)
328                                 min_pow = pow;
329                         ++it;
330                 }
331                 return min_pow;
332         }
333 }
334
335 /** Return coefficient of degree n in power series if s is the expansion
336  *  variable.  If the expansion point is nonzero, by definition the n=1
337  *  coefficient in s of a+b*(s-z)+c*(s-z)^2+Order((s-z)^3) is b (assuming
338  *  the expansion took place in the s in the first place).
339  *  If s is not the expansion variable, an attempt is made to convert the
340  *  series to a polynomial and return the corresponding coefficient from
341  *  there. */
342 ex pseries::coeff(const ex &s, int n) const
343 {
344         if (var.is_equal(s)) {
345                 if (seq.empty())
346                         return _ex0;
347                 
348                 // Binary search in sequence for given power
349                 numeric looking_for = numeric(n);
350                 int lo = 0, hi = seq.size() - 1;
351                 while (lo <= hi) {
352                         int mid = (lo + hi) / 2;
353                         GINAC_ASSERT(is_exactly_a<numeric>(seq[mid].coeff));
354                         int cmp = ex_to<numeric>(seq[mid].coeff).compare(looking_for);
355                         switch (cmp) {
356                                 case -1:
357                                         lo = mid + 1;
358                                         break;
359                                 case 0:
360                                         return seq[mid].rest;
361                                 case 1:
362                                         hi = mid - 1;
363                                         break;
364                                 default:
365                                         throw(std::logic_error("pseries::coeff: compare() didn't return -1, 0 or 1"));
366                         }
367                 }
368                 return _ex0;
369         } else
370                 return convert_to_poly().coeff(s, n);
371 }
372
373 /** Does nothing. */
374 ex pseries::collect(const ex &s, bool distributed) const
375 {
376         return *this;
377 }
378
379 /** Perform coefficient-wise automatic term rewriting rules in this class. */
380 ex pseries::eval(int level) const
381 {
382         if (level == 1)
383                 return this->hold();
384         
385         if (level == -max_recursion_level)
386                 throw (std::runtime_error("pseries::eval(): recursion limit exceeded"));
387         
388         // Construct a new series with evaluated coefficients
389         epvector new_seq;
390         new_seq.reserve(seq.size());
391         epvector::const_iterator it = seq.begin(), itend = seq.end();
392         while (it != itend) {
393                 new_seq.push_back(expair(it->rest.eval(level-1), it->coeff));
394                 ++it;
395         }
396         return (new pseries(relational(var,point), new_seq))->setflag(status_flags::dynallocated | status_flags::evaluated);
397 }
398
399 /** Evaluate coefficients numerically. */
400 ex pseries::evalf(int level) const
401 {
402         if (level == 1)
403                 return *this;
404         
405         if (level == -max_recursion_level)
406                 throw (std::runtime_error("pseries::evalf(): recursion limit exceeded"));
407         
408         // Construct a new series with evaluated coefficients
409         epvector new_seq;
410         new_seq.reserve(seq.size());
411         epvector::const_iterator it = seq.begin(), itend = seq.end();
412         while (it != itend) {
413                 new_seq.push_back(expair(it->rest.evalf(level-1), it->coeff));
414                 ++it;
415         }
416         return (new pseries(relational(var,point), new_seq))->setflag(status_flags::dynallocated | status_flags::evaluated);
417 }
418
419 ex pseries::conjugate() const
420 {
421         if(!var.info(info_flags::real))
422                 return conjugate_function(*this).hold();
423
424         epvector * newseq = conjugateepvector(seq);
425         ex newpoint = point.conjugate();
426
427         if (!newseq && are_ex_trivially_equal(point, newpoint)) {
428                 return *this;
429         }
430
431         ex result = (new pseries(var==newpoint, newseq ? *newseq : seq))->setflag(status_flags::dynallocated);
432         delete newseq;
433         return result;
434 }
435
436 ex pseries::real_part() const
437 {
438         if(!var.info(info_flags::real))
439                 return real_part_function(*this).hold();
440         ex newpoint = point.real_part();
441         if(newpoint != point)
442                 return real_part_function(*this).hold();
443
444         epvector v;
445         v.reserve(seq.size());
446         for(epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i)
447                 v.push_back(expair((i->rest).real_part(), i->coeff));
448         return (new pseries(var==point, v))->setflag(status_flags::dynallocated);
449 }
450
451 ex pseries::imag_part() const
452 {
453         if(!var.info(info_flags::real))
454                 return imag_part_function(*this).hold();
455         ex newpoint = point.real_part();
456         if(newpoint != point)
457                 return imag_part_function(*this).hold();
458
459         epvector v;
460         v.reserve(seq.size());
461         for(epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i)
462                 v.push_back(expair((i->rest).imag_part(), i->coeff));
463         return (new pseries(var==point, v))->setflag(status_flags::dynallocated);
464 }
465
466 ex pseries::eval_integ() const
467 {
468         epvector *newseq = NULL;
469         for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i) {
470                 if (newseq) {
471                         newseq->push_back(expair(i->rest.eval_integ(), i->coeff));
472                         continue;
473                 }
474                 ex newterm = i->rest.eval_integ();
475                 if (!are_ex_trivially_equal(newterm, i->rest)) {
476                         newseq = new epvector;
477                         newseq->reserve(seq.size());
478                         for (epvector::const_iterator j=seq.begin(); j!=i; ++j)
479                                 newseq->push_back(*j);
480                         newseq->push_back(expair(newterm, i->coeff));
481                 }
482         }
483
484         ex newpoint = point.eval_integ();
485         if (newseq || !are_ex_trivially_equal(newpoint, point))
486                 return (new pseries(var==newpoint, *newseq))
487                        ->setflag(status_flags::dynallocated);
488         return *this;
489 }
490
491 ex pseries::evalm() const
492 {
493         // evalm each coefficient
494         epvector newseq;
495         bool something_changed = false;
496         for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i) {
497                 if (something_changed) {
498                         ex newcoeff = i->rest.evalm();
499                         if (!newcoeff.is_zero())
500                                 newseq.push_back(expair(newcoeff, i->coeff));
501                 }
502                 else {
503                         ex newcoeff = i->rest.evalm();
504                         if (!are_ex_trivially_equal(newcoeff, i->rest)) {
505                                 something_changed = true;
506                                 newseq.reserve(seq.size());
507                                 std::copy(seq.begin(), i, std::back_inserter<epvector>(newseq));
508                                 if (!newcoeff.is_zero())
509                                         newseq.push_back(expair(newcoeff, i->coeff));
510                         }
511                 }
512         }
513         if (something_changed)
514                 return (new pseries(var==point, newseq))->setflag(status_flags::dynallocated);
515         else
516                 return *this;
517 }
518
519 ex pseries::subs(const exmap & m, unsigned options) const
520 {
521         // If expansion variable is being substituted, convert the series to a
522         // polynomial and do the substitution there because the result might
523         // no longer be a power series
524         if (m.find(var) != m.end())
525                 return convert_to_poly(true).subs(m, options);
526         
527         // Otherwise construct a new series with substituted coefficients and
528         // expansion point
529         epvector newseq;
530         newseq.reserve(seq.size());
531         epvector::const_iterator it = seq.begin(), itend = seq.end();
532         while (it != itend) {
533                 newseq.push_back(expair(it->rest.subs(m, options), it->coeff));
534                 ++it;
535         }
536         return (new pseries(relational(var,point.subs(m, options)), newseq))->setflag(status_flags::dynallocated);
537 }
538
539 /** Implementation of ex::expand() for a power series.  It expands all the
540  *  terms individually and returns the resulting series as a new pseries. */
541 ex pseries::expand(unsigned options) const
542 {
543         epvector newseq;
544         epvector::const_iterator i = seq.begin(), end = seq.end();
545         while (i != end) {
546                 ex restexp = i->rest.expand();
547                 if (!restexp.is_zero())
548                         newseq.push_back(expair(restexp, i->coeff));
549                 ++i;
550         }
551         return (new pseries(relational(var,point), newseq))
552                 ->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
553 }
554
555 /** Implementation of ex::diff() for a power series.
556  *  @see ex::diff */
557 ex pseries::derivative(const symbol & s) const
558 {
559         epvector new_seq;
560         epvector::const_iterator it = seq.begin(), itend = seq.end();
561
562         if (s == var) {
563                 
564                 // FIXME: coeff might depend on var
565                 while (it != itend) {
566                         if (is_order_function(it->rest)) {
567                                 new_seq.push_back(expair(it->rest, it->coeff - 1));
568                         } else {
569                                 ex c = it->rest * it->coeff;
570                                 if (!c.is_zero())
571                                         new_seq.push_back(expair(c, it->coeff - 1));
572                         }
573                         ++it;
574                 }
575
576         } else {
577
578                 while (it != itend) {
579                         if (is_order_function(it->rest)) {
580                                 new_seq.push_back(*it);
581                         } else {
582                                 ex c = it->rest.diff(s);
583                                 if (!c.is_zero())
584                                         new_seq.push_back(expair(c, it->coeff));
585                         }
586                         ++it;
587                 }
588         }
589
590         return pseries(relational(var,point), new_seq);
591 }
592
593 ex pseries::convert_to_poly(bool no_order) const
594 {
595         ex e;
596         epvector::const_iterator it = seq.begin(), itend = seq.end();
597         
598         while (it != itend) {
599                 if (is_order_function(it->rest)) {
600                         if (!no_order)
601                                 e += Order(power(var - point, it->coeff));
602                 } else
603                         e += it->rest * power(var - point, it->coeff);
604                 ++it;
605         }
606         return e;
607 }
608
609 bool pseries::is_terminating() const
610 {
611         return seq.empty() || !is_order_function((seq.end()-1)->rest);
612 }
613
614 ex pseries::coeffop(size_t i) const
615 {
616         if (i >=nops())
617                 throw (std::out_of_range("coeffop() out of range"));
618         return seq[i].rest;
619 }
620
621 ex pseries::exponop(size_t i) const
622 {
623         if (i >= nops())
624                 throw (std::out_of_range("exponop() out of range"));
625         return seq[i].coeff;
626 }
627
628
629 /*
630  *  Implementations of series expansion
631  */
632
633 /** Default implementation of ex::series(). This performs Taylor expansion.
634  *  @see ex::series */
635 ex basic::series(const relational & r, int order, unsigned options) const
636 {
637         epvector seq;
638         const symbol &s = ex_to<symbol>(r.lhs());
639
640         // default for order-values that make no sense for Taylor expansion
641         if ((order <= 0) && this->has(s)) {
642                 seq.push_back(expair(Order(_ex1), order));
643                 return pseries(r, seq);
644         }
645
646         // do Taylor expansion
647         numeric fac = 1;
648         ex deriv = *this;
649         ex coeff = deriv.subs(r, subs_options::no_pattern);
650
651         if (!coeff.is_zero()) {
652                 seq.push_back(expair(coeff, _ex0));
653         }
654
655         int n;
656         for (n=1; n<order; ++n) {
657                 fac = fac.mul(n);
658                 // We need to test for zero in order to see if the series terminates.
659                 // The problem is that there is no such thing as a perfect test for
660                 // zero.  Expanding the term occasionally helps a little...
661                 deriv = deriv.diff(s).expand();
662                 if (deriv.is_zero())  // Series terminates
663                         return pseries(r, seq);
664
665                 coeff = deriv.subs(r, subs_options::no_pattern);
666                 if (!coeff.is_zero())
667                         seq.push_back(expair(fac.inverse() * coeff, n));
668         }
669         
670         // Higher-order terms, if present
671         deriv = deriv.diff(s);
672         if (!deriv.expand().is_zero())
673                 seq.push_back(expair(Order(_ex1), n));
674         return pseries(r, seq);
675 }
676
677
678 /** Implementation of ex::series() for symbols.
679  *  @see ex::series */
680 ex symbol::series(const relational & r, int order, unsigned options) const
681 {
682         epvector seq;
683         const ex point = r.rhs();
684         GINAC_ASSERT(is_a<symbol>(r.lhs()));
685
686         if (this->is_equal_same_type(ex_to<symbol>(r.lhs()))) {
687                 if (order > 0 && !point.is_zero())
688                         seq.push_back(expair(point, _ex0));
689                 if (order > 1)
690                         seq.push_back(expair(_ex1, _ex1));
691                 else
692                         seq.push_back(expair(Order(_ex1), numeric(order)));
693         } else
694                 seq.push_back(expair(*this, _ex0));
695         return pseries(r, seq);
696 }
697
698
699 /** Add one series object to another, producing a pseries object that
700  *  represents the sum.
701  *
702  *  @param other  pseries object to add with
703  *  @return the sum as a pseries */
704 ex pseries::add_series(const pseries &other) const
705 {
706         // Adding two series with different variables or expansion points
707         // results in an empty (constant) series 
708         if (!is_compatible_to(other)) {
709                 epvector nul;
710                 nul.push_back(expair(Order(_ex1), _ex0));
711                 return pseries(relational(var,point), nul);
712         }
713         
714         // Series addition
715         epvector new_seq;
716         epvector::const_iterator a = seq.begin();
717         epvector::const_iterator b = other.seq.begin();
718         epvector::const_iterator a_end = seq.end();
719         epvector::const_iterator b_end = other.seq.end();
720         int pow_a = std::numeric_limits<int>::max(), pow_b = std::numeric_limits<int>::max();
721         for (;;) {
722                 // If a is empty, fill up with elements from b and stop
723                 if (a == a_end) {
724                         while (b != b_end) {
725                                 new_seq.push_back(*b);
726                                 ++b;
727                         }
728                         break;
729                 } else
730                         pow_a = ex_to<numeric>((*a).coeff).to_int();
731                 
732                 // If b is empty, fill up with elements from a and stop
733                 if (b == b_end) {
734                         while (a != a_end) {
735                                 new_seq.push_back(*a);
736                                 ++a;
737                         }
738                         break;
739                 } else
740                         pow_b = ex_to<numeric>((*b).coeff).to_int();
741                 
742                 // a and b are non-empty, compare powers
743                 if (pow_a < pow_b) {
744                         // a has lesser power, get coefficient from a
745                         new_seq.push_back(*a);
746                         if (is_order_function((*a).rest))
747                                 break;
748                         ++a;
749                 } else if (pow_b < pow_a) {
750                         // b has lesser power, get coefficient from b
751                         new_seq.push_back(*b);
752                         if (is_order_function((*b).rest))
753                                 break;
754                         ++b;
755                 } else {
756                         // Add coefficient of a and b
757                         if (is_order_function((*a).rest) || is_order_function((*b).rest)) {
758                                 new_seq.push_back(expair(Order(_ex1), (*a).coeff));
759                                 break;  // Order term ends the sequence
760                         } else {
761                                 ex sum = (*a).rest + (*b).rest;
762                                 if (!(sum.is_zero()))
763                                         new_seq.push_back(expair(sum, numeric(pow_a)));
764                                 ++a;
765                                 ++b;
766                         }
767                 }
768         }
769         return pseries(relational(var,point), new_seq);
770 }
771
772
773 /** Implementation of ex::series() for sums. This performs series addition when
774  *  adding pseries objects.
775  *  @see ex::series */
776 ex add::series(const relational & r, int order, unsigned options) const
777 {
778         ex acc; // Series accumulator
779         
780         // Get first term from overall_coeff
781         acc = overall_coeff.series(r, order, options);
782         
783         // Add remaining terms
784         epvector::const_iterator it = seq.begin();
785         epvector::const_iterator itend = seq.end();
786         for (; it!=itend; ++it) {
787                 ex op;
788                 if (is_exactly_a<pseries>(it->rest))
789                         op = it->rest;
790                 else
791                         op = it->rest.series(r, order, options);
792                 if (!it->coeff.is_equal(_ex1))
793                         op = ex_to<pseries>(op).mul_const(ex_to<numeric>(it->coeff));
794                 
795                 // Series addition
796                 acc = ex_to<pseries>(acc).add_series(ex_to<pseries>(op));
797         }
798         return acc;
799 }
800
801
802 /** Multiply a pseries object with a numeric constant, producing a pseries
803  *  object that represents the product.
804  *
805  *  @param other  constant to multiply with
806  *  @return the product as a pseries */
807 ex pseries::mul_const(const numeric &other) const
808 {
809         epvector new_seq;
810         new_seq.reserve(seq.size());
811         
812         epvector::const_iterator it = seq.begin(), itend = seq.end();
813         while (it != itend) {
814                 if (!is_order_function(it->rest))
815                         new_seq.push_back(expair(it->rest * other, it->coeff));
816                 else
817                         new_seq.push_back(*it);
818                 ++it;
819         }
820         return pseries(relational(var,point), new_seq);
821 }
822
823
824 /** Multiply one pseries object to another, producing a pseries object that
825  *  represents the product.
826  *
827  *  @param other  pseries object to multiply with
828  *  @return the product as a pseries */
829 ex pseries::mul_series(const pseries &other) const
830 {
831         // Multiplying two series with different variables or expansion points
832         // results in an empty (constant) series 
833         if (!is_compatible_to(other)) {
834                 epvector nul;
835                 nul.push_back(expair(Order(_ex1), _ex0));
836                 return pseries(relational(var,point), nul);
837         }
838
839         if (seq.empty() || other.seq.empty()) {
840                 return (new pseries(var==point, epvector()))
841                        ->setflag(status_flags::dynallocated);
842         }
843         
844         // Series multiplication
845         epvector new_seq;
846         int a_max = degree(var);
847         int b_max = other.degree(var);
848         int a_min = ldegree(var);
849         int b_min = other.ldegree(var);
850         int cdeg_min = a_min + b_min;
851         int cdeg_max = a_max + b_max;
852         
853         int higher_order_a = std::numeric_limits<int>::max();
854         int higher_order_b = std::numeric_limits<int>::max();
855         if (is_order_function(coeff(var, a_max)))
856                 higher_order_a = a_max + b_min;
857         if (is_order_function(other.coeff(var, b_max)))
858                 higher_order_b = b_max + a_min;
859         int higher_order_c = std::min(higher_order_a, higher_order_b);
860         if (cdeg_max >= higher_order_c)
861                 cdeg_max = higher_order_c - 1;
862         
863         for (int cdeg=cdeg_min; cdeg<=cdeg_max; ++cdeg) {
864                 ex co = _ex0;
865                 // c(i)=a(0)b(i)+...+a(i)b(0)
866                 for (int i=a_min; cdeg-i>=b_min; ++i) {
867                         ex a_coeff = coeff(var, i);
868                         ex b_coeff = other.coeff(var, cdeg-i);
869                         if (!is_order_function(a_coeff) && !is_order_function(b_coeff))
870                                 co += a_coeff * b_coeff;
871                 }
872                 if (!co.is_zero())
873                         new_seq.push_back(expair(co, numeric(cdeg)));
874         }
875         if (higher_order_c < std::numeric_limits<int>::max())
876                 new_seq.push_back(expair(Order(_ex1), numeric(higher_order_c)));
877         return pseries(relational(var, point), new_seq);
878 }
879
880
881 /** Implementation of ex::series() for product. This performs series
882  *  multiplication when multiplying series.
883  *  @see ex::series */
884 ex mul::series(const relational & r, int order, unsigned options) const
885 {
886         pseries acc; // Series accumulator
887
888         GINAC_ASSERT(is_a<symbol>(r.lhs()));
889         const ex& sym = r.lhs();
890                 
891         // holds ldegrees of the series of individual factors
892         std::vector<int> ldegrees;
893         std::vector<bool> ldegree_redo;
894
895         // find minimal degrees
896         const epvector::const_iterator itbeg = seq.begin();
897         const epvector::const_iterator itend = seq.end();
898         // first round: obtain a bound up to which minimal degrees have to be
899         // considered
900         for (epvector::const_iterator it=itbeg; it!=itend; ++it) {
901
902                 ex expon = it->coeff;
903                 int factor = 1;
904                 ex buf;
905                 if (expon.info(info_flags::integer)) {
906                         buf = it->rest;
907                         factor = ex_to<numeric>(expon).to_int();
908                 } else {
909                         buf = recombine_pair_to_ex(*it);
910                 }
911
912                 int real_ldegree = 0;
913                 bool flag_redo = false;
914                 try {
915                         real_ldegree = buf.expand().ldegree(sym-r.rhs());
916                 } catch (std::runtime_error) {}
917
918                 if (real_ldegree == 0) {
919                         if ( factor < 0 ) {
920                                 // This case must terminate, otherwise we would have division by
921                                 // zero.
922                                 int orderloop = 0;
923                                 do {
924                                         orderloop++;
925                                         real_ldegree = buf.series(r, orderloop, options).ldegree(sym);
926                                 } while (real_ldegree == orderloop);
927                         } else {
928                                 // Here it is possible that buf does not have a ldegree, therefore
929                                 // check only if ldegree is negative, otherwise reconsider the case
930                                 // in the second round.
931                                 real_ldegree = buf.series(r, 0, options).ldegree(sym);
932                                 if (real_ldegree == 0)
933                                         flag_redo = true;
934                         }
935                 }
936
937                 ldegrees.push_back(factor * real_ldegree);
938                 ldegree_redo.push_back(flag_redo);
939         }
940
941         int degbound = order-std::accumulate(ldegrees.begin(), ldegrees.end(), 0);
942         // Second round: determine the remaining positive ldegrees by the series
943         // method.
944         // here we can ignore ldegrees larger than degbound
945         size_t j = 0;
946         for (epvector::const_iterator it=itbeg; it!=itend; ++it) {
947                 if ( ldegree_redo[j] ) {
948                         ex expon = it->coeff;
949                         int factor = 1;
950                         ex buf;
951                         if (expon.info(info_flags::integer)) {
952                                 buf = it->rest;
953                                 factor = ex_to<numeric>(expon).to_int();
954                         } else {
955                                 buf = recombine_pair_to_ex(*it);
956                         }
957                         int real_ldegree = 0;
958                         int orderloop = 0;
959                         do {
960                                 orderloop++;
961                                 real_ldegree = buf.series(r, orderloop, options).ldegree(sym);
962                         } while ((real_ldegree == orderloop)
963                                         && ( factor*real_ldegree < degbound));
964                         ldegrees[j] = factor * real_ldegree;
965                         degbound -= factor * real_ldegree;
966                 }
967                 j++;
968         }
969
970         int degsum = std::accumulate(ldegrees.begin(), ldegrees.end(), 0);
971
972         if (degsum >= order) {
973                 epvector epv;
974                 epv.push_back(expair(Order(_ex1), order));
975                 return (new pseries(r, epv))->setflag(status_flags::dynallocated);
976         }
977
978         // Multiply with remaining terms
979         std::vector<int>::const_iterator itd = ldegrees.begin();
980         for (epvector::const_iterator it=itbeg; it!=itend; ++it, ++itd) {
981
982                 // do series expansion with adjusted order
983                 ex op = recombine_pair_to_ex(*it).series(r, order-degsum+(*itd), options);
984
985                 // Series multiplication
986                 if (it == itbeg)
987                         acc = ex_to<pseries>(op);
988                 else
989                         acc = ex_to<pseries>(acc.mul_series(ex_to<pseries>(op)));
990         }
991
992         return acc.mul_const(ex_to<numeric>(overall_coeff));
993 }
994
995
996 /** Compute the p-th power of a series.
997  *
998  *  @param p  power to compute
999  *  @param deg  truncation order of series calculation */
1000 ex pseries::power_const(const numeric &p, int deg) const
1001 {
1002         // method:
1003         // (due to Leonhard Euler)
1004         // let A(x) be this series and for the time being let it start with a
1005         // constant (later we'll generalize):
1006         //     A(x) = a_0 + a_1*x + a_2*x^2 + ...
1007         // We want to compute
1008         //     C(x) = A(x)^p
1009         //     C(x) = c_0 + c_1*x + c_2*x^2 + ...
1010         // Taking the derivative on both sides and multiplying with A(x) one
1011         // immediately arrives at
1012         //     C'(x)*A(x) = p*C(x)*A'(x)
1013         // Multiplying this out and comparing coefficients we get the recurrence
1014         // formula
1015         //     c_i = (i*p*a_i*c_0 + ((i-1)*p-1)*a_{i-1}*c_1 + ...
1016         //                    ... + (p-(i-1))*a_1*c_{i-1})/(a_0*i)
1017         // which can easily be solved given the starting value c_0 = (a_0)^p.
1018         // For the more general case where the leading coefficient of A(x) is not
1019         // a constant, just consider A2(x) = A(x)*x^m, with some integer m and
1020         // repeat the above derivation.  The leading power of C2(x) = A2(x)^2 is
1021         // then of course x^(p*m) but the recurrence formula still holds.
1022         
1023         if (seq.empty()) {
1024                 // as a special case, handle the empty (zero) series honoring the
1025                 // usual power laws such as implemented in power::eval()
1026                 if (p.real().is_zero())
1027                         throw std::domain_error("pseries::power_const(): pow(0,I) is undefined");
1028                 else if (p.real().is_negative())
1029                         throw pole_error("pseries::power_const(): division by zero",1);
1030                 else
1031                         return *this;
1032         }
1033         
1034         const int ldeg = ldegree(var);
1035         if (!(p*ldeg).is_integer())
1036                 throw std::runtime_error("pseries::power_const(): trying to assemble a Puiseux series");
1037
1038         // adjust number of coefficients
1039         int numcoeff = deg - (p*ldeg).to_int();
1040         if (numcoeff <= 0) {
1041                 epvector epv;
1042                 epv.reserve(1);
1043                 epv.push_back(expair(Order(_ex1), deg));
1044                 return (new pseries(relational(var,point), epv))
1045                        ->setflag(status_flags::dynallocated);
1046         }
1047         
1048         // O(x^n)^(-m) is undefined
1049         if (seq.size() == 1 && is_order_function(seq[0].rest) && p.real().is_negative())
1050                 throw pole_error("pseries::power_const(): division by zero",1);
1051         
1052         // Compute coefficients of the powered series
1053         exvector co;
1054         co.reserve(numcoeff);
1055         co.push_back(power(coeff(var, ldeg), p));
1056         for (int i=1; i<numcoeff; ++i) {
1057                 ex sum = _ex0;
1058                 for (int j=1; j<=i; ++j) {
1059                         ex c = coeff(var, j + ldeg);
1060                         if (is_order_function(c)) {
1061                                 co.push_back(Order(_ex1));
1062                                 break;
1063                         } else
1064                                 sum += (p * j - (i - j)) * co[i - j] * c;
1065                 }
1066                 co.push_back(sum / coeff(var, ldeg) / i);
1067         }
1068         
1069         // Construct new series (of non-zero coefficients)
1070         epvector new_seq;
1071         bool higher_order = false;
1072         for (int i=0; i<numcoeff; ++i) {
1073                 if (!co[i].is_zero())
1074                         new_seq.push_back(expair(co[i], p * ldeg + i));
1075                 if (is_order_function(co[i])) {
1076                         higher_order = true;
1077                         break;
1078                 }
1079         }
1080         if (!higher_order)
1081                 new_seq.push_back(expair(Order(_ex1), p * ldeg + numcoeff));
1082
1083         return pseries(relational(var,point), new_seq);
1084 }
1085
1086
1087 /** Return a new pseries object with the powers shifted by deg. */
1088 pseries pseries::shift_exponents(int deg) const
1089 {
1090         epvector newseq = seq;
1091         epvector::iterator i = newseq.begin(), end  = newseq.end();
1092         while (i != end) {
1093                 i->coeff += deg;
1094                 ++i;
1095         }
1096         return pseries(relational(var, point), newseq);
1097 }
1098
1099
1100 /** Implementation of ex::series() for powers. This performs Laurent expansion
1101  *  of reciprocals of series at singularities.
1102  *  @see ex::series */
1103 ex power::series(const relational & r, int order, unsigned options) const
1104 {
1105         // If basis is already a series, just power it
1106         if (is_exactly_a<pseries>(basis))
1107                 return ex_to<pseries>(basis).power_const(ex_to<numeric>(exponent), order);
1108
1109         // Basis is not a series, may there be a singularity?
1110         bool must_expand_basis = false;
1111         try {
1112                 basis.subs(r, subs_options::no_pattern);
1113         } catch (pole_error) {
1114                 must_expand_basis = true;
1115         }
1116
1117         bool exponent_is_regular = true;
1118         try {
1119                 exponent.subs(r, subs_options::no_pattern);
1120         } catch (pole_error) {
1121                 exponent_is_regular = false;
1122         }
1123
1124         if (!exponent_is_regular) {
1125                 ex l = exponent*log(basis);
1126                 // this == exp(l);
1127                 ex le = l.series(r, order, options);
1128                 // Note: expanding exp(l) won't help, since that will attempt
1129                 // Taylor expansion, and fail (because exponent is "singular")
1130                 // Still l itself might be expanded in Taylor series.
1131                 // Examples:
1132                 // sin(x)/x*log(cos(x))
1133                 // 1/x*log(1 + x)
1134                 return exp(le).series(r, order, options);
1135                 // Note: if l happens to have a Laurent expansion (with
1136                 // negative powers of (var - point)), expanding exp(le)
1137                 // will barf (which is The Right Thing).
1138         }
1139
1140         // Is the expression of type something^(-int)?
1141         if (!must_expand_basis && !exponent.info(info_flags::negint)
1142          && (!is_a<add>(basis) || !is_a<numeric>(exponent)))
1143                 return basic::series(r, order, options);
1144
1145         // Is the expression of type 0^something?
1146         if (!must_expand_basis && !basis.subs(r, subs_options::no_pattern).is_zero()
1147          && (!is_a<add>(basis) || !is_a<numeric>(exponent)))
1148                 return basic::series(r, order, options);
1149
1150         // Singularity encountered, is the basis equal to (var - point)?
1151         if (basis.is_equal(r.lhs() - r.rhs())) {
1152                 epvector new_seq;
1153                 if (ex_to<numeric>(exponent).to_int() < order)
1154                         new_seq.push_back(expair(_ex1, exponent));
1155                 else
1156                         new_seq.push_back(expair(Order(_ex1), exponent));
1157                 return pseries(r, new_seq);
1158         }
1159
1160         // No, expand basis into series
1161
1162         numeric numexp;
1163         if (is_a<numeric>(exponent)) {
1164                 numexp = ex_to<numeric>(exponent);
1165         } else {
1166                 numexp = 0;
1167         }
1168         const ex& sym = r.lhs();
1169         // find existing minimal degree
1170         ex eb = basis.expand();
1171         int real_ldegree = 0;
1172         if (eb.info(info_flags::rational_function))
1173                 real_ldegree = eb.ldegree(sym-r.rhs());
1174         if (real_ldegree == 0) {
1175                 int orderloop = 0;
1176                 do {
1177                         orderloop++;
1178                         real_ldegree = basis.series(r, orderloop, options).ldegree(sym);
1179                 } while (real_ldegree == orderloop);
1180         }
1181
1182         if (!(real_ldegree*numexp).is_integer())
1183                 throw std::runtime_error("pseries::power_const(): trying to assemble a Puiseux series");
1184         ex e = basis.series(r, (order + real_ldegree*(1-numexp)).to_int(), options);
1185         
1186         ex result;
1187         try {
1188                 result = ex_to<pseries>(e).power_const(numexp, order);
1189         } catch (pole_error) {
1190                 epvector ser;
1191                 ser.push_back(expair(Order(_ex1), order));
1192                 result = pseries(r, ser);
1193         }
1194
1195         return result;
1196 }
1197
1198
1199 /** Re-expansion of a pseries object. */
1200 ex pseries::series(const relational & r, int order, unsigned options) const
1201 {
1202         const ex p = r.rhs();
1203         GINAC_ASSERT(is_a<symbol>(r.lhs()));
1204         const symbol &s = ex_to<symbol>(r.lhs());
1205         
1206         if (var.is_equal(s) && point.is_equal(p)) {
1207                 if (order > degree(s))
1208                         return *this;
1209                 else {
1210                         epvector new_seq;
1211                         epvector::const_iterator it = seq.begin(), itend = seq.end();
1212                         while (it != itend) {
1213                                 int o = ex_to<numeric>(it->coeff).to_int();
1214                                 if (o >= order) {
1215                                         new_seq.push_back(expair(Order(_ex1), o));
1216                                         break;
1217                                 }
1218                                 new_seq.push_back(*it);
1219                                 ++it;
1220                         }
1221                         return pseries(r, new_seq);
1222                 }
1223         } else
1224                 return convert_to_poly().series(r, order, options);
1225 }
1226
1227 ex integral::series(const relational & r, int order, unsigned options) const
1228 {
1229         if (x.subs(r) != x)
1230                 throw std::logic_error("Cannot series expand wrt dummy variable");
1231         
1232         // Expanding integrant with r substituted taken in boundaries.
1233         ex fseries = f.series(r, order, options);
1234         epvector fexpansion;
1235         fexpansion.reserve(fseries.nops());
1236         for (size_t i=0; i<fseries.nops(); ++i) {
1237                 ex currcoeff = ex_to<pseries>(fseries).coeffop(i);
1238                 currcoeff = (currcoeff == Order(_ex1))
1239                         ? currcoeff
1240                         : integral(x, a.subs(r), b.subs(r), currcoeff);
1241                 if (currcoeff != 0)
1242                         fexpansion.push_back(
1243                                 expair(currcoeff, ex_to<pseries>(fseries).exponop(i)));
1244         }
1245
1246         // Expanding lower boundary
1247         ex result = (new pseries(r, fexpansion))->setflag(status_flags::dynallocated);
1248         ex aseries = (a-a.subs(r)).series(r, order, options);
1249         fseries = f.series(x == (a.subs(r)), order, options);
1250         for (size_t i=0; i<fseries.nops(); ++i) {
1251                 ex currcoeff = ex_to<pseries>(fseries).coeffop(i);
1252                 if (is_order_function(currcoeff))
1253                         break;
1254                 ex currexpon = ex_to<pseries>(fseries).exponop(i);
1255                 int orderforf = order-ex_to<numeric>(currexpon).to_int()-1;
1256                 currcoeff = currcoeff.series(r, orderforf);
1257                 ex term = ex_to<pseries>(aseries).power_const(ex_to<numeric>(currexpon+1),order);
1258                 term = ex_to<pseries>(term).mul_const(ex_to<numeric>(-1/(currexpon+1)));
1259                 term = ex_to<pseries>(term).mul_series(ex_to<pseries>(currcoeff));
1260                 result = ex_to<pseries>(result).add_series(ex_to<pseries>(term));
1261         }
1262
1263         // Expanding upper boundary
1264         ex bseries = (b-b.subs(r)).series(r, order, options);
1265         fseries = f.series(x == (b.subs(r)), order, options);
1266         for (size_t i=0; i<fseries.nops(); ++i) {
1267                 ex currcoeff = ex_to<pseries>(fseries).coeffop(i);
1268                 if (is_order_function(currcoeff))
1269                         break;
1270                 ex currexpon = ex_to<pseries>(fseries).exponop(i);
1271                 int orderforf = order-ex_to<numeric>(currexpon).to_int()-1;
1272                 currcoeff = currcoeff.series(r, orderforf);
1273                 ex term = ex_to<pseries>(bseries).power_const(ex_to<numeric>(currexpon+1),order);
1274                 term = ex_to<pseries>(term).mul_const(ex_to<numeric>(1/(currexpon+1)));
1275                 term = ex_to<pseries>(term).mul_series(ex_to<pseries>(currcoeff));
1276                 result = ex_to<pseries>(result).add_series(ex_to<pseries>(term));
1277         }
1278
1279         return result;
1280 }
1281
1282
1283 /** Compute the truncated series expansion of an expression.
1284  *  This function returns an expression containing an object of class pseries 
1285  *  to represent the series. If the series does not terminate within the given
1286  *  truncation order, the last term of the series will be an order term.
1287  *
1288  *  @param r  expansion relation, lhs holds variable and rhs holds point
1289  *  @param order  truncation order of series calculations
1290  *  @param options  of class series_options
1291  *  @return an expression holding a pseries object */
1292 ex ex::series(const ex & r, int order, unsigned options) const
1293 {
1294         ex e;
1295         relational rel_;
1296         
1297         if (is_a<relational>(r))
1298                 rel_ = ex_to<relational>(r);
1299         else if (is_a<symbol>(r))
1300                 rel_ = relational(r,_ex0);
1301         else
1302                 throw (std::logic_error("ex::series(): expansion point has unknown type"));
1303         
1304         e = bp->series(rel_, order, options);
1305         return e;
1306 }
1307
1308 GINAC_BIND_UNARCHIVER(pseries);
1309
1310 } // namespace GiNaC