]> www.ginac.de Git - ginac.git/blob - ginac/power.cpp
Synced to HEAD:
[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-2007 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 <vector>
24 #include <iostream>
25 #include <stdexcept>
26 #include <limits>
27
28 #include "power.h"
29 #include "expairseq.h"
30 #include "add.h"
31 #include "mul.h"
32 #include "ncmul.h"
33 #include "numeric.h"
34 #include "constant.h"
35 #include "operators.h"
36 #include "inifcns.h" // for log() in power::derivative()
37 #include "matrix.h"
38 #include "indexed.h"
39 #include "symbol.h"
40 #include "lst.h"
41 #include "archive.h"
42 #include "utils.h"
43 #include "relational.h"
44 #include "compiler.h"
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
55 typedef std::vector<int> intvector;
56
57 //////////
58 // default constructor
59 //////////
60
61 power::power() : inherited(&power::tinfo_static) { }
62
63 //////////
64 // other constructors
65 //////////
66
67 // all inlined
68
69 //////////
70 // archiving
71 //////////
72
73 power::power(const archive_node &n, lst &sym_lst) : inherited(n, sym_lst)
74 {
75         n.find_ex("basis", basis, sym_lst);
76         n.find_ex("exponent", exponent, sym_lst);
77 }
78
79 void power::archive(archive_node &n) const
80 {
81         inherited::archive(n);
82         n.add_ex("basis", basis);
83         n.add_ex("exponent", exponent);
84 }
85
86 DEFAULT_UNARCHIVE(power)
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(const print_csrc & c, unsigned level) const
166 {
167         if (is_a<print_csrc_cl_N>(c)) {
168                 if (exponent.is_equal(_ex_1)) {
169                         c.s << "recip(";
170                         basis.print(c);
171                         c.s << ')';
172                         return;
173                 }
174                 c.s << "expt(";
175                 basis.print(c);
176                 c.s << ", ";
177                 exponent.print(c);
178                 c.s << ')';
179                 return;
180         }
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         }
244         return inherited::info(inf);
245 }
246
247 size_t power::nops() const
248 {
249         return 2;
250 }
251
252 ex power::op(size_t i) const
253 {
254         GINAC_ASSERT(i<2);
255
256         return i==0 ? basis : exponent;
257 }
258
259 ex power::map(map_function & f) const
260 {
261         const ex &mapped_basis = f(basis);
262         const ex &mapped_exponent = f(exponent);
263
264         if (!are_ex_trivially_equal(basis, mapped_basis)
265          || !are_ex_trivially_equal(exponent, mapped_exponent))
266                 return (new power(mapped_basis, mapped_exponent))->setflag(status_flags::dynallocated);
267         else
268                 return *this;
269 }
270
271 bool power::is_polynomial(const ex & var) const
272 {
273         if (exponent.has(var))
274                 return false;
275         if (!exponent.info(info_flags::nonnegint))
276                 return false;
277         return basis.is_polynomial(var);
278 }
279
280 int power::degree(const ex & s) const
281 {
282         if (is_equal(ex_to<basic>(s)))
283                 return 1;
284         else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
285                 if (basis.is_equal(s))
286                         return ex_to<numeric>(exponent).to_int();
287                 else
288                         return basis.degree(s) * ex_to<numeric>(exponent).to_int();
289         } else if (basis.has(s))
290                 throw(std::runtime_error("power::degree(): undefined degree because of non-integer exponent"));
291         else
292                 return 0;
293 }
294
295 int power::ldegree(const ex & s) const 
296 {
297         if (is_equal(ex_to<basic>(s)))
298                 return 1;
299         else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
300                 if (basis.is_equal(s))
301                         return ex_to<numeric>(exponent).to_int();
302                 else
303                         return basis.ldegree(s) * ex_to<numeric>(exponent).to_int();
304         } else if (basis.has(s))
305                 throw(std::runtime_error("power::ldegree(): undefined degree because of non-integer exponent"));
306         else
307                 return 0;
308 }
309
310 ex power::coeff(const ex & s, int n) const
311 {
312         if (is_equal(ex_to<basic>(s)))
313                 return n==1 ? _ex1 : _ex0;
314         else if (!basis.is_equal(s)) {
315                 // basis not equal to s
316                 if (n == 0)
317                         return *this;
318                 else
319                         return _ex0;
320         } else {
321                 // basis equal to s
322                 if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
323                         // integer exponent
324                         int int_exp = ex_to<numeric>(exponent).to_int();
325                         if (n == int_exp)
326                                 return _ex1;
327                         else
328                                 return _ex0;
329                 } else {
330                         // non-integer exponents are treated as zero
331                         if (n == 0)
332                                 return *this;
333                         else
334                                 return _ex0;
335                 }
336         }
337 }
338
339 /** Perform automatic term rewriting rules in this class.  In the following
340  *  x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
341  *  stand for such expressions that contain a plain number.
342  *  - ^(x,0) -> 1  (also handles ^(0,0))
343  *  - ^(x,1) -> x
344  *  - ^(0,c) -> 0 or exception  (depending on the real part of c)
345  *  - ^(1,x) -> 1
346  *  - ^(c1,c2) -> *(c1^n,c1^(c2-n))  (so that 0<(c2-n)<1, try to evaluate roots, possibly in numerator and denominator of c1)
347  *  - ^(^(x,c1),c2) -> ^(x,c1*c2)  if x is positive and c1 is real.
348  *  - ^(^(x,c1),c2) -> ^(x,c1*c2)  (c2 integer or -1 < c1 <= 1, case c1=1 should not happen, see below!)
349  *  - ^(*(x,y,z),c) -> *(x^c,y^c,z^c)  (if c integer)
350  *  - ^(*(x,c1),c2) -> ^(x,c2)*c1^c2  (c1>0)
351  *  - ^(*(x,c1),c2) -> ^(-x,c2)*c1^c2  (c1<0)
352  *
353  *  @param level cut-off in recursive evaluation */
354 ex power::eval(int level) const
355 {
356         if ((level==1) && (flags & status_flags::evaluated))
357                 return *this;
358         else if (level == -max_recursion_level)
359                 throw(std::runtime_error("max recursion level reached"));
360         
361         const ex & ebasis    = level==1 ? basis    : basis.eval(level-1);
362         const ex & eexponent = level==1 ? exponent : exponent.eval(level-1);
363         
364         bool basis_is_numerical = false;
365         bool exponent_is_numerical = false;
366         const numeric *num_basis;
367         const numeric *num_exponent;
368         
369         if (is_exactly_a<numeric>(ebasis)) {
370                 basis_is_numerical = true;
371                 num_basis = &ex_to<numeric>(ebasis);
372         }
373         if (is_exactly_a<numeric>(eexponent)) {
374                 exponent_is_numerical = true;
375                 num_exponent = &ex_to<numeric>(eexponent);
376         }
377         
378         // ^(x,0) -> 1  (0^0 also handled here)
379         if (eexponent.is_zero()) {
380                 if (ebasis.is_zero())
381                         throw (std::domain_error("power::eval(): pow(0,0) is undefined"));
382                 else
383                         return _ex1;
384         }
385         
386         // ^(x,1) -> x
387         if (eexponent.is_equal(_ex1))
388                 return ebasis;
389
390         // ^(0,c1) -> 0 or exception  (depending on real value of c1)
391         if (ebasis.is_zero() && exponent_is_numerical) {
392                 if ((num_exponent->real()).is_zero())
393                         throw (std::domain_error("power::eval(): pow(0,I) is undefined"));
394                 else if ((num_exponent->real()).is_negative())
395                         throw (pole_error("power::eval(): division by zero",1));
396                 else
397                         return _ex0;
398         }
399
400         // ^(1,x) -> 1
401         if (ebasis.is_equal(_ex1))
402                 return _ex1;
403
404         // power of a function calculated by separate rules defined for this function
405         if (is_exactly_a<function>(ebasis))
406                 return ex_to<function>(ebasis).power(eexponent);
407
408         // Turn (x^c)^d into x^(c*d) in the case that x is positive and c is real.
409         if (is_exactly_a<power>(ebasis) && ebasis.op(0).info(info_flags::positive) && ebasis.op(1).info(info_flags::real))
410                 return power(ebasis.op(0), ebasis.op(1) * eexponent);
411
412         if (exponent_is_numerical) {
413
414                 // ^(c1,c2) -> c1^c2  (c1, c2 numeric(),
415                 // except if c1,c2 are rational, but c1^c2 is not)
416                 if (basis_is_numerical) {
417                         const bool basis_is_crational = num_basis->is_crational();
418                         const bool exponent_is_crational = num_exponent->is_crational();
419                         if (!basis_is_crational || !exponent_is_crational) {
420                                 // return a plain float
421                                 return (new numeric(num_basis->power(*num_exponent)))->setflag(status_flags::dynallocated |
422                                                                                                status_flags::evaluated |
423                                                                                                status_flags::expanded);
424                         }
425
426                         const numeric res = num_basis->power(*num_exponent);
427                         if (res.is_crational()) {
428                                 return res;
429                         }
430                         GINAC_ASSERT(!num_exponent->is_integer());  // has been handled by now
431
432                         // ^(c1,n/m) -> *(c1^q,c1^(n/m-q)), 0<(n/m-q)<1, q integer
433                         if (basis_is_crational && exponent_is_crational
434                             && num_exponent->is_real()
435                             && !num_exponent->is_integer()) {
436                                 const numeric n = num_exponent->numer();
437                                 const numeric m = num_exponent->denom();
438                                 numeric r;
439                                 numeric q = iquo(n, m, r);
440                                 if (r.is_negative()) {
441                                         r += m;
442                                         --q;
443                                 }
444                                 if (q.is_zero()) {  // the exponent was in the allowed range 0<(n/m)<1
445                                         if (num_basis->is_rational() && !num_basis->is_integer()) {
446                                                 // try it for numerator and denominator separately, in order to
447                                                 // partially simplify things like (5/8)^(1/3) -> 1/2*5^(1/3)
448                                                 const numeric bnum = num_basis->numer();
449                                                 const numeric bden = num_basis->denom();
450                                                 const numeric res_bnum = bnum.power(*num_exponent);
451                                                 const numeric res_bden = bden.power(*num_exponent);
452                                                 if (res_bnum.is_integer())
453                                                         return (new mul(power(bden,-*num_exponent),res_bnum))->setflag(status_flags::dynallocated | status_flags::evaluated);
454                                                 if (res_bden.is_integer())
455                                                         return (new mul(power(bnum,*num_exponent),res_bden.inverse()))->setflag(status_flags::dynallocated | status_flags::evaluated);
456                                         }
457                                         return this->hold();
458                                 } else {
459                                         // assemble resulting product, but allowing for a re-evaluation,
460                                         // because otherwise we'll end up with something like
461                                         //    (7/8)^(4/3)  ->  7/8*(1/2*7^(1/3))
462                                         // instead of 7/16*7^(1/3).
463                                         ex prod = power(*num_basis,r.div(m));
464                                         return prod*power(*num_basis,q);
465                                 }
466                         }
467                 }
468         
469                 // ^(^(x,c1),c2) -> ^(x,c1*c2)
470                 // (c1, c2 numeric(), c2 integer or -1 < c1 <= 1,
471                 // case c1==1 should not happen, see below!)
472                 if (is_exactly_a<power>(ebasis)) {
473                         const power & sub_power = ex_to<power>(ebasis);
474                         const ex & sub_basis = sub_power.basis;
475                         const ex & sub_exponent = sub_power.exponent;
476                         if (is_exactly_a<numeric>(sub_exponent)) {
477                                 const numeric & num_sub_exponent = ex_to<numeric>(sub_exponent);
478                                 GINAC_ASSERT(num_sub_exponent!=numeric(1));
479                                 if (num_exponent->is_integer() || (abs(num_sub_exponent) - (*_num1_p)).is_negative()) {
480                                         return power(sub_basis,num_sub_exponent.mul(*num_exponent));
481                                 }
482                         }
483                 }
484         
485                 // ^(*(x,y,z),c1) -> *(x^c1,y^c1,z^c1) (c1 integer)
486                 if (num_exponent->is_integer() && is_exactly_a<mul>(ebasis)) {
487                         return expand_mul(ex_to<mul>(ebasis), *num_exponent, 0);
488                 }
489
490                 // (2*x + 6*y)^(-4) -> 1/16*(x + 3*y)^(-4)
491                 if (num_exponent->is_integer() && is_exactly_a<add>(ebasis)) {
492                         numeric icont = ebasis.integer_content();
493                         const numeric& lead_coeff = 
494                                 ex_to<numeric>(ex_to<add>(ebasis).seq.begin()->coeff).div_dyn(icont);
495
496                         const bool canonicalizable = lead_coeff.is_integer();
497                         const bool unit_normal = lead_coeff.is_pos_integer();
498                         if (canonicalizable && (! unit_normal))
499                                 icont = icont.mul(*_num_1_p);
500                         
501                         if (canonicalizable && (icont != *_num1_p)) {
502                                 const add& addref = ex_to<add>(ebasis);
503                                 add* addp = new add(addref);
504                                 addp->setflag(status_flags::dynallocated);
505                                 addp->clearflag(status_flags::hash_calculated);
506                                 addp->overall_coeff = ex_to<numeric>(addp->overall_coeff).div_dyn(icont);
507                                 for (epvector::iterator i = addp->seq.begin(); i != addp->seq.end(); ++i)
508                                         i->coeff = ex_to<numeric>(i->coeff).div_dyn(icont);
509
510                                 const numeric c = icont.power(*num_exponent);
511                                 if (likely(c != *_num1_p))
512                                         return (new mul(power(*addp, *num_exponent), c))->setflag(status_flags::dynallocated);
513                                 else
514                                         return power(*addp, *num_exponent);
515                         }
516                 }
517
518                 // ^(*(...,x;c1),c2) -> *(^(*(...,x;1),c2),c1^c2)  (c1, c2 numeric(), c1>0)
519                 // ^(*(...,x;c1),c2) -> *(^(*(...,x;-1),c2),(-c1)^c2)  (c1, c2 numeric(), c1<0)
520                 if (is_exactly_a<mul>(ebasis)) {
521                         GINAC_ASSERT(!num_exponent->is_integer()); // should have been handled above
522                         const mul & mulref = ex_to<mul>(ebasis);
523                         if (!mulref.overall_coeff.is_equal(_ex1)) {
524                                 const numeric & num_coeff = ex_to<numeric>(mulref.overall_coeff);
525                                 if (num_coeff.is_real()) {
526                                         if (num_coeff.is_positive()) {
527                                                 mul *mulp = new mul(mulref);
528                                                 mulp->overall_coeff = _ex1;
529                                                 mulp->clearflag(status_flags::evaluated);
530                                                 mulp->clearflag(status_flags::hash_calculated);
531                                                 return (new mul(power(*mulp,exponent),
532                                                                 power(num_coeff,*num_exponent)))->setflag(status_flags::dynallocated);
533                                         } else {
534                                                 GINAC_ASSERT(num_coeff.compare(*_num0_p)<0);
535                                                 if (!num_coeff.is_equal(*_num_1_p)) {
536                                                         mul *mulp = new mul(mulref);
537                                                         mulp->overall_coeff = _ex_1;
538                                                         mulp->clearflag(status_flags::evaluated);
539                                                         mulp->clearflag(status_flags::hash_calculated);
540                                                         return (new mul(power(*mulp,exponent),
541                                                                         power(abs(num_coeff),*num_exponent)))->setflag(status_flags::dynallocated);
542                                                 }
543                                         }
544                                 }
545                         }
546                 }
547
548                 // ^(nc,c1) -> ncmul(nc,nc,...) (c1 positive integer, unless nc is a matrix)
549                 if (num_exponent->is_pos_integer() &&
550                     ebasis.return_type() != return_types::commutative &&
551                     !is_a<matrix>(ebasis)) {
552                         return ncmul(exvector(num_exponent->to_int(), ebasis), true);
553                 }
554         }
555         
556         if (are_ex_trivially_equal(ebasis,basis) &&
557             are_ex_trivially_equal(eexponent,exponent)) {
558                 return this->hold();
559         }
560         return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated |
561                                                        status_flags::evaluated);
562 }
563
564 ex power::evalf(int level) const
565 {
566         ex ebasis;
567         ex eexponent;
568         
569         if (level==1) {
570                 ebasis = basis;
571                 eexponent = exponent;
572         } else if (level == -max_recursion_level) {
573                 throw(std::runtime_error("max recursion level reached"));
574         } else {
575                 ebasis = basis.evalf(level-1);
576                 if (!is_exactly_a<numeric>(exponent))
577                         eexponent = exponent.evalf(level-1);
578                 else
579                         eexponent = exponent;
580         }
581
582         return power(ebasis,eexponent);
583 }
584
585 ex power::evalm() const
586 {
587         const ex ebasis = basis.evalm();
588         const ex eexponent = exponent.evalm();
589         if (is_a<matrix>(ebasis)) {
590                 if (is_exactly_a<numeric>(eexponent)) {
591                         return (new matrix(ex_to<matrix>(ebasis).pow(eexponent)))->setflag(status_flags::dynallocated);
592                 }
593         }
594         return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated);
595 }
596
597 bool power::has(const ex & other, unsigned options) const
598 {
599         if (!(options & has_options::algebraic))
600                 return basic::has(other, options);
601         if (!is_a<power>(other))
602                 return basic::has(other, options);
603         if (!exponent.info(info_flags::integer)
604                         || !other.op(1).info(info_flags::integer))
605                 return basic::has(other, options);
606         if (exponent.info(info_flags::posint)
607                         && other.op(1).info(info_flags::posint)
608                         && ex_to<numeric>(exponent).to_int()
609                                         > ex_to<numeric>(other.op(1)).to_int()
610                         && basis.match(other.op(0)))
611                 return true;
612         if (exponent.info(info_flags::negint)
613                         && other.op(1).info(info_flags::negint)
614                         && ex_to<numeric>(exponent).to_int()
615                                         < ex_to<numeric>(other.op(1)).to_int()
616                         && basis.match(other.op(0)))
617                 return true;
618         return basic::has(other, options);
619 }
620
621 // from mul.cpp
622 extern bool tryfactsubs(const ex &, const ex &, int &, lst &);
623
624 ex power::subs(const exmap & m, unsigned options) const
625 {       
626         const ex &subsed_basis = basis.subs(m, options);
627         const ex &subsed_exponent = exponent.subs(m, options);
628
629         if (!are_ex_trivially_equal(basis, subsed_basis)
630          || !are_ex_trivially_equal(exponent, subsed_exponent)) 
631                 return power(subsed_basis, subsed_exponent).subs_one_level(m, options);
632
633         if (!(options & subs_options::algebraic))
634                 return subs_one_level(m, options);
635
636         for (exmap::const_iterator it = m.begin(); it != m.end(); ++it) {
637                 int nummatches = std::numeric_limits<int>::max();
638                 lst repls;
639                 if (tryfactsubs(*this, it->first, nummatches, repls))
640                         return (ex_to<basic>((*this) * power(it->second.subs(ex(repls), subs_options::no_pattern) / it->first.subs(ex(repls), subs_options::no_pattern), nummatches))).subs_one_level(m, options);
641         }
642
643         return subs_one_level(m, options);
644 }
645
646 ex power::eval_ncmul(const exvector & v) const
647 {
648         return inherited::eval_ncmul(v);
649 }
650
651 ex power::conjugate() const
652 {
653         ex newbasis = basis.conjugate();
654         ex newexponent = exponent.conjugate();
655         if (are_ex_trivially_equal(basis, newbasis) && are_ex_trivially_equal(exponent, newexponent)) {
656                 return *this;
657         }
658         return (new power(newbasis, newexponent))->setflag(status_flags::dynallocated);
659 }
660
661 ex power::real_part() const
662 {
663         if (exponent.info(info_flags::integer)) {
664                 ex basis_real = basis.real_part();
665                 if (basis_real == basis)
666                         return *this;
667                 realsymbol a("a"),b("b");
668                 ex result;
669                 if (exponent.info(info_flags::posint))
670                         result = power(a+I*b,exponent);
671                 else
672                         result = power(a/(a*a+b*b)-I*b/(a*a+b*b),-exponent);
673                 result = result.expand();
674                 result = result.real_part();
675                 result = result.subs(lst( a==basis_real, b==basis.imag_part() ));
676                 return result;
677         }
678         
679         ex a = basis.real_part();
680         ex b = basis.imag_part();
681         ex c = exponent.real_part();
682         ex d = exponent.imag_part();
683         return power(abs(basis),c)*exp(-d*atan2(b,a))*cos(c*atan2(b,a)+d*log(abs(basis)));
684 }
685
686 ex power::imag_part() const
687 {
688         if (exponent.info(info_flags::integer)) {
689                 ex basis_real = basis.real_part();
690                 if (basis_real == basis)
691                         return 0;
692                 realsymbol a("a"),b("b");
693                 ex result;
694                 if (exponent.info(info_flags::posint))
695                         result = power(a+I*b,exponent);
696                 else
697                         result = power(a/(a*a+b*b)-I*b/(a*a+b*b),-exponent);
698                 result = result.expand();
699                 result = result.imag_part();
700                 result = result.subs(lst( a==basis_real, b==basis.imag_part() ));
701                 return result;
702         }
703         
704         ex a=basis.real_part();
705         ex b=basis.imag_part();
706         ex c=exponent.real_part();
707         ex d=exponent.imag_part();
708         return
709                 power(abs(basis),c)*exp(-d*atan2(b,a))*sin(c*atan2(b,a)+d*log(abs(basis)));
710 }
711
712 // protected
713
714 // protected
715
716 /** Implementation of ex::diff() for a power.
717  *  @see ex::diff */
718 ex power::derivative(const symbol & s) const
719 {
720         if (is_a<numeric>(exponent)) {
721                 // D(b^r) = r * b^(r-1) * D(b) (faster than the formula below)
722                 epvector newseq;
723                 newseq.reserve(2);
724                 newseq.push_back(expair(basis, exponent - _ex1));
725                 newseq.push_back(expair(basis.diff(s), _ex1));
726                 return mul(newseq, exponent);
727         } else {
728                 // D(b^e) = b^e * (D(e)*ln(b) + e*D(b)/b)
729                 return mul(*this,
730                            add(mul(exponent.diff(s), log(basis)),
731                            mul(mul(exponent, basis.diff(s)), power(basis, _ex_1))));
732         }
733 }
734
735 int power::compare_same_type(const basic & other) const
736 {
737         GINAC_ASSERT(is_exactly_a<power>(other));
738         const power &o = static_cast<const power &>(other);
739
740         int cmpval = basis.compare(o.basis);
741         if (cmpval)
742                 return cmpval;
743         else
744                 return exponent.compare(o.exponent);
745 }
746
747 unsigned power::return_type() const
748 {
749         return basis.return_type();
750 }
751
752 tinfo_t power::return_type_tinfo() const
753 {
754         return basis.return_type_tinfo();
755 }
756
757 ex power::expand(unsigned options) const
758 {
759         if (options == 0 && (flags & status_flags::expanded))
760                 return *this;
761         
762         const ex expanded_basis = basis.expand(options);
763         const ex expanded_exponent = exponent.expand(options);
764         
765         // x^(a+b) -> x^a * x^b
766         if (is_exactly_a<add>(expanded_exponent)) {
767                 const add &a = ex_to<add>(expanded_exponent);
768                 exvector distrseq;
769                 distrseq.reserve(a.seq.size() + 1);
770                 epvector::const_iterator last = a.seq.end();
771                 epvector::const_iterator cit = a.seq.begin();
772                 while (cit!=last) {
773                         distrseq.push_back(power(expanded_basis, a.recombine_pair_to_ex(*cit)));
774                         ++cit;
775                 }
776                 
777                 // Make sure that e.g. (x+y)^(2+a) expands the (x+y)^2 factor
778                 if (ex_to<numeric>(a.overall_coeff).is_integer()) {
779                         const numeric &num_exponent = ex_to<numeric>(a.overall_coeff);
780                         int int_exponent = num_exponent.to_int();
781                         if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
782                                 distrseq.push_back(expand_add(ex_to<add>(expanded_basis), int_exponent, options));
783                         else
784                                 distrseq.push_back(power(expanded_basis, a.overall_coeff));
785                 } else
786                         distrseq.push_back(power(expanded_basis, a.overall_coeff));
787                 
788                 // Make sure that e.g. (x+y)^(1+a) -> x*(x+y)^a + y*(x+y)^a
789                 ex r = (new mul(distrseq))->setflag(status_flags::dynallocated);
790                 return r.expand(options);
791         }
792         
793         if (!is_exactly_a<numeric>(expanded_exponent) ||
794                 !ex_to<numeric>(expanded_exponent).is_integer()) {
795                 if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent)) {
796                         return this->hold();
797                 } else {
798                         return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
799                 }
800         }
801         
802         // integer numeric exponent
803         const numeric & num_exponent = ex_to<numeric>(expanded_exponent);
804         int int_exponent = num_exponent.to_int();
805         
806         // (x+y)^n, n>0
807         if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
808                 return expand_add(ex_to<add>(expanded_basis), int_exponent, options);
809         
810         // (x*y)^n -> x^n * y^n
811         if (is_exactly_a<mul>(expanded_basis))
812                 return expand_mul(ex_to<mul>(expanded_basis), num_exponent, options, true);
813         
814         // cannot expand further
815         if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent))
816                 return this->hold();
817         else
818                 return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
819 }
820
821 //////////
822 // new virtual functions which can be overridden by derived classes
823 //////////
824
825 // none
826
827 //////////
828 // non-virtual functions in this class
829 //////////
830
831 /** expand a^n where a is an add and n is a positive integer.
832  *  @see power::expand */
833 ex power::expand_add(const add & a, int n, unsigned options) const
834 {
835         if (n==2)
836                 return expand_add_2(a, options);
837
838         const size_t m = a.nops();
839         exvector result;
840         // The number of terms will be the number of combinatorial compositions,
841         // i.e. the number of unordered arrangements of m nonnegative integers
842         // which sum up to n.  It is frequently written as C_n(m) and directly
843         // related with binomial coefficients:
844         result.reserve(binomial(numeric(n+m-1), numeric(m-1)).to_int());
845         intvector k(m-1);
846         intvector k_cum(m-1); // k_cum[l]:=sum(i=0,l,k[l]);
847         intvector upper_limit(m-1);
848         int l;
849
850         for (size_t l=0; l<m-1; ++l) {
851                 k[l] = 0;
852                 k_cum[l] = 0;
853                 upper_limit[l] = n;
854         }
855
856         while (true) {
857                 exvector term;
858                 term.reserve(m+1);
859                 for (l=0; l<m-1; ++l) {
860                         const ex & b = a.op(l);
861                         GINAC_ASSERT(!is_exactly_a<add>(b));
862                         GINAC_ASSERT(!is_exactly_a<power>(b) ||
863                                      !is_exactly_a<numeric>(ex_to<power>(b).exponent) ||
864                                      !ex_to<numeric>(ex_to<power>(b).exponent).is_pos_integer() ||
865                                      !is_exactly_a<add>(ex_to<power>(b).basis) ||
866                                      !is_exactly_a<mul>(ex_to<power>(b).basis) ||
867                                      !is_exactly_a<power>(ex_to<power>(b).basis));
868                         if (is_exactly_a<mul>(b))
869                                 term.push_back(expand_mul(ex_to<mul>(b), numeric(k[l]), options, true));
870                         else
871                                 term.push_back(power(b,k[l]));
872                 }
873
874                 const ex & b = a.op(l);
875                 GINAC_ASSERT(!is_exactly_a<add>(b));
876                 GINAC_ASSERT(!is_exactly_a<power>(b) ||
877                              !is_exactly_a<numeric>(ex_to<power>(b).exponent) ||
878                              !ex_to<numeric>(ex_to<power>(b).exponent).is_pos_integer() ||
879                              !is_exactly_a<add>(ex_to<power>(b).basis) ||
880                              !is_exactly_a<mul>(ex_to<power>(b).basis) ||
881                              !is_exactly_a<power>(ex_to<power>(b).basis));
882                 if (is_exactly_a<mul>(b))
883                         term.push_back(expand_mul(ex_to<mul>(b), numeric(n-k_cum[m-2]), options, true));
884                 else
885                         term.push_back(power(b,n-k_cum[m-2]));
886
887                 numeric f = binomial(numeric(n),numeric(k[0]));
888                 for (l=1; l<m-1; ++l)
889                         f *= binomial(numeric(n-k_cum[l-1]),numeric(k[l]));
890
891                 term.push_back(f);
892
893                 result.push_back(ex((new mul(term))->setflag(status_flags::dynallocated)).expand(options));
894
895                 // increment k[]
896                 l = m-2;
897                 while ((l>=0) && ((++k[l])>upper_limit[l])) {
898                         k[l] = 0;
899                         --l;
900                 }
901                 if (l<0) break;
902
903                 // recalc k_cum[] and upper_limit[]
904                 k_cum[l] = (l==0 ? k[0] : k_cum[l-1]+k[l]);
905
906                 for (size_t i=l+1; i<m-1; ++i)
907                         k_cum[i] = k_cum[i-1]+k[i];
908
909                 for (size_t i=l+1; i<m-1; ++i)
910                         upper_limit[i] = n-k_cum[i-1];
911         }
912
913         return (new add(result))->setflag(status_flags::dynallocated |
914                                           status_flags::expanded);
915 }
916
917
918 /** Special case of power::expand_add. Expands a^2 where a is an add.
919  *  @see power::expand_add */
920 ex power::expand_add_2(const add & a, unsigned options) const
921 {
922         epvector sum;
923         size_t a_nops = a.nops();
924         sum.reserve((a_nops*(a_nops+1))/2);
925         epvector::const_iterator last = a.seq.end();
926
927         // power(+(x,...,z;c),2)=power(+(x,...,z;0),2)+2*c*+(x,...,z;0)+c*c
928         // first part: ignore overall_coeff and expand other terms
929         for (epvector::const_iterator cit0=a.seq.begin(); cit0!=last; ++cit0) {
930                 const ex & r = cit0->rest;
931                 const ex & c = cit0->coeff;
932                 
933                 GINAC_ASSERT(!is_exactly_a<add>(r));
934                 GINAC_ASSERT(!is_exactly_a<power>(r) ||
935                              !is_exactly_a<numeric>(ex_to<power>(r).exponent) ||
936                              !ex_to<numeric>(ex_to<power>(r).exponent).is_pos_integer() ||
937                              !is_exactly_a<add>(ex_to<power>(r).basis) ||
938                              !is_exactly_a<mul>(ex_to<power>(r).basis) ||
939                              !is_exactly_a<power>(ex_to<power>(r).basis));
940                 
941                 if (c.is_equal(_ex1)) {
942                         if (is_exactly_a<mul>(r)) {
943                                 sum.push_back(expair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
944                                                      _ex1));
945                         } else {
946                                 sum.push_back(expair((new power(r,_ex2))->setflag(status_flags::dynallocated),
947                                                      _ex1));
948                         }
949                 } else {
950                         if (is_exactly_a<mul>(r)) {
951                                 sum.push_back(a.combine_ex_with_coeff_to_pair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
952                                                      ex_to<numeric>(c).power_dyn(*_num2_p)));
953                         } else {
954                                 sum.push_back(a.combine_ex_with_coeff_to_pair((new power(r,_ex2))->setflag(status_flags::dynallocated),
955                                                      ex_to<numeric>(c).power_dyn(*_num2_p)));
956                         }
957                 }
958
959                 for (epvector::const_iterator cit1=cit0+1; cit1!=last; ++cit1) {
960                         const ex & r1 = cit1->rest;
961                         const ex & c1 = cit1->coeff;
962                         sum.push_back(a.combine_ex_with_coeff_to_pair((new mul(r,r1))->setflag(status_flags::dynallocated),
963                                                                       _num2_p->mul(ex_to<numeric>(c)).mul_dyn(ex_to<numeric>(c1))));
964                 }
965         }
966         
967         GINAC_ASSERT(sum.size()==(a.seq.size()*(a.seq.size()+1))/2);
968         
969         // second part: add terms coming from overall_factor (if != 0)
970         if (!a.overall_coeff.is_zero()) {
971                 epvector::const_iterator i = a.seq.begin(), end = a.seq.end();
972                 while (i != end) {
973                         sum.push_back(a.combine_pair_with_coeff_to_pair(*i, ex_to<numeric>(a.overall_coeff).mul_dyn(*_num2_p)));
974                         ++i;
975                 }
976                 sum.push_back(expair(ex_to<numeric>(a.overall_coeff).power_dyn(*_num2_p),_ex1));
977         }
978         
979         GINAC_ASSERT(sum.size()==(a_nops*(a_nops+1))/2);
980         
981         return (new add(sum))->setflag(status_flags::dynallocated | status_flags::expanded);
982 }
983
984 /** Expand factors of m in m^n where m is a mul and n is an integer.
985  *  @see power::expand */
986 ex power::expand_mul(const mul & m, const numeric & n, unsigned options, bool from_expand) const
987 {
988         GINAC_ASSERT(n.is_integer());
989
990         if (n.is_zero()) {
991                 return _ex1;
992         }
993
994         // Leave it to multiplication since dummy indices have to be renamed
995         if (get_all_dummy_indices(m).size() > 0 && n.is_positive()) {
996                 ex result = m;
997                 exvector va = get_all_dummy_indices(m);
998                 sort(va.begin(), va.end(), ex_is_less());
999
1000                 for (int i=1; i < n.to_int(); i++)
1001                         result *= rename_dummy_indices_uniquely(va, m);
1002                 return result;
1003         }
1004
1005         epvector distrseq;
1006         distrseq.reserve(m.seq.size());
1007         bool need_reexpand = false;
1008
1009         epvector::const_iterator last = m.seq.end();
1010         epvector::const_iterator cit = m.seq.begin();
1011         while (cit!=last) {
1012                 expair p = m.combine_pair_with_coeff_to_pair(*cit, n);
1013                 if (from_expand && is_exactly_a<add>(cit->rest) && ex_to<numeric>(p.coeff).is_pos_integer()) {
1014                         // this happens when e.g. (a+b)^(1/2) gets squared and
1015                         // the resulting product needs to be reexpanded
1016                         need_reexpand = true;
1017                 }
1018                 distrseq.push_back(p);
1019                 ++cit;
1020         }
1021
1022         const mul & result = static_cast<const mul &>((new mul(distrseq, ex_to<numeric>(m.overall_coeff).power_dyn(n)))->setflag(status_flags::dynallocated));
1023         if (need_reexpand)
1024                 return ex(result).expand(options);
1025         if (from_expand)
1026                 return result.setflag(status_flags::expanded);
1027         return result;
1028 }
1029
1030 } // namespace GiNaC