Fix pow(+(...),2).expand().
[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
46 namespace GiNaC {
47
48 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(power, basic,
49   print_func<print_dflt>(&power::do_print_dflt).
50   print_func<print_latex>(&power::do_print_latex).
51   print_func<print_csrc>(&power::do_print_csrc).
52   print_func<print_python>(&power::do_print_python).
53   print_func<print_python_repr>(&power::do_print_python_repr).
54   print_func<print_csrc_cl_N>(&power::do_print_csrc_cl_N))
55
56 typedef std::vector<int> intvector;
57
58 //////////
59 // default constructor
60 //////////
61
62 power::power() { }
63
64 //////////
65 // other constructors
66 //////////
67
68 // all inlined
69
70 //////////
71 // archiving
72 //////////
73
74 void power::read_archive(const archive_node &n, lst &sym_lst)
75 {
76         inherited::read_archive(n, sym_lst);
77         n.find_ex("basis", basis, sym_lst);
78         n.find_ex("exponent", exponent, sym_lst);
79 }
80
81 void power::archive(archive_node &n) const
82 {
83         inherited::archive(n);
84         n.add_ex("basis", basis);
85         n.add_ex("exponent", exponent);
86 }
87
88 //////////
89 // functions overriding virtual functions from base classes
90 //////////
91
92 // public
93
94 void power::print_power(const print_context & c, const char *powersymbol, const char *openbrace, const char *closebrace, unsigned level) const
95 {
96         // Ordinary output of powers using '^' or '**'
97         if (precedence() <= level)
98                 c.s << openbrace << '(';
99         basis.print(c, precedence());
100         c.s << powersymbol;
101         c.s << openbrace;
102         exponent.print(c, precedence());
103         c.s << closebrace;
104         if (precedence() <= level)
105                 c.s << ')' << closebrace;
106 }
107
108 void power::do_print_dflt(const print_dflt & c, unsigned level) const
109 {
110         if (exponent.is_equal(_ex1_2)) {
111
112                 // Square roots are printed in a special way
113                 c.s << "sqrt(";
114                 basis.print(c);
115                 c.s << ')';
116
117         } else
118                 print_power(c, "^", "", "", level);
119 }
120
121 void power::do_print_latex(const print_latex & c, unsigned level) const
122 {
123         if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_negative()) {
124
125                 // Powers with negative numeric exponents are printed as fractions
126                 c.s << "\\frac{1}{";
127                 power(basis, -exponent).eval().print(c);
128                 c.s << '}';
129
130         } else if (exponent.is_equal(_ex1_2)) {
131
132                 // Square roots are printed in a special way
133                 c.s << "\\sqrt{";
134                 basis.print(c);
135                 c.s << '}';
136
137         } else
138                 print_power(c, "^", "{", "}", level);
139 }
140
141 static void print_sym_pow(const print_context & c, const symbol &x, int exp)
142 {
143         // Optimal output of integer powers of symbols to aid compiler CSE.
144         // C.f. ISO/IEC 14882:1998, section 1.9 [intro execution], paragraph 15
145         // to learn why such a parenthesation is really necessary.
146         if (exp == 1) {
147                 x.print(c);
148         } else if (exp == 2) {
149                 x.print(c);
150                 c.s << "*";
151                 x.print(c);
152         } else if (exp & 1) {
153                 x.print(c);
154                 c.s << "*";
155                 print_sym_pow(c, x, exp-1);
156         } else {
157                 c.s << "(";
158                 print_sym_pow(c, x, exp >> 1);
159                 c.s << ")*(";
160                 print_sym_pow(c, x, exp >> 1);
161                 c.s << ")";
162         }
163 }
164
165 void power::do_print_csrc_cl_N(const print_csrc_cl_N& c, unsigned level) const
166 {
167         if (exponent.is_equal(_ex_1)) {
168                 c.s << "recip(";
169                 basis.print(c);
170                 c.s << ')';
171                 return;
172         }
173         c.s << "expt(";
174         basis.print(c);
175         c.s << ", ";
176         exponent.print(c);
177         c.s << ')';
178 }
179
180 void power::do_print_csrc(const print_csrc & c, unsigned level) const
181 {
182         // Integer powers of symbols are printed in a special, optimized way
183         if (exponent.info(info_flags::integer)
184          && (is_a<symbol>(basis) || is_a<constant>(basis))) {
185                 int exp = ex_to<numeric>(exponent).to_int();
186                 if (exp > 0)
187                         c.s << '(';
188                 else {
189                         exp = -exp;
190                         c.s << "1.0/(";
191                 }
192                 print_sym_pow(c, ex_to<symbol>(basis), exp);
193                 c.s << ')';
194
195         // <expr>^-1 is printed as "1.0/<expr>" or with the recip() function of CLN
196         } else if (exponent.is_equal(_ex_1)) {
197                 c.s << "1.0/(";
198                 basis.print(c);
199                 c.s << ')';
200
201         // Otherwise, use the pow() function
202         } else {
203                 c.s << "pow(";
204                 basis.print(c);
205                 c.s << ',';
206                 exponent.print(c);
207                 c.s << ')';
208         }
209 }
210
211 void power::do_print_python(const print_python & c, unsigned level) const
212 {
213         print_power(c, "**", "", "", level);
214 }
215
216 void power::do_print_python_repr(const print_python_repr & c, unsigned level) const
217 {
218         c.s << class_name() << '(';
219         basis.print(c);
220         c.s << ',';
221         exponent.print(c);
222         c.s << ')';
223 }
224
225 bool power::info(unsigned inf) const
226 {
227         switch (inf) {
228                 case info_flags::polynomial:
229                 case info_flags::integer_polynomial:
230                 case info_flags::cinteger_polynomial:
231                 case info_flags::rational_polynomial:
232                 case info_flags::crational_polynomial:
233                         return exponent.info(info_flags::nonnegint) &&
234                                basis.info(inf);
235                 case info_flags::rational_function:
236                         return exponent.info(info_flags::integer) &&
237                                basis.info(inf);
238                 case info_flags::algebraic:
239                         return !exponent.info(info_flags::integer) ||
240                                basis.info(inf);
241                 case info_flags::expanded:
242                         return (flags & status_flags::expanded);
243                 case info_flags::positive:
244                         return basis.info(info_flags::positive) && exponent.info(info_flags::real);
245                 case info_flags::nonnegative:
246                         return (basis.info(info_flags::positive) && exponent.info(info_flags::real)) ||
247                                (basis.info(info_flags::real) && exponent.info(info_flags::integer) && exponent.info(info_flags::even));
248                 case info_flags::has_indices: {
249                         if (flags & status_flags::has_indices)
250                                 return true;
251                         else if (flags & status_flags::has_no_indices)
252                                 return false;
253                         else if (basis.info(info_flags::has_indices)) {
254                                 setflag(status_flags::has_indices);
255                                 clearflag(status_flags::has_no_indices);
256                                 return true;
257                         } else {
258                                 clearflag(status_flags::has_indices);
259                                 setflag(status_flags::has_no_indices);
260                                 return false;
261                         }
262                 }
263         }
264         return inherited::info(inf);
265 }
266
267 size_t power::nops() const
268 {
269         return 2;
270 }
271
272 ex power::op(size_t i) const
273 {
274         GINAC_ASSERT(i<2);
275
276         return i==0 ? basis : exponent;
277 }
278
279 ex power::map(map_function & f) const
280 {
281         const ex &mapped_basis = f(basis);
282         const ex &mapped_exponent = f(exponent);
283
284         if (!are_ex_trivially_equal(basis, mapped_basis)
285          || !are_ex_trivially_equal(exponent, mapped_exponent))
286                 return (new power(mapped_basis, mapped_exponent))->setflag(status_flags::dynallocated);
287         else
288                 return *this;
289 }
290
291 bool power::is_polynomial(const ex & var) const
292 {
293         if (basis.is_polynomial(var)) {
294                 if (basis.has(var))
295                         // basis is non-constant polynomial in var
296                         return exponent.info(info_flags::nonnegint);
297                 else
298                         // basis is constant in var
299                         return !exponent.has(var);
300         }
301         // basis is a non-polynomial function of var
302         return false;
303 }
304
305 int power::degree(const ex & s) const
306 {
307         if (is_equal(ex_to<basic>(s)))
308                 return 1;
309         else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
310                 if (basis.is_equal(s))
311                         return ex_to<numeric>(exponent).to_int();
312                 else
313                         return basis.degree(s) * ex_to<numeric>(exponent).to_int();
314         } else if (basis.has(s))
315                 throw(std::runtime_error("power::degree(): undefined degree because of non-integer exponent"));
316         else
317                 return 0;
318 }
319
320 int power::ldegree(const ex & s) const 
321 {
322         if (is_equal(ex_to<basic>(s)))
323                 return 1;
324         else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
325                 if (basis.is_equal(s))
326                         return ex_to<numeric>(exponent).to_int();
327                 else
328                         return basis.ldegree(s) * ex_to<numeric>(exponent).to_int();
329         } else if (basis.has(s))
330                 throw(std::runtime_error("power::ldegree(): undefined degree because of non-integer exponent"));
331         else
332                 return 0;
333 }
334
335 ex power::coeff(const ex & s, int n) const
336 {
337         if (is_equal(ex_to<basic>(s)))
338                 return n==1 ? _ex1 : _ex0;
339         else if (!basis.is_equal(s)) {
340                 // basis not equal to s
341                 if (n == 0)
342                         return *this;
343                 else
344                         return _ex0;
345         } else {
346                 // basis equal to s
347                 if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
348                         // integer exponent
349                         int int_exp = ex_to<numeric>(exponent).to_int();
350                         if (n == int_exp)
351                                 return _ex1;
352                         else
353                                 return _ex0;
354                 } else {
355                         // non-integer exponents are treated as zero
356                         if (n == 0)
357                                 return *this;
358                         else
359                                 return _ex0;
360                 }
361         }
362 }
363
364 /** Perform automatic term rewriting rules in this class.  In the following
365  *  x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
366  *  stand for such expressions that contain a plain number.
367  *  - ^(x,0) -> 1  (also handles ^(0,0))
368  *  - ^(x,1) -> x
369  *  - ^(0,c) -> 0 or exception  (depending on the real part of c)
370  *  - ^(1,x) -> 1
371  *  - ^(c1,c2) -> *(c1^n,c1^(c2-n))  (so that 0<(c2-n)<1, try to evaluate roots, possibly in numerator and denominator of c1)
372  *  - ^(^(x,c1),c2) -> ^(x,c1*c2)  if x is positive and c1 is real.
373  *  - ^(^(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!)
374  *  - ^(*(x,y,z),c) -> *(x^c,y^c,z^c)  (if c integer)
375  *  - ^(*(x,c1),c2) -> ^(x,c2)*c1^c2  (c1>0)
376  *  - ^(*(x,c1),c2) -> ^(-x,c2)*c1^c2  (c1<0)
377  *
378  *  @param level cut-off in recursive evaluation */
379 ex power::eval(int level) const
380 {
381         if ((level==1) && (flags & status_flags::evaluated))
382                 return *this;
383         else if (level == -max_recursion_level)
384                 throw(std::runtime_error("max recursion level reached"));
385         
386         const ex & ebasis    = level==1 ? basis    : basis.eval(level-1);
387         const ex & eexponent = level==1 ? exponent : exponent.eval(level-1);
388         
389         const numeric *num_basis = NULL;
390         const numeric *num_exponent = NULL;
391         
392         if (is_exactly_a<numeric>(ebasis)) {
393                 num_basis = &ex_to<numeric>(ebasis);
394         }
395         if (is_exactly_a<numeric>(eexponent)) {
396                 num_exponent = &ex_to<numeric>(eexponent);
397         }
398         
399         // ^(x,0) -> 1  (0^0 also handled here)
400         if (eexponent.is_zero()) {
401                 if (ebasis.is_zero())
402                         throw (std::domain_error("power::eval(): pow(0,0) is undefined"));
403                 else
404                         return _ex1;
405         }
406         
407         // ^(x,1) -> x
408         if (eexponent.is_equal(_ex1))
409                 return ebasis;
410
411         // ^(0,c1) -> 0 or exception  (depending on real value of c1)
412         if ( ebasis.is_zero() && num_exponent ) {
413                 if ((num_exponent->real()).is_zero())
414                         throw (std::domain_error("power::eval(): pow(0,I) is undefined"));
415                 else if ((num_exponent->real()).is_negative())
416                         throw (pole_error("power::eval(): division by zero",1));
417                 else
418                         return _ex0;
419         }
420
421         // ^(1,x) -> 1
422         if (ebasis.is_equal(_ex1))
423                 return _ex1;
424
425         // power of a function calculated by separate rules defined for this function
426         if (is_exactly_a<function>(ebasis))
427                 return ex_to<function>(ebasis).power(eexponent);
428
429         // Turn (x^c)^d into x^(c*d) in the case that x is positive and c is real.
430         if (is_exactly_a<power>(ebasis) && ebasis.op(0).info(info_flags::positive) && ebasis.op(1).info(info_flags::real))
431                 return power(ebasis.op(0), ebasis.op(1) * eexponent);
432
433         if ( num_exponent ) {
434
435                 // ^(c1,c2) -> c1^c2  (c1, c2 numeric(),
436                 // except if c1,c2 are rational, but c1^c2 is not)
437                 if ( num_basis ) {
438                         const bool basis_is_crational = num_basis->is_crational();
439                         const bool exponent_is_crational = num_exponent->is_crational();
440                         if (!basis_is_crational || !exponent_is_crational) {
441                                 // return a plain float
442                                 return (new numeric(num_basis->power(*num_exponent)))->setflag(status_flags::dynallocated |
443                                                                                                status_flags::evaluated |
444                                                                                                status_flags::expanded);
445                         }
446
447                         const numeric res = num_basis->power(*num_exponent);
448                         if (res.is_crational()) {
449                                 return res;
450                         }
451                         GINAC_ASSERT(!num_exponent->is_integer());  // has been handled by now
452
453                         // ^(c1,n/m) -> *(c1^q,c1^(n/m-q)), 0<(n/m-q)<1, q integer
454                         if (basis_is_crational && exponent_is_crational
455                             && num_exponent->is_real()
456                             && !num_exponent->is_integer()) {
457                                 const numeric n = num_exponent->numer();
458                                 const numeric m = num_exponent->denom();
459                                 numeric r;
460                                 numeric q = iquo(n, m, r);
461                                 if (r.is_negative()) {
462                                         r += m;
463                                         --q;
464                                 }
465                                 if (q.is_zero()) {  // the exponent was in the allowed range 0<(n/m)<1
466                                         if (num_basis->is_rational() && !num_basis->is_integer()) {
467                                                 // try it for numerator and denominator separately, in order to
468                                                 // partially simplify things like (5/8)^(1/3) -> 1/2*5^(1/3)
469                                                 const numeric bnum = num_basis->numer();
470                                                 const numeric bden = num_basis->denom();
471                                                 const numeric res_bnum = bnum.power(*num_exponent);
472                                                 const numeric res_bden = bden.power(*num_exponent);
473                                                 if (res_bnum.is_integer())
474                                                         return (new mul(power(bden,-*num_exponent),res_bnum))->setflag(status_flags::dynallocated | status_flags::evaluated);
475                                                 if (res_bden.is_integer())
476                                                         return (new mul(power(bnum,*num_exponent),res_bden.inverse()))->setflag(status_flags::dynallocated | status_flags::evaluated);
477                                         }
478                                         return this->hold();
479                                 } else {
480                                         // assemble resulting product, but allowing for a re-evaluation,
481                                         // because otherwise we'll end up with something like
482                                         //    (7/8)^(4/3)  ->  7/8*(1/2*7^(1/3))
483                                         // instead of 7/16*7^(1/3).
484                                         ex prod = power(*num_basis,r.div(m));
485                                         return prod*power(*num_basis,q);
486                                 }
487                         }
488                 }
489         
490                 // ^(^(x,c1),c2) -> ^(x,c1*c2)
491                 // (c1, c2 numeric(), c2 integer or -1 < c1 <= 1 or (c1=-1 and c2>0),
492                 // case c1==1 should not happen, see below!)
493                 if (is_exactly_a<power>(ebasis)) {
494                         const power & sub_power = ex_to<power>(ebasis);
495                         const ex & sub_basis = sub_power.basis;
496                         const ex & sub_exponent = sub_power.exponent;
497                         if (is_exactly_a<numeric>(sub_exponent)) {
498                                 const numeric & num_sub_exponent = ex_to<numeric>(sub_exponent);
499                                 GINAC_ASSERT(num_sub_exponent!=numeric(1));
500                                 if (num_exponent->is_integer() || (abs(num_sub_exponent) - (*_num1_p)).is_negative() 
501                                                 || (num_sub_exponent == *_num_1_p && num_exponent->is_positive())) {
502                                         return power(sub_basis,num_sub_exponent.mul(*num_exponent));
503                                 }
504                         }
505                 }
506         
507                 // ^(*(x,y,z),c1) -> *(x^c1,y^c1,z^c1) (c1 integer)
508                 if (num_exponent->is_integer() && is_exactly_a<mul>(ebasis)) {
509                         return expand_mul(ex_to<mul>(ebasis), *num_exponent, 0);
510                 }
511
512                 // (2*x + 6*y)^(-4) -> 1/16*(x + 3*y)^(-4)
513                 if (num_exponent->is_integer() && is_exactly_a<add>(ebasis)) {
514                         numeric icont = ebasis.integer_content();
515                         const numeric lead_coeff = 
516                                 ex_to<numeric>(ex_to<add>(ebasis).seq.begin()->coeff).div(icont);
517
518                         const bool canonicalizable = lead_coeff.is_integer();
519                         const bool unit_normal = lead_coeff.is_pos_integer();
520                         if (canonicalizable && (! unit_normal))
521                                 icont = icont.mul(*_num_1_p);
522                         
523                         if (canonicalizable && (icont != *_num1_p)) {
524                                 const add& addref = ex_to<add>(ebasis);
525                                 add* addp = new add(addref);
526                                 addp->setflag(status_flags::dynallocated);
527                                 addp->clearflag(status_flags::hash_calculated);
528                                 addp->overall_coeff = ex_to<numeric>(addp->overall_coeff).div_dyn(icont);
529                                 for (epvector::iterator i = addp->seq.begin(); i != addp->seq.end(); ++i)
530                                         i->coeff = ex_to<numeric>(i->coeff).div_dyn(icont);
531
532                                 const numeric c = icont.power(*num_exponent);
533                                 if (likely(c != *_num1_p))
534                                         return (new mul(power(*addp, *num_exponent), c))->setflag(status_flags::dynallocated);
535                                 else
536                                         return power(*addp, *num_exponent);
537                         }
538                 }
539
540                 // ^(*(...,x;c1),c2) -> *(^(*(...,x;1),c2),c1^c2)  (c1, c2 numeric(), c1>0)
541                 // ^(*(...,x;c1),c2) -> *(^(*(...,x;-1),c2),(-c1)^c2)  (c1, c2 numeric(), c1<0)
542                 if (is_exactly_a<mul>(ebasis)) {
543                         GINAC_ASSERT(!num_exponent->is_integer()); // should have been handled above
544                         const mul & mulref = ex_to<mul>(ebasis);
545                         if (!mulref.overall_coeff.is_equal(_ex1)) {
546                                 const numeric & num_coeff = ex_to<numeric>(mulref.overall_coeff);
547                                 if (num_coeff.is_real()) {
548                                         if (num_coeff.is_positive()) {
549                                                 mul *mulp = new mul(mulref);
550                                                 mulp->overall_coeff = _ex1;
551                                                 mulp->setflag(status_flags::dynallocated);
552                                                 mulp->clearflag(status_flags::evaluated);
553                                                 mulp->clearflag(status_flags::hash_calculated);
554                                                 return (new mul(power(*mulp,exponent),
555                                                                 power(num_coeff,*num_exponent)))->setflag(status_flags::dynallocated);
556                                         } else {
557                                                 GINAC_ASSERT(num_coeff.compare(*_num0_p)<0);
558                                                 if (!num_coeff.is_equal(*_num_1_p)) {
559                                                         mul *mulp = new mul(mulref);
560                                                         mulp->overall_coeff = _ex_1;
561                                                         mulp->setflag(status_flags::dynallocated);
562                                                         mulp->clearflag(status_flags::evaluated);
563                                                         mulp->clearflag(status_flags::hash_calculated);
564                                                         return (new mul(power(*mulp,exponent),
565                                                                         power(abs(num_coeff),*num_exponent)))->setflag(status_flags::dynallocated);
566                                                 }
567                                         }
568                                 }
569                         }
570                 }
571
572                 // ^(nc,c1) -> ncmul(nc,nc,...) (c1 positive integer, unless nc is a matrix)
573                 if (num_exponent->is_pos_integer() &&
574                     ebasis.return_type() != return_types::commutative &&
575                     !is_a<matrix>(ebasis)) {
576                         return ncmul(exvector(num_exponent->to_int(), ebasis), true);
577                 }
578         }
579         
580         if (are_ex_trivially_equal(ebasis,basis) &&
581             are_ex_trivially_equal(eexponent,exponent)) {
582                 return this->hold();
583         }
584         return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated |
585                                                        status_flags::evaluated);
586 }
587
588 ex power::evalf(int level) const
589 {
590         ex ebasis;
591         ex eexponent;
592         
593         if (level==1) {
594                 ebasis = basis;
595                 eexponent = exponent;
596         } else if (level == -max_recursion_level) {
597                 throw(std::runtime_error("max recursion level reached"));
598         } else {
599                 ebasis = basis.evalf(level-1);
600                 if (!is_exactly_a<numeric>(exponent))
601                         eexponent = exponent.evalf(level-1);
602                 else
603                         eexponent = exponent;
604         }
605
606         return power(ebasis,eexponent);
607 }
608
609 ex power::evalm() const
610 {
611         const ex ebasis = basis.evalm();
612         const ex eexponent = exponent.evalm();
613         if (is_a<matrix>(ebasis)) {
614                 if (is_exactly_a<numeric>(eexponent)) {
615                         return (new matrix(ex_to<matrix>(ebasis).pow(eexponent)))->setflag(status_flags::dynallocated);
616                 }
617         }
618         return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated);
619 }
620
621 bool power::has(const ex & other, unsigned options) const
622 {
623         if (!(options & has_options::algebraic))
624                 return basic::has(other, options);
625         if (!is_a<power>(other))
626                 return basic::has(other, options);
627         if (!exponent.info(info_flags::integer)
628                         || !other.op(1).info(info_flags::integer))
629                 return basic::has(other, options);
630         if (exponent.info(info_flags::posint)
631                         && other.op(1).info(info_flags::posint)
632                         && ex_to<numeric>(exponent).to_int()
633                                         > ex_to<numeric>(other.op(1)).to_int()
634                         && basis.match(other.op(0)))
635                 return true;
636         if (exponent.info(info_flags::negint)
637                         && other.op(1).info(info_flags::negint)
638                         && ex_to<numeric>(exponent).to_int()
639                                         < ex_to<numeric>(other.op(1)).to_int()
640                         && basis.match(other.op(0)))
641                 return true;
642         return basic::has(other, options);
643 }
644
645 // from mul.cpp
646 extern bool tryfactsubs(const ex &, const ex &, int &, exmap&);
647
648 ex power::subs(const exmap & m, unsigned options) const
649 {       
650         const ex &subsed_basis = basis.subs(m, options);
651         const ex &subsed_exponent = exponent.subs(m, options);
652
653         if (!are_ex_trivially_equal(basis, subsed_basis)
654          || !are_ex_trivially_equal(exponent, subsed_exponent)) 
655                 return power(subsed_basis, subsed_exponent).subs_one_level(m, options);
656
657         if (!(options & subs_options::algebraic))
658                 return subs_one_level(m, options);
659
660         for (exmap::const_iterator it = m.begin(); it != m.end(); ++it) {
661                 int nummatches = std::numeric_limits<int>::max();
662                 exmap repls;
663                 if (tryfactsubs(*this, it->first, nummatches, repls)) {
664                         ex anum = it->second.subs(repls, subs_options::no_pattern);
665                         ex aden = it->first.subs(repls, subs_options::no_pattern);
666                         ex result = (*this)*power(anum/aden, nummatches);
667                         return (ex_to<basic>(result)).subs_one_level(m, options);
668                 }
669         }
670
671         return subs_one_level(m, options);
672 }
673
674 ex power::eval_ncmul(const exvector & v) const
675 {
676         return inherited::eval_ncmul(v);
677 }
678
679 ex power::conjugate() const
680 {
681         // conjugate(pow(x,y))==pow(conjugate(x),conjugate(y)) unless on the
682         // branch cut which runs along the negative real axis.
683         if (basis.info(info_flags::positive)) {
684                 ex newexponent = exponent.conjugate();
685                 if (are_ex_trivially_equal(exponent, newexponent)) {
686                         return *this;
687                 }
688                 return (new power(basis, newexponent))->setflag(status_flags::dynallocated);
689         }
690         if (exponent.info(info_flags::integer)) {
691                 ex newbasis = basis.conjugate();
692                 if (are_ex_trivially_equal(basis, newbasis)) {
693                         return *this;
694                 }
695                 return (new power(newbasis, exponent))->setflag(status_flags::dynallocated);
696         }
697         return conjugate_function(*this).hold();
698 }
699
700 ex power::real_part() const
701 {
702         if (exponent.info(info_flags::integer)) {
703                 ex basis_real = basis.real_part();
704                 if (basis_real == basis)
705                         return *this;
706                 realsymbol a("a"),b("b");
707                 ex result;
708                 if (exponent.info(info_flags::posint))
709                         result = power(a+I*b,exponent);
710                 else
711                         result = power(a/(a*a+b*b)-I*b/(a*a+b*b),-exponent);
712                 result = result.expand();
713                 result = result.real_part();
714                 result = result.subs(lst( a==basis_real, b==basis.imag_part() ));
715                 return result;
716         }
717         
718         ex a = basis.real_part();
719         ex b = basis.imag_part();
720         ex c = exponent.real_part();
721         ex d = exponent.imag_part();
722         return power(abs(basis),c)*exp(-d*atan2(b,a))*cos(c*atan2(b,a)+d*log(abs(basis)));
723 }
724
725 ex power::imag_part() const
726 {
727         if (exponent.info(info_flags::integer)) {
728                 ex basis_real = basis.real_part();
729                 if (basis_real == basis)
730                         return 0;
731                 realsymbol a("a"),b("b");
732                 ex result;
733                 if (exponent.info(info_flags::posint))
734                         result = power(a+I*b,exponent);
735                 else
736                         result = power(a/(a*a+b*b)-I*b/(a*a+b*b),-exponent);
737                 result = result.expand();
738                 result = result.imag_part();
739                 result = result.subs(lst( a==basis_real, b==basis.imag_part() ));
740                 return result;
741         }
742         
743         ex a=basis.real_part();
744         ex b=basis.imag_part();
745         ex c=exponent.real_part();
746         ex d=exponent.imag_part();
747         return power(abs(basis),c)*exp(-d*atan2(b,a))*sin(c*atan2(b,a)+d*log(abs(basis)));
748 }
749
750 // protected
751
752 // protected
753
754 /** Implementation of ex::diff() for a power.
755  *  @see ex::diff */
756 ex power::derivative(const symbol & s) const
757 {
758         if (is_a<numeric>(exponent)) {
759                 // D(b^r) = r * b^(r-1) * D(b) (faster than the formula below)
760                 epvector newseq;
761                 newseq.reserve(2);
762                 newseq.push_back(expair(basis, exponent - _ex1));
763                 newseq.push_back(expair(basis.diff(s), _ex1));
764                 return mul(newseq, exponent);
765         } else {
766                 // D(b^e) = b^e * (D(e)*ln(b) + e*D(b)/b)
767                 return mul(*this,
768                            add(mul(exponent.diff(s), log(basis)),
769                            mul(mul(exponent, basis.diff(s)), power(basis, _ex_1))));
770         }
771 }
772
773 int power::compare_same_type(const basic & other) const
774 {
775         GINAC_ASSERT(is_exactly_a<power>(other));
776         const power &o = static_cast<const power &>(other);
777
778         int cmpval = basis.compare(o.basis);
779         if (cmpval)
780                 return cmpval;
781         else
782                 return exponent.compare(o.exponent);
783 }
784
785 unsigned power::return_type() const
786 {
787         return basis.return_type();
788 }
789
790 return_type_t power::return_type_tinfo() const
791 {
792         return basis.return_type_tinfo();
793 }
794
795 ex power::expand(unsigned options) const
796 {
797         if (is_a<symbol>(basis) && exponent.info(info_flags::integer)) {
798                 // A special case worth optimizing.
799                 setflag(status_flags::expanded);
800                 return *this;
801         }
802
803         // (x*p)^c -> x^c * p^c, if p>0
804         // makes sense before expanding the basis
805         if (is_exactly_a<mul>(basis) && !basis.info(info_flags::indefinite)) {
806                 const mul &m = ex_to<mul>(basis);
807                 exvector prodseq;
808                 epvector powseq;
809                 prodseq.reserve(m.seq.size() + 1);
810                 powseq.reserve(m.seq.size() + 1);
811                 epvector::const_iterator last = m.seq.end();
812                 epvector::const_iterator cit = m.seq.begin();
813                 bool possign = true;
814
815                 // search for positive/negative factors
816                 while (cit!=last) {
817                         ex e=m.recombine_pair_to_ex(*cit);
818                         if (e.info(info_flags::positive))
819                                 prodseq.push_back(pow(e, exponent).expand(options));
820                         else if (e.info(info_flags::negative)) {
821                                 prodseq.push_back(pow(-e, exponent).expand(options));
822                                 possign = !possign;
823                         } else
824                                 powseq.push_back(*cit);
825                         ++cit;
826                 }
827
828                 // take care on the numeric coefficient
829                 ex coeff=(possign? _ex1 : _ex_1);
830                 if (m.overall_coeff.info(info_flags::positive) && m.overall_coeff != _ex1)
831                         prodseq.push_back(power(m.overall_coeff, exponent));
832                 else if (m.overall_coeff.info(info_flags::negative) && m.overall_coeff != _ex_1)
833                         prodseq.push_back(power(-m.overall_coeff, exponent));
834                 else
835                         coeff *= m.overall_coeff;
836
837                 // If positive/negative factors are found, then extract them.
838                 // In either case we set a flag to avoid the second run on a part
839                 // which does not have positive/negative terms.
840                 if (prodseq.size() > 0) {
841                         ex newbasis = coeff*mul(powseq);
842                         ex_to<basic>(newbasis).setflag(status_flags::purely_indefinite);
843                         return ((new mul(prodseq))->setflag(status_flags::dynallocated)*(new power(newbasis, exponent))->setflag(status_flags::dynallocated).expand(options)).expand(options);
844                 } else
845                         ex_to<basic>(basis).setflag(status_flags::purely_indefinite);
846         }
847
848         const ex expanded_basis = basis.expand(options);
849         const ex expanded_exponent = exponent.expand(options);
850         
851         // x^(a+b) -> x^a * x^b
852         if (is_exactly_a<add>(expanded_exponent)) {
853                 const add &a = ex_to<add>(expanded_exponent);
854                 exvector distrseq;
855                 distrseq.reserve(a.seq.size() + 1);
856                 epvector::const_iterator last = a.seq.end();
857                 epvector::const_iterator cit = a.seq.begin();
858                 while (cit!=last) {
859                         distrseq.push_back(power(expanded_basis, a.recombine_pair_to_ex(*cit)));
860                         ++cit;
861                 }
862                 
863                 // Make sure that e.g. (x+y)^(2+a) expands the (x+y)^2 factor
864                 if (ex_to<numeric>(a.overall_coeff).is_integer()) {
865                         const numeric &num_exponent = ex_to<numeric>(a.overall_coeff);
866                         int int_exponent = num_exponent.to_int();
867                         if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
868                                 distrseq.push_back(expand_add(ex_to<add>(expanded_basis), int_exponent, options));
869                         else
870                                 distrseq.push_back(power(expanded_basis, a.overall_coeff));
871                 } else
872                         distrseq.push_back(power(expanded_basis, a.overall_coeff));
873                 
874                 // Make sure that e.g. (x+y)^(1+a) -> x*(x+y)^a + y*(x+y)^a
875                 ex r = (new mul(distrseq))->setflag(status_flags::dynallocated);
876                 return r.expand(options);
877         }
878         
879         if (!is_exactly_a<numeric>(expanded_exponent) ||
880                 !ex_to<numeric>(expanded_exponent).is_integer()) {
881                 if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent)) {
882                         return this->hold();
883                 } else {
884                         return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
885                 }
886         }
887         
888         // integer numeric exponent
889         const numeric & num_exponent = ex_to<numeric>(expanded_exponent);
890         int int_exponent = num_exponent.to_int();
891         
892         // (x+y)^n, n>0
893         if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
894                 return expand_add(ex_to<add>(expanded_basis), int_exponent, options);
895         
896         // (x*y)^n -> x^n * y^n
897         if (is_exactly_a<mul>(expanded_basis))
898                 return expand_mul(ex_to<mul>(expanded_basis), num_exponent, options, true);
899         
900         // cannot expand further
901         if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent))
902                 return this->hold();
903         else
904                 return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
905 }
906
907 //////////
908 // new virtual functions which can be overridden by derived classes
909 //////////
910
911 // none
912
913 //////////
914 // non-virtual functions in this class
915 //////////
916
917 /** expand a^n where a is an add and n is a positive integer.
918  *  @see power::expand */
919 ex power::expand_add(const add & a, int n, unsigned options) const
920 {
921         if (n==2)
922                 return expand_add_2(a, options);
923
924         const size_t m = a.nops();
925         exvector result;
926         // The number of terms will be the number of combinatorial compositions,
927         // i.e. the number of unordered arrangements of m nonnegative integers
928         // which sum up to n.  It is frequently written as C_n(m) and directly
929         // related with binomial coefficients:
930         result.reserve(binomial(numeric(n+m-1), numeric(m-1)).to_int());
931         intvector k(m-1);
932         intvector k_cum(m-1); // k_cum[l]:=sum(i=0,l,k[l]);
933         intvector upper_limit(m-1);
934
935         for (size_t l=0; l<m-1; ++l) {
936                 k[l] = 0;
937                 k_cum[l] = 0;
938                 upper_limit[l] = n;
939         }
940
941         while (true) {
942                 exvector term;
943                 term.reserve(m+1);
944                 for (std::size_t l = 0; l < m - 1; ++l) {
945                         const ex & b = a.op(l);
946                         GINAC_ASSERT(!is_exactly_a<add>(b));
947                         GINAC_ASSERT(!is_exactly_a<power>(b) ||
948                                      !is_exactly_a<numeric>(ex_to<power>(b).exponent) ||
949                                      !ex_to<numeric>(ex_to<power>(b).exponent).is_pos_integer() ||
950                                      !is_exactly_a<add>(ex_to<power>(b).basis) ||
951                                      !is_exactly_a<mul>(ex_to<power>(b).basis) ||
952                                      !is_exactly_a<power>(ex_to<power>(b).basis));
953                         if (is_exactly_a<mul>(b))
954                                 term.push_back(expand_mul(ex_to<mul>(b), numeric(k[l]), options, true));
955                         else
956                                 term.push_back(power(b,k[l]));
957                 }
958
959                 const ex & b = a.op(m - 1);
960                 GINAC_ASSERT(!is_exactly_a<add>(b));
961                 GINAC_ASSERT(!is_exactly_a<power>(b) ||
962                              !is_exactly_a<numeric>(ex_to<power>(b).exponent) ||
963                              !ex_to<numeric>(ex_to<power>(b).exponent).is_pos_integer() ||
964                              !is_exactly_a<add>(ex_to<power>(b).basis) ||
965                              !is_exactly_a<mul>(ex_to<power>(b).basis) ||
966                              !is_exactly_a<power>(ex_to<power>(b).basis));
967                 if (is_exactly_a<mul>(b))
968                         term.push_back(expand_mul(ex_to<mul>(b), numeric(n-k_cum[m-2]), options, true));
969                 else
970                         term.push_back(power(b,n-k_cum[m-2]));
971
972                 numeric f = binomial(numeric(n),numeric(k[0]));
973                 for (std::size_t l = 1; l < m - 1; ++l)
974                         f *= binomial(numeric(n-k_cum[l-1]),numeric(k[l]));
975
976                 term.push_back(f);
977
978                 result.push_back(ex((new mul(term))->setflag(status_flags::dynallocated)).expand(options));
979
980                 // increment k[]
981                 bool done = false;
982                 std::size_t l = m - 2;
983                 while ((++k[l]) > upper_limit[l]) {
984                         k[l] = 0;
985                         if (l != 0)
986                                 --l;
987                         else {
988                                 done = true;
989                                 break;
990                         }
991                 }
992                 if (done)
993                         break;
994
995                 // recalc k_cum[] and upper_limit[]
996                 k_cum[l] = (l==0 ? k[0] : k_cum[l-1]+k[l]);
997
998                 for (size_t i=l+1; i<m-1; ++i)
999                         k_cum[i] = k_cum[i-1]+k[i];
1000
1001                 for (size_t i=l+1; i<m-1; ++i)
1002                         upper_limit[i] = n-k_cum[i-1];
1003         }
1004
1005         return (new add(result))->setflag(status_flags::dynallocated |
1006                                           status_flags::expanded);
1007 }
1008
1009
1010 /** Special case of power::expand_add. Expands a^2 where a is an add.
1011  *  @see power::expand_add */
1012 ex power::expand_add_2(const add & a, unsigned options) const
1013 {
1014         epvector sum;
1015         size_t a_nops = a.nops();
1016         sum.reserve((a_nops*(a_nops+1))/2);
1017         epvector::const_iterator last = a.seq.end();
1018
1019         // power(+(x,...,z;c),2)=power(+(x,...,z;0),2)+2*c*+(x,...,z;0)+c*c
1020         // first part: ignore overall_coeff and expand other terms
1021         for (epvector::const_iterator cit0=a.seq.begin(); cit0!=last; ++cit0) {
1022                 const ex & r = cit0->rest;
1023                 const ex & c = cit0->coeff;
1024                 
1025                 GINAC_ASSERT(!is_exactly_a<add>(r));
1026                 GINAC_ASSERT(!is_exactly_a<power>(r) ||
1027                              !is_exactly_a<numeric>(ex_to<power>(r).exponent) ||
1028                              !ex_to<numeric>(ex_to<power>(r).exponent).is_pos_integer() ||
1029                              !is_exactly_a<add>(ex_to<power>(r).basis) ||
1030                              !is_exactly_a<mul>(ex_to<power>(r).basis) ||
1031                              !is_exactly_a<power>(ex_to<power>(r).basis));
1032                 
1033                 if (c.is_equal(_ex1)) {
1034                         if (is_exactly_a<mul>(r)) {
1035                                 sum.push_back(a.combine_ex_with_coeff_to_pair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
1036                                                                               _ex1));
1037                         } else {
1038                                 sum.push_back(a.combine_ex_with_coeff_to_pair((new power(r,_ex2))->setflag(status_flags::dynallocated),
1039                                                                               _ex1));
1040                         }
1041                 } else {
1042                         if (is_exactly_a<mul>(r)) {
1043                                 sum.push_back(a.combine_ex_with_coeff_to_pair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
1044                                                      ex_to<numeric>(c).power_dyn(*_num2_p)));
1045                         } else {
1046                                 sum.push_back(a.combine_ex_with_coeff_to_pair((new power(r,_ex2))->setflag(status_flags::dynallocated),
1047                                                      ex_to<numeric>(c).power_dyn(*_num2_p)));
1048                         }
1049                 }
1050
1051                 for (epvector::const_iterator cit1=cit0+1; cit1!=last; ++cit1) {
1052                         const ex & r1 = cit1->rest;
1053                         const ex & c1 = cit1->coeff;
1054                         sum.push_back(a.combine_ex_with_coeff_to_pair((new mul(r,r1))->setflag(status_flags::dynallocated),
1055                                                                       _num2_p->mul(ex_to<numeric>(c)).mul_dyn(ex_to<numeric>(c1))));
1056                 }
1057         }
1058         
1059         GINAC_ASSERT(sum.size()==(a.seq.size()*(a.seq.size()+1))/2);
1060         
1061         // second part: add terms coming from overall_factor (if != 0)
1062         if (!a.overall_coeff.is_zero()) {
1063                 epvector::const_iterator i = a.seq.begin(), end = a.seq.end();
1064                 while (i != end) {
1065                         sum.push_back(a.combine_pair_with_coeff_to_pair(*i, ex_to<numeric>(a.overall_coeff).mul_dyn(*_num2_p)));
1066                         ++i;
1067                 }
1068                 sum.push_back(expair(ex_to<numeric>(a.overall_coeff).power_dyn(*_num2_p),_ex1));
1069         }
1070         
1071         GINAC_ASSERT(sum.size()==(a_nops*(a_nops+1))/2);
1072         
1073         return (new add(sum))->setflag(status_flags::dynallocated | status_flags::expanded);
1074 }
1075
1076 /** Expand factors of m in m^n where m is a mul and n is an integer.
1077  *  @see power::expand */
1078 ex power::expand_mul(const mul & m, const numeric & n, unsigned options, bool from_expand) const
1079 {
1080         GINAC_ASSERT(n.is_integer());
1081
1082         if (n.is_zero()) {
1083                 return _ex1;
1084         }
1085
1086         // do not bother to rename indices if there are no any.
1087         if ((!(options & expand_options::expand_rename_idx)) 
1088                         && m.info(info_flags::has_indices))
1089                 options |= expand_options::expand_rename_idx;
1090         // Leave it to multiplication since dummy indices have to be renamed
1091         if ((options & expand_options::expand_rename_idx) &&
1092                 (get_all_dummy_indices(m).size() > 0) && n.is_positive()) {
1093                 ex result = m;
1094                 exvector va = get_all_dummy_indices(m);
1095                 sort(va.begin(), va.end(), ex_is_less());
1096
1097                 for (int i=1; i < n.to_int(); i++)
1098                         result *= rename_dummy_indices_uniquely(va, m);
1099                 return result;
1100         }
1101
1102         epvector distrseq;
1103         distrseq.reserve(m.seq.size());
1104         bool need_reexpand = false;
1105
1106         epvector::const_iterator last = m.seq.end();
1107         epvector::const_iterator cit = m.seq.begin();
1108         while (cit!=last) {
1109                 expair p = m.combine_pair_with_coeff_to_pair(*cit, n);
1110                 if (from_expand && is_exactly_a<add>(cit->rest) && ex_to<numeric>(p.coeff).is_pos_integer()) {
1111                         // this happens when e.g. (a+b)^(1/2) gets squared and
1112                         // the resulting product needs to be reexpanded
1113                         need_reexpand = true;
1114                 }
1115                 distrseq.push_back(p);
1116                 ++cit;
1117         }
1118
1119         const mul & result = static_cast<const mul &>((new mul(distrseq, ex_to<numeric>(m.overall_coeff).power_dyn(n)))->setflag(status_flags::dynallocated));
1120         if (need_reexpand)
1121                 return ex(result).expand(options);
1122         if (from_expand)
1123                 return result.setflag(status_flags::expanded);
1124         return result;
1125 }
1126
1127 GINAC_BIND_UNARCHIVER(power);
1128
1129 } // namespace GiNaC