afe2f1ef08fb5b34b79f3365d01bffe372ff9d73
[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  *  @param level cut-off in recursive evaluation */
378 ex power::eval(int level) const
379 {
380         if ((level==1) && (flags & status_flags::evaluated))
381                 return *this;
382         else if (level == -max_recursion_level)
383                 throw(std::runtime_error("max recursion level reached"));
384         
385         const ex & ebasis    = level==1 ? basis    : basis.eval(level-1);
386         const ex & eexponent = level==1 ? exponent : exponent.eval(level-1);
387         
388         const numeric *num_basis = nullptr;
389         const numeric *num_exponent = nullptr;
390         
391         if (is_exactly_a<numeric>(ebasis)) {
392                 num_basis = &ex_to<numeric>(ebasis);
393         }
394         if (is_exactly_a<numeric>(eexponent)) {
395                 num_exponent = &ex_to<numeric>(eexponent);
396         }
397         
398         // ^(x,0) -> 1  (0^0 also handled here)
399         if (eexponent.is_zero()) {
400                 if (ebasis.is_zero())
401                         throw (std::domain_error("power::eval(): pow(0,0) is undefined"));
402                 else
403                         return _ex1;
404         }
405         
406         // ^(x,1) -> x
407         if (eexponent.is_equal(_ex1))
408                 return ebasis;
409
410         // ^(0,c1) -> 0 or exception  (depending on real value of c1)
411         if ( ebasis.is_zero() && num_exponent ) {
412                 if ((num_exponent->real()).is_zero())
413                         throw (std::domain_error("power::eval(): pow(0,I) is undefined"));
414                 else if ((num_exponent->real()).is_negative())
415                         throw (pole_error("power::eval(): division by zero",1));
416                 else
417                         return _ex0;
418         }
419
420         // ^(1,x) -> 1
421         if (ebasis.is_equal(_ex1))
422                 return _ex1;
423
424         // power of a function calculated by separate rules defined for this function
425         if (is_exactly_a<function>(ebasis))
426                 return ex_to<function>(ebasis).power(eexponent);
427
428         // Turn (x^c)^d into x^(c*d) in the case that x is positive and c is real.
429         if (is_exactly_a<power>(ebasis) && ebasis.op(0).info(info_flags::positive) && ebasis.op(1).info(info_flags::real))
430                 return power(ebasis.op(0), ebasis.op(1) * eexponent);
431
432         if ( num_exponent ) {
433
434                 // ^(c1,c2) -> c1^c2  (c1, c2 numeric(),
435                 // except if c1,c2 are rational, but c1^c2 is not)
436                 if ( num_basis ) {
437                         const bool basis_is_crational = num_basis->is_crational();
438                         const bool exponent_is_crational = num_exponent->is_crational();
439                         if (!basis_is_crational || !exponent_is_crational) {
440                                 // return a plain float
441                                 return dynallocate<numeric>(num_basis->power(*num_exponent));
442                         }
443
444                         const numeric res = num_basis->power(*num_exponent);
445                         if (res.is_crational()) {
446                                 return res;
447                         }
448                         GINAC_ASSERT(!num_exponent->is_integer());  // has been handled by now
449
450                         // ^(c1,n/m) -> *(c1^q,c1^(n/m-q)), 0<(n/m-q)<1, q integer
451                         if (basis_is_crational && exponent_is_crational
452                             && num_exponent->is_real()
453                             && !num_exponent->is_integer()) {
454                                 const numeric n = num_exponent->numer();
455                                 const numeric m = num_exponent->denom();
456                                 numeric r;
457                                 numeric q = iquo(n, m, r);
458                                 if (r.is_negative()) {
459                                         r += m;
460                                         --q;
461                                 }
462                                 if (q.is_zero()) {  // the exponent was in the allowed range 0<(n/m)<1
463                                         if (num_basis->is_rational() && !num_basis->is_integer()) {
464                                                 // try it for numerator and denominator separately, in order to
465                                                 // partially simplify things like (5/8)^(1/3) -> 1/2*5^(1/3)
466                                                 const numeric bnum = num_basis->numer();
467                                                 const numeric bden = num_basis->denom();
468                                                 const numeric res_bnum = bnum.power(*num_exponent);
469                                                 const numeric res_bden = bden.power(*num_exponent);
470                                                 if (res_bnum.is_integer())
471                                                         return dynallocate<mul>(dynallocate<power>(bden,-*num_exponent),res_bnum).setflag(status_flags::evaluated);
472                                                 if (res_bden.is_integer())
473                                                         return dynallocate<mul>(dynallocate<power>(bnum,*num_exponent),res_bden.inverse()).setflag(status_flags::evaluated);
474                                         }
475                                         return this->hold();
476                                 } else {
477                                         // assemble resulting product, but allowing for a re-evaluation,
478                                         // because otherwise we'll end up with something like
479                                         //    (7/8)^(4/3)  ->  7/8*(1/2*7^(1/3))
480                                         // instead of 7/16*7^(1/3).
481                                         ex prod = power(*num_basis,r.div(m));
482                                         return prod*power(*num_basis,q);
483                                 }
484                         }
485                 }
486         
487                 // ^(^(x,c1),c2) -> ^(x,c1*c2)
488                 // (c1, c2 numeric(), c2 integer or -1 < c1 <= 1 or (c1=-1 and c2>0),
489                 // case c1==1 should not happen, see below!)
490                 if (is_exactly_a<power>(ebasis)) {
491                         const power & sub_power = ex_to<power>(ebasis);
492                         const ex & sub_basis = sub_power.basis;
493                         const ex & sub_exponent = sub_power.exponent;
494                         if (is_exactly_a<numeric>(sub_exponent)) {
495                                 const numeric & num_sub_exponent = ex_to<numeric>(sub_exponent);
496                                 GINAC_ASSERT(num_sub_exponent!=numeric(1));
497                                 if (num_exponent->is_integer() || (abs(num_sub_exponent) - (*_num1_p)).is_negative() ||
498                                     (num_sub_exponent == *_num_1_p && num_exponent->is_positive())) {
499                                         return power(sub_basis,num_sub_exponent.mul(*num_exponent));
500                                 }
501                         }
502                 }
503         
504                 // ^(*(x,y,z),c1) -> *(x^c1,y^c1,z^c1) (c1 integer)
505                 if (num_exponent->is_integer() && is_exactly_a<mul>(ebasis)) {
506                         return expand_mul(ex_to<mul>(ebasis), *num_exponent, 0);
507                 }
508
509                 // (2*x + 6*y)^(-4) -> 1/16*(x + 3*y)^(-4)
510                 if (num_exponent->is_integer() && is_exactly_a<add>(ebasis)) {
511                         numeric icont = ebasis.integer_content();
512                         const numeric lead_coeff = 
513                                 ex_to<numeric>(ex_to<add>(ebasis).seq.begin()->coeff).div(icont);
514
515                         const bool canonicalizable = lead_coeff.is_integer();
516                         const bool unit_normal = lead_coeff.is_pos_integer();
517                         if (canonicalizable && (! unit_normal))
518                                 icont = icont.mul(*_num_1_p);
519                         
520                         if (canonicalizable && (icont != *_num1_p)) {
521                                 const add& addref = ex_to<add>(ebasis);
522                                 add & addp = dynallocate<add>(addref);
523                                 addp.clearflag(status_flags::hash_calculated);
524                                 addp.overall_coeff = ex_to<numeric>(addp.overall_coeff).div_dyn(icont);
525                                 for (auto & i : addp.seq)
526                                         i.coeff = ex_to<numeric>(i.coeff).div_dyn(icont);
527
528                                 const numeric c = icont.power(*num_exponent);
529                                 if (likely(c != *_num1_p))
530                                         return dynallocate<mul>(dynallocate<power>(addp, *num_exponent), c);
531                                 else
532                                         return dynallocate<power>(addp, *num_exponent);
533                         }
534                 }
535
536                 // ^(*(...,x;c1),c2) -> *(^(*(...,x;1),c2),c1^c2)  (c1, c2 numeric(), c1>0)
537                 // ^(*(...,x;c1),c2) -> *(^(*(...,x;-1),c2),(-c1)^c2)  (c1, c2 numeric(), c1<0)
538                 if (is_exactly_a<mul>(ebasis)) {
539                         GINAC_ASSERT(!num_exponent->is_integer()); // should have been handled above
540                         const mul & mulref = ex_to<mul>(ebasis);
541                         if (!mulref.overall_coeff.is_equal(_ex1)) {
542                                 const numeric & num_coeff = ex_to<numeric>(mulref.overall_coeff);
543                                 if (num_coeff.is_real()) {
544                                         if (num_coeff.is_positive()) {
545                                                 mul & mulp = dynallocate<mul>(mulref);
546                                                 mulp.overall_coeff = _ex1;
547                                                 mulp.clearflag(status_flags::evaluated | status_flags::hash_calculated);
548                                                 return dynallocate<mul>(dynallocate<power>(mulp, exponent),
549                                                                         dynallocate<power>(num_coeff, *num_exponent));
550                                         } else {
551                                                 GINAC_ASSERT(num_coeff.compare(*_num0_p)<0);
552                                                 if (!num_coeff.is_equal(*_num_1_p)) {
553                                                         mul & mulp = dynallocate<mul>(mulref);
554                                                         mulp.overall_coeff = _ex_1;
555                                                         mulp.clearflag(status_flags::evaluated | status_flags::hash_calculated);
556                                                         return dynallocate<mul>(dynallocate<power>(mulp, exponent),
557                                                                                 dynallocate<power>(abs(num_coeff), *num_exponent));
558                                                 }
559                                         }
560                                 }
561                         }
562                 }
563
564                 // ^(nc,c1) -> ncmul(nc,nc,...) (c1 positive integer, unless nc is a matrix)
565                 if (num_exponent->is_pos_integer() &&
566                     ebasis.return_type() != return_types::commutative &&
567                     !is_a<matrix>(ebasis)) {
568                         return ncmul(exvector(num_exponent->to_int(), ebasis));
569                 }
570         }
571         
572         if (are_ex_trivially_equal(ebasis,basis) &&
573             are_ex_trivially_equal(eexponent,exponent)) {
574                 return this->hold();
575         }
576         return dynallocate<power>(ebasis, eexponent).setflag(status_flags::evaluated);
577 }
578
579 ex power::evalf(int level) const
580 {
581         ex ebasis;
582         ex eexponent;
583         
584         if (level==1) {
585                 ebasis = basis;
586                 eexponent = exponent;
587         } else if (level == -max_recursion_level) {
588                 throw(std::runtime_error("max recursion level reached"));
589         } else {
590                 ebasis = basis.evalf(level-1);
591                 if (!is_exactly_a<numeric>(exponent))
592                         eexponent = exponent.evalf(level-1);
593                 else
594                         eexponent = exponent;
595         }
596
597         return power(ebasis,eexponent);
598 }
599
600 ex power::evalm() const
601 {
602         const ex ebasis = basis.evalm();
603         const ex eexponent = exponent.evalm();
604         if (is_a<matrix>(ebasis)) {
605                 if (is_exactly_a<numeric>(eexponent)) {
606                         return dynallocate<matrix>(ex_to<matrix>(ebasis).pow(eexponent));
607                 }
608         }
609         return dynallocate<power>(ebasis, eexponent);
610 }
611
612 bool power::has(const ex & other, unsigned options) const
613 {
614         if (!(options & has_options::algebraic))
615                 return basic::has(other, options);
616         if (!is_a<power>(other))
617                 return basic::has(other, options);
618         if (!exponent.info(info_flags::integer) ||
619             !other.op(1).info(info_flags::integer))
620                 return basic::has(other, options);
621         if (exponent.info(info_flags::posint) &&
622             other.op(1).info(info_flags::posint) &&
623             ex_to<numeric>(exponent) > ex_to<numeric>(other.op(1)) &&
624             basis.match(other.op(0)))
625                 return true;
626         if (exponent.info(info_flags::negint) &&
627             other.op(1).info(info_flags::negint) &&
628             ex_to<numeric>(exponent) < ex_to<numeric>(other.op(1)) &&
629             basis.match(other.op(0)))
630                 return true;
631         return basic::has(other, options);
632 }
633
634 // from mul.cpp
635 extern bool tryfactsubs(const ex &, const ex &, int &, exmap&);
636
637 ex power::subs(const exmap & m, unsigned options) const
638 {       
639         const ex &subsed_basis = basis.subs(m, options);
640         const ex &subsed_exponent = exponent.subs(m, options);
641
642         if (!are_ex_trivially_equal(basis, subsed_basis)
643          || !are_ex_trivially_equal(exponent, subsed_exponent)) 
644                 return power(subsed_basis, subsed_exponent).subs_one_level(m, options);
645
646         if (!(options & subs_options::algebraic))
647                 return subs_one_level(m, options);
648
649         for (auto & it : m) {
650                 int nummatches = std::numeric_limits<int>::max();
651                 exmap repls;
652                 if (tryfactsubs(*this, it.first, nummatches, repls)) {
653                         ex anum = it.second.subs(repls, subs_options::no_pattern);
654                         ex aden = it.first.subs(repls, subs_options::no_pattern);
655                         ex result = (*this)*power(anum/aden, nummatches);
656                         return (ex_to<basic>(result)).subs_one_level(m, options);
657                 }
658         }
659
660         return subs_one_level(m, options);
661 }
662
663 ex power::eval_ncmul(const exvector & v) const
664 {
665         return inherited::eval_ncmul(v);
666 }
667
668 ex power::conjugate() const
669 {
670         // conjugate(pow(x,y))==pow(conjugate(x),conjugate(y)) unless on the
671         // branch cut which runs along the negative real axis.
672         if (basis.info(info_flags::positive)) {
673                 ex newexponent = exponent.conjugate();
674                 if (are_ex_trivially_equal(exponent, newexponent)) {
675                         return *this;
676                 }
677                 return dynallocate<power>(basis, newexponent);
678         }
679         if (exponent.info(info_flags::integer)) {
680                 ex newbasis = basis.conjugate();
681                 if (are_ex_trivially_equal(basis, newbasis)) {
682                         return *this;
683                 }
684                 return dynallocate<power>(newbasis, exponent);
685         }
686         return conjugate_function(*this).hold();
687 }
688
689 ex power::real_part() const
690 {
691         // basis == a+I*b, exponent == c+I*d
692         const ex a = basis.real_part();
693         const ex c = exponent.real_part();
694         if (basis.is_equal(a) && exponent.is_equal(c)) {
695                 // Re(a^c)
696                 return *this;
697         }
698
699         const ex b = basis.imag_part();
700         if (exponent.info(info_flags::integer)) {
701                 // Re((a+I*b)^c)  w/  c ∈ ℤ
702                 long N = ex_to<numeric>(c).to_long();
703                 // Use real terms in Binomial expansion to construct
704                 // Re(expand(power(a+I*b, N))).
705                 long NN = N > 0 ? N : -N;
706                 ex numer = N > 0 ? _ex1 : power(power(a,2) + power(b,2), NN);
707                 ex result = 0;
708                 for (long n = 0; n <= NN; n += 2) {
709                         ex term = binomial(NN, n) * power(a, NN-n) * power(b, n) / numer;
710                         if (n % 4 == 0) {
711                                 result += term;  // sign: I^n w/ n == 4*m
712                         } else {
713                                 result -= term;  // sign: I^n w/ n == 4*m+2
714                         }
715                 }
716                 return result;
717         }
718
719         // Re((a+I*b)^(c+I*d))
720         const ex d = exponent.imag_part();
721         return power(abs(basis),c)*exp(-d*atan2(b,a))*cos(c*atan2(b,a)+d*log(abs(basis)));
722 }
723
724 ex power::imag_part() const
725 {
726         const ex a = basis.real_part();
727         const ex c = exponent.real_part();
728         if (basis.is_equal(a) && exponent.is_equal(c)) {
729                 // Im(a^c)
730                 return 0;
731         }
732
733         const ex b = basis.imag_part();
734         if (exponent.info(info_flags::integer)) {
735                 // Im((a+I*b)^c)  w/  c ∈ ℤ
736                 long N = ex_to<numeric>(c).to_long();
737                 // Use imaginary terms in Binomial expansion to construct
738                 // Im(expand(power(a+I*b, N))).
739                 long p = N > 0 ? 1 : 3;  // modulus for positive sign
740                 long NN = N > 0 ? N : -N;
741                 ex numer = N > 0 ? _ex1 : power(power(a,2) + power(b,2), NN);
742                 ex result = 0;
743                 for (long n = 1; n <= NN; n += 2) {
744                         ex term = binomial(NN, n) * power(a, NN-n) * power(b, n) / numer;
745                         if (n % 4 == p) {
746                                 result += term;  // sign: I^n w/ n == 4*m+p
747                         } else {
748                                 result -= term;  // sign: I^n w/ n == 4*m+2+p
749                         }
750                 }
751                 return result;
752         }
753
754         // Im((a+I*b)^(c+I*d))
755         const ex d = exponent.imag_part();
756         return power(abs(basis),c)*exp(-d*atan2(b,a))*sin(c*atan2(b,a)+d*log(abs(basis)));
757 }
758
759 // protected
760
761 /** Implementation of ex::diff() for a power.
762  *  @see ex::diff */
763 ex power::derivative(const symbol & s) const
764 {
765         if (is_a<numeric>(exponent)) {
766                 // D(b^r) = r * b^(r-1) * D(b) (faster than the formula below)
767                 epvector newseq;
768                 newseq.reserve(2);
769                 newseq.push_back(expair(basis, exponent - _ex1));
770                 newseq.push_back(expair(basis.diff(s), _ex1));
771                 return mul(std::move(newseq), exponent);
772         } else {
773                 // D(b^e) = b^e * (D(e)*ln(b) + e*D(b)/b)
774                 return mul(*this,
775                            add(mul(exponent.diff(s), log(basis)),
776                            mul(mul(exponent, basis.diff(s)), power(basis, _ex_1))));
777         }
778 }
779
780 int power::compare_same_type(const basic & other) const
781 {
782         GINAC_ASSERT(is_exactly_a<power>(other));
783         const power &o = static_cast<const power &>(other);
784
785         int cmpval = basis.compare(o.basis);
786         if (cmpval)
787                 return cmpval;
788         else
789                 return exponent.compare(o.exponent);
790 }
791
792 unsigned power::return_type() const
793 {
794         return basis.return_type();
795 }
796
797 return_type_t power::return_type_tinfo() const
798 {
799         return basis.return_type_tinfo();
800 }
801
802 ex power::expand(unsigned options) const
803 {
804         if (is_a<symbol>(basis) && exponent.info(info_flags::integer)) {
805                 // A special case worth optimizing.
806                 setflag(status_flags::expanded);
807                 return *this;
808         }
809
810         // (x*p)^c -> x^c * p^c, if p>0
811         // makes sense before expanding the basis
812         if (is_exactly_a<mul>(basis) && !basis.info(info_flags::indefinite)) {
813                 const mul &m = ex_to<mul>(basis);
814                 exvector prodseq;
815                 epvector powseq;
816                 prodseq.reserve(m.seq.size() + 1);
817                 powseq.reserve(m.seq.size() + 1);
818                 bool possign = true;
819
820                 // search for positive/negative factors
821                 for (auto & cit : m.seq) {
822                         ex e=m.recombine_pair_to_ex(cit);
823                         if (e.info(info_flags::positive))
824                                 prodseq.push_back(pow(e, exponent).expand(options));
825                         else if (e.info(info_flags::negative)) {
826                                 prodseq.push_back(pow(-e, exponent).expand(options));
827                                 possign = !possign;
828                         } else
829                                 powseq.push_back(cit);
830                 }
831
832                 // take care on the numeric coefficient
833                 ex coeff=(possign? _ex1 : _ex_1);
834                 if (m.overall_coeff.info(info_flags::positive) && m.overall_coeff != _ex1)
835                         prodseq.push_back(power(m.overall_coeff, exponent));
836                 else if (m.overall_coeff.info(info_flags::negative) && m.overall_coeff != _ex_1)
837                         prodseq.push_back(power(-m.overall_coeff, exponent));
838                 else
839                         coeff *= m.overall_coeff;
840
841                 // If positive/negative factors are found, then extract them.
842                 // In either case we set a flag to avoid the second run on a part
843                 // which does not have positive/negative terms.
844                 if (prodseq.size() > 0) {
845                         ex newbasis = coeff*mul(std::move(powseq));
846                         ex_to<basic>(newbasis).setflag(status_flags::purely_indefinite);
847                         return dynallocate<mul>(std::move(prodseq)) * pow(newbasis, exponent);
848                 } else
849                         ex_to<basic>(basis).setflag(status_flags::purely_indefinite);
850         }
851
852         const ex expanded_basis = basis.expand(options);
853         const ex expanded_exponent = exponent.expand(options);
854         
855         // x^(a+b) -> x^a * x^b
856         if (is_exactly_a<add>(expanded_exponent)) {
857                 const add &a = ex_to<add>(expanded_exponent);
858                 exvector distrseq;
859                 distrseq.reserve(a.seq.size() + 1);
860                 for (auto & cit : a.seq) {
861                         distrseq.push_back(power(expanded_basis, a.recombine_pair_to_ex(cit)));
862                 }
863                 
864                 // Make sure that e.g. (x+y)^(2+a) expands the (x+y)^2 factor
865                 if (ex_to<numeric>(a.overall_coeff).is_integer()) {
866                         const numeric &num_exponent = ex_to<numeric>(a.overall_coeff);
867                         long int_exponent = num_exponent.to_int();
868                         if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
869                                 distrseq.push_back(expand_add(ex_to<add>(expanded_basis), int_exponent, options));
870                         else
871                                 distrseq.push_back(power(expanded_basis, a.overall_coeff));
872                 } else
873                         distrseq.push_back(power(expanded_basis, a.overall_coeff));
874                 
875                 // Make sure that e.g. (x+y)^(1+a) -> x*(x+y)^a + y*(x+y)^a
876                 ex r = dynallocate<mul>(distrseq);
877                 return r.expand(options);
878         }
879         
880         if (!is_exactly_a<numeric>(expanded_exponent) ||
881                 !ex_to<numeric>(expanded_exponent).is_integer()) {
882                 if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent)) {
883                         return this->hold();
884                 } else {
885                         return dynallocate<power>(expanded_basis, expanded_exponent).setflag(options == 0 ? status_flags::expanded : 0);
886                 }
887         }
888         
889         // integer numeric exponent
890         const numeric & num_exponent = ex_to<numeric>(expanded_exponent);
891         long int_exponent = num_exponent.to_long();
892         
893         // (x+y)^n, n>0
894         if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
895                 return expand_add(ex_to<add>(expanded_basis), int_exponent, options);
896         
897         // (x*y)^n -> x^n * y^n
898         if (is_exactly_a<mul>(expanded_basis))
899                 return expand_mul(ex_to<mul>(expanded_basis), num_exponent, options, true);
900         
901         // cannot expand further
902         if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent))
903                 return this->hold();
904         else
905                 return dynallocate<power>(expanded_basis, expanded_exponent).setflag(options == 0 ? status_flags::expanded : 0);
906 }
907
908 //////////
909 // new virtual functions which can be overridden by derived classes
910 //////////
911
912 // none
913
914 //////////
915 // non-virtual functions in this class
916 //////////
917
918 namespace {  // anonymous namespace for power::expand_add() helpers
919
920 /** Helper class to generate all bounded combinatorial partitions of an integer
921  *  n with exactly m parts (including zero parts) in non-decreasing order.
922  */
923 class partition_generator {
924 private:
925         // Partitions n into m parts, not including zero parts.
926         // (Cf. OEIS sequence A008284; implementation adapted from Jörg Arndt's
927         // FXT library)
928         struct mpartition2
929         {
930                 // partition: x[1] + x[2] + ... + x[m] = n and sentinel x[0] == 0
931                 std::vector<int> x;
932                 int n;   // n>0
933                 int m;   // 0<m<=n
934                 mpartition2(unsigned n_, unsigned m_)
935                   : x(m_+1), n(n_), m(m_)
936                 {
937                         for (int k=1; k<m; ++k)
938                                 x[k] = 1;
939                         x[m] = n - m + 1;
940                 }
941                 bool next_partition()
942                 {
943                         int u = x[m];  // last element
944                         int k = m;
945                         int s = u;
946                         while (--k) {
947                                 s += x[k];
948                                 if (x[k] + 2 <= u)
949                                         break;
950                         }
951                         if (k==0)
952                                 return false;  // current is last
953                         int f = x[k] + 1;
954                         while (k < m) {
955                                 x[k] = f;
956                                 s -= f;
957                                 ++k;
958                         }
959                         x[m] = s;
960                         return true;
961                 }
962         } mpgen;
963         int m;  // number of parts 0<m<=n
964         mutable std::vector<int> partition;  // current partition
965 public:
966         partition_generator(unsigned n_, unsigned m_)
967           : mpgen(n_, 1), m(m_), partition(m_)
968         { }
969         // returns current partition in non-decreasing order, padded with zeros
970         const std::vector<int>& current() const
971         {
972                 for (int i = 0; i < m - mpgen.m; ++i)
973                         partition[i] = 0;  // pad with zeros
974
975                 for (int i = m - mpgen.m; i < m; ++i)
976                         partition[i] = mpgen.x[i - m + mpgen.m + 1];
977
978                 return partition;
979         }
980         bool next()
981         {
982                 if (!mpgen.next_partition()) {
983                         if (mpgen.m == m || mpgen.m == mpgen.n)
984                                 return false;  // current is last
985                         // increment number of parts
986                         mpgen = mpartition2(mpgen.n, mpgen.m + 1);
987                 }
988                 return true;
989         }
990 };
991
992 /** Helper class to generate all compositions of a partition of an integer n,
993  *  starting with the compositions which has non-decreasing order.
994  */
995 class composition_generator {
996 private:
997         // Generates all distinct permutations of a multiset.
998         // (Based on Aaron Williams' algorithm 1 from "Loopless Generation of
999         // Multiset Permutations using a Constant Number of Variables by Prefix
1000         // Shifts." <http://webhome.csc.uvic.ca/~haron/CoolMulti.pdf>)
1001         struct coolmulti {
1002                 // element of singly linked list
1003                 struct element {
1004                         int value;
1005                         element* next;
1006                         element(int val, element* n)
1007                           : value(val), next(n) {}
1008                         ~element()
1009                         {   // recurses down to the end of the singly linked list
1010                                 delete next;
1011                         }
1012                 };
1013                 element *head, *i, *after_i;
1014                 // NB: Partition must be sorted in non-decreasing order.
1015                 explicit coolmulti(const std::vector<int>& partition)
1016                   : head(nullptr), i(nullptr), after_i(nullptr)
1017                 {
1018                         for (unsigned n = 0; n < partition.size(); ++n) {
1019                                 head = new element(partition[n], head);
1020                                 if (n <= 1)
1021                                         i = head;
1022                         }
1023                         after_i = i->next;
1024                 }
1025                 ~coolmulti()
1026                 {   // deletes singly linked list
1027                         delete head;
1028                 }
1029                 void next_permutation()
1030                 {
1031                         element *before_k;
1032                         if (after_i->next != nullptr && i->value >= after_i->next->value)
1033                                 before_k = after_i;
1034                         else
1035                                 before_k = i;
1036                         element *k = before_k->next;
1037                         before_k->next = k->next;
1038                         k->next = head;
1039                         if (k->value < head->value)
1040                                 i = k;
1041                         after_i = i->next;
1042                         head = k;
1043                 }
1044                 bool finished() const
1045                 {
1046                         return after_i->next == nullptr && after_i->value >= head->value;
1047                 }
1048         } cmgen;
1049         bool atend;  // needed for simplifying iteration over permutations
1050         bool trivial;  // likewise, true if all elements are equal
1051         mutable std::vector<int> composition;  // current compositions
1052 public:
1053         explicit composition_generator(const std::vector<int>& partition)
1054           : cmgen(partition), atend(false), trivial(true), composition(partition.size())
1055         {
1056                 for (unsigned i=1; i<partition.size(); ++i)
1057                         trivial = trivial && (partition[0] == partition[i]);
1058         }
1059         const std::vector<int>& current() const
1060         {
1061                 coolmulti::element* it = cmgen.head;
1062                 size_t i = 0;
1063                 while (it != nullptr) {
1064                         composition[i] = it->value;
1065                         it = it->next;
1066                         ++i;
1067                 }
1068                 return composition;
1069         }
1070         bool next()
1071         {
1072                 // This ugly contortion is needed because the original coolmulti
1073                 // algorithm requires code duplication of the payload procedure,
1074                 // one before the loop and one inside it.
1075                 if (trivial || atend)
1076                         return false;
1077                 cmgen.next_permutation();
1078                 atend = cmgen.finished();
1079                 return true;
1080         }
1081 };
1082
1083 /** Helper function to compute the multinomial coefficient n!/(p1!*p2!*...*pk!)
1084  *  where n = p1+p2+...+pk, i.e. p is a partition of n.
1085  */
1086 const numeric
1087 multinomial_coefficient(const std::vector<int> & p)
1088 {
1089         numeric n = 0, d = 1;
1090         for (auto & it : p) {
1091                 n += numeric(it);
1092                 d *= factorial(numeric(it));
1093         }
1094         return factorial(numeric(n)) / d;
1095 }
1096
1097 }  // anonymous namespace
1098
1099
1100 /** expand a^n where a is an add and n is a positive integer.
1101  *  @see power::expand */
1102 ex power::expand_add(const add & a, long n, unsigned options)
1103 {
1104         // The special case power(+(x,...y;x),2) can be optimized better.
1105         if (n==2)
1106                 return expand_add_2(a, options);
1107
1108         // method:
1109         //
1110         // Consider base as the sum of all symbolic terms and the overall numeric
1111         // coefficient and apply the binomial theorem:
1112         // S = power(+(x,...,z;c),n)
1113         //   = power(+(+(x,...,z;0);c),n)
1114         //   = sum(binomial(n,k)*power(+(x,...,z;0),k)*c^(n-k), k=1..n) + c^n
1115         // Then, apply the multinomial theorem to expand all power(+(x,...,z;0),k):
1116         // The multinomial theorem is computed by an outer loop over all
1117         // partitions of the exponent and an inner loop over all compositions of
1118         // that partition. This method makes the expansion a combinatorial
1119         // problem and allows us to directly construct the expanded sum and also
1120         // to re-use the multinomial coefficients (since they depend only on the
1121         // partition, not on the composition).
1122         // 
1123         // multinomial power(+(x,y,z;0),3) example:
1124         // partition : compositions                : multinomial coefficient
1125         // [0,0,3]   : [3,0,0],[0,3,0],[0,0,3]     : 3!/(3!*0!*0!) = 1
1126         // [0,1,2]   : [2,1,0],[1,2,0],[2,0,1],... : 3!/(2!*1!*0!) = 3
1127         // [1,1,1]   : [1,1,1]                     : 3!/(1!*1!*1!) = 6
1128         //  =>  (x + y + z)^3 =
1129         //        x^3 + y^3 + z^3
1130         //      + 3*x^2*y + 3*x*y^2 + 3*y^2*z + 3*y*z^2 + 3*x*z^2 + 3*x^2*z
1131         //      + 6*x*y*z
1132         //
1133         // multinomial power(+(x,y,z;0),4) example:
1134         // partition : compositions                : multinomial coefficient
1135         // [0,0,4]   : [4,0,0],[0,4,0],[0,0,4]     : 4!/(4!*0!*0!) = 1
1136         // [0,1,3]   : [3,1,0],[1,3,0],[3,0,1],... : 4!/(3!*1!*0!) = 4
1137         // [0,2,2]   : [2,2,0],[2,0,2],[0,2,2]     : 4!/(2!*2!*0!) = 6
1138         // [1,1,2]   : [2,1,1],[1,2,1],[1,1,2]     : 4!/(2!*1!*1!) = 12
1139         // (no [1,1,1,1] partition since it has too many parts)
1140         //  =>  (x + y + z)^4 =
1141         //        x^4 + y^4 + z^4
1142         //      + 4*x^3*y + 4*x*y^3 + 4*y^3*z + 4*y*z^3 + 4*x*z^3 + 4*x^3*z
1143         //      + 6*x^2*y^2 + 6*y^2*z^2 + 6*x^2*z^2
1144         //      + 12*x^2*y*z + 12*x*y^2*z + 12*x*y*z^2
1145         //
1146         // Summary:
1147         // r = 0
1148         // for k from 0 to n:
1149         //     f = c^(n-k)*binomial(n,k)
1150         //     for p in all partitions of n with m parts (including zero parts):
1151         //         h = f * multinomial coefficient of p
1152         //         for c in all compositions of p:
1153         //             t = 1
1154         //             for e in all elements of c:
1155         //                 t = t * a[e]^e
1156         //             r = r + h*t
1157         // return r
1158
1159         epvector result;
1160         // The number of terms will be the number of combinatorial compositions,
1161         // i.e. the number of unordered arrangements of m nonnegative integers
1162         // which sum up to n.  It is frequently written as C_n(m) and directly
1163         // related with binomial coefficients: binomial(n+m-1,m-1).
1164         size_t result_size = binomial(numeric(n+a.nops()-1), numeric(a.nops()-1)).to_long();
1165         if (!a.overall_coeff.is_zero()) {
1166                 // the result's overall_coeff is one of the terms
1167                 --result_size;
1168         }
1169         result.reserve(result_size);
1170
1171         // Iterate over all terms in binomial expansion of
1172         // S = power(+(x,...,z;c),n)
1173         //   = sum(binomial(n,k)*power(+(x,...,z;0),k)*c^(n-k), k=1..n) + c^n
1174         for (int k = 1; k <= n; ++k) {
1175                 numeric binomial_coefficient;  // binomial(n,k)*c^(n-k)
1176                 if (a.overall_coeff.is_zero()) {
1177                         // degenerate case with zero overall_coeff:
1178                         // apply multinomial theorem directly to power(+(x,...z;0),n)
1179                         binomial_coefficient = 1;
1180                         if (k < n) {
1181                                 continue;
1182                         }
1183                 } else {
1184                         binomial_coefficient = binomial(numeric(n), numeric(k)) * pow(ex_to<numeric>(a.overall_coeff), numeric(n-k));
1185                 }
1186
1187                 // Multinomial expansion of power(+(x,...,z;0),k)*c^(n-k):
1188                 // Iterate over all partitions of k with exactly as many parts as
1189                 // there are symbolic terms in the basis (including zero parts).
1190                 partition_generator partitions(k, a.seq.size());
1191                 do {
1192                         const std::vector<int>& partition = partitions.current();
1193                         // All monomials of this partition have the same number of terms and the same coefficient.
1194                         const unsigned msize = std::count_if(partition.begin(), partition.end(), [](int i) { return i > 0; });
1195                         const numeric coeff = multinomial_coefficient(partition) * binomial_coefficient;
1196
1197                         // Iterate over all compositions of the current partition.
1198                         composition_generator compositions(partition);
1199                         do {
1200                                 const std::vector<int>& exponent = compositions.current();
1201                                 epvector monomial;
1202                                 monomial.reserve(msize);
1203                                 numeric factor = coeff;
1204                                 for (unsigned i = 0; i < exponent.size(); ++i) {
1205                                         const ex & r = a.seq[i].rest;
1206                                         GINAC_ASSERT(!is_exactly_a<add>(r));
1207                                         GINAC_ASSERT(!is_exactly_a<power>(r) ||
1208                                                      !is_exactly_a<numeric>(ex_to<power>(r).exponent) ||
1209                                                      !ex_to<numeric>(ex_to<power>(r).exponent).is_pos_integer() ||
1210                                                      !is_exactly_a<add>(ex_to<power>(r).basis) ||
1211                                                      !is_exactly_a<mul>(ex_to<power>(r).basis) ||
1212                                                      !is_exactly_a<power>(ex_to<power>(r).basis));
1213                                         GINAC_ASSERT(is_exactly_a<numeric>(a.seq[i].coeff));
1214                                         const numeric & c = ex_to<numeric>(a.seq[i].coeff);
1215                                         if (exponent[i] == 0) {
1216                                                 // optimize away
1217                                         } else if (exponent[i] == 1) {
1218                                                 // optimized
1219                                                 monomial.push_back(expair(r, _ex1));
1220                                                 if (c != *_num1_p)
1221                                                         factor = factor.mul(c);
1222                                         } else { // general case exponent[i] > 1
1223                                                 monomial.push_back(expair(r, exponent[i]));
1224                                                 if (c != *_num1_p)
1225                                                         factor = factor.mul(c.power(exponent[i]));
1226                                         }
1227                                 }
1228                                 result.push_back(expair(mul(monomial).expand(options), factor));
1229                         } while (compositions.next());
1230                 } while (partitions.next());
1231         }
1232
1233         GINAC_ASSERT(result.size() == result_size);
1234         if (a.overall_coeff.is_zero()) {
1235                 return dynallocate<add>(std::move(result)).setflag(status_flags::expanded);
1236         } else {
1237                 return dynallocate<add>(std::move(result), ex_to<numeric>(a.overall_coeff).power(n)).setflag(status_flags::expanded);
1238         }
1239 }
1240
1241
1242 /** Special case of power::expand_add. Expands a^2 where a is an add.
1243  *  @see power::expand_add */
1244 ex power::expand_add_2(const add & a, unsigned options)
1245 {
1246         epvector result;
1247         size_t result_size = (a.nops() * (a.nops()+1)) / 2;
1248         if (!a.overall_coeff.is_zero()) {
1249                 // the result's overall_coeff is one of the terms
1250                 --result_size;
1251         }
1252         result.reserve(result_size);
1253
1254         epvector::const_iterator last = a.seq.end();
1255
1256         // power(+(x,...,z;c),2)=power(+(x,...,z;0),2)+2*c*+(x,...,z;0)+c*c
1257         // first part: ignore overall_coeff and expand other terms
1258         for (epvector::const_iterator cit0=a.seq.begin(); cit0!=last; ++cit0) {
1259                 const ex & r = cit0->rest;
1260                 const ex & c = cit0->coeff;
1261                 
1262                 GINAC_ASSERT(!is_exactly_a<add>(r));
1263                 GINAC_ASSERT(!is_exactly_a<power>(r) ||
1264                              !is_exactly_a<numeric>(ex_to<power>(r).exponent) ||
1265                              !ex_to<numeric>(ex_to<power>(r).exponent).is_pos_integer() ||
1266                              !is_exactly_a<add>(ex_to<power>(r).basis) ||
1267                              !is_exactly_a<mul>(ex_to<power>(r).basis) ||
1268                              !is_exactly_a<power>(ex_to<power>(r).basis));
1269                 
1270                 if (c.is_equal(_ex1)) {
1271                         if (is_exactly_a<mul>(r)) {
1272                                 result.push_back(expair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
1273                                                         _ex1));
1274                         } else {
1275                                 result.push_back(expair(dynallocate<power>(r, _ex2),
1276                                                         _ex1));
1277                         }
1278                 } else {
1279                         if (is_exactly_a<mul>(r)) {
1280                                 result.push_back(expair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
1281                                                         ex_to<numeric>(c).power_dyn(*_num2_p)));
1282                         } else {
1283                                 result.push_back(expair(dynallocate<power>(r, _ex2),
1284                                                         ex_to<numeric>(c).power_dyn(*_num2_p)));
1285                         }
1286                 }
1287
1288                 for (epvector::const_iterator cit1=cit0+1; cit1!=last; ++cit1) {
1289                         const ex & r1 = cit1->rest;
1290                         const ex & c1 = cit1->coeff;
1291                         result.push_back(expair(mul(r,r1).expand(options),
1292                                                 _num2_p->mul(ex_to<numeric>(c)).mul_dyn(ex_to<numeric>(c1))));
1293                 }
1294         }
1295         
1296         // second part: add terms coming from overall_coeff (if != 0)
1297         if (!a.overall_coeff.is_zero()) {
1298                 for (auto & i : a.seq)
1299                         result.push_back(a.combine_pair_with_coeff_to_pair(i, ex_to<numeric>(a.overall_coeff).mul_dyn(*_num2_p)));
1300         }
1301
1302         GINAC_ASSERT(result.size() == result_size);
1303
1304         if (a.overall_coeff.is_zero()) {
1305                 return dynallocate<add>(std::move(result)).setflag(status_flags::expanded);
1306         } else {
1307                 return dynallocate<add>(std::move(result), ex_to<numeric>(a.overall_coeff).power(2)).setflag(status_flags::expanded);
1308         }
1309 }
1310
1311 /** Expand factors of m in m^n where m is a mul and n is an integer.
1312  *  @see power::expand */
1313 ex power::expand_mul(const mul & m, const numeric & n, unsigned options, bool from_expand)
1314 {
1315         GINAC_ASSERT(n.is_integer());
1316
1317         if (n.is_zero()) {
1318                 return _ex1;
1319         }
1320
1321         // do not bother to rename indices if there are no any.
1322         if (!(options & expand_options::expand_rename_idx) &&
1323             m.info(info_flags::has_indices))
1324                 options |= expand_options::expand_rename_idx;
1325         // Leave it to multiplication since dummy indices have to be renamed
1326         if ((options & expand_options::expand_rename_idx) &&
1327             (get_all_dummy_indices(m).size() > 0) && n.is_positive()) {
1328                 ex result = m;
1329                 exvector va = get_all_dummy_indices(m);
1330                 sort(va.begin(), va.end(), ex_is_less());
1331
1332                 for (int i=1; i < n.to_int(); i++)
1333                         result *= rename_dummy_indices_uniquely(va, m);
1334                 return result;
1335         }
1336
1337         epvector distrseq;
1338         distrseq.reserve(m.seq.size());
1339         bool need_reexpand = false;
1340
1341         for (auto & cit : m.seq) {
1342                 expair p = m.combine_pair_with_coeff_to_pair(cit, n);
1343                 if (from_expand && is_exactly_a<add>(cit.rest) && ex_to<numeric>(p.coeff).is_pos_integer()) {
1344                         // this happens when e.g. (a+b)^(1/2) gets squared and
1345                         // the resulting product needs to be reexpanded
1346                         need_reexpand = true;
1347                 }
1348                 distrseq.push_back(p);
1349         }
1350
1351         const mul & result = dynallocate<mul>(std::move(distrseq), ex_to<numeric>(m.overall_coeff).power_dyn(n));
1352         if (need_reexpand)
1353                 return ex(result).expand(options);
1354         if (from_expand)
1355                 return result.setflag(status_flags::expanded);
1356         return result;
1357 }
1358
1359 GINAC_BIND_UNARCHIVER(power);
1360
1361 } // namespace GiNaC