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