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