]> www.ginac.de Git - ginac.git/blob - ginac/power.cpp
Merge some cosmetic patches.
[ginac.git] / ginac / power.cpp
1 /** @file power.cpp
2  *
3  *  Implementation of GiNaC's symbolic exponentiation (basis^exponent). */
4
5 /*
6  *  GiNaC Copyright (C) 1999-2015 Johannes Gutenberg University Mainz, Germany
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 2 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
21  */
22
23 #include "power.h"
24 #include "expairseq.h"
25 #include "add.h"
26 #include "mul.h"
27 #include "ncmul.h"
28 #include "numeric.h"
29 #include "constant.h"
30 #include "operators.h"
31 #include "inifcns.h" // for log() in power::derivative()
32 #include "matrix.h"
33 #include "indexed.h"
34 #include "symbol.h"
35 #include "lst.h"
36 #include "archive.h"
37 #include "utils.h"
38 #include "relational.h"
39 #include "compiler.h"
40
41 #include <iostream>
42 #include <limits>
43 #include <stdexcept>
44 #include <vector>
45 #include <algorithm>
46
47 namespace GiNaC {
48
49 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(power, basic,
50   print_func<print_dflt>(&power::do_print_dflt).
51   print_func<print_latex>(&power::do_print_latex).
52   print_func<print_csrc>(&power::do_print_csrc).
53   print_func<print_python>(&power::do_print_python).
54   print_func<print_python_repr>(&power::do_print_python_repr).
55   print_func<print_csrc_cl_N>(&power::do_print_csrc_cl_N))
56
57 //////////
58 // default constructor
59 //////////
60
61 power::power() { }
62
63 //////////
64 // other constructors
65 //////////
66
67 // all inlined
68
69 //////////
70 // archiving
71 //////////
72
73 void power::read_archive(const archive_node &n, lst &sym_lst)
74 {
75         inherited::read_archive(n, sym_lst);
76         n.find_ex("basis", basis, sym_lst);
77         n.find_ex("exponent", exponent, sym_lst);
78 }
79
80 void power::archive(archive_node &n) const
81 {
82         inherited::archive(n);
83         n.add_ex("basis", basis);
84         n.add_ex("exponent", exponent);
85 }
86
87 //////////
88 // functions overriding virtual functions from base classes
89 //////////
90
91 // public
92
93 void power::print_power(const print_context & c, const char *powersymbol, const char *openbrace, const char *closebrace, unsigned level) const
94 {
95         // Ordinary output of powers using '^' or '**'
96         if (precedence() <= level)
97                 c.s << openbrace << '(';
98         basis.print(c, precedence());
99         c.s << powersymbol;
100         c.s << openbrace;
101         exponent.print(c, precedence());
102         c.s << closebrace;
103         if (precedence() <= level)
104                 c.s << ')' << closebrace;
105 }
106
107 void power::do_print_dflt(const print_dflt & c, unsigned level) const
108 {
109         if (exponent.is_equal(_ex1_2)) {
110
111                 // Square roots are printed in a special way
112                 c.s << "sqrt(";
113                 basis.print(c);
114                 c.s << ')';
115
116         } else
117                 print_power(c, "^", "", "", level);
118 }
119
120 void power::do_print_latex(const print_latex & c, unsigned level) const
121 {
122         if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_negative()) {
123
124                 // Powers with negative numeric exponents are printed as fractions
125                 c.s << "\\frac{1}{";
126                 power(basis, -exponent).eval().print(c);
127                 c.s << '}';
128
129         } else if (exponent.is_equal(_ex1_2)) {
130
131                 // Square roots are printed in a special way
132                 c.s << "\\sqrt{";
133                 basis.print(c);
134                 c.s << '}';
135
136         } else
137                 print_power(c, "^", "{", "}", level);
138 }
139
140 static void print_sym_pow(const print_context & c, const symbol &x, int exp)
141 {
142         // Optimal output of integer powers of symbols to aid compiler CSE.
143         // C.f. ISO/IEC 14882:2011, section 1.9 [intro execution], paragraph 15
144         // to learn why such a parenthesation is really necessary.
145         if (exp == 1) {
146                 x.print(c);
147         } else if (exp == 2) {
148                 x.print(c);
149                 c.s << "*";
150                 x.print(c);
151         } else if (exp & 1) {
152                 x.print(c);
153                 c.s << "*";
154                 print_sym_pow(c, x, exp-1);
155         } else {
156                 c.s << "(";
157                 print_sym_pow(c, x, exp >> 1);
158                 c.s << ")*(";
159                 print_sym_pow(c, x, exp >> 1);
160                 c.s << ")";
161         }
162 }
163
164 void power::do_print_csrc_cl_N(const print_csrc_cl_N& c, unsigned level) const
165 {
166         if (exponent.is_equal(_ex_1)) {
167                 c.s << "recip(";
168                 basis.print(c);
169                 c.s << ')';
170                 return;
171         }
172         c.s << "expt(";
173         basis.print(c);
174         c.s << ", ";
175         exponent.print(c);
176         c.s << ')';
177 }
178
179 void power::do_print_csrc(const print_csrc & c, unsigned level) const
180 {
181         // Integer powers of symbols are printed in a special, optimized way
182         if (exponent.info(info_flags::integer) &&
183             (is_a<symbol>(basis) || is_a<constant>(basis))) {
184                 int exp = ex_to<numeric>(exponent).to_int();
185                 if (exp > 0)
186                         c.s << '(';
187                 else {
188                         exp = -exp;
189                         c.s << "1.0/(";
190                 }
191                 print_sym_pow(c, ex_to<symbol>(basis), exp);
192                 c.s << ')';
193
194         // <expr>^-1 is printed as "1.0/<expr>" or with the recip() function of CLN
195         } else if (exponent.is_equal(_ex_1)) {
196                 c.s << "1.0/(";
197                 basis.print(c);
198                 c.s << ')';
199
200         // Otherwise, use the pow() function
201         } else {
202                 c.s << "pow(";
203                 basis.print(c);
204                 c.s << ',';
205                 exponent.print(c);
206                 c.s << ')';
207         }
208 }
209
210 void power::do_print_python(const print_python & c, unsigned level) const
211 {
212         print_power(c, "**", "", "", level);
213 }
214
215 void power::do_print_python_repr(const print_python_repr & c, unsigned level) const
216 {
217         c.s << class_name() << '(';
218         basis.print(c);
219         c.s << ',';
220         exponent.print(c);
221         c.s << ')';
222 }
223
224 bool power::info(unsigned inf) const
225 {
226         switch (inf) {
227                 case info_flags::polynomial:
228                 case info_flags::integer_polynomial:
229                 case info_flags::cinteger_polynomial:
230                 case info_flags::rational_polynomial:
231                 case info_flags::crational_polynomial:
232                         return exponent.info(info_flags::nonnegint) &&
233                                basis.info(inf);
234                 case info_flags::rational_function:
235                         return exponent.info(info_flags::integer) &&
236                                basis.info(inf);
237                 case info_flags::algebraic:
238                         return !exponent.info(info_flags::integer) ||
239                                basis.info(inf);
240                 case info_flags::expanded:
241                         return (flags & status_flags::expanded);
242                 case info_flags::positive:
243                         return basis.info(info_flags::positive) && exponent.info(info_flags::real);
244                 case info_flags::nonnegative:
245                         return (basis.info(info_flags::positive) && exponent.info(info_flags::real)) ||
246                                (basis.info(info_flags::real) && exponent.info(info_flags::integer) && exponent.info(info_flags::even));
247                 case info_flags::has_indices: {
248                         if (flags & status_flags::has_indices)
249                                 return true;
250                         else if (flags & status_flags::has_no_indices)
251                                 return false;
252                         else if (basis.info(info_flags::has_indices)) {
253                                 setflag(status_flags::has_indices);
254                                 clearflag(status_flags::has_no_indices);
255                                 return true;
256                         } else {
257                                 clearflag(status_flags::has_indices);
258                                 setflag(status_flags::has_no_indices);
259                                 return false;
260                         }
261                 }
262         }
263         return inherited::info(inf);
264 }
265
266 size_t power::nops() const
267 {
268         return 2;
269 }
270
271 ex power::op(size_t i) const
272 {
273         GINAC_ASSERT(i<2);
274
275         return i==0 ? basis : exponent;
276 }
277
278 ex power::map(map_function & f) const
279 {
280         const ex &mapped_basis = f(basis);
281         const ex &mapped_exponent = f(exponent);
282
283         if (!are_ex_trivially_equal(basis, mapped_basis)
284          || !are_ex_trivially_equal(exponent, mapped_exponent))
285                 return dynallocate<power>(mapped_basis, mapped_exponent);
286         else
287                 return *this;
288 }
289
290 bool power::is_polynomial(const ex & var) const
291 {
292         if (basis.is_polynomial(var)) {
293                 if (basis.has(var))
294                         // basis is non-constant polynomial in var
295                         return exponent.info(info_flags::nonnegint);
296                 else
297                         // basis is constant in var
298                         return !exponent.has(var);
299         }
300         // basis is a non-polynomial function of var
301         return false;
302 }
303
304 int power::degree(const ex & s) const
305 {
306         if (is_equal(ex_to<basic>(s)))
307                 return 1;
308         else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
309                 if (basis.is_equal(s))
310                         return ex_to<numeric>(exponent).to_int();
311                 else
312                         return basis.degree(s) * ex_to<numeric>(exponent).to_int();
313         } else if (basis.has(s))
314                 throw(std::runtime_error("power::degree(): undefined degree because of non-integer exponent"));
315         else
316                 return 0;
317 }
318
319 int power::ldegree(const ex & s) const 
320 {
321         if (is_equal(ex_to<basic>(s)))
322                 return 1;
323         else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
324                 if (basis.is_equal(s))
325                         return ex_to<numeric>(exponent).to_int();
326                 else
327                         return basis.ldegree(s) * ex_to<numeric>(exponent).to_int();
328         } else if (basis.has(s))
329                 throw(std::runtime_error("power::ldegree(): undefined degree because of non-integer exponent"));
330         else
331                 return 0;
332 }
333
334 ex power::coeff(const ex & s, int n) const
335 {
336         if (is_equal(ex_to<basic>(s)))
337                 return n==1 ? _ex1 : _ex0;
338         else if (!basis.is_equal(s)) {
339                 // basis not equal to s
340                 if (n == 0)
341                         return *this;
342                 else
343                         return _ex0;
344         } else {
345                 // basis equal to s
346                 if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
347                         // integer exponent
348                         int int_exp = ex_to<numeric>(exponent).to_int();
349                         if (n == int_exp)
350                                 return _ex1;
351                         else
352                                 return _ex0;
353                 } else {
354                         // non-integer exponents are treated as zero
355                         if (n == 0)
356                                 return *this;
357                         else
358                                 return _ex0;
359                 }
360         }
361 }
362
363 /** Perform automatic term rewriting rules in this class.  In the following
364  *  x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
365  *  stand for such expressions that contain a plain number.
366  *  - ^(x,0) -> 1  (also handles ^(0,0))
367  *  - ^(x,1) -> x
368  *  - ^(0,c) -> 0 or exception  (depending on the real part of c)
369  *  - ^(1,x) -> 1
370  *  - ^(c1,c2) -> *(c1^n,c1^(c2-n))  (so that 0<(c2-n)<1, try to evaluate roots, possibly in numerator and denominator of c1)
371  *  - ^(^(x,c1),c2) -> ^(x,c1*c2)  if x is positive and c1 is real.
372  *  - ^(^(x,c1),c2) -> ^(x,c1*c2)  (c2 integer or -1 < c1 <= 1 or (c1=-1 and c2>0), case c1=1 should not happen, see below!)
373  *  - ^(*(x,y,z),c) -> *(x^c,y^c,z^c)  (if c integer)
374  *  - ^(*(x,c1),c2) -> ^(x,c2)*c1^c2  (c1>0)
375  *  - ^(*(x,c1),c2) -> ^(-x,c2)*c1^c2  (c1<0)
376  */
377 ex power::eval() const
378 {
379         if (flags & status_flags::evaluated)
380                 return *this;
381
382         const numeric *num_basis = nullptr;
383         const numeric *num_exponent = nullptr;
384
385         if (is_exactly_a<numeric>(basis)) {
386                 num_basis = &ex_to<numeric>(basis);
387         }
388         if (is_exactly_a<numeric>(exponent)) {
389                 num_exponent = &ex_to<numeric>(exponent);
390         }
391         
392         // ^(x,0) -> 1  (0^0 also handled here)
393         if (exponent.is_zero()) {
394                 if (basis.is_zero())
395                         throw (std::domain_error("power::eval(): pow(0,0) is undefined"));
396                 else
397                         return _ex1;
398         }
399         
400         // ^(x,1) -> x
401         if (exponent.is_equal(_ex1))
402                 return basis;
403
404         // ^(0,c1) -> 0 or exception  (depending on real value of c1)
405         if (basis.is_zero() && num_exponent) {
406                 if ((num_exponent->real()).is_zero())
407                         throw (std::domain_error("power::eval(): pow(0,I) is undefined"));
408                 else if ((num_exponent->real()).is_negative())
409                         throw (pole_error("power::eval(): division by zero",1));
410                 else
411                         return _ex0;
412         }
413
414         // ^(1,x) -> 1
415         if (basis.is_equal(_ex1))
416                 return _ex1;
417
418         // power of a function calculated by separate rules defined for this function
419         if (is_exactly_a<function>(basis))
420                 return ex_to<function>(basis).power(exponent);
421
422         // Turn (x^c)^d into x^(c*d) in the case that x is positive and c is real.
423         if (is_exactly_a<power>(basis) && basis.op(0).info(info_flags::positive) && basis.op(1).info(info_flags::real))
424                 return dynallocate<power>(basis.op(0), basis.op(1) * exponent);
425
426         if ( num_exponent ) {
427
428                 // ^(c1,c2) -> c1^c2  (c1, c2 numeric(),
429                 // except if c1,c2 are rational, but c1^c2 is not)
430                 if ( num_basis ) {
431                         const bool basis_is_crational = num_basis->is_crational();
432                         const bool exponent_is_crational = num_exponent->is_crational();
433                         if (!basis_is_crational || !exponent_is_crational) {
434                                 // return a plain float
435                                 return dynallocate<numeric>(num_basis->power(*num_exponent));
436                         }
437
438                         const numeric res = num_basis->power(*num_exponent);
439                         if (res.is_crational()) {
440                                 return res;
441                         }
442                         GINAC_ASSERT(!num_exponent->is_integer());  // has been handled by now
443
444                         // ^(c1,n/m) -> *(c1^q,c1^(n/m-q)), 0<(n/m-q)<1, q integer
445                         if (basis_is_crational && exponent_is_crational
446                             && num_exponent->is_real()
447                             && !num_exponent->is_integer()) {
448                                 const numeric n = num_exponent->numer();
449                                 const numeric m = num_exponent->denom();
450                                 numeric r;
451                                 numeric q = iquo(n, m, r);
452                                 if (r.is_negative()) {
453                                         r += m;
454                                         --q;
455                                 }
456                                 if (q.is_zero()) {  // the exponent was in the allowed range 0<(n/m)<1
457                                         if (num_basis->is_rational() && !num_basis->is_integer()) {
458                                                 // try it for numerator and denominator separately, in order to
459                                                 // partially simplify things like (5/8)^(1/3) -> 1/2*5^(1/3)
460                                                 const numeric bnum = num_basis->numer();
461                                                 const numeric bden = num_basis->denom();
462                                                 const numeric res_bnum = bnum.power(*num_exponent);
463                                                 const numeric res_bden = bden.power(*num_exponent);
464                                                 if (res_bnum.is_integer())
465                                                         return dynallocate<mul>(dynallocate<power>(bden,-*num_exponent),res_bnum).setflag(status_flags::evaluated);
466                                                 if (res_bden.is_integer())
467                                                         return dynallocate<mul>(dynallocate<power>(bnum,*num_exponent),res_bden.inverse()).setflag(status_flags::evaluated);
468                                         }
469                                         return this->hold();
470                                 } else {
471                                         // assemble resulting product, but allowing for a re-evaluation,
472                                         // because otherwise we'll end up with something like
473                                         //    (7/8)^(4/3)  ->  7/8*(1/2*7^(1/3))
474                                         // instead of 7/16*7^(1/3).
475                                         return pow(basis, r.div(m)) * pow(basis, q);
476                                 }
477                         }
478                 }
479         
480                 // ^(^(x,c1),c2) -> ^(x,c1*c2)
481                 // (c1, c2 numeric(), c2 integer or -1 < c1 <= 1 or (c1=-1 and c2>0),
482                 // case c1==1 should not happen, see below!)
483                 if (is_exactly_a<power>(basis)) {
484                         const power & sub_power = ex_to<power>(basis);
485                         const ex & sub_basis = sub_power.basis;
486                         const ex & sub_exponent = sub_power.exponent;
487                         if (is_exactly_a<numeric>(sub_exponent)) {
488                                 const numeric & num_sub_exponent = ex_to<numeric>(sub_exponent);
489                                 GINAC_ASSERT(num_sub_exponent!=numeric(1));
490                                 if (num_exponent->is_integer() || (abs(num_sub_exponent) - (*_num1_p)).is_negative() ||
491                                     (num_sub_exponent == *_num_1_p && num_exponent->is_positive())) {
492                                         return dynallocate<power>(sub_basis, num_sub_exponent.mul(*num_exponent));
493                                 }
494                         }
495                 }
496         
497                 // ^(*(x,y,z),c1) -> *(x^c1,y^c1,z^c1) (c1 integer)
498                 if (num_exponent->is_integer() && is_exactly_a<mul>(basis)) {
499                         return expand_mul(ex_to<mul>(basis), *num_exponent, false);
500                 }
501
502                 // (2*x + 6*y)^(-4) -> 1/16*(x + 3*y)^(-4)
503                 if (num_exponent->is_integer() && is_exactly_a<add>(basis)) {
504                         numeric icont = basis.integer_content();
505                         const numeric lead_coeff = 
506                                 ex_to<numeric>(ex_to<add>(basis).seq.begin()->coeff).div(icont);
507
508                         const bool canonicalizable = lead_coeff.is_integer();
509                         const bool unit_normal = lead_coeff.is_pos_integer();
510                         if (canonicalizable && (! unit_normal))
511                                 icont = icont.mul(*_num_1_p);
512                         
513                         if (canonicalizable && (icont != *_num1_p)) {
514                                 const add& addref = ex_to<add>(basis);
515                                 add & addp = dynallocate<add>(addref);
516                                 addp.clearflag(status_flags::hash_calculated);
517                                 addp.overall_coeff = ex_to<numeric>(addp.overall_coeff).div_dyn(icont);
518                                 for (auto & i : addp.seq)
519                                         i.coeff = ex_to<numeric>(i.coeff).div_dyn(icont);
520
521                                 const numeric c = icont.power(*num_exponent);
522                                 if (likely(c != *_num1_p))
523                                         return dynallocate<mul>(dynallocate<power>(addp, *num_exponent), c);
524                                 else
525                                         return dynallocate<power>(addp, *num_exponent);
526                         }
527                 }
528
529                 // ^(*(...,x;c1),c2) -> *(^(*(...,x;1),c2),c1^c2)  (c1, c2 numeric(), c1>0)
530                 // ^(*(...,x;c1),c2) -> *(^(*(...,x;-1),c2),(-c1)^c2)  (c1, c2 numeric(), c1<0)
531                 if (is_exactly_a<mul>(basis)) {
532                         GINAC_ASSERT(!num_exponent->is_integer()); // should have been handled above
533                         const mul & mulref = ex_to<mul>(basis);
534                         if (!mulref.overall_coeff.is_equal(_ex1)) {
535                                 const numeric & num_coeff = ex_to<numeric>(mulref.overall_coeff);
536                                 if (num_coeff.is_real()) {
537                                         if (num_coeff.is_positive()) {
538                                                 mul & mulp = dynallocate<mul>(mulref);
539                                                 mulp.overall_coeff = _ex1;
540                                                 mulp.clearflag(status_flags::evaluated | status_flags::hash_calculated);
541                                                 return dynallocate<mul>(dynallocate<power>(mulp, exponent),
542                                                                         dynallocate<power>(num_coeff, *num_exponent));
543                                         } else {
544                                                 GINAC_ASSERT(num_coeff.compare(*_num0_p)<0);
545                                                 if (!num_coeff.is_equal(*_num_1_p)) {
546                                                         mul & mulp = dynallocate<mul>(mulref);
547                                                         mulp.overall_coeff = _ex_1;
548                                                         mulp.clearflag(status_flags::evaluated | status_flags::hash_calculated);
549                                                         return dynallocate<mul>(dynallocate<power>(mulp, exponent),
550                                                                                 dynallocate<power>(abs(num_coeff), *num_exponent));
551                                                 }
552                                         }
553                                 }
554                         }
555                 }
556
557                 // ^(nc,c1) -> ncmul(nc,nc,...) (c1 positive integer, unless nc is a matrix)
558                 if (num_exponent->is_pos_integer() &&
559                     basis.return_type() != return_types::commutative &&
560                     !is_a<matrix>(basis)) {
561                         return ncmul(exvector(num_exponent->to_int(), basis));
562                 }
563         }
564
565         return this->hold();
566 }
567
568 ex power::evalf(int level) const
569 {
570         ex ebasis;
571         ex eexponent;
572         
573         if (level==1) {
574                 ebasis = basis;
575                 eexponent = exponent;
576         } else if (level == -max_recursion_level) {
577                 throw(std::runtime_error("max recursion level reached"));
578         } else {
579                 ebasis = basis.evalf(level-1);
580                 if (!is_exactly_a<numeric>(exponent))
581                         eexponent = exponent.evalf(level-1);
582                 else
583                         eexponent = exponent;
584         }
585
586         return dynallocate<power>(ebasis, eexponent);
587 }
588
589 ex power::evalm() const
590 {
591         const ex ebasis = basis.evalm();
592         const ex eexponent = exponent.evalm();
593         if (is_a<matrix>(ebasis)) {
594                 if (is_exactly_a<numeric>(eexponent)) {
595                         return dynallocate<matrix>(ex_to<matrix>(ebasis).pow(eexponent));
596                 }
597         }
598         return dynallocate<power>(ebasis, eexponent);
599 }
600
601 bool power::has(const ex & other, unsigned options) const
602 {
603         if (!(options & has_options::algebraic))
604                 return basic::has(other, options);
605         if (!is_a<power>(other))
606                 return basic::has(other, options);
607         if (!exponent.info(info_flags::integer) ||
608             !other.op(1).info(info_flags::integer))
609                 return basic::has(other, options);
610         if (exponent.info(info_flags::posint) &&
611             other.op(1).info(info_flags::posint) &&
612             ex_to<numeric>(exponent) > ex_to<numeric>(other.op(1)) &&
613             basis.match(other.op(0)))
614                 return true;
615         if (exponent.info(info_flags::negint) &&
616             other.op(1).info(info_flags::negint) &&
617             ex_to<numeric>(exponent) < ex_to<numeric>(other.op(1)) &&
618             basis.match(other.op(0)))
619                 return true;
620         return basic::has(other, options);
621 }
622
623 // from mul.cpp
624 extern bool tryfactsubs(const ex &, const ex &, int &, exmap&);
625
626 ex power::subs(const exmap & m, unsigned options) const
627 {       
628         const ex &subsed_basis = basis.subs(m, options);
629         const ex &subsed_exponent = exponent.subs(m, options);
630
631         if (!are_ex_trivially_equal(basis, subsed_basis)
632          || !are_ex_trivially_equal(exponent, subsed_exponent)) 
633                 return power(subsed_basis, subsed_exponent).subs_one_level(m, options);
634
635         if (!(options & subs_options::algebraic))
636                 return subs_one_level(m, options);
637
638         for (auto & it : m) {
639                 int nummatches = std::numeric_limits<int>::max();
640                 exmap repls;
641                 if (tryfactsubs(*this, it.first, nummatches, repls)) {
642                         ex anum = it.second.subs(repls, subs_options::no_pattern);
643                         ex aden = it.first.subs(repls, subs_options::no_pattern);
644                         ex result = (*this) * pow(anum/aden, nummatches);
645                         return (ex_to<basic>(result)).subs_one_level(m, options);
646                 }
647         }
648
649         return subs_one_level(m, options);
650 }
651
652 ex power::eval_ncmul(const exvector & v) const
653 {
654         return inherited::eval_ncmul(v);
655 }
656
657 ex power::conjugate() const
658 {
659         // conjugate(pow(x,y))==pow(conjugate(x),conjugate(y)) unless on the
660         // branch cut which runs along the negative real axis.
661         if (basis.info(info_flags::positive)) {
662                 ex newexponent = exponent.conjugate();
663                 if (are_ex_trivially_equal(exponent, newexponent)) {
664                         return *this;
665                 }
666                 return dynallocate<power>(basis, newexponent);
667         }
668         if (exponent.info(info_flags::integer)) {
669                 ex newbasis = basis.conjugate();
670                 if (are_ex_trivially_equal(basis, newbasis)) {
671                         return *this;
672                 }
673                 return dynallocate<power>(newbasis, exponent);
674         }
675         return conjugate_function(*this).hold();
676 }
677
678 ex power::real_part() const
679 {
680         // basis == a+I*b, exponent == c+I*d
681         const ex a = basis.real_part();
682         const ex c = exponent.real_part();
683         if (basis.is_equal(a) && exponent.is_equal(c)) {
684                 // Re(a^c)
685                 return *this;
686         }
687
688         const ex b = basis.imag_part();
689         if (exponent.info(info_flags::integer)) {
690                 // Re((a+I*b)^c)  w/  c âˆˆ â„¤
691                 long N = ex_to<numeric>(c).to_long();
692                 // Use real terms in Binomial expansion to construct
693                 // Re(expand(pow(a+I*b, N))).
694                 long NN = N > 0 ? N : -N;
695                 ex numer = N > 0 ? _ex1 : pow(pow(a,2) + pow(b,2), NN);
696                 ex result = 0;
697                 for (long n = 0; n <= NN; n += 2) {
698                         ex term = binomial(NN, n) * pow(a, NN-n) * pow(b, n) / numer;
699                         if (n % 4 == 0) {
700                                 result += term;  // sign: I^n w/ n == 4*m
701                         } else {
702                                 result -= term;  // sign: I^n w/ n == 4*m+2
703                         }
704                 }
705                 return result;
706         }
707
708         // Re((a+I*b)^(c+I*d))
709         const ex d = exponent.imag_part();
710         return pow(abs(basis),c) * exp(-d*atan2(b,a)) * cos(c*atan2(b,a)+d*log(abs(basis)));
711 }
712
713 ex power::imag_part() const
714 {
715         // basis == a+I*b, exponent == c+I*d
716         const ex a = basis.real_part();
717         const ex c = exponent.real_part();
718         if (basis.is_equal(a) && exponent.is_equal(c)) {
719                 // Im(a^c)
720                 return 0;
721         }
722
723         const ex b = basis.imag_part();
724         if (exponent.info(info_flags::integer)) {
725                 // Im((a+I*b)^c)  w/  c âˆˆ â„¤
726                 long N = ex_to<numeric>(c).to_long();
727                 // Use imaginary terms in Binomial expansion to construct
728                 // Im(expand(pow(a+I*b, N))).
729                 long p = N > 0 ? 1 : 3;  // modulus for positive sign
730                 long NN = N > 0 ? N : -N;
731                 ex numer = N > 0 ? _ex1 : pow(pow(a,2) + pow(b,2), NN);
732                 ex result = 0;
733                 for (long n = 1; n <= NN; n += 2) {
734                         ex term = binomial(NN, n) * pow(a, NN-n) * pow(b, n) / numer;
735                         if (n % 4 == p) {
736                                 result += term;  // sign: I^n w/ n == 4*m+p
737                         } else {
738                                 result -= term;  // sign: I^n w/ n == 4*m+2+p
739                         }
740                 }
741                 return result;
742         }
743
744         // Im((a+I*b)^(c+I*d))
745         const ex d = exponent.imag_part();
746         return pow(abs(basis),c) * exp(-d*atan2(b,a)) * sin(c*atan2(b,a)+d*log(abs(basis)));
747 }
748
749 // protected
750
751 /** Implementation of ex::diff() for a power.
752  *  @see ex::diff */
753 ex power::derivative(const symbol & s) const
754 {
755         if (is_a<numeric>(exponent)) {
756                 // D(b^r) = r * b^(r-1) * D(b) (faster than the formula below)
757                 const epvector newseq = {expair(basis, exponent - _ex1), expair(basis.diff(s), _ex1)};
758                 return dynallocate<mul>(std::move(newseq), exponent);
759         } else {
760                 // D(b^e) = b^e * (D(e)*ln(b) + e*D(b)/b)
761                 return *this * (exponent.diff(s)*log(basis) + exponent*basis.diff(s)*pow(basis, _ex_1));
762         }
763 }
764
765 int power::compare_same_type(const basic & other) const
766 {
767         GINAC_ASSERT(is_exactly_a<power>(other));
768         const power &o = static_cast<const power &>(other);
769
770         int cmpval = basis.compare(o.basis);
771         if (cmpval)
772                 return cmpval;
773         else
774                 return exponent.compare(o.exponent);
775 }
776
777 unsigned power::return_type() const
778 {
779         return basis.return_type();
780 }
781
782 return_type_t power::return_type_tinfo() const
783 {
784         return basis.return_type_tinfo();
785 }
786
787 ex power::expand(unsigned options) const
788 {
789         if (is_a<symbol>(basis) && exponent.info(info_flags::integer)) {
790                 // A special case worth optimizing.
791                 setflag(status_flags::expanded);
792                 return *this;
793         }
794
795         // (x*p)^c -> x^c * p^c, if p>0
796         // makes sense before expanding the basis
797         if (is_exactly_a<mul>(basis) && !basis.info(info_flags::indefinite)) {
798                 const mul &m = ex_to<mul>(basis);
799                 exvector prodseq;
800                 epvector powseq;
801                 prodseq.reserve(m.seq.size() + 1);
802                 powseq.reserve(m.seq.size() + 1);
803                 bool possign = true;
804
805                 // search for positive/negative factors
806                 for (auto & cit : m.seq) {
807                         ex e=m.recombine_pair_to_ex(cit);
808                         if (e.info(info_flags::positive))
809                                 prodseq.push_back(pow(e, exponent).expand(options));
810                         else if (e.info(info_flags::negative)) {
811                                 prodseq.push_back(pow(-e, exponent).expand(options));
812                                 possign = !possign;
813                         } else
814                                 powseq.push_back(cit);
815                 }
816
817                 // take care on the numeric coefficient
818                 ex coeff=(possign? _ex1 : _ex_1);
819                 if (m.overall_coeff.info(info_flags::positive) && m.overall_coeff != _ex1)
820                         prodseq.push_back(pow(m.overall_coeff, exponent));
821                 else if (m.overall_coeff.info(info_flags::negative) && m.overall_coeff != _ex_1)
822                         prodseq.push_back(pow(-m.overall_coeff, exponent));
823                 else
824                         coeff *= m.overall_coeff;
825
826                 // If positive/negative factors are found, then extract them.
827                 // In either case we set a flag to avoid the second run on a part
828                 // which does not have positive/negative terms.
829                 if (prodseq.size() > 0) {
830                         ex newbasis = dynallocate<mul>(std::move(powseq), coeff);
831                         ex_to<basic>(newbasis).setflag(status_flags::purely_indefinite);
832                         return dynallocate<mul>(std::move(prodseq)) * pow(newbasis, exponent);
833                 } else
834                         ex_to<basic>(basis).setflag(status_flags::purely_indefinite);
835         }
836
837         const ex expanded_basis = basis.expand(options);
838         const ex expanded_exponent = exponent.expand(options);
839         
840         // x^(a+b) -> x^a * x^b
841         if (is_exactly_a<add>(expanded_exponent)) {
842                 const add &a = ex_to<add>(expanded_exponent);
843                 exvector distrseq;
844                 distrseq.reserve(a.seq.size() + 1);
845                 for (auto & cit : a.seq) {
846                         distrseq.push_back(pow(expanded_basis, a.recombine_pair_to_ex(cit)));
847                 }
848                 
849                 // Make sure that e.g. (x+y)^(2+a) expands the (x+y)^2 factor
850                 if (ex_to<numeric>(a.overall_coeff).is_integer()) {
851                         const numeric &num_exponent = ex_to<numeric>(a.overall_coeff);
852                         long int_exponent = num_exponent.to_int();
853                         if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
854                                 distrseq.push_back(expand_add(ex_to<add>(expanded_basis), int_exponent, options));
855                         else
856                                 distrseq.push_back(pow(expanded_basis, a.overall_coeff));
857                 } else
858                         distrseq.push_back(pow(expanded_basis, a.overall_coeff));
859                 
860                 // Make sure that e.g. (x+y)^(1+a) -> x*(x+y)^a + y*(x+y)^a
861                 ex r = dynallocate<mul>(distrseq);
862                 return r.expand(options);
863         }
864         
865         if (!is_exactly_a<numeric>(expanded_exponent) ||
866                 !ex_to<numeric>(expanded_exponent).is_integer()) {
867                 if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent)) {
868                         return this->hold();
869                 } else {
870                         return dynallocate<power>(expanded_basis, expanded_exponent).setflag(options == 0 ? status_flags::expanded : 0);
871                 }
872         }
873         
874         // integer numeric exponent
875         const numeric & num_exponent = ex_to<numeric>(expanded_exponent);
876         long int_exponent = num_exponent.to_long();
877         
878         // (x+y)^n, n>0
879         if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
880                 return expand_add(ex_to<add>(expanded_basis), int_exponent, options);
881         
882         // (x*y)^n -> x^n * y^n
883         if (is_exactly_a<mul>(expanded_basis))
884                 return expand_mul(ex_to<mul>(expanded_basis), num_exponent, options, true);
885         
886         // cannot expand further
887         if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent))
888                 return this->hold();
889         else
890                 return dynallocate<power>(expanded_basis, expanded_exponent).setflag(options == 0 ? status_flags::expanded : 0);
891 }
892
893 //////////
894 // new virtual functions which can be overridden by derived classes
895 //////////
896
897 // none
898
899 //////////
900 // non-virtual functions in this class
901 //////////
902
903 namespace {  // anonymous namespace for power::expand_add() helpers
904
905 /** Helper class to generate all bounded combinatorial partitions of an integer
906  *  n with exactly m parts (including zero parts) in non-decreasing order.
907  */
908 class partition_generator {
909 private:
910         // Partitions n into m parts, not including zero parts.
911         // (Cf. OEIS sequence A008284; implementation adapted from Jörg Arndt's
912         // FXT library)
913         struct mpartition2
914         {
915                 // partition: x[1] + x[2] + ... + x[m] = n and sentinel x[0] == 0
916                 std::vector<int> x;
917                 int n;   // n>0
918                 int m;   // 0<m<=n
919                 mpartition2(unsigned n_, unsigned m_)
920                   : x(m_+1), n(n_), m(m_)
921                 {
922                         for (int k=1; k<m; ++k)
923                                 x[k] = 1;
924                         x[m] = n - m + 1;
925                 }
926                 bool next_partition()
927                 {
928                         int u = x[m];  // last element
929                         int k = m;
930                         int s = u;
931                         while (--k) {
932                                 s += x[k];
933                                 if (x[k] + 2 <= u)
934                                         break;
935                         }
936                         if (k==0)
937                                 return false;  // current is last
938                         int f = x[k] + 1;
939                         while (k < m) {
940                                 x[k] = f;
941                                 s -= f;
942                                 ++k;
943                         }
944                         x[m] = s;
945                         return true;
946                 }
947         } mpgen;
948         int m;  // number of parts 0<m<=n
949         mutable std::vector<int> partition;  // current partition
950 public:
951         partition_generator(unsigned n_, unsigned m_)
952           : mpgen(n_, 1), m(m_), partition(m_)
953         { }
954         // returns current partition in non-decreasing order, padded with zeros
955         const std::vector<int>& current() const
956         {
957                 for (int i = 0; i < m - mpgen.m; ++i)
958                         partition[i] = 0;  // pad with zeros
959
960                 for (int i = m - mpgen.m; i < m; ++i)
961                         partition[i] = mpgen.x[i - m + mpgen.m + 1];
962
963                 return partition;
964         }
965         bool next()
966         {
967                 if (!mpgen.next_partition()) {
968                         if (mpgen.m == m || mpgen.m == mpgen.n)
969                                 return false;  // current is last
970                         // increment number of parts
971                         mpgen = mpartition2(mpgen.n, mpgen.m + 1);
972                 }
973                 return true;
974         }
975 };
976
977 /** Helper class to generate all compositions of a partition of an integer n,
978  *  starting with the compositions which has non-decreasing order.
979  */
980 class composition_generator {
981 private:
982         // Generates all distinct permutations of a multiset.
983         // (Based on Aaron Williams' algorithm 1 from "Loopless Generation of
984         // Multiset Permutations using a Constant Number of Variables by Prefix
985         // Shifts." <http://webhome.csc.uvic.ca/~haron/CoolMulti.pdf>)
986         struct coolmulti {
987                 // element of singly linked list
988                 struct element {
989                         int value;
990                         element* next;
991                         element(int val, element* n)
992                           : value(val), next(n) {}
993                         ~element()
994                         {   // recurses down to the end of the singly linked list
995                                 delete next;
996                         }
997                 };
998                 element *head, *i, *after_i;
999                 // NB: Partition must be sorted in non-decreasing order.
1000                 explicit coolmulti(const std::vector<int>& partition)
1001                   : head(nullptr), i(nullptr), after_i(nullptr)
1002                 {
1003                         for (unsigned n = 0; n < partition.size(); ++n) {
1004                                 head = new element(partition[n], head);
1005                                 if (n <= 1)
1006                                         i = head;
1007                         }
1008                         after_i = i->next;
1009                 }
1010                 ~coolmulti()
1011                 {   // deletes singly linked list
1012                         delete head;
1013                 }
1014                 void next_permutation()
1015                 {
1016                         element *before_k;
1017                         if (after_i->next != nullptr && i->value >= after_i->next->value)
1018                                 before_k = after_i;
1019                         else
1020                                 before_k = i;
1021                         element *k = before_k->next;
1022                         before_k->next = k->next;
1023                         k->next = head;
1024                         if (k->value < head->value)
1025                                 i = k;
1026                         after_i = i->next;
1027                         head = k;
1028                 }
1029                 bool finished() const
1030                 {
1031                         return after_i->next == nullptr && after_i->value >= head->value;
1032                 }
1033         } cmgen;
1034         bool atend;  // needed for simplifying iteration over permutations
1035         bool trivial;  // likewise, true if all elements are equal
1036         mutable std::vector<int> composition;  // current compositions
1037 public:
1038         explicit composition_generator(const std::vector<int>& partition)
1039           : cmgen(partition), atend(false), trivial(true), composition(partition.size())
1040         {
1041                 for (unsigned i=1; i<partition.size(); ++i)
1042                         trivial = trivial && (partition[0] == partition[i]);
1043         }
1044         const std::vector<int>& current() const
1045         {
1046                 coolmulti::element* it = cmgen.head;
1047                 size_t i = 0;
1048                 while (it != nullptr) {
1049                         composition[i] = it->value;
1050                         it = it->next;
1051                         ++i;
1052                 }
1053                 return composition;
1054         }
1055         bool next()
1056         {
1057                 // This ugly contortion is needed because the original coolmulti
1058                 // algorithm requires code duplication of the payload procedure,
1059                 // one before the loop and one inside it.
1060                 if (trivial || atend)
1061                         return false;
1062                 cmgen.next_permutation();
1063                 atend = cmgen.finished();
1064                 return true;
1065         }
1066 };
1067
1068 /** Helper function to compute the multinomial coefficient n!/(p1!*p2!*...*pk!)
1069  *  where n = p1+p2+...+pk, i.e. p is a partition of n.
1070  */
1071 const numeric
1072 multinomial_coefficient(const std::vector<int> & p)
1073 {
1074         numeric n = 0, d = 1;
1075         for (auto & it : p) {
1076                 n += numeric(it);
1077                 d *= factorial(numeric(it));
1078         }
1079         return factorial(numeric(n)) / d;
1080 }
1081
1082 }  // anonymous namespace
1083
1084
1085 /** expand a^n where a is an add and n is a positive integer.
1086  *  @see power::expand */
1087 ex power::expand_add(const add & a, long n, unsigned options)
1088 {
1089         // The special case power(+(x,...y;x),2) can be optimized better.
1090         if (n==2)
1091                 return expand_add_2(a, options);
1092
1093         // method:
1094         //
1095         // Consider base as the sum of all symbolic terms and the overall numeric
1096         // coefficient and apply the binomial theorem:
1097         // S = power(+(x,...,z;c),n)
1098         //   = power(+(+(x,...,z;0);c),n)
1099         //   = sum(binomial(n,k)*power(+(x,...,z;0),k)*c^(n-k), k=1..n) + c^n
1100         // Then, apply the multinomial theorem to expand all power(+(x,...,z;0),k):
1101         // The multinomial theorem is computed by an outer loop over all
1102         // partitions of the exponent and an inner loop over all compositions of
1103         // that partition. This method makes the expansion a combinatorial
1104         // problem and allows us to directly construct the expanded sum and also
1105         // to re-use the multinomial coefficients (since they depend only on the
1106         // partition, not on the composition).
1107         // 
1108         // multinomial power(+(x,y,z;0),3) example:
1109         // partition : compositions                : multinomial coefficient
1110         // [0,0,3]   : [3,0,0],[0,3,0],[0,0,3]     : 3!/(3!*0!*0!) = 1
1111         // [0,1,2]   : [2,1,0],[1,2,0],[2,0,1],... : 3!/(2!*1!*0!) = 3
1112         // [1,1,1]   : [1,1,1]                     : 3!/(1!*1!*1!) = 6
1113         //  =>  (x + y + z)^3 =
1114         //        x^3 + y^3 + z^3
1115         //      + 3*x^2*y + 3*x*y^2 + 3*y^2*z + 3*y*z^2 + 3*x*z^2 + 3*x^2*z
1116         //      + 6*x*y*z
1117         //
1118         // multinomial power(+(x,y,z;0),4) example:
1119         // partition : compositions                : multinomial coefficient
1120         // [0,0,4]   : [4,0,0],[0,4,0],[0,0,4]     : 4!/(4!*0!*0!) = 1
1121         // [0,1,3]   : [3,1,0],[1,3,0],[3,0,1],... : 4!/(3!*1!*0!) = 4
1122         // [0,2,2]   : [2,2,0],[2,0,2],[0,2,2]     : 4!/(2!*2!*0!) = 6
1123         // [1,1,2]   : [2,1,1],[1,2,1],[1,1,2]     : 4!/(2!*1!*1!) = 12
1124         // (no [1,1,1,1] partition since it has too many parts)
1125         //  =>  (x + y + z)^4 =
1126         //        x^4 + y^4 + z^4
1127         //      + 4*x^3*y + 4*x*y^3 + 4*y^3*z + 4*y*z^3 + 4*x*z^3 + 4*x^3*z
1128         //      + 6*x^2*y^2 + 6*y^2*z^2 + 6*x^2*z^2
1129         //      + 12*x^2*y*z + 12*x*y^2*z + 12*x*y*z^2
1130         //
1131         // Summary:
1132         // r = 0
1133         // for k from 0 to n:
1134         //     f = c^(n-k)*binomial(n,k)
1135         //     for p in all partitions of n with m parts (including zero parts):
1136         //         h = f * multinomial coefficient of p
1137         //         for c in all compositions of p:
1138         //             t = 1
1139         //             for e in all elements of c:
1140         //                 t = t * a[e]^e
1141         //             r = r + h*t
1142         // return r
1143
1144         epvector result;
1145         // The number of terms will be the number of combinatorial compositions,
1146         // i.e. the number of unordered arrangements of m nonnegative integers
1147         // which sum up to n.  It is frequently written as C_n(m) and directly
1148         // related with binomial coefficients: binomial(n+m-1,m-1).
1149         size_t result_size = binomial(numeric(n+a.nops()-1), numeric(a.nops()-1)).to_long();
1150         if (!a.overall_coeff.is_zero()) {
1151                 // the result's overall_coeff is one of the terms
1152                 --result_size;
1153         }
1154         result.reserve(result_size);
1155
1156         // Iterate over all terms in binomial expansion of
1157         // S = power(+(x,...,z;c),n)
1158         //   = sum(binomial(n,k)*power(+(x,...,z;0),k)*c^(n-k), k=1..n) + c^n
1159         for (int k = 1; k <= n; ++k) {
1160                 numeric binomial_coefficient;  // binomial(n,k)*c^(n-k)
1161                 if (a.overall_coeff.is_zero()) {
1162                         // degenerate case with zero overall_coeff:
1163                         // apply multinomial theorem directly to power(+(x,...z;0),n)
1164                         binomial_coefficient = 1;
1165                         if (k < n) {
1166                                 continue;
1167                         }
1168                 } else {
1169                         binomial_coefficient = binomial(numeric(n), numeric(k)) * pow(ex_to<numeric>(a.overall_coeff), numeric(n-k));
1170                 }
1171
1172                 // Multinomial expansion of power(+(x,...,z;0),k)*c^(n-k):
1173                 // Iterate over all partitions of k with exactly as many parts as
1174                 // there are symbolic terms in the basis (including zero parts).
1175                 partition_generator partitions(k, a.seq.size());
1176                 do {
1177                         const std::vector<int>& partition = partitions.current();
1178                         // All monomials of this partition have the same number of terms and the same coefficient.
1179                         const unsigned msize = std::count_if(partition.begin(), partition.end(), [](int i) { return i > 0; });
1180                         const numeric coeff = multinomial_coefficient(partition) * binomial_coefficient;
1181
1182                         // Iterate over all compositions of the current partition.
1183                         composition_generator compositions(partition);
1184                         do {
1185                                 const std::vector<int>& exponent = compositions.current();
1186                                 epvector monomial;
1187                                 monomial.reserve(msize);
1188                                 numeric factor = coeff;
1189                                 for (unsigned i = 0; i < exponent.size(); ++i) {
1190                                         const ex & r = a.seq[i].rest;
1191                                         GINAC_ASSERT(!is_exactly_a<add>(r));
1192                                         GINAC_ASSERT(!is_exactly_a<power>(r) ||
1193                                                      !is_exactly_a<numeric>(ex_to<power>(r).exponent) ||
1194                                                      !ex_to<numeric>(ex_to<power>(r).exponent).is_pos_integer() ||
1195                                                      !is_exactly_a<add>(ex_to<power>(r).basis) ||
1196                                                      !is_exactly_a<mul>(ex_to<power>(r).basis) ||
1197                                                      !is_exactly_a<power>(ex_to<power>(r).basis));
1198                                         GINAC_ASSERT(is_exactly_a<numeric>(a.seq[i].coeff));
1199                                         const numeric & c = ex_to<numeric>(a.seq[i].coeff);
1200                                         if (exponent[i] == 0) {
1201                                                 // optimize away
1202                                         } else if (exponent[i] == 1) {
1203                                                 // optimized
1204                                                 monomial.push_back(expair(r, _ex1));
1205                                                 if (c != *_num1_p)
1206                                                         factor = factor.mul(c);
1207                                         } else { // general case exponent[i] > 1
1208                                                 monomial.push_back(expair(r, exponent[i]));
1209                                                 if (c != *_num1_p)
1210                                                         factor = factor.mul(c.power(exponent[i]));
1211                                         }
1212                                 }
1213                                 result.push_back(expair(mul(monomial).expand(options), factor));
1214                         } while (compositions.next());
1215                 } while (partitions.next());
1216         }
1217
1218         GINAC_ASSERT(result.size() == result_size);
1219         if (a.overall_coeff.is_zero()) {
1220                 return dynallocate<add>(std::move(result)).setflag(status_flags::expanded);
1221         } else {
1222                 return dynallocate<add>(std::move(result), ex_to<numeric>(a.overall_coeff).power(n)).setflag(status_flags::expanded);
1223         }
1224 }
1225
1226
1227 /** Special case of power::expand_add. Expands a^2 where a is an add.
1228  *  @see power::expand_add */
1229 ex power::expand_add_2(const add & a, unsigned options)
1230 {
1231         epvector result;
1232         size_t result_size = (a.nops() * (a.nops()+1)) / 2;
1233         if (!a.overall_coeff.is_zero()) {
1234                 // the result's overall_coeff is one of the terms
1235                 --result_size;
1236         }
1237         result.reserve(result_size);
1238
1239         epvector::const_iterator last = a.seq.end();
1240
1241         // power(+(x,...,z;c),2)=power(+(x,...,z;0),2)+2*c*+(x,...,z;0)+c*c
1242         // first part: ignore overall_coeff and expand other terms
1243         for (epvector::const_iterator cit0=a.seq.begin(); cit0!=last; ++cit0) {
1244                 const ex & r = cit0->rest;
1245                 const ex & c = cit0->coeff;
1246                 
1247                 GINAC_ASSERT(!is_exactly_a<add>(r));
1248                 GINAC_ASSERT(!is_exactly_a<power>(r) ||
1249                              !is_exactly_a<numeric>(ex_to<power>(r).exponent) ||
1250                              !ex_to<numeric>(ex_to<power>(r).exponent).is_pos_integer() ||
1251                              !is_exactly_a<add>(ex_to<power>(r).basis) ||
1252                              !is_exactly_a<mul>(ex_to<power>(r).basis) ||
1253                              !is_exactly_a<power>(ex_to<power>(r).basis));
1254                 
1255                 if (c.is_equal(_ex1)) {
1256                         if (is_exactly_a<mul>(r)) {
1257                                 result.push_back(expair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
1258                                                         _ex1));
1259                         } else {
1260                                 result.push_back(expair(dynallocate<power>(r, _ex2),
1261                                                         _ex1));
1262                         }
1263                 } else {
1264                         if (is_exactly_a<mul>(r)) {
1265                                 result.push_back(expair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
1266                                                         ex_to<numeric>(c).power_dyn(*_num2_p)));
1267                         } else {
1268                                 result.push_back(expair(dynallocate<power>(r, _ex2),
1269                                                         ex_to<numeric>(c).power_dyn(*_num2_p)));
1270                         }
1271                 }
1272
1273                 for (epvector::const_iterator cit1=cit0+1; cit1!=last; ++cit1) {
1274                         const ex & r1 = cit1->rest;
1275                         const ex & c1 = cit1->coeff;
1276                         result.push_back(expair(mul(r,r1).expand(options),
1277                                                 _num2_p->mul(ex_to<numeric>(c)).mul_dyn(ex_to<numeric>(c1))));
1278                 }
1279         }
1280         
1281         // second part: add terms coming from overall_coeff (if != 0)
1282         if (!a.overall_coeff.is_zero()) {
1283                 for (auto & i : a.seq)
1284                         result.push_back(a.combine_pair_with_coeff_to_pair(i, ex_to<numeric>(a.overall_coeff).mul_dyn(*_num2_p)));
1285         }
1286
1287         GINAC_ASSERT(result.size() == result_size);
1288
1289         if (a.overall_coeff.is_zero()) {
1290                 return dynallocate<add>(std::move(result)).setflag(status_flags::expanded);
1291         } else {
1292                 return dynallocate<add>(std::move(result), ex_to<numeric>(a.overall_coeff).power(2)).setflag(status_flags::expanded);
1293         }
1294 }
1295
1296 /** Expand factors of m in m^n where m is a mul and n is an integer.
1297  *  @see power::expand */
1298 ex power::expand_mul(const mul & m, const numeric & n, unsigned options, bool from_expand)
1299 {
1300         GINAC_ASSERT(n.is_integer());
1301
1302         if (n.is_zero()) {
1303                 return _ex1;
1304         }
1305
1306         // do not bother to rename indices if there are no any.
1307         if (!(options & expand_options::expand_rename_idx) &&
1308             m.info(info_flags::has_indices))
1309                 options |= expand_options::expand_rename_idx;
1310         // Leave it to multiplication since dummy indices have to be renamed
1311         if ((options & expand_options::expand_rename_idx) &&
1312             (get_all_dummy_indices(m).size() > 0) && n.is_positive()) {
1313                 ex result = m;
1314                 exvector va = get_all_dummy_indices(m);
1315                 sort(va.begin(), va.end(), ex_is_less());
1316
1317                 for (int i=1; i < n.to_int(); i++)
1318                         result *= rename_dummy_indices_uniquely(va, m);
1319                 return result;
1320         }
1321
1322         epvector distrseq;
1323         distrseq.reserve(m.seq.size());
1324         bool need_reexpand = false;
1325
1326         for (auto & cit : m.seq) {
1327                 expair p = m.combine_pair_with_coeff_to_pair(cit, n);
1328                 if (from_expand && is_exactly_a<add>(cit.rest) && ex_to<numeric>(p.coeff).is_pos_integer()) {
1329                         // this happens when e.g. (a+b)^(1/2) gets squared and
1330                         // the resulting product needs to be reexpanded
1331                         need_reexpand = true;
1332                 }
1333                 distrseq.push_back(p);
1334         }
1335
1336         const mul & result = dynallocate<mul>(std::move(distrseq), ex_to<numeric>(m.overall_coeff).power_dyn(n));
1337         if (need_reexpand)
1338                 return ex(result).expand(options);
1339         if (from_expand)
1340                 return result.setflag(status_flags::expanded);
1341         return result;
1342 }
1343
1344 GINAC_BIND_UNARCHIVER(power);
1345
1346 } // namespace GiNaC