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