3 * Implementation of class for extended truncated power series and
4 * methods for series expansion. */
7 * GiNaC Copyright (C) 1999-2020 Johannes Gutenberg University Mainz, Germany
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.
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.
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
26 #include "inifcns.h" // for Order function
30 #include "relational.h"
31 #include "operators.h"
43 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(pseries, basic,
44 print_func<print_context>(&pseries::do_print).
45 print_func<print_latex>(&pseries::do_print_latex).
46 print_func<print_tree>(&pseries::do_print_tree).
47 print_func<print_python>(&pseries::do_print_python).
48 print_func<print_python_repr>(&pseries::do_print_python_repr))
55 pseries::pseries() { }
62 /** Construct pseries from a vector of coefficients and powers.
63 * expair.rest holds the coefficient, expair.coeff holds the power.
64 * The powers must be integers (positive or negative) and in ascending order;
65 * the last coefficient can be Order(_ex1) to represent a truncated,
66 * non-terminating series.
68 * @param rel_ expansion variable and point (must hold a relational)
69 * @param ops_ vector of {coefficient, power} pairs (coefficient must not be zero)
70 * @return newly constructed pseries */
71 pseries::pseries(const ex &rel_, const epvector &ops_)
74 #ifdef DO_GINAC_ASSERT
76 while (i != seq.end()) {
79 GINAC_ASSERT(!is_order_function(i->rest));
82 GINAC_ASSERT(is_a<numeric>(i->coeff));
83 GINAC_ASSERT(ex_to<numeric>(i->coeff) < ex_to<numeric>(ip1->coeff));
86 #endif // def DO_GINAC_ASSERT
87 GINAC_ASSERT(is_a<relational>(rel_));
88 GINAC_ASSERT(is_a<symbol>(rel_.lhs()));
92 pseries::pseries(const ex &rel_, epvector &&ops_)
93 : seq(std::move(ops_))
95 #ifdef DO_GINAC_ASSERT
97 while (i != seq.end()) {
100 GINAC_ASSERT(!is_order_function(i->rest));
103 GINAC_ASSERT(is_a<numeric>(i->coeff));
104 GINAC_ASSERT(ex_to<numeric>(i->coeff) < ex_to<numeric>(ip1->coeff));
107 #endif // def DO_GINAC_ASSERT
108 GINAC_ASSERT(is_a<relational>(rel_));
109 GINAC_ASSERT(is_a<symbol>(rel_.lhs()));
119 void pseries::read_archive(const archive_node &n, lst &sym_lst)
121 inherited::read_archive(n, sym_lst);
122 auto range = n.find_property_range("coeff", "power");
123 seq.reserve((range.end-range.begin)/2);
125 for (auto loc = range.begin; loc < range.end;) {
128 n.find_ex_by_loc(loc++, rest, sym_lst);
129 n.find_ex_by_loc(loc++, coeff, sym_lst);
130 seq.emplace_back(expair(rest, coeff));
133 n.find_ex("var", var, sym_lst);
134 n.find_ex("point", point, sym_lst);
137 void pseries::archive(archive_node &n) const
139 inherited::archive(n);
140 for (auto & it : seq) {
141 n.add_ex("coeff", it.rest);
142 n.add_ex("power", it.coeff);
144 n.add_ex("var", var);
145 n.add_ex("point", point);
150 // functions overriding virtual functions from base classes
153 void pseries::print_series(const print_context & c, const char *openbrace, const char *closebrace, const char *mul_sym, const char *pow_sym, unsigned level) const
155 if (precedence() <= level)
158 // objects of type pseries must not have any zero entries, so the
159 // trivial (zero) pseries needs a special treatment here:
163 auto i = seq.begin(), end = seq.end();
166 // print a sign, if needed
167 if (i != seq.begin())
170 if (!is_order_function(i->rest)) {
172 // print 'rest', i.e. the expansion coefficient
173 if (i->rest.info(info_flags::numeric) &&
174 i->rest.info(info_flags::positive)) {
177 c.s << openbrace << '(';
179 c.s << ')' << closebrace;
182 // print 'coeff', something like (x-1)^42
183 if (!i->coeff.is_zero()) {
185 if (!point.is_zero()) {
186 c.s << openbrace << '(';
187 (var-point).print(c);
188 c.s << ')' << closebrace;
191 if (i->coeff.compare(_ex1)) {
194 if (i->coeff.info(info_flags::negative)) {
204 Order(pow(var - point, i->coeff)).print(c);
208 if (precedence() <= level)
212 void pseries::do_print(const print_context & c, unsigned level) const
214 print_series(c, "", "", "*", "^", level);
217 void pseries::do_print_latex(const print_latex & c, unsigned level) const
219 print_series(c, "{", "}", " ", "^", level);
222 void pseries::do_print_python(const print_python & c, unsigned level) const
224 print_series(c, "", "", "*", "**", level);
227 void pseries::do_print_tree(const print_tree & c, unsigned level) const
229 c.s << std::string(level, ' ') << class_name() << " @" << this
230 << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec
232 size_t num = seq.size();
233 for (size_t i=0; i<num; ++i) {
234 seq[i].rest.print(c, level + c.delta_indent);
235 seq[i].coeff.print(c, level + c.delta_indent);
236 c.s << std::string(level + c.delta_indent, ' ') << "-----" << std::endl;
238 var.print(c, level + c.delta_indent);
239 point.print(c, level + c.delta_indent);
242 void pseries::do_print_python_repr(const print_python_repr & c, unsigned level) const
244 c.s << class_name() << "(relational(";
249 size_t num = seq.size();
250 for (size_t i=0; i<num; ++i) {
254 seq[i].rest.print(c);
256 seq[i].coeff.print(c);
262 int pseries::compare_same_type(const basic & other) const
264 GINAC_ASSERT(is_a<pseries>(other));
265 const pseries &o = static_cast<const pseries &>(other);
267 // first compare the lengths of the series...
268 if (seq.size()>o.seq.size())
270 if (seq.size()<o.seq.size())
273 // ...then the expansion point...
274 int cmpval = var.compare(o.var);
277 cmpval = point.compare(o.point);
281 // ...and if that failed the individual elements
282 auto it = seq.begin(), o_it = o.seq.begin();
283 while (it!=seq.end() && o_it!=o.seq.end()) {
284 cmpval = it->compare(*o_it);
291 // so they are equal.
295 /** Return the number of operands including a possible order term. */
296 size_t pseries::nops() const
301 /** Return the ith term in the series when represented as a sum. */
302 ex pseries::op(size_t i) const
305 throw (std::out_of_range("op() out of range"));
307 if (is_order_function(seq[i].rest))
308 return Order(pow(var-point, seq[i].coeff));
309 return seq[i].rest * pow(var - point, seq[i].coeff);
312 /** Return degree of highest power of the series. This is usually the exponent
313 * of the Order term. If s is not the expansion variable of the series, the
314 * series is examined termwise. */
315 int pseries::degree(const ex &s) const
321 // Return last/greatest exponent
322 return ex_to<numeric>((seq.end()-1)->coeff).to_int();
324 int max_pow = std::numeric_limits<int>::min();
325 for (auto & it : seq)
326 max_pow = std::max(max_pow, it.rest.degree(s));
330 /** Return degree of lowest power of the series. This is usually the exponent
331 * of the leading term. If s is not the expansion variable of the series, the
332 * series is examined termwise. If s is the expansion variable but the
333 * expansion point is not zero the series is not expanded to find the degree.
334 * I.e.: (1-x) + (1-x)^2 + Order((1-x)^3) has ldegree(x) 1, not 0. */
335 int pseries::ldegree(const ex &s) const
341 // Return first/smallest exponent
342 return ex_to<numeric>((seq.begin())->coeff).to_int();
344 int min_pow = std::numeric_limits<int>::max();
345 for (auto & it : seq)
346 min_pow = std::min(min_pow, it.rest.degree(s));
350 /** Return coefficient of degree n in power series if s is the expansion
351 * variable. If the expansion point is nonzero, by definition the n=1
352 * coefficient in s of a+b*(s-z)+c*(s-z)^2+Order((s-z)^3) is b (assuming
353 * the expansion took place in the s in the first place).
354 * If s is not the expansion variable, an attempt is made to convert the
355 * series to a polynomial and return the corresponding coefficient from
357 ex pseries::coeff(const ex &s, int n) const
359 if (var.is_equal(s)) {
363 // Binary search in sequence for given power
364 numeric looking_for = numeric(n);
365 int lo = 0, hi = seq.size() - 1;
367 int mid = (lo + hi) / 2;
368 GINAC_ASSERT(is_exactly_a<numeric>(seq[mid].coeff));
369 int cmp = ex_to<numeric>(seq[mid].coeff).compare(looking_for);
375 return seq[mid].rest;
380 throw(std::logic_error("pseries::coeff: compare() didn't return -1, 0 or 1"));
385 return convert_to_poly().coeff(s, n);
389 ex pseries::collect(const ex &s, bool distributed) const
394 /** Perform coefficient-wise automatic term rewriting rules in this class. */
395 ex pseries::eval() const
400 /** Evaluate coefficients numerically. */
401 ex pseries::evalf() const
403 // Construct a new series with evaluated coefficients
405 new_seq.reserve(seq.size());
406 for (auto & it : seq)
407 new_seq.emplace_back(expair(it.rest.evalf(), it.coeff));
409 return dynallocate<pseries>(relational(var,point), std::move(new_seq)).setflag(status_flags::evaluated);
412 ex pseries::conjugate() const
414 if(!var.info(info_flags::real))
415 return conjugate_function(*this).hold();
417 std::unique_ptr<epvector> newseq(conjugateepvector(seq));
418 ex newpoint = point.conjugate();
420 if (!newseq && are_ex_trivially_equal(point, newpoint)) {
424 return dynallocate<pseries>(var==newpoint, newseq ? std::move(*newseq) : seq);
427 ex pseries::real_part() const
429 if(!var.info(info_flags::real))
430 return real_part_function(*this).hold();
431 ex newpoint = point.real_part();
432 if(newpoint != point)
433 return real_part_function(*this).hold();
436 v.reserve(seq.size());
437 for (auto & it : seq)
438 v.emplace_back(expair(it.rest.real_part(), it.coeff));
439 return dynallocate<pseries>(var==point, std::move(v));
442 ex pseries::imag_part() const
444 if(!var.info(info_flags::real))
445 return imag_part_function(*this).hold();
446 ex newpoint = point.real_part();
447 if(newpoint != point)
448 return imag_part_function(*this).hold();
451 v.reserve(seq.size());
452 for (auto & it : seq)
453 v.emplace_back(expair(it.rest.imag_part(), it.coeff));
454 return dynallocate<pseries>(var==point, std::move(v));
457 ex pseries::eval_integ() const
459 std::unique_ptr<epvector> newseq(nullptr);
460 for (auto i=seq.begin(); i!=seq.end(); ++i) {
462 newseq->emplace_back(expair(i->rest.eval_integ(), i->coeff));
465 ex newterm = i->rest.eval_integ();
466 if (!are_ex_trivially_equal(newterm, i->rest)) {
467 newseq.reset(new epvector);
468 newseq->reserve(seq.size());
469 for (auto j=seq.begin(); j!=i; ++j)
470 newseq->push_back(*j);
471 newseq->emplace_back(expair(newterm, i->coeff));
475 ex newpoint = point.eval_integ();
476 if (newseq || !are_ex_trivially_equal(newpoint, point))
477 return dynallocate<pseries>(var==newpoint, std::move(*newseq));
481 ex pseries::evalm() const
483 // evalm each coefficient
485 bool something_changed = false;
486 for (auto i=seq.begin(); i!=seq.end(); ++i) {
487 if (something_changed) {
488 ex newcoeff = i->rest.evalm();
489 if (!newcoeff.is_zero())
490 newseq.emplace_back(expair(newcoeff, i->coeff));
492 ex newcoeff = i->rest.evalm();
493 if (!are_ex_trivially_equal(newcoeff, i->rest)) {
494 something_changed = true;
495 newseq.reserve(seq.size());
496 std::copy(seq.begin(), i, std::back_inserter<epvector>(newseq));
497 if (!newcoeff.is_zero())
498 newseq.emplace_back(expair(newcoeff, i->coeff));
502 if (something_changed)
503 return dynallocate<pseries>(var==point, std::move(newseq));
508 ex pseries::subs(const exmap & m, unsigned options) const
510 // If expansion variable is being substituted, convert the series to a
511 // polynomial and do the substitution there because the result might
512 // no longer be a power series
513 if (m.find(var) != m.end())
514 return convert_to_poly(true).subs(m, options);
516 // Otherwise construct a new series with substituted coefficients and
519 newseq.reserve(seq.size());
520 for (auto & it : seq)
521 newseq.emplace_back(expair(it.rest.subs(m, options), it.coeff));
522 return dynallocate<pseries>(relational(var,point.subs(m, options)), std::move(newseq));
525 /** Implementation of ex::expand() for a power series. It expands all the
526 * terms individually and returns the resulting series as a new pseries. */
527 ex pseries::expand(unsigned options) const
530 for (auto & it : seq) {
531 ex restexp = it.rest.expand();
532 if (!restexp.is_zero())
533 newseq.emplace_back(expair(restexp, it.coeff));
535 return dynallocate<pseries>(relational(var,point), std::move(newseq)).setflag(options == 0 ? status_flags::expanded : 0);
538 /** Implementation of ex::diff() for a power series.
540 ex pseries::derivative(const symbol & s) const
546 // FIXME: coeff might depend on var
547 for (auto & it : seq) {
548 if (is_order_function(it.rest)) {
549 new_seq.emplace_back(expair(it.rest, it.coeff - 1));
551 ex c = it.rest * it.coeff;
553 new_seq.emplace_back(expair(c, it.coeff - 1));
559 for (auto & it : seq) {
560 if (is_order_function(it.rest)) {
561 new_seq.push_back(it);
563 ex c = it.rest.diff(s);
565 new_seq.emplace_back(expair(c, it.coeff));
570 return pseries(relational(var,point), std::move(new_seq));
573 ex pseries::convert_to_poly(bool no_order) const
576 for (auto & it : seq) {
577 if (is_order_function(it.rest)) {
579 e += Order(pow(var - point, it.coeff));
581 e += it.rest * pow(var - point, it.coeff);
586 bool pseries::is_terminating() const
588 return seq.empty() || !is_order_function((seq.end()-1)->rest);
591 ex pseries::coeffop(size_t i) const
594 throw (std::out_of_range("coeffop() out of range"));
598 ex pseries::exponop(size_t i) const
601 throw (std::out_of_range("exponop() out of range"));
607 * Implementations of series expansion
610 /** Default implementation of ex::series(). This performs Taylor expansion.
612 ex basic::series(const relational & r, int order, unsigned options) const
615 const symbol &s = ex_to<symbol>(r.lhs());
617 // default for order-values that make no sense for Taylor expansion
618 if ((order <= 0) && this->has(s)) {
619 seq.emplace_back(expair(Order(_ex1), order));
620 return pseries(r, std::move(seq));
623 // do Taylor expansion
626 ex coeff = deriv.subs(r, subs_options::no_pattern);
628 if (!coeff.is_zero()) {
629 seq.emplace_back(expair(coeff, _ex0));
633 for (n=1; n<order; ++n) {
635 // We need to test for zero in order to see if the series terminates.
636 // The problem is that there is no such thing as a perfect test for
637 // zero. Expanding the term occasionally helps a little...
638 deriv = deriv.diff(s).expand();
639 if (deriv.is_zero()) // Series terminates
640 return pseries(r, std::move(seq));
642 coeff = deriv.subs(r, subs_options::no_pattern);
643 if (!coeff.is_zero())
644 seq.emplace_back(expair(fac * coeff, n));
647 // Higher-order terms, if present
648 deriv = deriv.diff(s);
649 if (!deriv.expand().is_zero())
650 seq.emplace_back(expair(Order(_ex1), n));
651 return pseries(r, std::move(seq));
655 /** Implementation of ex::series() for symbols.
657 ex symbol::series(const relational & r, int order, unsigned options) const
660 const ex point = r.rhs();
661 GINAC_ASSERT(is_a<symbol>(r.lhs()));
663 if (this->is_equal_same_type(ex_to<symbol>(r.lhs()))) {
664 if (order > 0 && !point.is_zero())
665 seq.emplace_back(expair(point, _ex0));
667 seq.emplace_back(expair(_ex1, _ex1));
669 seq.emplace_back(expair(Order(_ex1), numeric(order)));
671 seq.emplace_back(expair(*this, _ex0));
672 return pseries(r, std::move(seq));
676 /** Add one series object to another, producing a pseries object that
677 * represents the sum.
679 * @param other pseries object to add with
680 * @return the sum as a pseries */
681 ex pseries::add_series(const pseries &other) const
683 // Adding two series with different variables or expansion points
684 // results in an empty (constant) series
685 if (!is_compatible_to(other)) {
686 epvector nul { expair(Order(_ex1), _ex0) };
687 return pseries(relational(var,point), std::move(nul));
692 auto a = seq.begin(), a_end = seq.end();
693 auto b = other.seq.begin(), b_end = other.seq.end();
694 int pow_a = std::numeric_limits<int>::max(), pow_b = std::numeric_limits<int>::max();
696 // If a is empty, fill up with elements from b and stop
699 new_seq.push_back(*b);
704 pow_a = ex_to<numeric>((*a).coeff).to_int();
706 // If b is empty, fill up with elements from a and stop
709 new_seq.push_back(*a);
714 pow_b = ex_to<numeric>((*b).coeff).to_int();
716 // a and b are non-empty, compare powers
718 // a has lesser power, get coefficient from a
719 new_seq.push_back(*a);
720 if (is_order_function((*a).rest))
723 } else if (pow_b < pow_a) {
724 // b has lesser power, get coefficient from b
725 new_seq.push_back(*b);
726 if (is_order_function((*b).rest))
730 // Add coefficient of a and b
731 if (is_order_function((*a).rest) || is_order_function((*b).rest)) {
732 new_seq.emplace_back(expair(Order(_ex1), (*a).coeff));
733 break; // Order term ends the sequence
735 ex sum = (*a).rest + (*b).rest;
736 if (!(sum.is_zero()))
737 new_seq.emplace_back(expair(sum, numeric(pow_a)));
743 return pseries(relational(var,point), std::move(new_seq));
747 /** Implementation of ex::series() for sums. This performs series addition when
748 * adding pseries objects.
750 ex add::series(const relational & r, int order, unsigned options) const
752 ex acc; // Series accumulator
754 // Get first term from overall_coeff
755 acc = overall_coeff.series(r, order, options);
757 // Add remaining terms
758 for (auto & it : seq) {
760 if (is_exactly_a<pseries>(it.rest))
763 op = it.rest.series(r, order, options);
764 if (!it.coeff.is_equal(_ex1))
765 op = ex_to<pseries>(op).mul_const(ex_to<numeric>(it.coeff));
768 acc = ex_to<pseries>(acc).add_series(ex_to<pseries>(op));
774 /** Multiply a pseries object with a numeric constant, producing a pseries
775 * object that represents the product.
777 * @param other constant to multiply with
778 * @return the product as a pseries */
779 ex pseries::mul_const(const numeric &other) const
782 new_seq.reserve(seq.size());
784 for (auto & it : seq) {
785 if (!is_order_function(it.rest))
786 new_seq.emplace_back(expair(it.rest * other, it.coeff));
788 new_seq.push_back(it);
790 return pseries(relational(var,point), std::move(new_seq));
794 /** Multiply one pseries object to another, producing a pseries object that
795 * represents the product.
797 * @param other pseries object to multiply with
798 * @return the product as a pseries */
799 ex pseries::mul_series(const pseries &other) const
801 // Multiplying two series with different variables or expansion points
802 // results in an empty (constant) series
803 if (!is_compatible_to(other)) {
804 epvector nul { expair(Order(_ex1), _ex0) };
805 return pseries(relational(var,point), std::move(nul));
808 if (seq.empty() || other.seq.empty()) {
809 return dynallocate<pseries>(var==point, epvector());
812 // Series multiplication
814 const int a_max = degree(var);
815 const int b_max = other.degree(var);
816 const int a_min = ldegree(var);
817 const int b_min = other.ldegree(var);
818 const int cdeg_min = a_min + b_min;
819 int cdeg_max = a_max + b_max;
821 int higher_order_a = std::numeric_limits<int>::max();
822 int higher_order_b = std::numeric_limits<int>::max();
823 if (is_order_function(coeff(var, a_max)))
824 higher_order_a = a_max + b_min;
825 if (is_order_function(other.coeff(var, b_max)))
826 higher_order_b = b_max + a_min;
827 const int higher_order_c = std::min(higher_order_a, higher_order_b);
828 if (cdeg_max >= higher_order_c)
829 cdeg_max = higher_order_c - 1;
831 std::map<int, ex> rest_map_a, rest_map_b;
832 for (const auto& it : seq)
833 rest_map_a[ex_to<numeric>(it.coeff).to_int()] = it.rest;
835 if (other.var.is_equal(var))
836 for (const auto& it : other.seq)
837 rest_map_b[ex_to<numeric>(it.coeff).to_int()] = it.rest;
839 for (int cdeg=cdeg_min; cdeg<=cdeg_max; ++cdeg) {
841 // c(i)=a(0)b(i)+...+a(i)b(0)
842 for (int i=a_min; cdeg-i>=b_min; ++i) {
843 const auto& ita = rest_map_a.find(i);
844 if (ita == rest_map_a.end())
846 const auto& itb = rest_map_b.find(cdeg-i);
847 if (itb == rest_map_b.end())
849 if (!is_order_function(ita->second) && !is_order_function(itb->second))
850 co += ita->second * itb->second;
853 new_seq.emplace_back(expair(co, numeric(cdeg)));
855 if (higher_order_c < std::numeric_limits<int>::max())
856 new_seq.emplace_back(expair(Order(_ex1), numeric(higher_order_c)));
857 return pseries(relational(var, point), std::move(new_seq));
861 /** Implementation of ex::series() for product. This performs series
862 * multiplication when multiplying series.
864 ex mul::series(const relational & r, int order, unsigned options) const
866 pseries acc; // Series accumulator
868 GINAC_ASSERT(is_a<symbol>(r.lhs()));
869 const ex& sym = r.lhs();
871 // holds ldegrees of the series of individual factors
872 std::vector<int> ldegrees;
873 std::vector<bool> ldegree_redo;
875 // find minimal degrees
876 // first round: obtain a bound up to which minimal degrees have to be
878 for (auto & it : seq) {
883 if (expon.info(info_flags::integer)) {
885 factor = ex_to<numeric>(expon).to_int();
887 buf = recombine_pair_to_ex(it);
890 int real_ldegree = 0;
891 bool flag_redo = false;
893 real_ldegree = buf.expand().ldegree(sym-r.rhs());
894 } catch (std::runtime_error) {}
896 if (real_ldegree == 0) {
898 // This case must terminate, otherwise we would have division by
903 real_ldegree = buf.series(r, orderloop, options).ldegree(sym);
904 } while (real_ldegree == orderloop);
906 // Here it is possible that buf does not have a ldegree, therefore
907 // check only if ldegree is negative, otherwise reconsider the case
908 // in the second round.
909 real_ldegree = buf.series(r, 0, options).ldegree(sym);
910 if (real_ldegree == 0)
915 ldegrees.push_back(factor * real_ldegree);
916 ldegree_redo.push_back(flag_redo);
919 int degbound = order-std::accumulate(ldegrees.begin(), ldegrees.end(), 0);
920 // Second round: determine the remaining positive ldegrees by the series
922 // here we can ignore ldegrees larger than degbound
924 for (auto & it : seq) {
925 if ( ldegree_redo[j] ) {
929 if (expon.info(info_flags::integer)) {
931 factor = ex_to<numeric>(expon).to_int();
933 buf = recombine_pair_to_ex(it);
935 int real_ldegree = 0;
939 real_ldegree = buf.series(r, orderloop, options).ldegree(sym);
940 } while ((real_ldegree == orderloop)
941 && (factor*real_ldegree < degbound));
942 ldegrees[j] = factor * real_ldegree;
943 degbound -= factor * real_ldegree;
948 int degsum = std::accumulate(ldegrees.begin(), ldegrees.end(), 0);
950 if (degsum > order) {
951 return dynallocate<pseries>(r, epvector{{Order(_ex1), order}});
954 // Multiply with remaining terms
955 auto itd = ldegrees.begin();
956 for (auto it=seq.begin(), itend=seq.end(); it!=itend; ++it, ++itd) {
958 // do series expansion with adjusted order
959 ex op = recombine_pair_to_ex(*it).series(r, order-degsum+(*itd), options);
961 // Series multiplication
962 if (it == seq.begin())
963 acc = ex_to<pseries>(op);
965 acc = ex_to<pseries>(acc.mul_series(ex_to<pseries>(op)));
968 return acc.mul_const(ex_to<numeric>(overall_coeff));
972 /** Compute the p-th power of a series.
974 * @param p power to compute
975 * @param deg truncation order of series calculation */
976 ex pseries::power_const(const numeric &p, int deg) const
979 // (due to Leonhard Euler)
980 // let A(x) be this series and for the time being let it start with a
981 // constant (later we'll generalize):
982 // A(x) = a_0 + a_1*x + a_2*x^2 + ...
983 // We want to compute
985 // C(x) = c_0 + c_1*x + c_2*x^2 + ...
986 // Taking the derivative on both sides and multiplying with A(x) one
987 // immediately arrives at
988 // C'(x)*A(x) = p*C(x)*A'(x)
989 // Multiplying this out and comparing coefficients we get the recurrence
991 // c_i = (i*p*a_i*c_0 + ((i-1)*p-1)*a_{i-1}*c_1 + ...
992 // ... + (p-(i-1))*a_1*c_{i-1})/(a_0*i)
993 // which can easily be solved given the starting value c_0 = (a_0)^p.
994 // For the more general case where the leading coefficient of A(x) is not
995 // a constant, just consider A2(x) = A(x)*x^m, with some integer m and
996 // repeat the above derivation. The leading power of C2(x) = A2(x)^2 is
997 // then of course x^(p*m) but the recurrence formula still holds.
1000 // as a special case, handle the empty (zero) series honoring the
1001 // usual power laws such as implemented in power::eval()
1002 if (p.real().is_zero())
1003 throw std::domain_error("pseries::power_const(): pow(0,I) is undefined");
1004 else if (p.real().is_negative())
1005 throw pole_error("pseries::power_const(): division by zero",1);
1010 const int ldeg = ldegree(var);
1011 if (!(p*ldeg).is_integer())
1012 throw std::runtime_error("pseries::power_const(): trying to assemble a Puiseux series");
1014 // adjust number of coefficients
1015 int numcoeff = deg - (p*ldeg).to_int();
1016 if (numcoeff <= 0) {
1017 epvector epv { expair(Order(_ex1), deg) };
1018 return dynallocate<pseries>(relational(var,point), std::move(epv));
1021 // O(x^n)^(-m) is undefined
1022 if (seq.size() == 1 && is_order_function(seq[0].rest) && p.real().is_negative())
1023 throw pole_error("pseries::power_const(): division by zero",1);
1025 // Compute coefficients of the powered series
1027 co.reserve(numcoeff);
1028 co.push_back(pow(coeff(var, ldeg), p));
1029 for (int i=1; i<numcoeff; ++i) {
1031 for (int j=1; j<=i; ++j) {
1032 ex c = coeff(var, j + ldeg);
1033 if (is_order_function(c)) {
1034 co.push_back(Order(_ex1));
1037 sum += (p * j - (i - j)) * co[i - j] * c;
1039 co.push_back(sum / coeff(var, ldeg) / i);
1042 // Construct new series (of non-zero coefficients)
1044 bool higher_order = false;
1045 for (int i=0; i<numcoeff; ++i) {
1046 if (!co[i].is_zero())
1047 new_seq.emplace_back(expair(co[i], p * ldeg + i));
1048 if (is_order_function(co[i])) {
1049 higher_order = true;
1054 new_seq.emplace_back(expair(Order(_ex1), p * ldeg + numcoeff));
1056 return pseries(relational(var,point), std::move(new_seq));
1060 /** Return a new pseries object with the powers shifted by deg. */
1061 pseries pseries::shift_exponents(int deg) const
1063 epvector newseq = seq;
1064 for (auto & it : newseq)
1066 return pseries(relational(var, point), std::move(newseq));
1070 /** Implementation of ex::series() for powers. This performs Laurent expansion
1071 * of reciprocals of series at singularities.
1072 * @see ex::series */
1073 ex power::series(const relational & r, int order, unsigned options) const
1075 // If basis is already a series, just power it
1076 if (is_exactly_a<pseries>(basis))
1077 return ex_to<pseries>(basis).power_const(ex_to<numeric>(exponent), order);
1079 // Basis is not a series, may there be a singularity?
1080 bool must_expand_basis = false;
1082 basis.subs(r, subs_options::no_pattern);
1083 } catch (pole_error) {
1084 must_expand_basis = true;
1087 bool exponent_is_regular = true;
1089 exponent.subs(r, subs_options::no_pattern);
1090 } catch (pole_error) {
1091 exponent_is_regular = false;
1094 if (!exponent_is_regular) {
1095 ex l = exponent*log(basis);
1097 ex le = l.series(r, order, options);
1098 // Note: expanding exp(l) won't help, since that will attempt
1099 // Taylor expansion, and fail (because exponent is "singular")
1100 // Still l itself might be expanded in Taylor series.
1102 // sin(x)/x*log(cos(x))
1104 return exp(le).series(r, order, options);
1105 // Note: if l happens to have a Laurent expansion (with
1106 // negative powers of (var - point)), expanding exp(le)
1107 // will barf (which is The Right Thing).
1110 // Is the expression of type something^(-int)?
1111 if (!must_expand_basis && !exponent.info(info_flags::negint)
1112 && (!is_a<add>(basis) || !is_a<numeric>(exponent)))
1113 return basic::series(r, order, options);
1115 // Is the expression of type 0^something?
1116 if (!must_expand_basis && !basis.subs(r, subs_options::no_pattern).is_zero()
1117 && (!is_a<add>(basis) || !is_a<numeric>(exponent)))
1118 return basic::series(r, order, options);
1120 // Singularity encountered, is the basis equal to (var - point)?
1121 if (basis.is_equal(r.lhs() - r.rhs())) {
1123 if (ex_to<numeric>(exponent).to_int() < order)
1124 new_seq.emplace_back(expair(_ex1, exponent));
1126 new_seq.emplace_back(expair(Order(_ex1), exponent));
1127 return pseries(r, std::move(new_seq));
1130 // No, expand basis into series
1133 if (is_a<numeric>(exponent)) {
1134 numexp = ex_to<numeric>(exponent);
1138 const ex& sym = r.lhs();
1139 // find existing minimal degree
1140 ex eb = basis.expand();
1141 int real_ldegree = 0;
1142 if (eb.info(info_flags::rational_function))
1143 real_ldegree = eb.ldegree(sym-r.rhs());
1144 if (real_ldegree == 0) {
1148 real_ldegree = basis.series(r, orderloop, options).ldegree(sym);
1149 } while (real_ldegree == orderloop);
1152 if (!(real_ldegree*numexp).is_integer())
1153 throw std::runtime_error("pseries::power_const(): trying to assemble a Puiseux series");
1154 ex e = basis.series(r, (order + real_ldegree*(1-numexp)).to_int(), options);
1158 result = ex_to<pseries>(e).power_const(numexp, order);
1159 } catch (pole_error) {
1160 epvector ser { expair(Order(_ex1), order) };
1161 result = pseries(r, std::move(ser));
1168 /** Re-expansion of a pseries object. */
1169 ex pseries::series(const relational & r, int order, unsigned options) const
1171 const ex p = r.rhs();
1172 GINAC_ASSERT(is_a<symbol>(r.lhs()));
1173 const symbol &s = ex_to<symbol>(r.lhs());
1175 if (var.is_equal(s) && point.is_equal(p)) {
1176 if (order > degree(s))
1180 for (auto & it : seq) {
1181 int o = ex_to<numeric>(it.coeff).to_int();
1183 new_seq.emplace_back(expair(Order(_ex1), o));
1186 new_seq.push_back(it);
1188 return pseries(r, std::move(new_seq));
1191 return convert_to_poly().series(r, order, options);
1194 ex integral::series(const relational & r, int order, unsigned options) const
1197 throw std::logic_error("Cannot series expand wrt dummy variable");
1199 // Expanding integrand with r substituted taken in boundaries.
1200 ex fseries = f.series(r, order, options);
1201 epvector fexpansion;
1202 fexpansion.reserve(fseries.nops());
1203 for (size_t i=0; i<fseries.nops(); ++i) {
1204 ex currcoeff = ex_to<pseries>(fseries).coeffop(i);
1205 currcoeff = (currcoeff == Order(_ex1))
1207 : integral(x, a.subs(r), b.subs(r), currcoeff);
1209 fexpansion.emplace_back(
1210 expair(currcoeff, ex_to<pseries>(fseries).exponop(i)));
1213 // Expanding lower boundary
1214 ex result = dynallocate<pseries>(r, std::move(fexpansion));
1215 ex aseries = (a-a.subs(r)).series(r, order, options);
1216 fseries = f.series(x == (a.subs(r)), order, options);
1217 for (size_t i=0; i<fseries.nops(); ++i) {
1218 ex currcoeff = ex_to<pseries>(fseries).coeffop(i);
1219 if (is_order_function(currcoeff))
1221 ex currexpon = ex_to<pseries>(fseries).exponop(i);
1222 int orderforf = order-ex_to<numeric>(currexpon).to_int()-1;
1223 currcoeff = currcoeff.series(r, orderforf);
1224 ex term = ex_to<pseries>(aseries).power_const(ex_to<numeric>(currexpon+1),order);
1225 term = ex_to<pseries>(term).mul_const(ex_to<numeric>(-1/(currexpon+1)));
1226 term = ex_to<pseries>(term).mul_series(ex_to<pseries>(currcoeff));
1227 result = ex_to<pseries>(result).add_series(ex_to<pseries>(term));
1230 // Expanding upper boundary
1231 ex bseries = (b-b.subs(r)).series(r, order, options);
1232 fseries = f.series(x == (b.subs(r)), order, options);
1233 for (size_t i=0; i<fseries.nops(); ++i) {
1234 ex currcoeff = ex_to<pseries>(fseries).coeffop(i);
1235 if (is_order_function(currcoeff))
1237 ex currexpon = ex_to<pseries>(fseries).exponop(i);
1238 int orderforf = order-ex_to<numeric>(currexpon).to_int()-1;
1239 currcoeff = currcoeff.series(r, orderforf);
1240 ex term = ex_to<pseries>(bseries).power_const(ex_to<numeric>(currexpon+1),order);
1241 term = ex_to<pseries>(term).mul_const(ex_to<numeric>(1/(currexpon+1)));
1242 term = ex_to<pseries>(term).mul_series(ex_to<pseries>(currcoeff));
1243 result = ex_to<pseries>(result).add_series(ex_to<pseries>(term));
1250 /** Compute the truncated series expansion of an expression.
1251 * This function returns an expression containing an object of class pseries
1252 * to represent the series. If the series does not terminate within the given
1253 * truncation order, the last term of the series will be an order term.
1255 * @param r expansion relation, lhs holds variable and rhs holds point
1256 * @param order truncation order of series calculations
1257 * @param options of class series_options
1258 * @return an expression holding a pseries object */
1259 ex ex::series(const ex & r, int order, unsigned options) const
1264 if (is_a<relational>(r))
1265 rel_ = ex_to<relational>(r);
1266 else if (is_a<symbol>(r))
1267 rel_ = relational(r,_ex0);
1269 throw (std::logic_error("ex::series(): expansion point has unknown type"));
1271 e = bp->series(rel_, order, options);
1275 GINAC_BIND_UNARCHIVER(pseries);
1277 } // namespace GiNaC