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