]> www.ginac.de Git - ginac.git/blob - ginac/pseries.cpp
- Macro GINAC_CHECK_LIBCLN only checks if doublefactorial is available now.
[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-2000 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 "archive.h"
35 #include "utils.h"
36 #include "debugmsg.h"
37
38 #ifndef NO_GINAC_NAMESPACE
39 namespace GiNaC {
40 #endif // ndef NO_GINAC_NAMESPACE
41
42 GINAC_IMPLEMENT_REGISTERED_CLASS(pseries, basic)
43
44 /*
45  *  Default constructor, destructor, copy constructor, assignment operator and helpers
46  */
47
48 pseries::pseries() : basic(TINFO_pseries)
49 {
50     debugmsg("pseries default constructor", LOGLEVEL_CONSTRUCT);
51 }
52
53 pseries::~pseries()
54 {
55     debugmsg("pseries destructor", LOGLEVEL_DESTRUCT);
56     destroy(false);
57 }
58
59 pseries::pseries(const pseries &other)
60 {
61     debugmsg("pseries copy constructor", LOGLEVEL_CONSTRUCT);
62     copy(other);
63 }
64
65 const pseries &pseries::operator=(const pseries & other)
66 {
67     debugmsg("pseries operator=", LOGLEVEL_ASSIGNMENT);
68     if (this != &other) {
69         destroy(true);
70         copy(other);
71     }
72     return *this;
73 }
74
75 void pseries::copy(const pseries &other)
76 {
77     inherited::copy(other);
78     seq = other.seq;
79     var = other.var;
80     point = other.point;
81 }
82
83 void pseries::destroy(bool call_parent)
84 {
85     if (call_parent)
86         inherited::destroy(call_parent);
87 }
88
89
90 /*
91  *  Other constructors
92  */
93
94 /** Construct pseries from a vector of coefficients and powers.
95  *  expair.rest holds the coefficient, expair.coeff holds the power.
96  *  The powers must be integers (positive or negative) and in ascending order;
97  *  the last coefficient can be Order(_ex1()) to represent a truncated,
98  *  non-terminating series.
99  *
100  *  @param var_  series variable (must hold a symbol)
101  *  @param point_  expansion point
102  *  @param ops_  vector of {coefficient, power} pairs (coefficient must not be zero)
103  *  @return newly constructed pseries */
104 pseries::pseries(const ex &var_, const ex &point_, const epvector &ops_)
105     : basic(TINFO_pseries), seq(ops_), var(var_), point(point_)
106 {
107     debugmsg("pseries constructor from ex,ex,epvector", LOGLEVEL_CONSTRUCT);
108     GINAC_ASSERT(is_ex_exactly_of_type(var_, symbol));
109 }
110
111
112 /*
113  *  Archiving
114  */
115
116 /** Construct object from archive_node. */
117 pseries::pseries(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
118 {
119     debugmsg("pseries constructor from archive_node", LOGLEVEL_CONSTRUCT);
120     for (unsigned int i=0; true; i++) {
121         ex rest;
122         ex coeff;
123         if (n.find_ex("coeff", rest, sym_lst, i) && n.find_ex("power", coeff, sym_lst, i))
124             seq.push_back(expair(rest, coeff));
125         else
126             break;
127     }
128     n.find_ex("var", var, sym_lst);
129     n.find_ex("point", point, sym_lst);
130 }
131
132 /** Unarchive the object. */
133 ex pseries::unarchive(const archive_node &n, const lst &sym_lst)
134 {
135     return (new pseries(n, sym_lst))->setflag(status_flags::dynallocated);
136 }
137
138 /** Archive the object. */
139 void pseries::archive(archive_node &n) const
140 {
141     inherited::archive(n);
142     epvector::const_iterator i = seq.begin(), iend = seq.end();
143     while (i != iend) {
144         n.add_ex("coeff", i->rest);
145         n.add_ex("power", i->coeff);
146         i++;
147     }
148     n.add_ex("var", var);
149     n.add_ex("point", point);
150 }
151
152
153 /*
154  *  Functions overriding virtual functions from base classes
155  */
156
157 basic *pseries::duplicate() const
158 {
159     debugmsg("pseries duplicate", LOGLEVEL_DUPLICATE);
160     return new pseries(*this);
161 }
162
163 void pseries::print(ostream &os, unsigned upper_precedence) const
164 {
165         debugmsg("symbol print", LOGLEVEL_PRINT);
166         convert_to_poly().print(os, upper_precedence);
167 }
168
169 void pseries::printraw(ostream &os) const
170 {
171         debugmsg("symbol printraw", LOGLEVEL_PRINT);
172         os << "pseries(" << var << ";" << point << ";";
173         for (epvector::const_iterator i=seq.begin(); i!=seq.end(); i++) {
174                 os << "(" << (*i).rest << "," << (*i).coeff << "),";
175         }
176         os << ")";
177 }
178
179 unsigned pseries::nops(void) const
180 {
181         return seq.size();
182 }
183
184 ex pseries::op(int i) const
185 {
186         if (i < 0 || i >= seq.size())
187             throw (std::out_of_range("op() out of range"));
188         return seq[i].rest * power(var - point, seq[i].coeff);
189 }
190
191 ex &pseries::let_op(int i)
192 {
193     throw (std::logic_error("let_op not defined for pseries"));
194 }
195
196 int pseries::degree(const symbol &s) const
197 {
198     if (var.is_equal(s)) {
199         // Return last exponent
200         if (seq.size())
201             return ex_to_numeric((*(seq.end() - 1)).coeff).to_int();
202         else
203             return 0;
204     } else {
205         epvector::const_iterator it = seq.begin(), itend = seq.end();
206         if (it == itend)
207             return 0;
208         int max_pow = INT_MIN;
209         while (it != itend) {
210             int pow = it->rest.degree(s);
211             if (pow > max_pow)
212                 max_pow = pow;
213             it++;
214         }
215         return max_pow;
216     }
217 }
218
219 int pseries::ldegree(const symbol &s) const
220 {
221     if (var.is_equal(s)) {
222         // Return first exponent
223         if (seq.size())
224             return ex_to_numeric((*(seq.begin())).coeff).to_int();
225         else
226             return 0;
227     } else {
228         epvector::const_iterator it = seq.begin(), itend = seq.end();
229         if (it == itend)
230             return 0;
231         int min_pow = INT_MAX;
232         while (it != itend) {
233             int pow = it->rest.ldegree(s);
234             if (pow < min_pow)
235                 min_pow = pow;
236             it++;
237         }
238         return min_pow;
239     }
240 }
241
242 ex pseries::coeff(const symbol &s, int n) const
243 {
244     if (var.is_equal(s)) {
245         epvector::const_iterator it = seq.begin(), itend = seq.end();
246         while (it != itend) {
247             int pow = ex_to_numeric(it->coeff).to_int();
248             if (pow == n)
249                 return it->rest;
250             if (pow > n)
251                 return _ex0();
252             it++;
253         }
254         return _ex0();
255     } else
256         return convert_to_poly().coeff(s, n);
257 }
258
259 ex pseries::eval(int level) const
260 {
261     if (level == 1)
262         return this->hold();
263     
264     // Construct a new series with evaluated coefficients
265     epvector new_seq;
266     new_seq.reserve(seq.size());
267     epvector::const_iterator it = seq.begin(), itend = seq.end();
268     while (it != itend) {
269         new_seq.push_back(expair(it->rest.eval(level-1), it->coeff));
270         it++;
271     }
272     return (new pseries(var, point, new_seq))->setflag(status_flags::dynallocated | status_flags::evaluated);
273 }
274
275 /** Evaluate numerically.  The order term is dropped. */
276 ex pseries::evalf(int level) const
277 {
278     return convert_to_poly().evalf(level);
279 }
280
281 ex pseries::subs(const lst & ls, const lst & lr) const
282 {
283         // If expansion variable is being substituted, convert the series to a
284         // polynomial and do the substitution there because the result might
285         // no longer be a power series
286         if (ls.has(var))
287                 return convert_to_poly(true).subs(ls, lr);
288
289         // Otherwise construct a new series with substituted coefficients and
290         // expansion point
291         epvector new_seq;
292         new_seq.reserve(seq.size());
293         epvector::const_iterator it = seq.begin(), itend = seq.end();
294         while (it != itend) {
295                 new_seq.push_back(expair(it->rest.subs(ls, lr), it->coeff));
296                 it++;
297         }
298     return (new pseries(var, point.subs(ls, lr), new_seq))->setflag(status_flags::dynallocated);
299 }
300
301
302 /*
303  *  Construct ordinary polynomial out of series
304  */
305
306 /** Convert a pseries object to an ordinary polynomial.
307  *
308  *  @param no_order flag: discard higher order terms */
309 ex pseries::convert_to_poly(bool no_order) const
310 {
311     ex e;
312     epvector::const_iterator it = seq.begin(), itend = seq.end();
313     
314     while (it != itend) {
315         if (is_order_function(it->rest)) {
316             if (!no_order)
317                 e += Order(power(var - point, it->coeff));
318         } else
319             e += it->rest * power(var - point, it->coeff);
320         it++;
321     }
322     return e;
323 }
324
325
326 /*
327  *  Implementation of series expansion
328  */
329
330 /** Default implementation of ex::series(). This performs Taylor expansion.
331  *  @see ex::series */
332 ex basic::series(const symbol & s, const ex & point, int order) const
333 {
334     epvector seq;
335     numeric fac(1);
336     ex deriv = *this;
337     ex coeff = deriv.subs(s == point);
338     if (!coeff.is_zero())
339         seq.push_back(expair(coeff, numeric(0)));
340     
341     int n;
342     for (n=1; n<order; n++) {
343         fac = fac.mul(numeric(n));
344         deriv = deriv.diff(s).expand();
345         if (deriv.is_zero()) {
346             // Series terminates
347             return pseries(s, point, seq);
348         }
349         coeff = fac.inverse() * deriv.subs(s == point);
350         if (!coeff.is_zero())
351             seq.push_back(expair(coeff, numeric(n)));
352     }
353     
354     // Higher-order terms, if present
355     deriv = deriv.diff(s);
356     if (!deriv.is_zero())
357         seq.push_back(expair(Order(_ex1()), numeric(n)));
358     return pseries(s, point, seq);
359 }
360
361
362 /** Implementation of ex::series() for symbols.
363  *  @see ex::series */
364 ex symbol::series(const symbol & s, const ex & point, int order) const
365 {
366         epvector seq;
367         if (is_equal(s)) {
368                 if (order > 0 && !point.is_zero())
369                         seq.push_back(expair(point, _ex0()));
370                 if (order > 1)
371                         seq.push_back(expair(_ex1(), _ex1()));
372                 else
373                         seq.push_back(expair(Order(_ex1()), numeric(order)));
374         } else
375                 seq.push_back(expair(*this, _ex0()));
376         return pseries(s, point, seq);
377 }
378
379
380 /** Add one series object to another, producing a pseries object that represents
381  *  the sum.
382  *
383  *  @param other  pseries object to add with
384  *  @return the sum as a pseries */
385 ex pseries::add_series(const pseries &other) const
386 {
387     // Adding two series with different variables or expansion points
388     // results in an empty (constant) series 
389     if (!is_compatible_to(other)) {
390         epvector nul;
391         nul.push_back(expair(Order(_ex1()), _ex0()));
392         return pseries(var, point, nul);
393     }
394     
395     // Series addition
396     epvector new_seq;
397     epvector::const_iterator a = seq.begin();
398     epvector::const_iterator b = other.seq.begin();
399     epvector::const_iterator a_end = seq.end();
400     epvector::const_iterator b_end = other.seq.end();
401     int pow_a = INT_MAX, pow_b = INT_MAX;
402     for (;;) {
403         // If a is empty, fill up with elements from b and stop
404         if (a == a_end) {
405             while (b != b_end) {
406                 new_seq.push_back(*b);
407                 b++;
408             }
409             break;
410         } else
411             pow_a = ex_to_numeric((*a).coeff).to_int();
412         
413         // If b is empty, fill up with elements from a and stop
414         if (b == b_end) {
415             while (a != a_end) {
416                 new_seq.push_back(*a);
417                 a++;
418             }
419             break;
420         } else
421             pow_b = ex_to_numeric((*b).coeff).to_int();
422         
423         // a and b are non-empty, compare powers
424         if (pow_a < pow_b) {
425             // a has lesser power, get coefficient from a
426             new_seq.push_back(*a);
427             if (is_order_function((*a).rest))
428                 break;
429             a++;
430         } else if (pow_b < pow_a) {
431             // b has lesser power, get coefficient from b
432             new_seq.push_back(*b);
433             if (is_order_function((*b).rest))
434                 break;
435             b++;
436         } else {
437             // Add coefficient of a and b
438             if (is_order_function((*a).rest) || is_order_function((*b).rest)) {
439                 new_seq.push_back(expair(Order(_ex1()), (*a).coeff));
440                 break;  // Order term ends the sequence
441             } else {
442                 ex sum = (*a).rest + (*b).rest;
443                 if (!(sum.is_zero()))
444                     new_seq.push_back(expair(sum, numeric(pow_a)));
445                 a++;
446                 b++;
447             }
448         }
449     }
450     return pseries(var, point, new_seq);
451 }
452
453
454 /** Implementation of ex::series() for sums. This performs series addition when
455  *  adding pseries objects.
456  *  @see ex::series */
457 ex add::series(const symbol & s, const ex & point, int order) const
458 {
459     ex acc; // Series accumulator
460     
461     // Get first term from overall_coeff
462     acc = overall_coeff.series(s, point, order);
463
464     // Add remaining terms
465     epvector::const_iterator it = seq.begin();
466     epvector::const_iterator itend = seq.end();
467     for (; it!=itend; it++) {
468         ex op;
469         if (is_ex_exactly_of_type(it->rest, pseries))
470             op = it->rest;
471         else
472             op = it->rest.series(s, point, order);
473         if (!it->coeff.is_equal(_ex1()))
474             op = ex_to_pseries(op).mul_const(ex_to_numeric(it->coeff));
475         
476         // Series addition
477         acc = ex_to_pseries(acc).add_series(ex_to_pseries(op));
478     }
479     return acc;
480 }
481
482
483 /** Multiply a pseries object with a numeric constant, producing a pseries object
484  *  that represents the product.
485  *
486  *  @param other  constant to multiply with
487  *  @return the product as a pseries */
488 ex pseries::mul_const(const numeric &other) const
489 {
490     epvector new_seq;
491     new_seq.reserve(seq.size());
492     
493     epvector::const_iterator it = seq.begin(), itend = seq.end();
494     while (it != itend) {
495         if (!is_order_function(it->rest))
496             new_seq.push_back(expair(it->rest * other, it->coeff));
497         else
498             new_seq.push_back(*it);
499         it++;
500     }
501     return pseries(var, point, new_seq);
502 }
503
504
505 /** Multiply one pseries object to another, producing a pseries object that
506  *  represents the product.
507  *
508  *  @param other  pseries object to multiply with
509  *  @return the product as a pseries */
510 ex pseries::mul_series(const pseries &other) const
511 {
512     // Multiplying two series with different variables or expansion points
513     // results in an empty (constant) series 
514     if (!is_compatible_to(other)) {
515         epvector nul;
516         nul.push_back(expair(Order(_ex1()), _ex0()));
517         return pseries(var, point, nul);
518     }
519
520     // Series multiplication
521     epvector new_seq;
522     
523     const symbol *s = static_cast<symbol *>(var.bp);
524     int a_max = degree(*s);
525     int b_max = other.degree(*s);
526     int a_min = ldegree(*s);
527     int b_min = other.ldegree(*s);
528     int cdeg_min = a_min + b_min;
529     int cdeg_max = a_max + b_max;
530     
531     int higher_order_a = INT_MAX;
532     int higher_order_b = INT_MAX;
533     if (is_order_function(coeff(*s, a_max)))
534         higher_order_a = a_max + b_min;
535     if (is_order_function(other.coeff(*s, b_max)))
536         higher_order_b = b_max + a_min;
537     int higher_order_c = min(higher_order_a, higher_order_b);
538     if (cdeg_max >= higher_order_c)
539         cdeg_max = higher_order_c - 1;
540     
541     for (int cdeg=cdeg_min; cdeg<=cdeg_max; cdeg++) {
542         ex co = _ex0();
543         // c(i)=a(0)b(i)+...+a(i)b(0)
544         for (int i=a_min; cdeg-i>=b_min; i++) {
545             ex a_coeff = coeff(*s, i);
546             ex b_coeff = other.coeff(*s, cdeg-i);
547             if (!is_order_function(a_coeff) && !is_order_function(b_coeff))
548                 co += coeff(*s, i) * other.coeff(*s, cdeg-i);
549         }
550         if (!co.is_zero())
551             new_seq.push_back(expair(co, numeric(cdeg)));
552     }
553     if (higher_order_c < INT_MAX)
554         new_seq.push_back(expair(Order(_ex1()), numeric(higher_order_c)));
555     return pseries(var, point, new_seq);
556 }
557
558
559 /** Implementation of ex::series() for product. This performs series
560  *  multiplication when multiplying series.
561  *  @see ex::series */
562 ex mul::series(const symbol & s, const ex & point, int order) const
563 {
564     ex acc; // Series accumulator
565     
566     // Get first term from overall_coeff
567     acc = overall_coeff.series(s, point, order);
568     
569     // Multiply with remaining terms
570     epvector::const_iterator it = seq.begin();
571     epvector::const_iterator itend = seq.end();
572     for (; it!=itend; it++) {
573         ex op = it->rest;
574         if (op.info(info_flags::numeric)) {
575             // series * const (special case, faster)
576             ex f = power(op, it->coeff);
577             acc = ex_to_pseries(acc).mul_const(ex_to_numeric(f));
578             continue;
579         } else if (!is_ex_exactly_of_type(op, pseries))
580             op = op.series(s, point, order);
581         if (!it->coeff.is_equal(_ex1()))
582             op = ex_to_pseries(op).power_const(ex_to_numeric(it->coeff), order);
583
584         // Series multiplication
585         acc = ex_to_pseries(acc).mul_series(ex_to_pseries(op));
586     }
587     return acc;
588 }
589
590
591 /** Compute the p-th power of a series.
592  *
593  *  @param p  power to compute
594  *  @param deg  truncation order of series calculation */
595 ex pseries::power_const(const numeric &p, int deg) const
596 {
597     int i;
598     const symbol *s = static_cast<symbol *>(var.bp);
599     int ldeg = ldegree(*s);
600     
601     // Calculate coefficients of powered series
602     exvector co;
603     co.reserve(deg);
604     ex co0;
605     co.push_back(co0 = power(coeff(*s, ldeg), p));
606     bool all_sums_zero = true;
607     for (i=1; i<deg; i++) {
608         ex sum = _ex0();
609         for (int j=1; j<=i; j++) {
610             ex c = coeff(*s, j + ldeg);
611             if (is_order_function(c)) {
612                 co.push_back(Order(_ex1()));
613                 break;
614             } else
615                 sum += (p * j - (i - j)) * co[i - j] * c;
616         }
617         if (!sum.is_zero())
618             all_sums_zero = false;
619         co.push_back(co0 * sum / numeric(i));
620     }
621     
622     // Construct new series (of non-zero coefficients)
623     epvector new_seq;
624     bool higher_order = false;
625     for (i=0; i<deg; i++) {
626         if (!co[i].is_zero())
627             new_seq.push_back(expair(co[i], numeric(i) + p * ldeg));
628         if (is_order_function(co[i])) {
629             higher_order = true;
630             break;
631         }
632     }
633     if (!higher_order && !all_sums_zero)
634         new_seq.push_back(expair(Order(_ex1()), numeric(deg) + p * ldeg));
635     return pseries(var, point, new_seq);
636 }
637
638
639 /** Implementation of ex::series() for powers. This performs Laurent expansion
640  *  of reciprocals of series at singularities.
641  *  @see ex::series */
642 ex power::series(const symbol & s, const ex & point, int order) const
643 {
644     ex e;
645     if (!is_ex_exactly_of_type(basis, pseries)) {
646         // Basis is not a series, may there be a singulary?
647         if (!exponent.info(info_flags::negint))
648             return basic::series(s, point, order);
649         
650         // Expression is of type something^(-int), check for singularity
651         if (!basis.subs(s == point).is_zero())
652             return basic::series(s, point, order);
653         
654         // Singularity encountered, expand basis into series
655         e = basis.series(s, point, order);
656     } else {
657         // Basis is a series
658         e = basis;
659     }
660     
661     // Power e
662     return ex_to_pseries(e).power_const(ex_to_numeric(exponent), order);
663 }
664
665
666 /** Compute the truncated series expansion of an expression.
667  *  This function returns an expression containing an object of class pseries to
668  *  represent the series. If the series does not terminate within the given
669  *  truncation order, the last term of the series will be an order term.
670  *
671  *  @param s  expansion variable
672  *  @param point  expansion point
673  *  @param order  truncation order of series calculations
674  *  @return an expression holding a pseries object */
675 ex ex::series(const symbol &s, const ex &point, int order) const
676 {
677     GINAC_ASSERT(bp!=0);
678     return bp->series(s, point, order);
679 }
680
681
682 // Global constants
683 const pseries some_pseries;
684 const type_info & typeid_pseries = typeid(some_pseries);
685
686 #ifndef NO_GINAC_NAMESPACE
687 } // namespace GiNaC
688 #endif // ndef NO_GINAC_NAMESPACE