]> www.ginac.de Git - ginac.git/blob - ginac/pseries.cpp
* add::print() shouldn't put parens around overall_coeff.
[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-2001 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  */
23
24 #include <stdexcept>
25
26 #include "pseries.h"
27 #include "add.h"
28 #include "inifcns.h"
29 #include "lst.h"
30 #include "mul.h"
31 #include "power.h"
32 #include "relational.h"
33 #include "symbol.h"
34 #include "print.h"
35 #include "archive.h"
36 #include "utils.h"
37 #include "debugmsg.h"
38
39 namespace GiNaC {
40
41 GINAC_IMPLEMENT_REGISTERED_CLASS(pseries, basic)
42
43
44 /*
45  *  Default ctor, dtor, copy ctor, assignment operator and helpers
46  */
47
48 pseries::pseries() : basic(TINFO_pseries)
49 {
50         debugmsg("pseries default ctor", LOGLEVEL_CONSTRUCT);
51 }
52
53 void pseries::copy(const pseries &other)
54 {
55         inherited::copy(other);
56         seq = other.seq;
57         var = other.var;
58         point = other.point;
59 }
60
61 DEFAULT_DESTROY(pseries)
62
63
64 /*
65  *  Other ctors
66  */
67
68 /** Construct pseries from a vector of coefficients and powers.
69  *  expair.rest holds the coefficient, expair.coeff holds the power.
70  *  The powers must be integers (positive or negative) and in ascending order;
71  *  the last coefficient can be Order(_ex1()) to represent a truncated,
72  *  non-terminating series.
73  *
74  *  @param rel_  expansion variable and point (must hold a relational)
75  *  @param ops_  vector of {coefficient, power} pairs (coefficient must not be zero)
76  *  @return newly constructed pseries */
77 pseries::pseries(const ex &rel_, const epvector &ops_) : basic(TINFO_pseries), seq(ops_)
78 {
79         debugmsg("pseries ctor from ex,epvector", LOGLEVEL_CONSTRUCT);
80         GINAC_ASSERT(is_ex_exactly_of_type(rel_, relational));
81         GINAC_ASSERT(is_ex_exactly_of_type(rel_.lhs(),symbol));
82         point = rel_.rhs();
83         var = *static_cast<symbol *>(rel_.lhs().bp);
84 }
85
86
87 /*
88  *  Archiving
89  */
90
91 pseries::pseries(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
92 {
93         debugmsg("pseries ctor from archive_node", LOGLEVEL_CONSTRUCT);
94         for (unsigned int i=0; true; ++i) {
95                 ex rest;
96                 ex coeff;
97                 if (n.find_ex("coeff", rest, sym_lst, i) && n.find_ex("power", coeff, sym_lst, i))
98                         seq.push_back(expair(rest, coeff));
99                 else
100                         break;
101         }
102         n.find_ex("var", var, sym_lst);
103         n.find_ex("point", point, sym_lst);
104 }
105
106 void pseries::archive(archive_node &n) const
107 {
108         inherited::archive(n);
109         epvector::const_iterator i = seq.begin(), iend = seq.end();
110         while (i != iend) {
111                 n.add_ex("coeff", i->rest);
112                 n.add_ex("power", i->coeff);
113                 ++i;
114         }
115         n.add_ex("var", var);
116         n.add_ex("point", point);
117 }
118
119 DEFAULT_UNARCHIVE(pseries)
120
121 //////////
122 // functions overriding virtual functions from bases classes
123 //////////
124
125 void pseries::print(const print_context & c, unsigned level) const
126 {
127         debugmsg("pseries print", LOGLEVEL_PRINT);
128
129         if (is_of_type(c, print_tree)) {
130
131                 c.s << std::string(level, ' ') << class_name()
132                     << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
133                     << std::endl;
134                 unsigned delta_indent = static_cast<const print_tree &>(c).delta_indent;
135                 for (unsigned i=0; i<seq.size(); ++i) {
136                         seq[i].rest.print(c, level + delta_indent);
137                         seq[i].coeff.print(c, level + delta_indent);
138                         c.s << std::string(level + delta_indent, ' ') << "-----" << std::endl;
139                 }
140                 var.print(c, level + delta_indent);
141                 point.print(c, level + delta_indent);
142
143         } else {
144
145                 if (precedence <= level)
146                         c.s << "(";
147
148                 // objects of type pseries must not have any zero entries, so the
149                 // trivial (zero) pseries needs a special treatment here:
150                 if (seq.size() == 0)
151                         c.s << '0';
152                 for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i) {
153                         // print a sign, if needed
154                         if (i != seq.begin())
155                                 c.s << '+';
156                         if (!is_order_function(i->rest)) {
157                                 // print 'rest', i.e. the expansion coefficient
158                                 if (i->rest.info(info_flags::numeric) &&
159                                         i->rest.info(info_flags::positive)) {
160                                         i->rest.print(c);
161                                 } else {
162                                         c.s << '(';
163                                         i->rest.print(c);
164                                         c.s << ')';
165                                 }
166                                 // print 'coeff', something like (x-1)^42
167                                 if (!i->coeff.is_zero()) {
168                                         c.s << '*';
169                                         if (!point.is_zero()) {
170                                                 c.s << '(';
171                                                 (var-point).print(c);
172                                                 c.s << ')';
173                                         } else
174                                                 var.print(c);
175                                         if (i->coeff.compare(_ex1())) {
176                                                 c.s << '^';
177                                                 if (i->coeff.info(info_flags::negative)) {
178                                                         c.s << '(';
179                                                         i->coeff.print(c);
180                                                         c.s << ')';
181                                                 } else
182                                                         i->coeff.print(c);
183                                         }
184                                 }
185                         } else
186                                 Order(power(var-point,i->coeff)).print(c);
187                 }
188
189                 if (precedence <= level)
190                         c.s << ")";
191         }
192 }
193
194 int pseries::compare_same_type(const basic & other) const
195 {
196         GINAC_ASSERT(is_of_type(other, pseries));
197         const pseries &o = static_cast<const pseries &>(other);
198         
199         // first compare the lengths of the series...
200         if (seq.size()>o.seq.size())
201                 return 1;
202         if (seq.size()<o.seq.size())
203                 return -1;
204         
205         // ...then the expansion point...
206         int cmpval = var.compare(o.var);
207         if (cmpval)
208                 return cmpval;
209         cmpval = point.compare(o.point);
210         if (cmpval)
211                 return cmpval;
212         
213         // ...and if that failed the individual elements
214         epvector::const_iterator it = seq.begin(), o_it = o.seq.begin();
215         while (it!=seq.end() && o_it!=o.seq.end()) {
216                 cmpval = it->compare(*o_it);
217                 if (cmpval)
218                         return cmpval;
219                 ++it;
220                 ++o_it;
221         }
222
223         // so they are equal.
224         return 0;
225 }
226
227 /** Return the number of operands including a possible order term. */
228 unsigned pseries::nops(void) const
229 {
230         return seq.size();
231 }
232
233 /** Return the ith term in the series when represented as a sum. */
234 ex pseries::op(int i) const
235 {
236         if (i < 0 || unsigned(i) >= seq.size())
237                 throw (std::out_of_range("op() out of range"));
238         return seq[i].rest * power(var - point, seq[i].coeff);
239 }
240
241 ex &pseries::let_op(int i)
242 {
243         throw (std::logic_error("let_op not defined for pseries"));
244 }
245
246 /** Return degree of highest power of the series.  This is usually the exponent
247  *  of the Order term.  If s is not the expansion variable of the series, the
248  *  series is examined termwise. */
249 int pseries::degree(const ex &s) const
250 {
251         if (var.is_equal(s)) {
252                 // Return last exponent
253                 if (seq.size())
254                         return ex_to_numeric((*(seq.end() - 1)).coeff).to_int();
255                 else
256                         return 0;
257         } else {
258                 epvector::const_iterator it = seq.begin(), itend = seq.end();
259                 if (it == itend)
260                         return 0;
261                 int max_pow = INT_MIN;
262                 while (it != itend) {
263                         int pow = it->rest.degree(s);
264                         if (pow > max_pow)
265                                 max_pow = pow;
266                         ++it;
267                 }
268                 return max_pow;
269         }
270 }
271
272 /** Return degree of lowest power of the series.  This is usually the exponent
273  *  of the leading term.  If s is not the expansion variable of the series, the
274  *  series is examined termwise.  If s is the expansion variable but the
275  *  expansion point is not zero the series is not expanded to find the degree.
276  *  I.e.: (1-x) + (1-x)^2 + Order((1-x)^3) has ldegree(x) 1, not 0. */
277 int pseries::ldegree(const ex &s) const
278 {
279         if (var.is_equal(s)) {
280                 // Return first exponent
281                 if (seq.size())
282                         return ex_to_numeric((*(seq.begin())).coeff).to_int();
283                 else
284                         return 0;
285         } else {
286                 epvector::const_iterator it = seq.begin(), itend = seq.end();
287                 if (it == itend)
288                         return 0;
289                 int min_pow = INT_MAX;
290                 while (it != itend) {
291                         int pow = it->rest.ldegree(s);
292                         if (pow < min_pow)
293                                 min_pow = pow;
294                         ++it;
295                 }
296                 return min_pow;
297         }
298 }
299
300 /** Return coefficient of degree n in power series if s is the expansion
301  *  variable.  If the expansion point is nonzero, by definition the n=1
302  *  coefficient in s of a+b*(s-z)+c*(s-z)^2+Order((s-z)^3) is b (assuming
303  *  the expansion took place in the s in the first place).
304  *  If s is not the expansion variable, an attempt is made to convert the
305  *  series to a polynomial and return the corresponding coefficient from
306  *  there. */
307 ex pseries::coeff(const ex &s, int n) const
308 {
309         if (var.is_equal(s)) {
310                 if (seq.size() == 0)
311                         return _ex0();
312                 
313                 // Binary search in sequence for given power
314                 numeric looking_for = numeric(n);
315                 int lo = 0, hi = seq.size() - 1;
316                 while (lo <= hi) {
317                         int mid = (lo + hi) / 2;
318                         GINAC_ASSERT(is_ex_exactly_of_type(seq[mid].coeff, numeric));
319                         int cmp = ex_to_numeric(seq[mid].coeff).compare(looking_for);
320                         switch (cmp) {
321                                 case -1:
322                                         lo = mid + 1;
323                                         break;
324                                 case 0:
325                                         return seq[mid].rest;
326                                 case 1:
327                                         hi = mid - 1;
328                                         break;
329                                 default:
330                                         throw(std::logic_error("pseries::coeff: compare() didn't return -1, 0 or 1"));
331                         }
332                 }
333                 return _ex0();
334         } else
335                 return convert_to_poly().coeff(s, n);
336 }
337
338 /** Does nothing. */
339 ex pseries::collect(const ex &s) const
340 {
341         return *this;
342 }
343
344 /** Evaluate coefficients. */
345 ex pseries::eval(int level) const
346 {
347         if (level == 1)
348                 return this->hold();
349         
350         if (level == -max_recursion_level)
351                 throw (std::runtime_error("pseries::eval(): recursion limit exceeded"));
352         
353         // Construct a new series with evaluated coefficients
354         epvector new_seq;
355         new_seq.reserve(seq.size());
356         epvector::const_iterator it = seq.begin(), itend = seq.end();
357         while (it != itend) {
358                 new_seq.push_back(expair(it->rest.eval(level-1), it->coeff));
359                 ++it;
360         }
361         return (new pseries(relational(var,point), new_seq))->setflag(status_flags::dynallocated | status_flags::evaluated);
362 }
363
364 /** Evaluate coefficients numerically. */
365 ex pseries::evalf(int level) const
366 {
367         if (level == 1)
368                 return *this;
369         
370         if (level == -max_recursion_level)
371                 throw (std::runtime_error("pseries::evalf(): recursion limit exceeded"));
372         
373         // Construct a new series with evaluated coefficients
374         epvector new_seq;
375         new_seq.reserve(seq.size());
376         epvector::const_iterator it = seq.begin(), itend = seq.end();
377         while (it != itend) {
378                 new_seq.push_back(expair(it->rest.evalf(level-1), it->coeff));
379                 ++it;
380         }
381         return (new pseries(relational(var,point), new_seq))->setflag(status_flags::dynallocated | status_flags::evaluated);
382 }
383
384 ex pseries::subs(const lst & ls, const lst & lr) const
385 {
386         // If expansion variable is being substituted, convert the series to a
387         // polynomial and do the substitution there because the result might
388         // no longer be a power series
389         if (ls.has(var))
390                 return convert_to_poly(true).subs(ls, lr);
391         
392         // Otherwise construct a new series with substituted coefficients and
393         // expansion point
394         epvector newseq;
395         newseq.reserve(seq.size());
396         epvector::const_iterator it = seq.begin(), itend = seq.end();
397         while (it != itend) {
398                 newseq.push_back(expair(it->rest.subs(ls, lr), it->coeff));
399                 ++it;
400         }
401         return (new pseries(relational(var,point.subs(ls, lr)), newseq))->setflag(status_flags::dynallocated);
402 }
403
404 /** Implementation of ex::expand() for a power series.  It expands all the
405  *  terms individually and returns the resulting series as a new pseries. */
406 ex pseries::expand(unsigned options) const
407 {
408         epvector newseq;
409         for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i) {
410                 ex restexp = i->rest.expand();
411                 if (!restexp.is_zero())
412                         newseq.push_back(expair(restexp, i->coeff));
413         }
414         return (new pseries(relational(var,point), newseq))
415                 ->setflag(status_flags::dynallocated | status_flags::expanded);
416 }
417
418 /** Implementation of ex::diff() for a power series.  It treats the series as a
419  *  polynomial.
420  *  @see ex::diff */
421 ex pseries::derivative(const symbol & s) const
422 {
423         if (s == var) {
424                 epvector new_seq;
425                 epvector::const_iterator it = seq.begin(), itend = seq.end();
426                 
427                 // FIXME: coeff might depend on var
428                 while (it != itend) {
429                         if (is_order_function(it->rest)) {
430                                 new_seq.push_back(expair(it->rest, it->coeff - 1));
431                         } else {
432                                 ex c = it->rest * it->coeff;
433                                 if (!c.is_zero())
434                                         new_seq.push_back(expair(c, it->coeff - 1));
435                         }
436                         ++it;
437                 }
438                 return pseries(relational(var,point), new_seq);
439         } else {
440                 return *this;
441         }
442 }
443
444 ex pseries::convert_to_poly(bool no_order) const
445 {
446         ex e;
447         epvector::const_iterator it = seq.begin(), itend = seq.end();
448         
449         while (it != itend) {
450                 if (is_order_function(it->rest)) {
451                         if (!no_order)
452                                 e += Order(power(var - point, it->coeff));
453                 } else
454                         e += it->rest * power(var - point, it->coeff);
455                 ++it;
456         }
457         return e;
458 }
459
460 bool pseries::is_terminating(void) const
461 {
462         return seq.size() == 0 || !is_order_function((seq.end()-1)->rest);
463 }
464
465
466 /*
467  *  Implementations of series expansion
468  */
469
470 /** Default implementation of ex::series(). This performs Taylor expansion.
471  *  @see ex::series */
472 ex basic::series(const relational & r, int order, unsigned options) const
473 {
474         epvector seq;
475         numeric fac(1);
476         ex deriv = *this;
477         ex coeff = deriv.subs(r);
478         const symbol &s = static_cast<symbol &>(*r.lhs().bp);
479         
480         if (!coeff.is_zero())
481                 seq.push_back(expair(coeff, numeric(0)));
482         
483         int n;
484         for (n=1; n<order; ++n) {
485                 fac = fac.mul(numeric(n));
486                 deriv = deriv.diff(s).expand();
487                 if (deriv.is_zero()) {
488                         // Series terminates
489                         return pseries(r, seq);
490                 }
491                 coeff = deriv.subs(r);
492                 if (!coeff.is_zero())
493                         seq.push_back(expair(fac.inverse() * coeff, numeric(n)));
494         }
495         
496         // Higher-order terms, if present
497         deriv = deriv.diff(s);
498         if (!deriv.expand().is_zero())
499                 seq.push_back(expair(Order(_ex1()), numeric(n)));
500         return pseries(r, seq);
501 }
502
503
504 /** Implementation of ex::series() for symbols.
505  *  @see ex::series */
506 ex symbol::series(const relational & r, int order, unsigned options) const
507 {
508         epvector seq;
509         const ex point = r.rhs();
510         GINAC_ASSERT(is_ex_exactly_of_type(r.lhs(),symbol));
511         ex s = r.lhs();
512         
513         if (this->is_equal(*s.bp)) {
514                 if (order > 0 && !point.is_zero())
515                         seq.push_back(expair(point, _ex0()));
516                 if (order > 1)
517                         seq.push_back(expair(_ex1(), _ex1()));
518                 else
519                         seq.push_back(expair(Order(_ex1()), numeric(order)));
520         } else
521                 seq.push_back(expair(*this, _ex0()));
522         return pseries(r, seq);
523 }
524
525
526 /** Add one series object to another, producing a pseries object that
527  *  represents the sum.
528  *
529  *  @param other  pseries object to add with
530  *  @return the sum as a pseries */
531 ex pseries::add_series(const pseries &other) const
532 {
533         // Adding two series with different variables or expansion points
534         // results in an empty (constant) series 
535         if (!is_compatible_to(other)) {
536                 epvector nul;
537                 nul.push_back(expair(Order(_ex1()), _ex0()));
538                 return pseries(relational(var,point), nul);
539         }
540         
541         // Series addition
542         epvector new_seq;
543         epvector::const_iterator a = seq.begin();
544         epvector::const_iterator b = other.seq.begin();
545         epvector::const_iterator a_end = seq.end();
546         epvector::const_iterator b_end = other.seq.end();
547         int pow_a = INT_MAX, pow_b = INT_MAX;
548         for (;;) {
549                 // If a is empty, fill up with elements from b and stop
550                 if (a == a_end) {
551                         while (b != b_end) {
552                                 new_seq.push_back(*b);
553                                 ++b;
554                         }
555                         break;
556                 } else
557                         pow_a = ex_to_numeric((*a).coeff).to_int();
558                 
559                 // If b is empty, fill up with elements from a and stop
560                 if (b == b_end) {
561                         while (a != a_end) {
562                                 new_seq.push_back(*a);
563                                 ++a;
564                         }
565                         break;
566                 } else
567                         pow_b = ex_to_numeric((*b).coeff).to_int();
568                 
569                 // a and b are non-empty, compare powers
570                 if (pow_a < pow_b) {
571                         // a has lesser power, get coefficient from a
572                         new_seq.push_back(*a);
573                         if (is_order_function((*a).rest))
574                                 break;
575                         ++a;
576                 } else if (pow_b < pow_a) {
577                         // b has lesser power, get coefficient from b
578                         new_seq.push_back(*b);
579                         if (is_order_function((*b).rest))
580                                 break;
581                         ++b;
582                 } else {
583                         // Add coefficient of a and b
584                         if (is_order_function((*a).rest) || is_order_function((*b).rest)) {
585                                 new_seq.push_back(expair(Order(_ex1()), (*a).coeff));
586                                 break;  // Order term ends the sequence
587                         } else {
588                                 ex sum = (*a).rest + (*b).rest;
589                                 if (!(sum.is_zero()))
590                                         new_seq.push_back(expair(sum, numeric(pow_a)));
591                                 ++a;
592                                 ++b;
593                         }
594                 }
595         }
596         return pseries(relational(var,point), new_seq);
597 }
598
599
600 /** Implementation of ex::series() for sums. This performs series addition when
601  *  adding pseries objects.
602  *  @see ex::series */
603 ex add::series(const relational & r, int order, unsigned options) const
604 {
605         ex acc; // Series accumulator
606         
607         // Get first term from overall_coeff
608         acc = overall_coeff.series(r, order, options);
609         
610         // Add remaining terms
611         epvector::const_iterator it = seq.begin();
612         epvector::const_iterator itend = seq.end();
613         for (; it!=itend; ++it) {
614                 ex op;
615                 if (is_ex_exactly_of_type(it->rest, pseries))
616                         op = it->rest;
617                 else
618                         op = it->rest.series(r, order, options);
619                 if (!it->coeff.is_equal(_ex1()))
620                         op = ex_to_pseries(op).mul_const(ex_to_numeric(it->coeff));
621                 
622                 // Series addition
623                 acc = ex_to_pseries(acc).add_series(ex_to_pseries(op));
624         }
625         return acc;
626 }
627
628
629 /** Multiply a pseries object with a numeric constant, producing a pseries
630  *  object that represents the product.
631  *
632  *  @param other  constant to multiply with
633  *  @return the product as a pseries */
634 ex pseries::mul_const(const numeric &other) const
635 {
636         epvector new_seq;
637         new_seq.reserve(seq.size());
638         
639         epvector::const_iterator it = seq.begin(), itend = seq.end();
640         while (it != itend) {
641                 if (!is_order_function(it->rest))
642                         new_seq.push_back(expair(it->rest * other, it->coeff));
643                 else
644                         new_seq.push_back(*it);
645                 ++it;
646         }
647         return pseries(relational(var,point), new_seq);
648 }
649
650
651 /** Multiply one pseries object to another, producing a pseries object that
652  *  represents the product.
653  *
654  *  @param other  pseries object to multiply with
655  *  @return the product as a pseries */
656 ex pseries::mul_series(const pseries &other) const
657 {
658         // Multiplying two series with different variables or expansion points
659         // results in an empty (constant) series 
660         if (!is_compatible_to(other)) {
661                 epvector nul;
662                 nul.push_back(expair(Order(_ex1()), _ex0()));
663                 return pseries(relational(var,point), nul);
664         }
665         
666         // Series multiplication
667         epvector new_seq;
668         
669         int a_max = degree(var);
670         int b_max = other.degree(var);
671         int a_min = ldegree(var);
672         int b_min = other.ldegree(var);
673         int cdeg_min = a_min + b_min;
674         int cdeg_max = a_max + b_max;
675         
676         int higher_order_a = INT_MAX;
677         int higher_order_b = INT_MAX;
678         if (is_order_function(coeff(var, a_max)))
679                 higher_order_a = a_max + b_min;
680         if (is_order_function(other.coeff(var, b_max)))
681                 higher_order_b = b_max + a_min;
682         int higher_order_c = std::min(higher_order_a, higher_order_b);
683         if (cdeg_max >= higher_order_c)
684                 cdeg_max = higher_order_c - 1;
685         
686         for (int cdeg=cdeg_min; cdeg<=cdeg_max; ++cdeg) {
687                 ex co = _ex0();
688                 // c(i)=a(0)b(i)+...+a(i)b(0)
689                 for (int i=a_min; cdeg-i>=b_min; ++i) {
690                         ex a_coeff = coeff(var, i);
691                         ex b_coeff = other.coeff(var, cdeg-i);
692                         if (!is_order_function(a_coeff) && !is_order_function(b_coeff))
693                                 co += a_coeff * b_coeff;
694                 }
695                 if (!co.is_zero())
696                         new_seq.push_back(expair(co, numeric(cdeg)));
697         }
698         if (higher_order_c < INT_MAX)
699                 new_seq.push_back(expair(Order(_ex1()), numeric(higher_order_c)));
700         return pseries(relational(var, point), new_seq);
701 }
702
703
704 /** Implementation of ex::series() for product. This performs series
705  *  multiplication when multiplying series.
706  *  @see ex::series */
707 ex mul::series(const relational & r, int order, unsigned options) const
708 {
709         ex acc; // Series accumulator
710         
711         // Get first term from overall_coeff
712         acc = overall_coeff.series(r, order, options);
713         
714         // Multiply with remaining terms
715         epvector::const_iterator it = seq.begin();
716         epvector::const_iterator itend = seq.end();
717         for (; it!=itend; ++it) {
718                 ex op = it->rest;
719                 if (op.info(info_flags::numeric)) {
720                         // series * const (special case, faster)
721                         ex f = power(op, it->coeff);
722                         acc = ex_to_pseries(acc).mul_const(ex_to_numeric(f));
723                         continue;
724                 } else if (!is_ex_exactly_of_type(op, pseries))
725                         op = op.series(r, order, options);
726                 if (!it->coeff.is_equal(_ex1()))
727                         op = ex_to_pseries(op).power_const(ex_to_numeric(it->coeff), order);
728
729                 // Series multiplication
730                 acc = ex_to_pseries(acc).mul_series(ex_to_pseries(op));
731         }
732         return acc;
733 }
734
735
736 /** Compute the p-th power of a series.
737  *
738  *  @param p  power to compute
739  *  @param deg  truncation order of series calculation */
740 ex pseries::power_const(const numeric &p, int deg) const
741 {
742         // method:
743         // let A(x) be this series and for the time being let it start with a
744         // constant (later we'll generalize):
745         //     A(x) = a_0 + a_1*x + a_2*x^2 + ...
746         // We want to compute
747         //     C(x) = A(x)^p
748         //     C(x) = c_0 + c_1*x + c_2*x^2 + ...
749         // Taking the derivative on both sides and multiplying with A(x) one
750         // immediately arrives at
751         //     C'(x)*A(x) = p*C(x)*A'(x)
752         // Multiplying this out and comparing coefficients we get the recurrence
753         // formula
754         //     c_i = (i*p*a_i*c_0 + ((i-1)*p-1)*a_{i-1}*c_1 + ...
755         //                    ... + (p-(i-1))*a_1*c_{i-1})/(a_0*i)
756         // which can easily be solved given the starting value c_0 = (a_0)^p.
757         // For the more general case where the leading coefficient of A(x) is not
758         // a constant, just consider A2(x) = A(x)*x^m, with some integer m and
759         // repeat the above derivation.  The leading power of C2(x) = A2(x)^2 is
760         // then of course x^(p*m) but the recurrence formula still holds.
761         
762         if (seq.size()==0) {
763                 // as a spacial case, handle the empty (zero) series honoring the
764                 // usual power laws such as implemented in power::eval()
765                 if (p.real().is_zero())
766                         throw (std::domain_error("pseries::power_const(): pow(0,I) is undefined"));
767                 else if (p.real().is_negative())
768                         throw (pole_error("pseries::power_const(): division by zero",1));
769                 else
770                         return *this;
771         }
772         
773         int ldeg = ldegree(var);
774         
775         // Compute coefficients of the powered series
776         exvector co;
777         co.reserve(deg);
778         co.push_back(power(coeff(var, ldeg), p));
779         bool all_sums_zero = true;
780         for (int i=1; i<deg; ++i) {
781                 ex sum = _ex0();
782                 for (int j=1; j<=i; ++j) {
783                         ex c = coeff(var, j + ldeg);
784                         if (is_order_function(c)) {
785                                 co.push_back(Order(_ex1()));
786                                 break;
787                         } else
788                                 sum += (p * j - (i - j)) * co[i - j] * c;
789                 }
790                 if (!sum.is_zero())
791                         all_sums_zero = false;
792                 co.push_back(sum / coeff(var, ldeg) / numeric(i));
793         }
794         
795         // Construct new series (of non-zero coefficients)
796         epvector new_seq;
797         bool higher_order = false;
798         for (int i=0; i<deg; ++i) {
799                 if (!co[i].is_zero())
800                         new_seq.push_back(expair(co[i], numeric(i) + p * ldeg));
801                 if (is_order_function(co[i])) {
802                         higher_order = true;
803                         break;
804                 }
805         }
806         if (!higher_order && !all_sums_zero)
807                 new_seq.push_back(expair(Order(_ex1()), numeric(deg) + p * ldeg));
808         return pseries(relational(var,point), new_seq);
809 }
810
811
812 /** Return a new pseries object with the powers shifted by deg. */
813 pseries pseries::shift_exponents(int deg) const
814 {
815         epvector newseq(seq);
816         for (epvector::iterator i=newseq.begin(); i!=newseq.end(); ++i)
817                 i->coeff = i->coeff + deg;
818         return pseries(relational(var, point), newseq);
819 }
820
821
822 /** Implementation of ex::series() for powers. This performs Laurent expansion
823  *  of reciprocals of series at singularities.
824  *  @see ex::series */
825 ex power::series(const relational & r, int order, unsigned options) const
826 {
827         ex e;
828         if (!is_ex_exactly_of_type(basis, pseries)) {
829                 // Basis is not a series, may there be a singularity?
830                 bool must_expand_basis = false;
831                 try {
832                         basis.subs(r);
833                 } catch (pole_error) {
834                         must_expand_basis = true;
835                 }
836                 
837                 // Is the expression of type something^(-int)?
838                 if (!must_expand_basis && !exponent.info(info_flags::negint))
839                         return basic::series(r, order, options);
840                 
841                 // Is the expression of type 0^something?
842                 if (!must_expand_basis && !basis.subs(r).is_zero())
843                         return basic::series(r, order, options);
844                 
845                 // Singularity encountered, expand basis into series
846                 e = basis.series(r, order, options);
847         } else {
848                 // Basis is a series
849                 e = basis;
850         }
851         
852         // Power e
853         return ex_to_pseries(e).power_const(ex_to_numeric(exponent), order);
854 }
855
856
857 /** Re-expansion of a pseries object. */
858 ex pseries::series(const relational & r, int order, unsigned options) const
859 {
860         const ex p = r.rhs();
861         GINAC_ASSERT(is_ex_exactly_of_type(r.lhs(),symbol));
862         const symbol &s = static_cast<symbol &>(*r.lhs().bp);
863         
864         if (var.is_equal(s) && point.is_equal(p)) {
865                 if (order > degree(s))
866                         return *this;
867                 else {
868                         epvector new_seq;
869                         epvector::const_iterator it = seq.begin(), itend = seq.end();
870                         while (it != itend) {
871                                 int o = ex_to_numeric(it->coeff).to_int();
872                                 if (o >= order) {
873                                         new_seq.push_back(expair(Order(_ex1()), o));
874                                         break;
875                                 }
876                                 new_seq.push_back(*it);
877                                 ++it;
878                         }
879                         return pseries(r, new_seq);
880                 }
881         } else
882                 return convert_to_poly().series(r, order, options);
883 }
884
885
886 /** Compute the truncated series expansion of an expression.
887  *  This function returns an expression containing an object of class pseries 
888  *  to represent the series. If the series does not terminate within the given
889  *  truncation order, the last term of the series will be an order term.
890  *
891  *  @param r  expansion relation, lhs holds variable and rhs holds point
892  *  @param order  truncation order of series calculations
893  *  @param options  of class series_options
894  *  @return an expression holding a pseries object */
895 ex ex::series(const ex & r, int order, unsigned options) const
896 {
897         GINAC_ASSERT(bp!=0);
898         ex e;
899         relational rel_;
900         
901         if (is_ex_exactly_of_type(r,relational))
902                 rel_ = ex_to_relational(r);
903         else if (is_ex_exactly_of_type(r,symbol))
904                 rel_ = relational(r,_ex0());
905         else
906                 throw (std::logic_error("ex::series(): expansion point has unknown type"));
907         
908         try {
909                 e = bp->series(rel_, order, options);
910         } catch (std::exception &x) {
911                 throw (std::logic_error(std::string("unable to compute series (") + x.what() + ")"));
912         }
913         return e;
914 }
915
916 //////////
917 // static member variables
918 //////////
919
920 // protected
921
922 unsigned pseries::precedence = 38;  // for clarity just below add::precedence
923
924 } // namespace GiNaC