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