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