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